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/Motif support by Robert Webb
* Athena port by Bill Foster
*
* 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 <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#ifdef FEAT_GUI_NEXTAW
# include <X11/neXtaw/Form.h>
# include <X11/neXtaw/SimpleMenu.h>
# include <X11/neXtaw/MenuButton.h>
# include <X11/neXtaw/SmeBSB.h>
# include <X11/neXtaw/SmeLine.h>
# include <X11/neXtaw/Box.h>
# include <X11/neXtaw/Dialog.h>
# include <X11/neXtaw/Text.h>
# include <X11/neXtaw/AsciiText.h>
# include <X11/neXtaw/Scrollbar.h>
#else
# include <X11/Xaw/Form.h>
# include <X11/Xaw/SimpleMenu.h>
# include <X11/Xaw/MenuButton.h>
# include <X11/Xaw/SmeBSB.h>
# include <X11/Xaw/SmeLine.h>
# include <X11/Xaw/Box.h>
# include <X11/Xaw/Dialog.h>
# include <X11/Xaw/Text.h>
# include <X11/Xaw/AsciiText.h>
#endif /* FEAT_GUI_NEXTAW */
#include "vim.h"
#ifndef FEAT_GUI_NEXTAW
# include "gui_at_sb.h"
#endif
extern Widget vimShell;
static Widget vimForm = (Widget)0;
Widget textArea = (Widget)0;
#ifdef FEAT_MENU
static Widget menuBar = (Widget)0;
static XtIntervalId timer = 0; /* 0 = expired, otherwise active */
/* Used to figure out menu ordering */
static vimmenu_T *a_cur_menu = NULL;
static Cardinal athena_calculate_ins_pos __ARGS((Widget));
static Pixmap gui_athena_create_pullright_pixmap __ARGS((Widget));
static void gui_athena_menu_timeout __ARGS((XtPointer, XtIntervalId *));
static void gui_athena_popup_callback __ARGS((Widget, XtPointer, XtPointer));
static void gui_athena_delayed_arm_action __ARGS((Widget, XEvent *, String *,
Cardinal *));
static void gui_athena_popdown_submenus_action __ARGS((Widget, XEvent *,
String *, Cardinal *));
static XtActionsRec pullAction[2] = {
{ "menu-delayedpopup", (XtActionProc)gui_athena_delayed_arm_action},
{ "menu-popdownsubmenus", (XtActionProc)gui_athena_popdown_submenus_action}
};
#endif
#ifdef FEAT_TOOLBAR
static void gui_mch_reset_focus __ARGS((void));
static Widget toolBar = (Widget)0;
#endif
static void gui_athena_scroll_cb_jump __ARGS((Widget, XtPointer, XtPointer));
static void gui_athena_scroll_cb_scroll __ARGS((Widget, XtPointer, XtPointer));
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_MENU)
static void gui_athena_menu_colors __ARGS((Widget id));
#endif
static void gui_athena_scroll_colors __ARGS((Widget id));
#ifdef FEAT_MENU
static XtTranslations popupTrans, parentTrans, menuTrans, supermenuTrans;
static Pixmap pullerBitmap = None;
static int puller_width = 0;
#endif
/*
* Scrollbar callback (XtNjumpProc) for when the scrollbar is dragged with the
* left or middle mouse button.
*/
static void
gui_athena_scroll_cb_jump(w, client_data, call_data)
Widget w UNUSED;
XtPointer client_data, call_data;
{
scrollbar_T *sb, *sb_info;
long value;
sb = gui_find_scrollbar((long)client_data);
if (sb == NULL)
return;
else 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;
value = (long)(*((float *)call_data) * (float)(sb_info->max + 1) + 0.001);
if (value > sb_info->max)
value = sb_info->max;
gui_drag_scrollbar(sb, value, TRUE);
}
/*
* Scrollbar callback (XtNscrollProc) for paging up or down with the left or
* right mouse buttons.
*/
static void
gui_athena_scroll_cb_scroll(w, client_data, call_data)
Widget w UNUSED;
XtPointer client_data, call_data;
{
scrollbar_T *sb, *sb_info;
long value;
int data = (int)(long)call_data;
int page;
sb = gui_find_scrollbar((long)client_data);
if (sb == NULL)
return;
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];
if (sb_info->size > 5)
page = sb_info->size - 2; /* use two lines of context */
else
page = sb_info->size;
#ifdef FEAT_GUI_NEXTAW
if (data < 0)
{
data = (data - gui.char_height + 1) / gui.char_height;
if (data > -sb_info->size)
data = -1;
else
data = -page;
}
else if (data > 0)
{
data = (data + gui.char_height - 1) / gui.char_height;
if (data < sb_info->size)
data = 1;
else
data = page;
}
#else
switch (data)
{
case ONE_LINE_DATA: data = 1; break;
case -ONE_LINE_DATA: data = -1; break;
case ONE_PAGE_DATA: data = page; break;
case -ONE_PAGE_DATA: data = -page; break;
case END_PAGE_DATA: data = sb_info->max; break;
case -END_PAGE_DATA: data = -sb_info->max; break;
default: data = 0; break;
}
#endif
}
else /* Bottom scrollbar */
{
sb_info = sb;
#ifdef FEAT_GUI_NEXTAW
if (data < 0)
{
data = (data - gui.char_width + 1) / gui.char_width;
if (data > -sb->size)
data = -1;
}
else if (data > 0)
{
data = (data + gui.char_width - 1) / gui.char_width;
if (data < sb->size)
data = 1;
}
#endif
if (data < -1) /* page-width left */
{
if (sb->size > 8)
data = -(sb->size - 5);
else
data = -sb->size;
}
else if (data > 1) /* page-width right */
{
if (sb->size > 8)
data = (sb->size - 5);
else
data = sb->size;
}
}
value = sb_info->value + data;
if (value > sb_info->max)
value = sb_info->max;
else if (value < 0)
value = 0;
/* Update the bottom scrollbar an extra time (why is this needed?? */
if (sb->wp == NULL) /* Bottom scrollbar */
gui_mch_set_scrollbar_thumb(sb, value, sb->size, sb->max);
gui_drag_scrollbar(sb, value, FALSE);
}
/*
* Create all the Athena widgets necessary.
*/
void
gui_x11_create_widgets()
{
/*
* We don't have any borders handled internally by the textArea to worry
* about so only skip over the configured border width.
*/
gui.border_offset = gui.border_width;
/* The form containing all the other widgets */
vimForm = XtVaCreateManagedWidget("vimForm",
formWidgetClass, vimShell,
XtNborderWidth, 0,
NULL);
gui_athena_scroll_colors(vimForm);
#ifdef FEAT_MENU
/* The top menu bar */
menuBar = XtVaCreateManagedWidget("menuBar",
boxWidgetClass, vimForm,
XtNresizable, True,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainRight,
XtNinsertPosition, athena_calculate_ins_pos,
NULL);
gui_athena_menu_colors(menuBar);
if (gui.menu_fg_pixel != INVALCOLOR)
XtVaSetValues(menuBar, XtNborderColor, gui.menu_fg_pixel, NULL);
#endif
#ifdef FEAT_TOOLBAR
/* Don't create it Managed, it will be managed when creating the first
* item. Otherwise an empty toolbar shows up. */
toolBar = XtVaCreateWidget("toolBar",
boxWidgetClass, vimForm,
XtNresizable, True,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainRight,
XtNorientation, XtorientHorizontal,
XtNhSpace, 1,
XtNvSpace, 3,
XtNinsertPosition, athena_calculate_ins_pos,
NULL);
gui_athena_menu_colors(toolBar);
#endif
/* The text area. */
textArea = XtVaCreateManagedWidget("textArea",
coreWidgetClass, vimForm,
XtNresizable, True,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainLeft,
XtNbackground, gui.back_pixel,
XtNborderWidth, 0,
NULL);
/*
* Install the callbacks.
*/
gui_x11_callbacks(textArea, vimForm);
#ifdef FEAT_MENU
popupTrans = XtParseTranslationTable(
"<EnterWindow>: menu-popdownsubmenus() highlight() menu-delayedpopup()\n"
"<LeaveWindow>: unhighlight()\n"
"<BtnUp>: menu-popdownsubmenus() XtMenuPopdown() notify() unhighlight()\n"
"<Motion>: highlight() menu-delayedpopup()");
parentTrans = XtParseTranslationTable("<LeaveWindow>: unhighlight()");
menuTrans = XtParseTranslationTable(
"<EnterWindow>: menu-popdownsubmenus() highlight() menu-delayedpopup()\n"
"<LeaveWindow>: menu-popdownsubmenus() XtMenuPopdown() unhighlight()\n"
"<BtnUp>: notify() unhighlight()\n"
"<BtnMotion>: highlight() menu-delayedpopup()");
supermenuTrans = XtParseTranslationTable(
"<EnterWindow>: menu-popdownsubmenus() highlight() menu-delayedpopup()\n"
"<LeaveWindow>: unhighlight()\n"
"<BtnUp>: menu-popdownsubmenus() XtMenuPopdown() notify() unhighlight()\n"
"<BtnMotion>: highlight() menu-delayedpopup()");
XtAppAddActions(XtWidgetToApplicationContext(vimForm), pullAction,
XtNumber(pullAction));
#endif
/* Pretend we don't have input focus, we will get an event if we do. */
gui.in_focus = FALSE;
}
#ifdef FEAT_MENU
/*
* Calculates the Pixmap based on the size of the current menu font.
*/
static Pixmap
gui_athena_create_pullright_pixmap(w)
Widget w;
{
Pixmap retval;
#ifdef FONTSET_ALWAYS
XFontSet font = None;
#else
XFontStruct *font = NULL;
#endif
#ifdef FONTSET_ALWAYS
if (gui.menu_fontset == NOFONTSET)
#else
if (gui.menu_font == NOFONT)
#endif
{
XrmValue from, to;
WidgetList children;
Cardinal num_children;
#ifdef FONTSET_ALWAYS
from.size = strlen(from.addr = XtDefaultFontSet);
to.addr = (XtPointer)&font;
to.size = sizeof(XFontSet);
#else
from.size = strlen(from.addr = XtDefaultFont);
to.addr = (XtPointer)&font;
to.size = sizeof(XFontStruct *);
#endif
/* Assumption: The menuBar children will use the same font as the
* pulldown menu items AND they will all be of type
* XtNfont.
*/
XtVaGetValues(menuBar, XtNchildren, &children,
XtNnumChildren, &num_children,
NULL);
if (XtConvertAndStore(w ? w :
(num_children > 0) ? children[0] : menuBar,
XtRString, &from,
#ifdef FONTSET_ALWAYS
XtRFontSet, &to
#else
XtRFontStruct, &to
#endif
) == False)
return None;
/* "font" should now contain data */
}
else
#ifdef FONTSET_ALWAYS
font = (XFontSet)gui.menu_fontset;
#else
font = (XFontStruct *)gui.menu_font;
#endif
{
int width, height;
GC draw_gc, undraw_gc;
XGCValues gc_values;
XPoint points[3];
#ifdef FONTSET_ALWAYS
height = fontset_height2(font);
#else
height = font->max_bounds.ascent + font->max_bounds.descent;
#endif
width = height - 2;
puller_width = width + 4;
retval = XCreatePixmap(gui.dpy,DefaultRootWindow(gui.dpy),width,
height, 1);
gc_values.foreground = 1;
gc_values.background = 0;
draw_gc = XCreateGC(gui.dpy, retval,
GCForeground | GCBackground,
&gc_values);
gc_values.foreground = 0;
gc_values.background = 1;
undraw_gc = XCreateGC(gui.dpy, retval,
GCForeground | GCBackground,
&gc_values);
points[0].x = 0;
points[0].y = 0;
points[1].x = width - 1;
points[1].y = (height - 1) / 2;
points[2].x = 0;
points[2].y = height - 1;
XFillRectangle(gui.dpy, retval, undraw_gc, 0, 0, height, height);
XFillPolygon(gui.dpy, retval, draw_gc, points, XtNumber(points),
Convex, CoordModeOrigin);
XFreeGC(gui.dpy, draw_gc);
XFreeGC(gui.dpy, undraw_gc);
}
return retval;
}
#endif
/*
* Called when the GUI is not going to start after all.
*/
void
gui_x11_destroy_widgets()
{
textArea = NULL;
#ifdef FEAT_MENU
menuBar = NULL;
#endif
#ifdef FEAT_TOOLBAR
toolBar = NULL;
#endif
}
#if defined(FEAT_TOOLBAR) || defined(PROTO)
# include "gui_x11_pm.h"
# ifdef HAVE_X11_XPM_H
# include <X11/xpm.h>
# endif
static void createXpmImages __ARGS((char_u *path, char **xpm, Pixmap *sen));
static void get_toolbar_pixmap __ARGS((vimmenu_T *menu, Pixmap *sen));
/*
* Allocated a pixmap for toolbar menu "menu".
* Return in "sen".
*/
static void
get_toolbar_pixmap(menu, sen)
vimmenu_T *menu;
Pixmap *sen;
{
char_u buf[MAXPATHL]; /* buffer storing expanded pathname */
char **xpm = NULL; /* xpm array */
buf[0] = NUL; /* start with NULL path */
if (menu->iconfile != NULL)
{
/* Use the "icon=" argument. */
gui_find_iconfile(menu->iconfile, buf, "xpm");
createXpmImages(buf, NULL, sen);
/* If it failed, try using the menu name. */
if (*sen == (Pixmap)0 && gui_find_bitmap(menu->name, buf, "xpm") == OK)
createXpmImages(buf, NULL, sen);
if (*sen != (Pixmap)0)
return;
}
if (menu->icon_builtin || gui_find_bitmap(menu->name, buf, "xpm") == FAIL)
{
if (menu->iconidx >= 0 && menu->iconidx
< (int)(sizeof(built_in_pixmaps) / sizeof(built_in_pixmaps[0])))
xpm = built_in_pixmaps[menu->iconidx];
else
xpm = tb_blank_xpm;
}
if (xpm != NULL || buf[0] != NUL)
createXpmImages(buf, xpm, sen);
}
/*
* Read an Xpm file, doing color substitutions for the foreground and
* background colors. If there is an error reading a color xpm file,
* drop back and read the monochrome file. If successful, create the
* insensitive Pixmap too.
*/
static void
createXpmImages(path, xpm, sen)
char_u *path;
char **xpm;
Pixmap *sen;
{
Window rootWindow;
XpmAttributes attrs;
XpmColorSymbol color[5] =
{
{"none", "none", 0},
{"iconColor1", NULL, 0},
{"bottomShadowColor", NULL, 0},
{"topShadowColor", NULL, 0},
{"selectColor", NULL, 0}
};
int screenNum;
int status;
Pixmap mask;
Pixmap map;
gui_mch_get_toolbar_colors(
&color[BACKGROUND].pixel,
&color[FOREGROUND].pixel,
&color[BOTTOM_SHADOW].pixel,
&color[TOP_SHADOW].pixel,
&color[HIGHLIGHT].pixel);
/* Setup the color subsititution table */
attrs.valuemask = XpmColorSymbols;
attrs.colorsymbols = color;
attrs.numsymbols = 5;
screenNum = DefaultScreen(gui.dpy);
rootWindow = RootWindow(gui.dpy, screenNum);
/* Create the "sensitive" pixmap */
if (xpm != NULL)
status = XpmCreatePixmapFromData(gui.dpy, rootWindow, xpm,
&map, &mask, &attrs);
else
status = XpmReadFileToPixmap(gui.dpy, rootWindow, (char *)path,
&map, &mask, &attrs);
if (status == XpmSuccess && map != 0)
{
XGCValues gcvalues;
GC back_gc;
GC mask_gc;
/* Need to create new Pixmaps with the mask applied. */
gcvalues.foreground = color[BACKGROUND].pixel;
back_gc = XCreateGC(gui.dpy, map, GCForeground, &gcvalues);
mask_gc = XCreateGC(gui.dpy, map, GCForeground, &gcvalues);
XSetClipMask(gui.dpy, mask_gc, mask);
/* Create the "sensitive" pixmap. */
*sen = XCreatePixmap(gui.dpy, rootWindow,
attrs.width, attrs.height,
DefaultDepth(gui.dpy, screenNum));
XFillRectangle(gui.dpy, *sen, back_gc, 0, 0,
attrs.width, attrs.height);
XCopyArea(gui.dpy, map, *sen, mask_gc, 0, 0,
attrs.width, attrs.height, 0, 0);
XFreeGC(gui.dpy, back_gc);
XFreeGC(gui.dpy, mask_gc);
XFreePixmap(gui.dpy, map);
}
else
*sen = 0;
XpmFreeAttributes(&attrs);
}
void
gui_mch_set_toolbar_pos(x, y, w, h)
int x;
int y;
int w;
int h;
{
Dimension border;
int height;
if (!XtIsManaged(toolBar)) /* nothing to do */
return;
XtUnmanageChild(toolBar);
XtVaGetValues(toolBar,
XtNborderWidth, &border,
NULL);
height = h - 2 * border;
if (height < 0)
height = 1;
XtVaSetValues(toolBar,
XtNhorizDistance, x,
XtNvertDistance, y,
XtNwidth, w - 2 * border,
XtNheight, height,
NULL);
XtManageChild(toolBar);
}
#endif
void
gui_mch_set_text_area_pos(x, y, w, h)
int x;
int y;
int w;
int h;
{
XtUnmanageChild(textArea);
XtVaSetValues(textArea,
XtNhorizDistance, x,
XtNvertDistance, y,
XtNwidth, w,
XtNheight, h,
NULL);
XtManageChild(textArea);
#ifdef FEAT_TOOLBAR
/* Give keyboard focus to the textArea instead of the toolbar. */
gui_mch_reset_focus();
#endif
}
#ifdef FEAT_TOOLBAR
/*
* A toolbar button has been pushed; now reset the input focus
* such that the user can type page up/down etc. and have the
* input go to the editor window, not the button
*/
static void
gui_mch_reset_focus()
{
XtSetKeyboardFocus(vimForm, textArea);
}
#endif
void
gui_x11_set_back_color()
{
if (textArea != NULL)
XtVaSetValues(textArea,
XtNbackground, gui.back_pixel,
NULL);
}
#if defined(FEAT_MENU) || defined(PROTO)
/*
* Menu stuff.
*/
static char_u *make_pull_name __ARGS((char_u * name));
static Widget get_popup_entry __ARGS((Widget w));
static Widget submenu_widget __ARGS((Widget));
static Boolean has_submenu __ARGS((Widget));
static void gui_mch_submenu_change __ARGS((vimmenu_T *mp, int colors));
static void gui_athena_menu_font __ARGS((Widget id));
static Boolean gui_athena_menu_has_submenus __ARGS((Widget, Widget));
void
gui_mch_enable_menu(flag)
int flag;
{
if (flag)
{
XtManageChild(menuBar);
# ifdef FEAT_TOOLBAR
if (XtIsManaged(toolBar))
{
XtVaSetValues(toolBar,
XtNvertDistance, gui.menu_height,
NULL);
XtVaSetValues(textArea,
XtNvertDistance, gui.menu_height + gui.toolbar_height,
NULL);
}
# endif
}
else
{
XtUnmanageChild(menuBar);
# ifdef FEAT_TOOLBAR
if (XtIsManaged(toolBar))
{
XtVaSetValues(toolBar,
XtNvertDistance, 0,
NULL);
}
# endif
}
}
void
gui_mch_set_menu_pos(x, y, w, h)
int x;
int y;
int w;
int h;
{
Dimension border;
int height;
XtUnmanageChild(menuBar);
XtVaGetValues(menuBar, XtNborderWidth, &border, NULL);
/* avoid trouble when there are no menu items, and h is 1 */
height = h - 2 * border;
if (height < 0)
height = 1;
XtVaSetValues(menuBar,
XtNhorizDistance, x,
XtNvertDistance, y,
XtNwidth, w - 2 * border,
XtNheight, height,
NULL);
XtManageChild(menuBar);
}
/*
* Used to calculate the insertion position of a widget with respect to its
* neighbors.
*
* Valid range of return values is: 0 (beginning of children) to
* numChildren (end of children).
*/
static Cardinal
athena_calculate_ins_pos(widget)
Widget widget;
{
/* Assume that if the parent of the vimmenu_T is NULL, then we can get
* to this menu by traversing "next", starting at "root_menu".
*
* This holds true for popup menus, toolbar, and toplevel menu items.
*/
/* Popup menus: "id" is NULL. Only submenu_id is valid */
/* Menus that are not toplevel: "parent" will be non-NULL, "id" &
* "submenu_id" will be non-NULL.
*/
/* Toplevel menus: "parent" is NULL, id is the widget of the menu item */
WidgetList children;
Cardinal num_children = 0;
int retval;
Arg args[2];
int n = 0;
int i;
XtSetArg(args[n], XtNchildren, &children); n++;
XtSetArg(args[n], XtNnumChildren, &num_children); n++;
XtGetValues(XtParent(widget), args, n);
retval = num_children;
for (i = 0; i < (int)num_children; ++i)
{
Widget current = children[i];
vimmenu_T *menu = NULL;
for (menu = (a_cur_menu->parent == NULL)
? root_menu : a_cur_menu->parent->children;
menu != NULL;
menu = menu->next)
if (current == menu->id
&& a_cur_menu->priority < menu->priority
&& i < retval)
retval = i;
}
return retval;
}
void
gui_mch_add_menu(menu, idx)
vimmenu_T *menu;
int idx UNUSED;
{
char_u *pullright_name;
Dimension height, space, border;
vimmenu_T *parent = menu->parent;
a_cur_menu = menu;
if (parent == NULL)
{
if (menu_is_popup(menu->dname))
{
menu->submenu_id = XtVaCreatePopupShell((char *)menu->dname,
simpleMenuWidgetClass, vimShell,
XtNinsertPosition, athena_calculate_ins_pos,
XtNtranslations, popupTrans,
NULL);
gui_athena_menu_colors(menu->submenu_id);
}
else if (menu_is_menubar(menu->dname))
{
menu->id = XtVaCreateManagedWidget((char *)menu->dname,
menuButtonWidgetClass, menuBar,
XtNmenuName, menu->dname,
#ifdef FONTSET_ALWAYS
XtNinternational, True,
#endif
NULL);
if (menu->id == (Widget)0)
return;
gui_athena_menu_colors(menu->id);
gui_athena_menu_font(menu->id);
menu->submenu_id = XtVaCreatePopupShell((char *)menu->dname,
simpleMenuWidgetClass, menu->id,
XtNinsertPosition, athena_calculate_ins_pos,
XtNtranslations, supermenuTrans,
NULL);
gui_athena_menu_colors(menu->submenu_id);
gui_athena_menu_font(menu->submenu_id);
/* Don't update the menu height when it was set at a fixed value */
if (!gui.menu_height_fixed)
{
/*
* When we add a top-level item to the menu bar, we can figure
* out how high the menu bar should be.
*/
XtVaGetValues(menuBar,
XtNvSpace, &space,
XtNborderWidth, &border,
NULL);
XtVaGetValues(menu->id,
XtNheight, &height,
NULL);
gui.menu_height = height + 2 * (space + border);
}
}
}
else if (parent->submenu_id != (Widget)0)
{
menu->id = XtVaCreateManagedWidget((char *)menu->dname,
smeBSBObjectClass, parent->submenu_id,
XtNlabel, menu->dname,
#ifdef FONTSET_ALWAYS
XtNinternational, True,
#endif
NULL);
if (menu->id == (Widget)0)
return;
if (pullerBitmap == None)
pullerBitmap = gui_athena_create_pullright_pixmap(menu->id);
XtVaSetValues(menu->id, XtNrightBitmap, pullerBitmap,
NULL);
/* If there are other menu items that are not pulldown menus,
* we need to adjust the right margins of those, too.
*/
{
WidgetList children;
Cardinal num_children;
int i;
XtVaGetValues(parent->submenu_id, XtNchildren, &children,
XtNnumChildren, &num_children,
NULL);
for (i = 0; i < (int)num_children; ++i)
{
XtVaSetValues(children[i],
XtNrightMargin, puller_width,
NULL);
}
}
gui_athena_menu_colors(menu->id);
gui_athena_menu_font(menu->id);
pullright_name = make_pull_name(menu->dname);
menu->submenu_id = XtVaCreatePopupShell((char *)pullright_name,
simpleMenuWidgetClass, parent->submenu_id,
XtNtranslations, menuTrans,
NULL);
gui_athena_menu_colors(menu->submenu_id);
gui_athena_menu_font(menu->submenu_id);
vim_free(pullright_name);
XtAddCallback(menu->submenu_id, XtNpopupCallback,
gui_athena_popup_callback, (XtPointer)menu);
if (parent->parent != NULL)
XtOverrideTranslations(parent->submenu_id, parentTrans);
}
a_cur_menu = NULL;
}
/* Used to determine whether a SimpleMenu has pulldown entries.
*
* "id" is the parent of the menu items.
* Ignore widget "ignore" in the pane.
*/
static Boolean
gui_athena_menu_has_submenus(id, ignore)
Widget id;
Widget ignore;
{
WidgetList children;
Cardinal num_children;
int i;
XtVaGetValues(id, XtNchildren, &children,
XtNnumChildren, &num_children,
NULL);
for (i = 0; i < (int)num_children; ++i)
{
if (children[i] == ignore)
continue;
if (has_submenu(children[i]))
return True;
}
return False;
}
static void
gui_athena_menu_font(id)
Widget id;
{
#ifdef FONTSET_ALWAYS
if (gui.menu_fontset != NOFONTSET)
{
if (XtIsManaged(id))
{
XtUnmanageChild(id);
XtVaSetValues(id, XtNfontSet, gui.menu_fontset, NULL);
/* We should force the widget to recalculate it's
* geometry now. */
XtManageChild(id);
}
else
XtVaSetValues(id, XtNfontSet, gui.menu_fontset, NULL);
if (has_submenu(id))
XtVaSetValues(id, XtNrightBitmap, pullerBitmap, NULL);
}
#else
int managed = FALSE;
if (gui.menu_font != NOFONT)
{
if (XtIsManaged(id))
{
XtUnmanageChild(id);
managed = TRUE;
}
# ifdef FEAT_XFONTSET
if (gui.fontset != NOFONTSET)
XtVaSetValues(id, XtNfontSet, gui.menu_font, NULL);
else
# endif
XtVaSetValues(id, XtNfont, gui.menu_font, NULL);
if (has_submenu(id))
XtVaSetValues(id, XtNrightBitmap, pullerBitmap, NULL);
/* Force the widget to recalculate it's geometry now. */
if (managed)
XtManageChild(id);
}
#endif
}
void
gui_mch_new_menu_font()
{
Pixmap oldpuller = None;
if (menuBar == (Widget)0)
return;
if (pullerBitmap != None)
{
oldpuller = pullerBitmap;
pullerBitmap = gui_athena_create_pullright_pixmap(NULL);
}
gui_mch_submenu_change(root_menu, FALSE);
{
/* Iterate through the menubar menu items and get the height of
* each one. The menu bar height is set to the maximum of all
* the heights.
*/
vimmenu_T *mp;
int max_height = 9999;
for (mp = root_menu; mp != NULL; mp = mp->next)
{
if (menu_is_menubar(mp->dname))
{
Dimension height;
XtVaGetValues(mp->id,
XtNheight, &height,
NULL);
if (height < max_height)
max_height = height;
}
}
if (max_height != 9999)
{
/* Don't update the menu height when it was set at a fixed value */
if (!gui.menu_height_fixed)
{
Dimension space, border;
XtVaGetValues(menuBar,
XtNvSpace, &space,
XtNborderWidth, &border,
NULL);
gui.menu_height = max_height + 2 * (space + border);
}
}
}
/* Now, to simulate the window being resized. Only, this
* will resize the window to it's current state.
*
* There has to be a better way, but I do not see one at this time.
* (David Harrison)
*/
{
Position w, h;
XtVaGetValues(vimShell,
XtNwidth, &w,
XtNheight, &h,
NULL);
gui_resize_shell(w, h
#ifdef FEAT_XIM
- xim_get_status_area_height()
#endif
);
}
gui_set_shellsize(FALSE, TRUE, RESIZE_VERT);
ui_new_shellsize();
if (oldpuller != None)
XFreePixmap(gui.dpy, oldpuller);
}
#if defined(FEAT_BEVAL) || defined(PROTO)
void
gui_mch_new_tooltip_font()
{
# ifdef FEAT_TOOLBAR
vimmenu_T *menu;
if (toolBar == (Widget)0)
return;
menu = gui_find_menu((char_u *)"ToolBar");
if (menu != NULL)
gui_mch_submenu_change(menu, FALSE);
# endif
}
void
gui_mch_new_tooltip_colors()
{
# ifdef FEAT_TOOLBAR
vimmenu_T *menu;
if (toolBar == (Widget)0)
return;
menu = gui_find_menu((char_u *)"ToolBar");
if (menu != NULL)
gui_mch_submenu_change(menu, TRUE);
# endif
}
#endif
static void
gui_mch_submenu_change(menu, colors)
vimmenu_T *menu;
int colors; /* TRUE for colors, FALSE for font */
{
vimmenu_T *mp;
for (mp = menu; mp != NULL; mp = mp->next)
{
if (mp->id != (Widget)0)
{
if (colors)
{
gui_athena_menu_colors(mp->id);
#ifdef FEAT_TOOLBAR
/* For a toolbar item: Free the pixmap and allocate a new one,
* so that the background color is right. */
if (mp->image != (Pixmap)0)
{
XFreePixmap(gui.dpy, mp->image);
get_toolbar_pixmap(mp, &mp->image);
if (mp->image != (Pixmap)0)
XtVaSetValues(mp->id, XtNbitmap, mp->image, NULL);
}
# ifdef FEAT_BEVAL
/* If we have a tooltip, then we need to change it's colors */
if (mp->tip != NULL)
{
Arg args[2];
args[0].name = XtNbackground;
args[0].value = gui.tooltip_bg_pixel;
args[1].name = XtNforeground;
args[1].value = gui.tooltip_fg_pixel;
XtSetValues(mp->tip->balloonLabel, &args[0], XtNumber(args));
}
# endif
#endif
}
else
{
gui_athena_menu_font(mp->id);
#ifdef FEAT_BEVAL
/* If we have a tooltip, then we need to change it's font */
/* Assume XtNinternational == True (in createBalloonEvalWindow)
*/
if (mp->tip != NULL)
{
Arg args[1];
args[0].name = XtNfontSet;
args[0].value = (XtArgVal)gui.tooltip_fontset;
XtSetValues(mp->tip->balloonLabel, &args[0], XtNumber(args));
}
#endif
}
}
if (mp->children != NULL)
{
/* Set the colors/font for the tear off widget */
if (mp->submenu_id != (Widget)0)
{
if (colors)
gui_athena_menu_colors(mp->submenu_id);
else
gui_athena_menu_font(mp->submenu_id);
}
/* Set the colors for the children */
gui_mch_submenu_change(mp->children, colors);
}
}
}
/*
* Make a submenu name into a pullright name.
* Replace '.' by '_', can't include '.' in the submenu name.
*/
static char_u *
make_pull_name(name)
char_u * name;
{
char_u *pname;
char_u *p;
pname = vim_strnsave(name, STRLEN(name) + strlen("-pullright"));
if (pname != NULL)
{
strcat((char *)pname, "-pullright");
while ((p = vim_strchr(pname, '.')) != NULL)
*p = '_';
}
return pname;
}
void
gui_mch_add_menu_item(menu, idx)
vimmenu_T *menu;
int idx UNUSED;
{
vimmenu_T *parent = menu->parent;
a_cur_menu = menu;
# ifdef FEAT_TOOLBAR
if (menu_is_toolbar(parent->name))
{
WidgetClass type;
int n;
Arg args[21];
n = 0;
if (menu_is_separator(menu->name))
{
XtSetArg(args[n], XtNlabel, ""); n++;
XtSetArg(args[n], XtNborderWidth, 0); n++;
}
else
{
get_toolbar_pixmap(menu, &menu->image);
XtSetArg(args[n], XtNlabel, menu->dname); n++;
XtSetArg(args[n], XtNinternalHeight, 1); n++;
XtSetArg(args[n], XtNinternalWidth, 1); n++;
XtSetArg(args[n], XtNborderWidth, 1); n++;
if (menu->image != 0)
XtSetArg(args[n], XtNbitmap, menu->image); n++;
}
XtSetArg(args[n], XtNhighlightThickness, 0); n++;
type = commandWidgetClass;
/* TODO: figure out the position in the toolbar?
* This currently works fine for the default toolbar, but
* what if we add/remove items during later runtime?
*/
/* NOTE: "idx" isn't used here. The position is calculated by
* athena_calculate_ins_pos(). The position it calculates
* should be equal to "idx".
*/
/* TODO: Could we just store "idx" and use that as the child
* placement?
*/
if (menu->id == NULL)
{
menu->id = XtCreateManagedWidget((char *)menu->dname,
type, toolBar, args, n);
XtAddCallback(menu->id,
XtNcallback, gui_x11_menu_cb, menu);
}
else
XtSetValues(menu->id, args, n);
gui_athena_menu_colors(menu->id);
#ifdef FEAT_BEVAL
gui_mch_menu_set_tip(menu);
#endif
menu->parent = parent;
menu->submenu_id = NULL;
if (!XtIsManaged(toolBar)
&& vim_strchr(p_go, GO_TOOLBAR) != NULL)
gui_mch_show_toolbar(TRUE);
gui.toolbar_height = gui_mch_compute_toolbar_height();
return;
} /* toolbar menu item */
# endif
/* Add menu separator */
if (menu_is_separator(menu->name))
{
menu->submenu_id = (Widget)0;
menu->id = XtVaCreateManagedWidget((char *)menu->dname,
smeLineObjectClass, parent->submenu_id,
NULL);
if (menu->id == (Widget)0)
return;
gui_athena_menu_colors(menu->id);
}
else
{
if (parent != NULL && parent->submenu_id != (Widget)0)
{
menu->submenu_id = (Widget)0;
menu->id = XtVaCreateManagedWidget((char *)menu->dname,
smeBSBObjectClass, parent->submenu_id,
XtNlabel, menu->dname,
#ifdef FONTSET_ALWAYS
XtNinternational, True,
#endif
NULL);
if (menu->id == (Widget)0)
return;
/* If there are other "pulldown" items in this pane, then adjust
* the right margin to accommodate the arrow pixmap, otherwise
* the right margin will be the same as the left margin.
*/
{
Dimension left_margin;
XtVaGetValues(menu->id, XtNleftMargin, &left_margin, NULL);
XtVaSetValues(menu->id, XtNrightMargin,
gui_athena_menu_has_submenus(parent->submenu_id, NULL) ?
puller_width :
left_margin,
NULL);
}
gui_athena_menu_colors(menu->id);
gui_athena_menu_font(menu->id);
XtAddCallback(menu->id, XtNcallback, gui_x11_menu_cb,
(XtPointer)menu);
}
}
a_cur_menu = NULL;
}
#if defined(FEAT_TOOLBAR) || defined(PROTO)
void
gui_mch_show_toolbar(int showit)
{
Cardinal numChildren; /* how many children toolBar has */
if (toolBar == (Widget)0)
return;
XtVaGetValues(toolBar, XtNnumChildren, &numChildren, NULL);
if (showit && numChildren > 0)
{
/* Assume that we want to show the toolbar if p_toolbar contains valid
* option settings, therefore p_toolbar must not be NULL.
*/
WidgetList children;
XtVaGetValues(toolBar, XtNchildren, &children, NULL);
{
void (*action)(BalloonEval *);
int text = 0;
if (strstr((const char *)p_toolbar, "tooltips"))
action = &gui_mch_enable_beval_area;
else
action = &gui_mch_disable_beval_area;
if (strstr((const char *)p_toolbar, "text"))
text = 1;
else if (strstr((const char *)p_toolbar, "icons"))
text = -1;
if (text != 0)
{
vimmenu_T *toolbar;
vimmenu_T *cur;
for (toolbar = root_menu; toolbar; toolbar = toolbar->next)
if (menu_is_toolbar(toolbar->dname))
break;
/* Assumption: toolbar is NULL if there is no toolbar,
* otherwise it contains the toolbar menu structure.
*
* Assumption: "numChildren" == the number of items in the list
* of items beginning with toolbar->children.
*/
if (toolbar)
{
for (cur = toolbar->children; cur; cur = cur->next)
{
Arg args[2];
int n = 0;
/* Enable/Disable tooltip (OK to enable while currently
* enabled)
*/
if (cur->tip != NULL)
(*action)(cur->tip);
if (text == 1)
{
XtSetArg(args[n], XtNbitmap, None);
n++;
XtSetArg(args[n], XtNlabel,
menu_is_separator(cur->name) ? "" :
(char *)cur->dname);
n++;
}
else
{
XtSetArg(args[n], XtNbitmap, cur->image);
n++;
XtSetArg(args[n], XtNlabel, (cur->image == None) ?
menu_is_separator(cur->name) ?
"" :
(char *)cur->dname
:
(char *)None);
n++;
}
if (cur->id != NULL)
{
XtUnmanageChild(cur->id);
XtSetValues(cur->id, args, n);
XtManageChild(cur->id);
}
}
}
}
}
gui.toolbar_height = gui_mch_compute_toolbar_height();
XtManageChild(toolBar);
if (XtIsManaged(menuBar))
{
XtVaSetValues(textArea,
XtNvertDistance, gui.toolbar_height + gui.menu_height,
NULL);
XtVaSetValues(toolBar,
XtNvertDistance, gui.menu_height,
NULL);
}
else
{
XtVaSetValues(textArea,
XtNvertDistance, gui.toolbar_height,
NULL);
XtVaSetValues(toolBar,
XtNvertDistance, 0,
NULL);
}
}
else
{
gui.toolbar_height = 0;
if (XtIsManaged(menuBar))
XtVaSetValues(textArea,
XtNvertDistance, gui.menu_height,
NULL);
else
XtVaSetValues(textArea,
XtNvertDistance, 0,
NULL);
XtUnmanageChild(toolBar);
}
gui_set_shellsize(FALSE, FALSE, RESIZE_VERT);
}
int
gui_mch_compute_toolbar_height()
{
Dimension height; /* total Toolbar height */
Dimension whgt; /* height of each widget */
Dimension marginHeight; /* XmNmarginHeight of toolBar */
Dimension shadowThickness; /* thickness of Xtparent(toolBar) */
WidgetList children; /* list of toolBar's children */
Cardinal numChildren; /* how many children toolBar has */
int i;
height = 0;
shadowThickness = 0;
marginHeight = 0;
if (toolBar != (Widget)0)
{
XtVaGetValues(toolBar,
XtNborderWidth, &shadowThickness,
XtNvSpace, &marginHeight,
XtNchildren, &children,
XtNnumChildren, &numChildren,
NULL);
for (i = 0; i < (int)numChildren; i++)
{
whgt = 0;
XtVaGetValues(children[i], XtNheight, &whgt, NULL);
if (height < whgt)
height = whgt;
}
}
return (int)(height + (marginHeight << 1) + (shadowThickness << 1));
}
void
gui_mch_get_toolbar_colors(bgp, fgp, bsp, tsp, hsp)
Pixel *bgp;
Pixel *fgp;
Pixel *bsp;
Pixel *tsp;
Pixel *hsp;
{
XtVaGetValues(toolBar, XtNbackground, bgp, XtNborderColor, fgp, NULL);
*bsp = *bgp;
*tsp = *fgp;
*hsp = *tsp;
}
#endif
void
gui_mch_toggle_tearoffs(enable)
int enable UNUSED;
{
/* no tearoff menus */
}
void
gui_mch_new_menu_colors()
{
if (menuBar == (Widget)0)
return;
if (gui.menu_fg_pixel != INVALCOLOR)
XtVaSetValues(menuBar, XtNborderColor, gui.menu_fg_pixel, NULL);
gui_athena_menu_colors(menuBar);
#ifdef FEAT_TOOLBAR
gui_athena_menu_colors(toolBar);
#endif
gui_mch_submenu_change(root_menu, TRUE);
}
/*
* Destroy the machine specific menu widget.
*/
void
gui_mch_destroy_menu(menu)
vimmenu_T *menu;
{
Widget parent;
/* There is no item for the toolbar. */
if (menu->id == (Widget)0)
return;
parent = XtParent(menu->id);
/* When removing the last "pulldown" menu item from a pane, adjust the
* right margins of the remaining widgets.
*/
if (menu->submenu_id != (Widget)0)
{
/* Go through the menu items in the parent of this item and
* adjust their margins, if necessary.
* This takes care of the case when we delete the last menu item in a
* pane that has a submenu. In this case, there will be no arrow
* pixmaps shown anymore.
*/
{
WidgetList children;
Cardinal num_children;
int i;
Dimension right_margin = 0;
Boolean get_left_margin = False;
XtVaGetValues(parent, XtNchildren, &children,
XtNnumChildren, &num_children,
NULL);
if (gui_athena_menu_has_submenus(parent, menu->id))
right_margin = puller_width;
else
get_left_margin = True;
for (i = 0; i < (int)num_children; ++i)
{
if (children[i] == menu->id)
continue;
if (get_left_margin == True)
{
Dimension left_margin;
XtVaGetValues(children[i], XtNleftMargin, &left_margin,
NULL);
XtVaSetValues(children[i], XtNrightMargin, left_margin,
NULL);
}
else
XtVaSetValues(children[i], XtNrightMargin, right_margin,
NULL);
}
}
}
/* Please be sure to destroy the parent widget first (i.e. menu->id).
*
* This code should be basically identical to that in the file gui_motif.c
* because they are both Xt based.
*/
if (menu->id != (Widget)0)
{
Cardinal num_children;
Dimension height, space, border;
XtVaGetValues(menuBar,
XtNvSpace, &space,
XtNborderWidth, &border,
NULL);
XtVaGetValues(menu->id,
XtNheight, &height,
NULL);
#if defined(FEAT_TOOLBAR) && defined(FEAT_BEVAL)
if (parent == toolBar && menu->tip != NULL)
{
/* We try to destroy this before the actual menu, because there are
* callbacks, etc. that will be unregistered during the tooltip
* destruction.
*
* If you call "gui_mch_destroy_beval_area()" after destroying
* menu->id, then the tooltip's window will have already been
* deallocated by Xt, and unknown behaviour will ensue (probably
* a core dump).
*/
gui_mch_destroy_beval_area(menu->tip);
menu->tip = NULL;
}
#endif
/*
* This is a hack to stop the Athena simpleMenuWidget from getting a
* BadValue error when a menu's last child is destroyed. We check to
* see if this is the last child and if so, don't delete it. The parent
* will be deleted soon anyway, and it will delete it's children like
* all good widgets do.
*/
/* NOTE: The cause of the BadValue X Protocol Error is because when the
* last child is destroyed, it is first unmanaged, thus causing a
* geometry resize request from the parent Shell widget.
* Since the Shell widget has no more children, it is resized to have
* width/height of 0. XConfigureWindow() is then called with the
* width/height of 0, which generates the BadValue.
*
* This happens in phase two of the widget destruction process.
*/
{
if (parent != menuBar
#ifdef FEAT_TOOLBAR
&& parent != toolBar
#endif
)
{
XtVaGetValues(parent, XtNnumChildren, &num_children, NULL);
if (num_children > 1)
XtDestroyWidget(menu->id);
}
else
XtDestroyWidget(menu->id);
menu->id = (Widget)0;
}
if (parent == menuBar)
{
if (!gui.menu_height_fixed)
gui.menu_height = height + 2 * (space + border);
}
#ifdef FEAT_TOOLBAR
else if (parent == toolBar)
{
/* When removing last toolbar item, don't display the toolbar. */
XtVaGetValues(toolBar, XtNnumChildren, &num_children, NULL);
if (num_children == 0)
gui_mch_show_toolbar(FALSE);
else
gui.toolbar_height = gui_mch_compute_toolbar_height();
}
#endif
}
if (menu->submenu_id != (Widget)0)
{
XtDestroyWidget(menu->submenu_id);
menu->submenu_id = (Widget)0;
}
}
static void
gui_athena_menu_timeout(client_data, id)
XtPointer client_data;
XtIntervalId *id UNUSED;
{
Widget w = (Widget)client_data;
Widget popup;
timer = 0;
if (XtIsSubclass(w,smeBSBObjectClass))
{
Pixmap p;
XtVaGetValues(w, XtNrightBitmap, &p, NULL);
if ((p != None) && (p != XtUnspecifiedPixmap))
{
/* We are dealing with an item that has a submenu */
popup = get_popup_entry(XtParent(w));
if (popup == (Widget)0)
return;
XtPopup(popup, XtGrabNonexclusive);
}
}
}
/* This routine is used to calculate the position (in screen coordinates)
* where a submenu should appear relative to the menu entry that popped it
* up. It should appear even with and just slightly to the left of the
* rightmost end of the menu entry that caused the popup.
*
* This is called when XtPopup() is called.
*/
static void
gui_athena_popup_callback(w, client_data, call_data)
Widget w;
XtPointer client_data;
XtPointer call_data UNUSED;
{
/* Assumption: XtIsSubclass(XtParent(w),simpleMenuWidgetClass) */
vimmenu_T *menu = (vimmenu_T *)client_data;
Dimension width;
Position root_x, root_y;
/* First, popdown any siblings that may have menus popped up */
{
vimmenu_T *i;
for (i = menu->parent->children; i != NULL; i = i->next)
{
if (i->submenu_id != NULL && XtIsManaged(i->submenu_id))
XtPopdown(i->submenu_id);
}
}
XtVaGetValues(XtParent(w),
XtNwidth, &width,
NULL);
/* Assumption: XawSimpleMenuGetActiveEntry(XtParent(w)) == menu->id */
/* i.e. This IS the active entry */
XtTranslateCoords(menu->id,width - 5, 0, &root_x, &root_y);
XtVaSetValues(w, XtNx, root_x,
XtNy, root_y,
NULL);
}
static void
gui_athena_popdown_submenus_action(w, event, args, nargs)
Widget w;
XEvent *event;
String *args;
Cardinal *nargs;
{
WidgetList children;
Cardinal num_children;
XtVaGetValues(w, XtNchildren, &children,
XtNnumChildren, &num_children,
NULL);
for (; num_children > 0; --num_children)
{
Widget child = children[num_children - 1];
if (has_submenu(child))
{
Widget temp_w;
temp_w = submenu_widget(child);
gui_athena_popdown_submenus_action(temp_w,event,args,nargs);
XtPopdown(temp_w);
}
}
}
/* Used to determine if the given widget has a submenu that can be popped up. */
static Boolean
has_submenu(widget)
Widget widget;
{
if ((widget != NULL) && XtIsSubclass(widget,smeBSBObjectClass))
{
Pixmap p;
XtVaGetValues(widget, XtNrightBitmap, &p, NULL);
if ((p != None) && (p != XtUnspecifiedPixmap))
return True;
}
return False;
}
static void
gui_athena_delayed_arm_action(w, event, args, nargs)
Widget w;
XEvent *event;
String *args;
Cardinal *nargs;
{
Dimension width, height;
if (event->type != MotionNotify)
return;
XtVaGetValues(w,
XtNwidth, &width,
XtNheight, &height,
NULL);
if (event->xmotion.x >= (int)width || event->xmotion.y >= (int)height)
return;
{
static Widget previous_active_widget = NULL;
Widget current;
current = XawSimpleMenuGetActiveEntry(w);
if (current != previous_active_widget)
{
if (timer)
{
/* If the timeout hasn't been triggered, remove it */
XtRemoveTimeOut(timer);
}
gui_athena_popdown_submenus_action(w,event,args,nargs);
if (has_submenu(current))
{
XtAppAddTimeOut(XtWidgetToApplicationContext(w), 600L,
gui_athena_menu_timeout,
(XtPointer)current);
}
previous_active_widget = current;
}
}
}
static Widget
get_popup_entry(w)
Widget w;
{
Widget menuw;
/* Get the active entry for the current menu */
if ((menuw = XawSimpleMenuGetActiveEntry(w)) == (Widget)0)
return NULL;
return submenu_widget(menuw);
}
/* Given the widget that has been determined to have a submenu, return the submenu widget
* that is to be popped up.
*/
static Widget
submenu_widget(widget)
Widget widget;
{
/* Precondition: has_submenu(widget) == True
* XtIsSubclass(XtParent(widget),simpleMenuWidgetClass) == True
*/
char_u *pullright_name;
Widget popup;
pullright_name = make_pull_name((char_u *)XtName(widget));
popup = XtNameToWidget(XtParent(widget), (char *)pullright_name);
vim_free(pullright_name);
return popup;
/* Postcondition: (popup != NULL) implies
* (XtIsSubclass(popup,simpleMenuWidgetClass) == True) */
}
void
gui_mch_show_popupmenu(menu)
vimmenu_T *menu;
{
int rootx, rooty, winx, winy;
Window root, child;
unsigned int mask;
if (menu->submenu_id == (Widget)0)
return;
/* Position the popup menu at the pointer */
if (XQueryPointer(gui.dpy, XtWindow(vimShell), &root, &child,
&rootx, &rooty, &winx, &winy, &mask))
{
rootx -= 30;
if (rootx < 0)
rootx = 0;
rooty -= 5;
if (rooty < 0)
rooty = 0;
XtVaSetValues(menu->submenu_id,
XtNx, rootx,
XtNy, rooty,
NULL);
}
XtOverrideTranslations(menu->submenu_id, popupTrans);
XtPopupSpringLoaded(menu->submenu_id);
}
#endif /* FEAT_MENU */
/*
* Set the menu and scrollbar colors to their default values.
*/
void
gui_mch_def_colors()
{
/*
* Get the colors ourselves. Using the automatic conversion doesn't
* handle looking for approximate colors.
*/
if (gui.in_use)
{
gui.menu_fg_pixel = gui_get_color((char_u *)gui.rsrc_menu_fg_name);
gui.menu_bg_pixel = gui_get_color((char_u *)gui.rsrc_menu_bg_name);
gui.scroll_fg_pixel = gui_get_color((char_u *)gui.rsrc_scroll_fg_name);
gui.scroll_bg_pixel = gui_get_color((char_u *)gui.rsrc_scroll_bg_name);
#ifdef FEAT_BEVAL
gui.tooltip_fg_pixel = gui_get_color((char_u *)gui.rsrc_tooltip_fg_name);
gui.tooltip_bg_pixel = gui_get_color((char_u *)gui.rsrc_tooltip_bg_name);
#endif
}
}
/*
* Scrollbar stuff.
*/
void
gui_mch_set_scrollbar_thumb(sb, val, size, max)
scrollbar_T *sb;
long val;
long size;
long max;
{
double v, s;
if (sb->id == (Widget)0)
return;
/*
* Athena scrollbar must go from 0.0 to 1.0.
*/
if (max == 0)
{
/* So you can't scroll it at all (normally it scrolls past end) */
#ifdef FEAT_GUI_NEXTAW
XawScrollbarSetThumb(sb->id, 0.0, 1.0);
#else
vim_XawScrollbarSetThumb(sb->id, 0.0, 1.0, 0.0);
#endif
}
else
{
v = (double)val / (double)(max + 1);
s = (double)size / (double)(max + 1);
#ifdef FEAT_GUI_NEXTAW
XawScrollbarSetThumb(sb->id, v, s);
#else
vim_XawScrollbarSetThumb(sb->id, v, s, 1.0);
#endif
}
}
void
gui_mch_set_scrollbar_pos(sb, x, y, w, h)
scrollbar_T *sb;
int x;
int y;
int w;
int h;
{
if (sb->id == (Widget)0)
return;
XtUnmanageChild(sb->id);
XtVaSetValues(sb->id,
XtNhorizDistance, x,
XtNvertDistance, y,
XtNwidth, w,
XtNheight, h,
NULL);
XtManageChild(sb->id);
}
void
gui_mch_enable_scrollbar(sb, flag)
scrollbar_T *sb;
int flag;
{
if (sb->id != (Widget)0)
{
if (flag)
XtManageChild(sb->id);
else
XtUnmanageChild(sb->id);
}
}
void
gui_mch_create_scrollbar(sb, orient)
scrollbar_T *sb;
int orient; /* SBAR_VERT or SBAR_HORIZ */
{
sb->id = XtVaCreateWidget("scrollBar",
#ifdef FEAT_GUI_NEXTAW
scrollbarWidgetClass, vimForm,
#else
vim_scrollbarWidgetClass, vimForm,
#endif
XtNresizable, True,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainLeft,
XtNborderWidth, 0,
XtNorientation, (orient == SBAR_VERT) ? XtorientVertical
: XtorientHorizontal,
XtNforeground, gui.scroll_fg_pixel,
XtNbackground, gui.scroll_bg_pixel,
NULL);
if (sb->id == (Widget)0)
return;
XtAddCallback(sb->id, XtNjumpProc,
gui_athena_scroll_cb_jump, (XtPointer)sb->ident);
XtAddCallback(sb->id, XtNscrollProc,
gui_athena_scroll_cb_scroll, (XtPointer)sb->ident);
#ifdef FEAT_GUI_NEXTAW
XawScrollbarSetThumb(sb->id, 0.0, 1.0);
#else
vim_XawScrollbarSetThumb(sb->id, 0.0, 1.0, 0.0);
#endif
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
void
gui_mch_destroy_scrollbar(sb)
scrollbar_T *sb;
{
if (sb->id != (Widget)0)
XtDestroyWidget(sb->id);
}
#endif
void
gui_mch_set_scrollbar_colors(sb)
scrollbar_T *sb;
{
if (sb->id != (Widget)0)
XtVaSetValues(sb->id,
XtNforeground, gui.scroll_fg_pixel,
XtNbackground, gui.scroll_bg_pixel,
NULL);
/* This is needed for the rectangle below the vertical scrollbars. */
if (sb == &gui.bottom_sbar && vimForm != (Widget)0)
gui_athena_scroll_colors(vimForm);
}
/*
* Miscellaneous stuff:
*/
Window
gui_x11_get_wid()
{
return XtWindow(textArea);
}
#if defined(FEAT_BROWSE) || defined(PROTO)
/*
* Put up a file requester.
* Returns the selected name in allocated memory, or NULL for Cancel.
*/
char_u *
gui_mch_browse(saving, title, dflt, ext, initdir, filter)
int saving UNUSED; /* select file to write */
char_u *title; /* title for the window */
char_u *dflt; /* default name */
char_u *ext UNUSED; /* extension added */
char_u *initdir; /* initial directory, NULL for current dir */
char_u *filter UNUSED; /* file name filter */
{
Position x, y;
char_u dirbuf[MAXPATHL];
/* Concatenate "initdir" and "dflt". */
if (initdir == NULL || *initdir == NUL)
mch_dirname(dirbuf, MAXPATHL);
else if (STRLEN(initdir) + 2 < MAXPATHL)
STRCPY(dirbuf, initdir);
else
dirbuf[0] = NUL;
if (dflt != NULL && *dflt != NUL
&& STRLEN(dirbuf) + 2 + STRLEN(dflt) < MAXPATHL)
{
add_pathsep(dirbuf);
STRCAT(dirbuf, dflt);
}
/* Position the file selector just below the menubar */
XtTranslateCoords(vimShell, (Position)0, (Position)
#ifdef FEAT_MENU
gui.menu_height
#else
0
#endif
, &x, &y);
return (char_u *)vim_SelFile(vimShell, (char *)title, (char *)dirbuf,
NULL, (int)x, (int)y, gui.menu_fg_pixel, gui.menu_bg_pixel,
gui.scroll_fg_pixel, gui.scroll_bg_pixel);
}
#endif
#if defined(FEAT_GUI_DIALOG) || defined(PROTO)
static int dialogStatus;
static Atom dialogatom;
static void keyhit_callback __ARGS((Widget w, XtPointer client_data, XEvent *event, Boolean *cont));
static void butproc __ARGS((Widget w, XtPointer client_data, XtPointer call_data));
static void dialog_wm_handler __ARGS((Widget w, XtPointer client_data, XEvent *event, Boolean *dum));
/*
* Callback function for the textfield. When CR is hit this works like
* hitting the "OK" button, ESC like "Cancel".
*/
static void
keyhit_callback(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)
{
if (*buf == CAR)
dialogStatus = 1;
else if (*buf == ESC)
dialogStatus = 0;
}
}
static void
butproc(w, client_data, call_data)
Widget w UNUSED;
XtPointer client_data;
XtPointer call_data UNUSED;
{
dialogStatus = (int)(long)client_data + 1;
}
/*
* Function called when dialog window closed.
*/
static void
dialog_wm_handler(w, client_data, event, dum)
Widget w UNUSED;
XtPointer client_data UNUSED;
XEvent *event;
Boolean *dum UNUSED;
{
if (event->type == ClientMessage
&& (Atom)((XClientMessageEvent *)event)->data.l[0] == dialogatom)
dialogStatus = 0;
}
int
gui_mch_dialog(type, title, message, buttons, dfltbutton, textfield, ex_cmd)
int type UNUSED;
char_u *title;
char_u *message;
char_u *buttons;
int dfltbutton UNUSED;
char_u *textfield;
int ex_cmd UNUSED;
{
char_u *buts;
char_u *p, *next;
XtAppContext app;
XEvent event;
Position wd, hd;
Position wv, hv;
Position x, y;
Widget dialog;
Widget dialogshell;
Widget dialogmessage;
Widget dialogtextfield = 0;
Widget dialogButton;
Widget prev_dialogButton = NULL;
int butcount;
int vertical;
if (title == NULL)
title = (char_u *)_("Vim dialog");
dialogStatus = -1;
/* if our pointer is currently hidden, then we should show it. */
gui_mch_mousehide(FALSE);
/* Check 'v' flag in 'guioptions': vertical button placement. */
vertical = (vim_strchr(p_go, GO_VERTICAL) != NULL);
/* The shell is created each time, to make sure it is resized properly */
dialogshell = XtVaCreatePopupShell("dialogShell",
transientShellWidgetClass, vimShell,
XtNtitle, title,
NULL);
if (dialogshell == (Widget)0)
goto error;
dialog = XtVaCreateManagedWidget("dialog",
formWidgetClass, dialogshell,
XtNdefaultDistance, 20,
NULL);
if (dialog == (Widget)0)
goto error;
gui_athena_menu_colors(dialog);
dialogmessage = XtVaCreateManagedWidget("dialogMessage",
labelWidgetClass, dialog,
XtNlabel, message,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainLeft,
XtNresizable, True,
XtNborderWidth, 0,
NULL);
gui_athena_menu_colors(dialogmessage);
if (textfield != NULL)
{
dialogtextfield = XtVaCreateManagedWidget("textfield",
asciiTextWidgetClass, dialog,
XtNwidth, 400,
XtNtop, XtChainTop,
XtNbottom, XtChainTop,
XtNleft, XtChainLeft,
XtNright, XtChainRight,
XtNfromVert, dialogmessage,
XtNresizable, True,
XtNstring, textfield,
XtNlength, IOSIZE,
XtNuseStringInPlace, True,
XtNeditType, XawtextEdit,
XtNwrap, XawtextWrapNever,
XtNresize, XawtextResizeHeight,
NULL);
XtManageChild(dialogtextfield);
XtAddEventHandler(dialogtextfield, KeyPressMask, False,
(XtEventHandler)keyhit_callback, (XtPointer)NULL);
XawTextSetInsertionPoint(dialogtextfield,
(XawTextPosition)STRLEN(textfield));
XtSetKeyboardFocus(dialog, dialogtextfield);
}
/* make a copy, so that we can insert NULs */
buts = vim_strsave(buttons);
if (buts == NULL)
return -1;
p = buts;
for (butcount = 0; *p; ++butcount)
{
for (next = p; *next; ++next)
{
if (*next == DLG_HOTKEY_CHAR)
STRMOVE(next, next + 1);
if (*next == DLG_BUTTON_SEP)
{
*next++ = NUL;
break;
}
}
dialogButton = XtVaCreateManagedWidget("button",
commandWidgetClass, dialog,
XtNlabel, p,
XtNtop, XtChainBottom,
XtNbottom, XtChainBottom,
XtNleft, XtChainLeft,
XtNright, XtChainLeft,
XtNfromVert, textfield == NULL ? dialogmessage : dialogtextfield,
XtNvertDistance, vertical ? 4 : 20,
XtNresizable, False,
NULL);
gui_athena_menu_colors(dialogButton);
if (butcount > 0)
XtVaSetValues(dialogButton,
vertical ? XtNfromVert : XtNfromHoriz, prev_dialogButton,
NULL);
XtAddCallback(dialogButton, XtNcallback, butproc, (XtPointer)(long_u)butcount);
p = next;
prev_dialogButton = dialogButton;
}
vim_free(buts);
XtRealizeWidget(dialogshell);
/* Setup for catching the close-window event, don't let it close Vim! */
dialogatom = XInternAtom(gui.dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(gui.dpy, XtWindow(dialogshell), &dialogatom, 1);
XtAddEventHandler(dialogshell, NoEventMask, True, dialog_wm_handler, NULL);
XtVaGetValues(dialogshell,
XtNwidth, &wd,
XtNheight, &hd,
NULL);
XtVaGetValues(vimShell,
XtNwidth, &wv,
XtNheight, &hv,
NULL);
XtTranslateCoords(vimShell,
(Position)((wv - wd) / 2),
(Position)((hv - hd) / 2),
&x, &y);
if (x < 0)
x = 0;
if (y < 0)
y = 0;
XtVaSetValues(dialogshell, XtNx, x, XtNy, y, NULL);
/* Position the mouse pointer in the dialog, required for when focus
* follows mouse. */
XWarpPointer(gui.dpy, (Window)0, XtWindow(dialogshell), 0, 0, 0, 0, 20, 40);
app = XtWidgetToApplicationContext(dialogshell);
XtPopup(dialogshell, XtGrabNonexclusive);
for (;;)
{
XtAppNextEvent(app, &event);
XtDispatchEvent(&event);
if (dialogStatus >= 0)
break;
}
XtPopdown(dialogshell);
if (textfield != NULL && dialogStatus < 0)
*textfield = NUL;
error:
XtDestroyWidget(dialogshell);
return dialogStatus;
}
#endif
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_MENU)
/*
* Set the colors of Widget "id" to the menu colors.
*/
static void
gui_athena_menu_colors(id)
Widget id;
{
if (gui.menu_bg_pixel != INVALCOLOR)
XtVaSetValues(id, XtNbackground, gui.menu_bg_pixel, NULL);
if (gui.menu_fg_pixel != INVALCOLOR)
XtVaSetValues(id, XtNforeground, gui.menu_fg_pixel, NULL);
}
#endif
/*
* Set the colors of Widget "id" to the scroll colors.
*/
static void
gui_athena_scroll_colors(id)
Widget id;
{
if (gui.scroll_bg_pixel != INVALCOLOR)
XtVaSetValues(id, XtNbackground, gui.scroll_bg_pixel, NULL);
if (gui.scroll_fg_pixel != INVALCOLOR)
XtVaSetValues(id, XtNforeground, gui.scroll_fg_pixel, NULL);
}
| zyz2011-vim | src/gui_athena.c | C | gpl2 | 57,458 |
/* vi:set ts=8 sts=4 sw=4:
*
* NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
*
* This is NOT the original regular expression code as written by Henry
* Spencer. This code has been modified specifically for use with Vim, and
* should not be used apart from compiling Vim. If you want a good regular
* expression library, get the original code.
*
* NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
*/
#ifndef _REGEXP_H
#define _REGEXP_H
/*
* The number of sub-matches is limited to 10.
* The first one (index 0) is the whole match, referenced with "\0".
* The second one (index 1) is the first sub-match, referenced with "\1".
* This goes up to the tenth (index 9), referenced with "\9".
*/
#define NSUBEXP 10
/*
* Structure returned by vim_regcomp() to pass on to vim_regexec().
* These fields are only to be used in regexp.c!
* See regep.c for an explanation.
*/
typedef struct
{
int regstart;
char_u reganch;
char_u *regmust;
int regmlen;
unsigned regflags;
char_u reghasz;
char_u program[1]; /* actually longer.. */
} regprog_T;
/*
* Structure to be used for single-line matching.
* Sub-match "no" starts at "startp[no]" and ends just before "endp[no]".
* When there is no match, the pointer is NULL.
*/
typedef struct
{
regprog_T *regprog;
char_u *startp[NSUBEXP];
char_u *endp[NSUBEXP];
int rm_ic;
} regmatch_T;
/*
* Structure to be used for multi-line matching.
* Sub-match "no" starts in line "startpos[no].lnum" column "startpos[no].col"
* and ends in line "endpos[no].lnum" just before column "endpos[no].col".
* The line numbers are relative to the first line, thus startpos[0].lnum is
* always 0.
* When there is no match, the line number is -1.
*/
typedef struct
{
regprog_T *regprog;
lpos_T startpos[NSUBEXP];
lpos_T endpos[NSUBEXP];
int rmm_ic;
colnr_T rmm_maxcol; /* when not zero: maximum column */
} regmmatch_T;
/*
* Structure used to store external references: "\z\(\)" to "\z\1".
* Use a reference count to avoid the need to copy this around. When it goes
* from 1 to zero the matches need to be freed.
*/
typedef struct
{
short refcnt;
char_u *matches[NSUBEXP];
} reg_extmatch_T;
#endif /* _REGEXP_H */
| zyz2011-vim | src/regexp.h | C | gpl2 | 2,308 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unixio.h>
#include "vim.h"
int main(int argc, char *argv[])
{
FILE *fpi, *fpo;
char cmd[132], buf[BUFSIZ], *argp, *error_file, target[132], *mms;
int err = 0, err_line = 0;
mms = "mms";
argc--;
argv++;
while (argc-- > 0)
{
argp = *argv++;
if (*argp == '-')
{
switch (*++argp)
{
case 'm':
mms = ++argp;
break;
case 'e':
if (!*(error_file = ++argp))
{
error_file = *argv++;
argc--;
}
break;
default:
break;
}
}
else
{
if (*target)
strcat(target, " ");
strcat(target, argp);
}
}
vim_snprintf(cmd, sizeof(cmd), "%s/output=tmp:errors.vim_tmp %s",
mms, target);
system(cmd);
fpi = fopen("tmp:errors.vim_tmp", "r");
fpo = fopen(error_file, "w");
while (fgets(buf, BUFSIZ, fpi))
{
if (!memcmp(buf, "%CC-", 4))
{
err_line++;
buf[strlen(buf)-1] = '\0';
err++;
}
else
{
if (err_line)
{
if (strstr(buf, _("At line")))
{
err_line = 0;
fprintf(fpo, "@");
}
else
buf[strlen(buf)-1] = '\0';
}
}
fprintf(fpo, "%s", buf);
}
fclose(fpi);
fclose(fpo);
while (!delete("tmp:errors.vim_tmp"))
/*nop*/;
exit(err ? 44 : 1);
return(0);
}
| zyz2011-vim | src/os_vms_mms.c | C | gpl2 | 1,328 |
/* 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.
*/
/*
* misc1.c: functions that didn't seem to fit elsewhere
*/
#include "vim.h"
#include "version.h"
static char_u *vim_version_dir __ARGS((char_u *vimdir));
static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
static int copy_indent __ARGS((int size, char_u *src));
/*
* Count the size (in window cells) of the indent in the current line.
*/
int
get_indent()
{
return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
}
/*
* Count the size (in window cells) of the indent in line "lnum".
*/
int
get_indent_lnum(lnum)
linenr_T lnum;
{
return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
}
#if defined(FEAT_FOLDING) || defined(PROTO)
/*
* Count the size (in window cells) of the indent in line "lnum" of buffer
* "buf".
*/
int
get_indent_buf(buf, lnum)
buf_T *buf;
linenr_T lnum;
{
return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
}
#endif
/*
* count the size (in window cells) of the indent in line "ptr", with
* 'tabstop' at "ts"
*/
int
get_indent_str(ptr, ts)
char_u *ptr;
int ts;
{
int count = 0;
for ( ; *ptr; ++ptr)
{
if (*ptr == TAB) /* count a tab for what it is worth */
count += ts - (count % ts);
else if (*ptr == ' ')
++count; /* count a space for one */
else
break;
}
return count;
}
/*
* Set the indent of the current line.
* Leaves the cursor on the first non-blank in the line.
* Caller must take care of undo.
* "flags":
* SIN_CHANGED: call changed_bytes() if the line was changed.
* SIN_INSERT: insert the indent in front of the line.
* SIN_UNDO: save line for undo before changing it.
* Returns TRUE if the line was changed.
*/
int
set_indent(size, flags)
int size; /* measured in spaces */
int flags;
{
char_u *p;
char_u *newline;
char_u *oldline;
char_u *s;
int todo;
int ind_len; /* measured in characters */
int line_len;
int doit = FALSE;
int ind_done = 0; /* measured in spaces */
int tab_pad;
int retval = FALSE;
int orig_char_len = -1; /* number of initial whitespace chars when
'et' and 'pi' are both set */
/*
* First check if there is anything to do and compute the number of
* characters needed for the indent.
*/
todo = size;
ind_len = 0;
p = oldline = ml_get_curline();
/* Calculate the buffer size for the new indent, and check to see if it
* isn't already set */
/* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
* 'preserveindent' are set count the number of characters at the
* beginning of the line to be copied */
if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
{
/* If 'preserveindent' is set then reuse as much as possible of
* the existing indent structure for the new indent */
if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
{
ind_done = 0;
/* count as many characters as we can use */
while (todo > 0 && vim_iswhite(*p))
{
if (*p == TAB)
{
tab_pad = (int)curbuf->b_p_ts
- (ind_done % (int)curbuf->b_p_ts);
/* stop if this tab will overshoot the target */
if (todo < tab_pad)
break;
todo -= tab_pad;
++ind_len;
ind_done += tab_pad;
}
else
{
--todo;
++ind_len;
++ind_done;
}
++p;
}
/* Set initial number of whitespace chars to copy if we are
* preserving indent but expandtab is set */
if (curbuf->b_p_et)
orig_char_len = ind_len;
/* Fill to next tabstop with a tab, if possible */
tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
if (todo >= tab_pad && orig_char_len == -1)
{
doit = TRUE;
todo -= tab_pad;
++ind_len;
/* ind_done += tab_pad; */
}
}
/* count tabs required for indent */
while (todo >= (int)curbuf->b_p_ts)
{
if (*p != TAB)
doit = TRUE;
else
++p;
todo -= (int)curbuf->b_p_ts;
++ind_len;
/* ind_done += (int)curbuf->b_p_ts; */
}
}
/* count spaces required for indent */
while (todo > 0)
{
if (*p != ' ')
doit = TRUE;
else
++p;
--todo;
++ind_len;
/* ++ind_done; */
}
/* Return if the indent is OK already. */
if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
return FALSE;
/* Allocate memory for the new line. */
if (flags & SIN_INSERT)
p = oldline;
else
p = skipwhite(p);
line_len = (int)STRLEN(p) + 1;
/* If 'preserveindent' and 'expandtab' are both set keep the original
* characters and allocate accordingly. We will fill the rest with spaces
* after the if (!curbuf->b_p_et) below. */
if (orig_char_len != -1)
{
newline = alloc(orig_char_len + size - ind_done + line_len);
if (newline == NULL)
return FALSE;
todo = size - ind_done;
ind_len = orig_char_len + todo; /* Set total length of indent in
* characters, which may have been
* undercounted until now */
p = oldline;
s = newline;
while (orig_char_len > 0)
{
*s++ = *p++;
orig_char_len--;
}
/* Skip over any additional white space (useful when newindent is less
* than old) */
while (vim_iswhite(*p))
++p;
}
else
{
todo = size;
newline = alloc(ind_len + line_len);
if (newline == NULL)
return FALSE;
s = newline;
}
/* Put the characters in the new line. */
/* if 'expandtab' isn't set: use TABs */
if (!curbuf->b_p_et)
{
/* If 'preserveindent' is set then reuse as much as possible of
* the existing indent structure for the new indent */
if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
{
p = oldline;
ind_done = 0;
while (todo > 0 && vim_iswhite(*p))
{
if (*p == TAB)
{
tab_pad = (int)curbuf->b_p_ts
- (ind_done % (int)curbuf->b_p_ts);
/* stop if this tab will overshoot the target */
if (todo < tab_pad)
break;
todo -= tab_pad;
ind_done += tab_pad;
}
else
{
--todo;
++ind_done;
}
*s++ = *p++;
}
/* Fill to next tabstop with a tab, if possible */
tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
if (todo >= tab_pad)
{
*s++ = TAB;
todo -= tab_pad;
}
p = skipwhite(p);
}
while (todo >= (int)curbuf->b_p_ts)
{
*s++ = TAB;
todo -= (int)curbuf->b_p_ts;
}
}
while (todo > 0)
{
*s++ = ' ';
--todo;
}
mch_memmove(s, p, (size_t)line_len);
/* Replace the line (unless undo fails). */
if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
{
ml_replace(curwin->w_cursor.lnum, newline, FALSE);
if (flags & SIN_CHANGED)
changed_bytes(curwin->w_cursor.lnum, 0);
/* Correct saved cursor position if it's after the indent. */
if (saved_cursor.lnum == curwin->w_cursor.lnum
&& saved_cursor.col >= (colnr_T)(p - oldline))
saved_cursor.col += ind_len - (colnr_T)(p - oldline);
retval = TRUE;
}
else
vim_free(newline);
curwin->w_cursor.col = ind_len;
return retval;
}
/*
* Copy the indent from ptr to the current line (and fill to size)
* Leaves the cursor on the first non-blank in the line.
* Returns TRUE if the line was changed.
*/
static int
copy_indent(size, src)
int size;
char_u *src;
{
char_u *p = NULL;
char_u *line = NULL;
char_u *s;
int todo;
int ind_len;
int line_len = 0;
int tab_pad;
int ind_done;
int round;
/* Round 1: compute the number of characters needed for the indent
* Round 2: copy the characters. */
for (round = 1; round <= 2; ++round)
{
todo = size;
ind_len = 0;
ind_done = 0;
s = src;
/* Count/copy the usable portion of the source line */
while (todo > 0 && vim_iswhite(*s))
{
if (*s == TAB)
{
tab_pad = (int)curbuf->b_p_ts
- (ind_done % (int)curbuf->b_p_ts);
/* Stop if this tab will overshoot the target */
if (todo < tab_pad)
break;
todo -= tab_pad;
ind_done += tab_pad;
}
else
{
--todo;
++ind_done;
}
++ind_len;
if (p != NULL)
*p++ = *s;
++s;
}
/* Fill to next tabstop with a tab, if possible */
tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
if (todo >= tab_pad && !curbuf->b_p_et)
{
todo -= tab_pad;
++ind_len;
if (p != NULL)
*p++ = TAB;
}
/* Add tabs required for indent */
while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
{
todo -= (int)curbuf->b_p_ts;
++ind_len;
if (p != NULL)
*p++ = TAB;
}
/* Count/add spaces required for indent */
while (todo > 0)
{
--todo;
++ind_len;
if (p != NULL)
*p++ = ' ';
}
if (p == NULL)
{
/* Allocate memory for the result: the copied indent, new indent
* and the rest of the line. */
line_len = (int)STRLEN(ml_get_curline()) + 1;
line = alloc(ind_len + line_len);
if (line == NULL)
return FALSE;
p = line;
}
}
/* Append the original line */
mch_memmove(p, ml_get_curline(), (size_t)line_len);
/* Replace the line */
ml_replace(curwin->w_cursor.lnum, line, FALSE);
/* Put the cursor after the indent. */
curwin->w_cursor.col = ind_len;
return TRUE;
}
/*
* Return the indent of the current line after a number. Return -1 if no
* number was found. Used for 'n' in 'formatoptions': numbered list.
* Since a pattern is used it can actually handle more than numbers.
*/
int
get_number_indent(lnum)
linenr_T lnum;
{
colnr_T col;
pos_T pos;
if (lnum > curbuf->b_ml.ml_line_count)
return -1;
pos.lnum = 0;
#ifdef FEAT_COMMENTS
if (has_format_option(FO_Q_COMS) && has_format_option(FO_Q_NUMBER))
{
regmatch_T regmatch;
int lead_len; /* length of comment leader */
lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
if (regmatch.regprog != NULL)
{
regmatch.rm_ic = FALSE;
/* vim_regexec() expects a pointer to a line. This lets us
* start matching for the flp beyond any comment leader... */
if (vim_regexec(®match, ml_get(lnum) + lead_len, (colnr_T)0))
{
pos.lnum = lnum;
pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
#ifdef FEAT_VIRTUALEDIT
pos.coladd = 0;
#endif
}
}
vim_free(regmatch.regprog);
}
else
{
/*
* What follows is the orig code that is not "comment aware"...
*
* I'm not sure if regmmatch_T (multi-match) is needed in this case.
* It may be true that this section would work properly using the
* regmatch_T code above, in which case, these two separate sections
* should be consolidated w/ FEAT_COMMENTS making lead_len > 0...
*/
#endif
regmmatch_T regmatch;
regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
if (regmatch.regprog != NULL)
{
regmatch.rmm_ic = FALSE;
regmatch.rmm_maxcol = 0;
if (vim_regexec_multi(®match, curwin, curbuf,
lnum, (colnr_T)0, NULL))
{
pos.lnum = regmatch.endpos[0].lnum + lnum;
pos.col = regmatch.endpos[0].col;
#ifdef FEAT_VIRTUALEDIT
pos.coladd = 0;
#endif
}
vim_free(regmatch.regprog);
}
#ifdef FEAT_COMMENTS
}
#endif
if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
return -1;
getvcol(curwin, &pos, &col, NULL, NULL);
return (int)col;
}
#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
static int cin_is_cinword __ARGS((char_u *line));
/*
* Return TRUE if the string "line" starts with a word from 'cinwords'.
*/
static int
cin_is_cinword(line)
char_u *line;
{
char_u *cinw;
char_u *cinw_buf;
int cinw_len;
int retval = FALSE;
int len;
cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
cinw_buf = alloc((unsigned)cinw_len);
if (cinw_buf != NULL)
{
line = skipwhite(line);
for (cinw = curbuf->b_p_cinw; *cinw; )
{
len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
if (STRNCMP(line, cinw_buf, len) == 0
&& (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
{
retval = TRUE;
break;
}
}
vim_free(cinw_buf);
}
return retval;
}
#endif
/*
* open_line: Add a new line below or above the current line.
*
* For VREPLACE mode, we only add a new line when we get to the end of the
* file, otherwise we just start replacing the next line.
*
* Caller must take care of undo. Since VREPLACE may affect any number of
* lines however, it may call u_save_cursor() again when starting to change a
* new line.
* "flags": OPENLINE_DELSPACES delete spaces after cursor
* OPENLINE_DO_COM format comments
* OPENLINE_KEEPTRAIL keep trailing spaces
* OPENLINE_MARKFIX adjust mark positions after the line break
* OPENLINE_COM_LIST format comments with list or 2nd line indent
*
* "second_line_indent": indent for after ^^D in Insert mode or if flag
* OPENLINE_COM_LIST
*
* Return TRUE for success, FALSE for failure
*/
int
open_line(dir, flags, second_line_indent)
int dir; /* FORWARD or BACKWARD */
int flags;
int second_line_indent;
{
char_u *saved_line; /* copy of the original line */
char_u *next_line = NULL; /* copy of the next line */
char_u *p_extra = NULL; /* what goes to next line */
int less_cols = 0; /* less columns for mark in new line */
int less_cols_off = 0; /* columns to skip for mark adjust */
pos_T old_cursor; /* old cursor position */
int newcol = 0; /* new cursor column */
int newindent = 0; /* auto-indent of the new line */
int n;
int trunc_line = FALSE; /* truncate current line afterwards */
int retval = FALSE; /* return value, default is FAIL */
#ifdef FEAT_COMMENTS
int extra_len = 0; /* length of p_extra string */
int lead_len; /* length of comment leader */
char_u *lead_flags; /* position in 'comments' for comment leader */
char_u *leader = NULL; /* copy of comment leader */
#endif
char_u *allocated = NULL; /* allocated memory */
#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
|| defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
char_u *p;
#endif
int saved_char = NUL; /* init for GCC */
#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
pos_T *pos;
#endif
#ifdef FEAT_SMARTINDENT
int do_si = (!p_paste && curbuf->b_p_si
# ifdef FEAT_CINDENT
&& !curbuf->b_p_cin
# endif
);
int no_si = FALSE; /* reset did_si afterwards */
int first_char = NUL; /* init for GCC */
#endif
#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
int vreplace_mode;
#endif
int did_append; /* appended a new line */
int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
/*
* make a copy of the current line so we can mess with it
*/
saved_line = vim_strsave(ml_get_curline());
if (saved_line == NULL) /* out of memory! */
return FALSE;
#ifdef FEAT_VREPLACE
if (State & VREPLACE_FLAG)
{
/*
* With VREPLACE we make a copy of the next line, which we will be
* starting to replace. First make the new line empty and let vim play
* with the indenting and comment leader to its heart's content. Then
* we grab what it ended up putting on the new line, put back the
* original line, and call ins_char() to put each new character onto
* the line, replacing what was there before and pushing the right
* stuff onto the replace stack. -- webb.
*/
if (curwin->w_cursor.lnum < orig_line_count)
next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
else
next_line = vim_strsave((char_u *)"");
if (next_line == NULL) /* out of memory! */
goto theend;
/*
* In VREPLACE mode, a NL replaces the rest of the line, and starts
* replacing the next line, so push all of the characters left on the
* line onto the replace stack. We'll push any other characters that
* might be replaced at the start of the next line (due to autoindent
* etc) a bit later.
*/
replace_push(NUL); /* Call twice because BS over NL expects it */
replace_push(NUL);
p = saved_line + curwin->w_cursor.col;
while (*p != NUL)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
p += replace_push_mb(p);
else
#endif
replace_push(*p++);
}
saved_line[curwin->w_cursor.col] = NUL;
}
#endif
if ((State & INSERT)
#ifdef FEAT_VREPLACE
&& !(State & VREPLACE_FLAG)
#endif
)
{
p_extra = saved_line + curwin->w_cursor.col;
#ifdef FEAT_SMARTINDENT
if (do_si) /* need first char after new line break */
{
p = skipwhite(p_extra);
first_char = *p;
}
#endif
#ifdef FEAT_COMMENTS
extra_len = (int)STRLEN(p_extra);
#endif
saved_char = *p_extra;
*p_extra = NUL;
}
u_clearline(); /* cannot do "U" command when adding lines */
#ifdef FEAT_SMARTINDENT
did_si = FALSE;
#endif
ai_col = 0;
/*
* If we just did an auto-indent, then we didn't type anything on
* the prior line, and it should be truncated. Do this even if 'ai' is not
* set because automatically inserting a comment leader also sets did_ai.
*/
if (dir == FORWARD && did_ai)
trunc_line = TRUE;
/*
* If 'autoindent' and/or 'smartindent' is set, try to figure out what
* indent to use for the new line.
*/
if (curbuf->b_p_ai
#ifdef FEAT_SMARTINDENT
|| do_si
#endif
)
{
/*
* count white space on current line
*/
newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
newindent = second_line_indent; /* for ^^D command in insert mode */
#ifdef FEAT_SMARTINDENT
/*
* Do smart indenting.
* In insert/replace mode (only when dir == FORWARD)
* we may move some text to the next line. If it starts with '{'
* don't add an indent. Fixes inserting a NL before '{' in line
* "if (condition) {"
*/
if (!trunc_line && do_si && *saved_line != NUL
&& (p_extra == NULL || first_char != '{'))
{
char_u *ptr;
char_u last_char;
old_cursor = curwin->w_cursor;
ptr = saved_line;
# ifdef FEAT_COMMENTS
if (flags & OPENLINE_DO_COM)
lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
else
lead_len = 0;
# endif
if (dir == FORWARD)
{
/*
* Skip preprocessor directives, unless they are
* recognised as comments.
*/
if (
# ifdef FEAT_COMMENTS
lead_len == 0 &&
# endif
ptr[0] == '#')
{
while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
ptr = ml_get(--curwin->w_cursor.lnum);
newindent = get_indent();
}
# ifdef FEAT_COMMENTS
if (flags & OPENLINE_DO_COM)
lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
else
lead_len = 0;
if (lead_len > 0)
{
/*
* This case gets the following right:
* \*
* * A comment (read '\' as '/').
* *\
* #define IN_THE_WAY
* This should line up here;
*/
p = skipwhite(ptr);
if (p[0] == '/' && p[1] == '*')
p++;
if (p[0] == '*')
{
for (p++; *p; p++)
{
if (p[0] == '/' && p[-1] == '*')
{
/*
* End of C comment, indent should line up
* with the line containing the start of
* the comment
*/
curwin->w_cursor.col = (colnr_T)(p - ptr);
if ((pos = findmatch(NULL, NUL)) != NULL)
{
curwin->w_cursor.lnum = pos->lnum;
newindent = get_indent();
}
}
}
}
}
else /* Not a comment line */
# endif
{
/* Find last non-blank in line */
p = ptr + STRLEN(ptr) - 1;
while (p > ptr && vim_iswhite(*p))
--p;
last_char = *p;
/*
* find the character just before the '{' or ';'
*/
if (last_char == '{' || last_char == ';')
{
if (p > ptr)
--p;
while (p > ptr && vim_iswhite(*p))
--p;
}
/*
* Try to catch lines that are split over multiple
* lines. eg:
* if (condition &&
* condition) {
* Should line up here!
* }
*/
if (*p == ')')
{
curwin->w_cursor.col = (colnr_T)(p - ptr);
if ((pos = findmatch(NULL, '(')) != NULL)
{
curwin->w_cursor.lnum = pos->lnum;
newindent = get_indent();
ptr = ml_get_curline();
}
}
/*
* If last character is '{' do indent, without
* checking for "if" and the like.
*/
if (last_char == '{')
{
did_si = TRUE; /* do indent */
no_si = TRUE; /* don't delete it when '{' typed */
}
/*
* Look for "if" and the like, use 'cinwords'.
* Don't do this if the previous line ended in ';' or
* '}'.
*/
else if (last_char != ';' && last_char != '}'
&& cin_is_cinword(ptr))
did_si = TRUE;
}
}
else /* dir == BACKWARD */
{
/*
* Skip preprocessor directives, unless they are
* recognised as comments.
*/
if (
# ifdef FEAT_COMMENTS
lead_len == 0 &&
# endif
ptr[0] == '#')
{
int was_backslashed = FALSE;
while ((ptr[0] == '#' || was_backslashed) &&
curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
was_backslashed = TRUE;
else
was_backslashed = FALSE;
ptr = ml_get(++curwin->w_cursor.lnum);
}
if (was_backslashed)
newindent = 0; /* Got to end of file */
else
newindent = get_indent();
}
p = skipwhite(ptr);
if (*p == '}') /* if line starts with '}': do indent */
did_si = TRUE;
else /* can delete indent when '{' typed */
can_si_back = TRUE;
}
curwin->w_cursor = old_cursor;
}
if (do_si)
can_si = TRUE;
#endif /* FEAT_SMARTINDENT */
did_ai = TRUE;
}
#ifdef FEAT_COMMENTS
/*
* Find out if the current line starts with a comment leader.
* This may then be inserted in front of the new line.
*/
end_comment_pending = NUL;
if (flags & OPENLINE_DO_COM)
lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
else
lead_len = 0;
if (lead_len > 0)
{
char_u *lead_repl = NULL; /* replaces comment leader */
int lead_repl_len = 0; /* length of *lead_repl */
char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
char_u lead_end[COM_MAX_LEN]; /* end-comment string */
char_u *comment_end = NULL; /* where lead_end has been found */
int extra_space = FALSE; /* append extra space */
int current_flag;
int require_blank = FALSE; /* requires blank after middle */
char_u *p2;
/*
* If the comment leader has the start, middle or end flag, it may not
* be used or may be replaced with the middle leader.
*/
for (p = lead_flags; *p && *p != ':'; ++p)
{
if (*p == COM_BLANK)
{
require_blank = TRUE;
continue;
}
if (*p == COM_START || *p == COM_MIDDLE)
{
current_flag = *p;
if (*p == COM_START)
{
/*
* Doing "O" on a start of comment does not insert leader.
*/
if (dir == BACKWARD)
{
lead_len = 0;
break;
}
/* find start of middle part */
(void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
require_blank = FALSE;
}
/*
* Isolate the strings of the middle and end leader.
*/
while (*p && p[-1] != ':') /* find end of middle flags */
{
if (*p == COM_BLANK)
require_blank = TRUE;
++p;
}
(void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
while (*p && p[-1] != ':') /* find end of end flags */
{
/* Check whether we allow automatic ending of comments */
if (*p == COM_AUTO_END)
end_comment_pending = -1; /* means we want to set it */
++p;
}
n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
if (end_comment_pending == -1) /* we can set it now */
end_comment_pending = lead_end[n - 1];
/*
* If the end of the comment is in the same line, don't use
* the comment leader.
*/
if (dir == FORWARD)
{
for (p = saved_line + lead_len; *p; ++p)
if (STRNCMP(p, lead_end, n) == 0)
{
comment_end = p;
lead_len = 0;
break;
}
}
/*
* Doing "o" on a start of comment inserts the middle leader.
*/
if (lead_len > 0)
{
if (current_flag == COM_START)
{
lead_repl = lead_middle;
lead_repl_len = (int)STRLEN(lead_middle);
}
/*
* If we have hit RETURN immediately after the start
* comment leader, then put a space after the middle
* comment leader on the next line.
*/
if (!vim_iswhite(saved_line[lead_len - 1])
&& ((p_extra != NULL
&& (int)curwin->w_cursor.col == lead_len)
|| (p_extra == NULL
&& saved_line[lead_len] == NUL)
|| require_blank))
extra_space = TRUE;
}
break;
}
if (*p == COM_END)
{
/*
* Doing "o" on the end of a comment does not insert leader.
* Remember where the end is, might want to use it to find the
* start (for C-comments).
*/
if (dir == FORWARD)
{
comment_end = skipwhite(saved_line);
lead_len = 0;
break;
}
/*
* Doing "O" on the end of a comment inserts the middle leader.
* Find the string for the middle leader, searching backwards.
*/
while (p > curbuf->b_p_com && *p != ',')
--p;
for (lead_repl = p; lead_repl > curbuf->b_p_com
&& lead_repl[-1] != ':'; --lead_repl)
;
lead_repl_len = (int)(p - lead_repl);
/* We can probably always add an extra space when doing "O" on
* the comment-end */
extra_space = TRUE;
/* Check whether we allow automatic ending of comments */
for (p2 = p; *p2 && *p2 != ':'; p2++)
{
if (*p2 == COM_AUTO_END)
end_comment_pending = -1; /* means we want to set it */
}
if (end_comment_pending == -1)
{
/* Find last character in end-comment string */
while (*p2 && *p2 != ',')
p2++;
end_comment_pending = p2[-1];
}
break;
}
if (*p == COM_FIRST)
{
/*
* Comment leader for first line only: Don't repeat leader
* when using "O", blank out leader when using "o".
*/
if (dir == BACKWARD)
lead_len = 0;
else
{
lead_repl = (char_u *)"";
lead_repl_len = 0;
}
break;
}
}
if (lead_len)
{
/* allocate buffer (may concatenate p_extra later) */
leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
+ (second_line_indent > 0 ? second_line_indent : 0) + 1);
allocated = leader; /* remember to free it later */
if (leader == NULL)
lead_len = 0;
else
{
vim_strncpy(leader, saved_line, lead_len);
/*
* Replace leader with lead_repl, right or left adjusted
*/
if (lead_repl != NULL)
{
int c = 0;
int off = 0;
for (p = lead_flags; *p != NUL && *p != ':'; )
{
if (*p == COM_RIGHT || *p == COM_LEFT)
c = *p++;
else if (VIM_ISDIGIT(*p) || *p == '-')
off = getdigits(&p);
else
++p;
}
if (c == COM_RIGHT) /* right adjusted leader */
{
/* find last non-white in the leader to line up with */
for (p = leader + lead_len - 1; p > leader
&& vim_iswhite(*p); --p)
;
++p;
#ifdef FEAT_MBYTE
/* Compute the length of the replaced characters in
* screen characters, not bytes. */
{
int repl_size = vim_strnsize(lead_repl,
lead_repl_len);
int old_size = 0;
char_u *endp = p;
int l;
while (old_size < repl_size && p > leader)
{
mb_ptr_back(leader, p);
old_size += ptr2cells(p);
}
l = lead_repl_len - (int)(endp - p);
if (l != 0)
mch_memmove(endp + l, endp,
(size_t)((leader + lead_len) - endp));
lead_len += l;
}
#else
if (p < leader + lead_repl_len)
p = leader;
else
p -= lead_repl_len;
#endif
mch_memmove(p, lead_repl, (size_t)lead_repl_len);
if (p + lead_repl_len > leader + lead_len)
p[lead_repl_len] = NUL;
/* blank-out any other chars from the old leader. */
while (--p >= leader)
{
#ifdef FEAT_MBYTE
int l = mb_head_off(leader, p);
if (l > 1)
{
p -= l;
if (ptr2cells(p) > 1)
{
p[1] = ' ';
--l;
}
mch_memmove(p + 1, p + l + 1,
(size_t)((leader + lead_len) - (p + l + 1)));
lead_len -= l;
*p = ' ';
}
else
#endif
if (!vim_iswhite(*p))
*p = ' ';
}
}
else /* left adjusted leader */
{
p = skipwhite(leader);
#ifdef FEAT_MBYTE
/* Compute the length of the replaced characters in
* screen characters, not bytes. Move the part that is
* not to be overwritten. */
{
int repl_size = vim_strnsize(lead_repl,
lead_repl_len);
int i;
int l;
for (i = 0; p[i] != NUL && i < lead_len; i += l)
{
l = (*mb_ptr2len)(p + i);
if (vim_strnsize(p, i + l) > repl_size)
break;
}
if (i != lead_repl_len)
{
mch_memmove(p + lead_repl_len, p + i,
(size_t)(lead_len - i - (p - leader)));
lead_len += lead_repl_len - i;
}
}
#endif
mch_memmove(p, lead_repl, (size_t)lead_repl_len);
/* Replace any remaining non-white chars in the old
* leader by spaces. Keep Tabs, the indent must
* remain the same. */
for (p += lead_repl_len; p < leader + lead_len; ++p)
if (!vim_iswhite(*p))
{
/* Don't put a space before a TAB. */
if (p + 1 < leader + lead_len && p[1] == TAB)
{
--lead_len;
mch_memmove(p, p + 1,
(leader + lead_len) - p);
}
else
{
#ifdef FEAT_MBYTE
int l = (*mb_ptr2len)(p);
if (l > 1)
{
if (ptr2cells(p) > 1)
{
/* Replace a double-wide char with
* two spaces */
--l;
*p++ = ' ';
}
mch_memmove(p + 1, p + l,
(leader + lead_len) - p);
lead_len -= l - 1;
}
#endif
*p = ' ';
}
}
*p = NUL;
}
/* Recompute the indent, it may have changed. */
if (curbuf->b_p_ai
#ifdef FEAT_SMARTINDENT
|| do_si
#endif
)
newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
/* Add the indent offset */
if (newindent + off < 0)
{
off = -newindent;
newindent = 0;
}
else
newindent += off;
/* Correct trailing spaces for the shift, so that
* alignment remains equal. */
while (off > 0 && lead_len > 0
&& leader[lead_len - 1] == ' ')
{
/* Don't do it when there is a tab before the space */
if (vim_strchr(skipwhite(leader), '\t') != NULL)
break;
--lead_len;
--off;
}
/* If the leader ends in white space, don't add an
* extra space */
if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
extra_space = FALSE;
leader[lead_len] = NUL;
}
if (extra_space)
{
leader[lead_len++] = ' ';
leader[lead_len] = NUL;
}
newcol = lead_len;
/*
* if a new indent will be set below, remove the indent that
* is in the comment leader
*/
if (newindent
#ifdef FEAT_SMARTINDENT
|| did_si
#endif
)
{
while (lead_len && vim_iswhite(*leader))
{
--lead_len;
--newcol;
++leader;
}
}
}
#ifdef FEAT_SMARTINDENT
did_si = can_si = FALSE;
#endif
}
else if (comment_end != NULL)
{
/*
* We have finished a comment, so we don't use the leader.
* If this was a C-comment and 'ai' or 'si' is set do a normal
* indent to align with the line containing the start of the
* comment.
*/
if (comment_end[0] == '*' && comment_end[1] == '/' &&
(curbuf->b_p_ai
#ifdef FEAT_SMARTINDENT
|| do_si
#endif
))
{
old_cursor = curwin->w_cursor;
curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
if ((pos = findmatch(NULL, NUL)) != NULL)
{
curwin->w_cursor.lnum = pos->lnum;
newindent = get_indent();
}
curwin->w_cursor = old_cursor;
}
}
}
#endif
/* (State == INSERT || State == REPLACE), only when dir == FORWARD */
if (p_extra != NULL)
{
*p_extra = saved_char; /* restore char that NUL replaced */
/*
* When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
* non-blank.
*
* When in REPLACE mode, put the deleted blanks on the replace stack,
* preceded by a NUL, so they can be put back when a BS is entered.
*/
if (REPLACE_NORMAL(State))
replace_push(NUL); /* end of extra blanks */
if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
{
while ((*p_extra == ' ' || *p_extra == '\t')
#ifdef FEAT_MBYTE
&& (!enc_utf8
|| !utf_iscomposing(utf_ptr2char(p_extra + 1)))
#endif
)
{
if (REPLACE_NORMAL(State))
replace_push(*p_extra);
++p_extra;
++less_cols_off;
}
}
if (*p_extra != NUL)
did_ai = FALSE; /* append some text, don't truncate now */
/* columns for marks adjusted for removed columns */
less_cols = (int)(p_extra - saved_line);
}
if (p_extra == NULL)
p_extra = (char_u *)""; /* append empty line */
#ifdef FEAT_COMMENTS
/* concatenate leader and p_extra, if there is a leader */
if (lead_len)
{
if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
{
int i;
int padding = second_line_indent
- (newindent + (int)STRLEN(leader));
/* Here whitespace is inserted after the comment char.
* Below, set_indent(newindent, SIN_INSERT) will insert the
* whitespace needed before the comment char. */
for (i = 0; i < padding; i++)
{
STRCAT(leader, " ");
newcol++;
}
}
STRCAT(leader, p_extra);
p_extra = leader;
did_ai = TRUE; /* So truncating blanks works with comments */
less_cols -= lead_len;
}
else
end_comment_pending = NUL; /* turns out there was no leader */
#endif
old_cursor = curwin->w_cursor;
if (dir == BACKWARD)
--curwin->w_cursor.lnum;
#ifdef FEAT_VREPLACE
if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
#endif
{
if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
== FAIL)
goto theend;
/* Postpone calling changed_lines(), because it would mess up folding
* with markers. */
mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
did_append = TRUE;
}
#ifdef FEAT_VREPLACE
else
{
/*
* In VREPLACE mode we are starting to replace the next line.
*/
curwin->w_cursor.lnum++;
if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
{
/* In case we NL to a new line, BS to the previous one, and NL
* again, we don't want to save the new line for undo twice.
*/
(void)u_save_cursor(); /* errors are ignored! */
vr_lines_changed++;
}
ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
changed_bytes(curwin->w_cursor.lnum, 0);
curwin->w_cursor.lnum--;
did_append = FALSE;
}
#endif
if (newindent
#ifdef FEAT_SMARTINDENT
|| did_si
#endif
)
{
++curwin->w_cursor.lnum;
#ifdef FEAT_SMARTINDENT
if (did_si)
{
if (p_sr)
newindent -= newindent % (int)curbuf->b_p_sw;
newindent += (int)curbuf->b_p_sw;
}
#endif
/* Copy the indent */
if (curbuf->b_p_ci)
{
(void)copy_indent(newindent, saved_line);
/*
* Set the 'preserveindent' option so that any further screwing
* with the line doesn't entirely destroy our efforts to preserve
* it. It gets restored at the function end.
*/
curbuf->b_p_pi = TRUE;
}
else
(void)set_indent(newindent, SIN_INSERT);
less_cols -= curwin->w_cursor.col;
ai_col = curwin->w_cursor.col;
/*
* In REPLACE mode, for each character in the new indent, there must
* be a NUL on the replace stack, for when it is deleted with BS
*/
if (REPLACE_NORMAL(State))
for (n = 0; n < (int)curwin->w_cursor.col; ++n)
replace_push(NUL);
newcol += curwin->w_cursor.col;
#ifdef FEAT_SMARTINDENT
if (no_si)
did_si = FALSE;
#endif
}
#ifdef FEAT_COMMENTS
/*
* In REPLACE mode, for each character in the extra leader, there must be
* a NUL on the replace stack, for when it is deleted with BS.
*/
if (REPLACE_NORMAL(State))
while (lead_len-- > 0)
replace_push(NUL);
#endif
curwin->w_cursor = old_cursor;
if (dir == FORWARD)
{
if (trunc_line || (State & INSERT))
{
/* truncate current line at cursor */
saved_line[curwin->w_cursor.col] = NUL;
/* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
truncate_spaces(saved_line);
ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
saved_line = NULL;
if (did_append)
{
changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
curwin->w_cursor.lnum + 1, 1L);
did_append = FALSE;
/* Move marks after the line break to the new line. */
if (flags & OPENLINE_MARKFIX)
mark_col_adjust(curwin->w_cursor.lnum,
curwin->w_cursor.col + less_cols_off,
1L, (long)-less_cols);
}
else
changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
}
/*
* Put the cursor on the new line. Careful: the scrollup() above may
* have moved w_cursor, we must use old_cursor.
*/
curwin->w_cursor.lnum = old_cursor.lnum + 1;
}
if (did_append)
changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
curwin->w_cursor.col = newcol;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
/*
* In VREPLACE mode, we are handling the replace stack ourselves, so stop
* fixthisline() from doing it (via change_indent()) by telling it we're in
* normal INSERT mode.
*/
if (State & VREPLACE_FLAG)
{
vreplace_mode = State; /* So we know to put things right later */
State = INSERT;
}
else
vreplace_mode = 0;
#endif
#ifdef FEAT_LISP
/*
* May do lisp indenting.
*/
if (!p_paste
# ifdef FEAT_COMMENTS
&& leader == NULL
# endif
&& curbuf->b_p_lisp
&& curbuf->b_p_ai)
{
fixthisline(get_lisp_indent);
p = ml_get_curline();
ai_col = (colnr_T)(skipwhite(p) - p);
}
#endif
#ifdef FEAT_CINDENT
/*
* May do indenting after opening a new line.
*/
if (!p_paste
&& (curbuf->b_p_cin
# ifdef FEAT_EVAL
|| *curbuf->b_p_inde != NUL
# endif
)
&& in_cinkeys(dir == FORWARD
? KEY_OPEN_FORW
: KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
{
do_c_expr_indent();
p = ml_get_curline();
ai_col = (colnr_T)(skipwhite(p) - p);
}
#endif
#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
if (vreplace_mode != 0)
State = vreplace_mode;
#endif
#ifdef FEAT_VREPLACE
/*
* Finally, VREPLACE gets the stuff on the new line, then puts back the
* original line, and inserts the new stuff char by char, pushing old stuff
* onto the replace stack (via ins_char()).
*/
if (State & VREPLACE_FLAG)
{
/* Put new line in p_extra */
p_extra = vim_strsave(ml_get_curline());
if (p_extra == NULL)
goto theend;
/* Put back original line */
ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
/* Insert new stuff into line again */
curwin->w_cursor.col = 0;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
ins_bytes(p_extra); /* will call changed_bytes() */
vim_free(p_extra);
next_line = NULL;
}
#endif
retval = TRUE; /* success! */
theend:
curbuf->b_p_pi = saved_pi;
vim_free(saved_line);
vim_free(next_line);
vim_free(allocated);
return retval;
}
#if defined(FEAT_COMMENTS) || defined(PROTO)
/*
* get_leader_len() returns the length of the prefix of the given string
* which introduces a comment. If this string is not a comment then 0 is
* returned.
* When "flags" is not NULL, it is set to point to the flags of the recognized
* comment leader.
* "backward" must be true for the "O" command.
* If "include_space" is set, include trailing whitespace while calculating the
* length.
*/
int
get_leader_len(line, flags, backward, include_space)
char_u *line;
char_u **flags;
int backward;
int include_space;
{
int i, j;
int result;
int got_com = FALSE;
int found_one;
char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
char_u *string; /* pointer to comment string */
char_u *list;
int middle_match_len = 0;
char_u *prev_list;
char_u *saved_flags = NULL;
result = i = 0;
while (vim_iswhite(line[i])) /* leading white space is ignored */
++i;
/*
* Repeat to match several nested comment strings.
*/
while (line[i] != NUL)
{
/*
* scan through the 'comments' option for a match
*/
found_one = FALSE;
for (list = curbuf->b_p_com; *list; )
{
/* Get one option part into part_buf[]. Advance "list" to next
* one. Put "string" at start of string. */
if (!got_com && flags != NULL)
*flags = list; /* remember where flags started */
prev_list = list;
(void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
string = vim_strchr(part_buf, ':');
if (string == NULL) /* missing ':', ignore this part */
continue;
*string++ = NUL; /* isolate flags from string */
/* If we found a middle match previously, use that match when this
* is not a middle or end. */
if (middle_match_len != 0
&& vim_strchr(part_buf, COM_MIDDLE) == NULL
&& vim_strchr(part_buf, COM_END) == NULL)
break;
/* When we already found a nested comment, only accept further
* nested comments. */
if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
continue;
/* When 'O' flag present and using "O" command skip this one. */
if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
continue;
/* Line contents and string must match.
* When string starts with white space, must have some white space
* (but the amount does not need to match, there might be a mix of
* TABs and spaces). */
if (vim_iswhite(string[0]))
{
if (i == 0 || !vim_iswhite(line[i - 1]))
continue; /* missing shite space */
while (vim_iswhite(string[0]))
++string;
}
for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
;
if (string[j] != NUL)
continue; /* string doesn't match */
/* When 'b' flag used, there must be white space or an
* end-of-line after the string in the line. */
if (vim_strchr(part_buf, COM_BLANK) != NULL
&& !vim_iswhite(line[i + j]) && line[i + j] != NUL)
continue;
/* We have found a match, stop searching unless this is a middle
* comment. The middle comment can be a substring of the end
* comment in which case it's better to return the length of the
* end comment and its flags. Thus we keep searching with middle
* and end matches and use an end match if it matches better. */
if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
{
if (middle_match_len == 0)
{
middle_match_len = j;
saved_flags = prev_list;
}
continue;
}
if (middle_match_len != 0 && j > middle_match_len)
/* Use this match instead of the middle match, since it's a
* longer thus better match. */
middle_match_len = 0;
if (middle_match_len == 0)
i += j;
found_one = TRUE;
break;
}
if (middle_match_len != 0)
{
/* Use the previously found middle match after failing to find a
* match with an end. */
if (!got_com && flags != NULL)
*flags = saved_flags;
i += middle_match_len;
found_one = TRUE;
}
/* No match found, stop scanning. */
if (!found_one)
break;
result = i;
/* Include any trailing white space. */
while (vim_iswhite(line[i]))
++i;
if (include_space)
result = i;
/* If this comment doesn't nest, stop here. */
got_com = TRUE;
if (vim_strchr(part_buf, COM_NEST) == NULL)
break;
}
return result;
}
/*
* Return the offset at which the last comment in line starts. If there is no
* comment in the whole line, -1 is returned.
*
* When "flags" is not null, it is set to point to the flags describing the
* recognized comment leader.
*/
int
get_last_leader_offset(line, flags)
char_u *line;
char_u **flags;
{
int result = -1;
int i, j;
int lower_check_bound = 0;
char_u *string;
char_u *com_leader;
char_u *com_flags;
char_u *list;
int found_one;
char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
/*
* Repeat to match several nested comment strings.
*/
i = (int)STRLEN(line);
while (--i >= lower_check_bound)
{
/*
* scan through the 'comments' option for a match
*/
found_one = FALSE;
for (list = curbuf->b_p_com; *list; )
{
char_u *flags_save = list;
/*
* Get one option part into part_buf[]. Advance list to next one.
* put string at start of string.
*/
(void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
string = vim_strchr(part_buf, ':');
if (string == NULL) /* If everything is fine, this cannot actually
* happen. */
{
continue;
}
*string++ = NUL; /* Isolate flags from string. */
com_leader = string;
/*
* Line contents and string must match.
* When string starts with white space, must have some white space
* (but the amount does not need to match, there might be a mix of
* TABs and spaces).
*/
if (vim_iswhite(string[0]))
{
if (i == 0 || !vim_iswhite(line[i - 1]))
continue;
while (vim_iswhite(string[0]))
++string;
}
for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
/* do nothing */;
if (string[j] != NUL)
continue;
/*
* When 'b' flag used, there must be white space or an
* end-of-line after the string in the line.
*/
if (vim_strchr(part_buf, COM_BLANK) != NULL
&& !vim_iswhite(line[i + j]) && line[i + j] != NUL)
{
continue;
}
/*
* We have found a match, stop searching.
*/
found_one = TRUE;
if (flags)
*flags = flags_save;
com_flags = flags_save;
break;
}
if (found_one)
{
char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
int len1, len2, off;
result = i;
/*
* If this comment nests, continue searching.
*/
if (vim_strchr(part_buf, COM_NEST) != NULL)
continue;
lower_check_bound = i;
/* Let's verify whether the comment leader found is a substring
* of other comment leaders. If it is, let's adjust the
* lower_check_bound so that we make sure that we have determined
* the comment leader correctly.
*/
while (vim_iswhite(*com_leader))
++com_leader;
len1 = (int)STRLEN(com_leader);
for (list = curbuf->b_p_com; *list; )
{
char_u *flags_save = list;
(void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
if (flags_save == com_flags)
continue;
string = vim_strchr(part_buf2, ':');
++string;
while (vim_iswhite(*string))
++string;
len2 = (int)STRLEN(string);
if (len2 == 0)
continue;
/* Now we have to verify whether string ends with a substring
* beginning the com_leader. */
for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
{
--off;
if (!STRNCMP(string + off, com_leader, len2 - off))
{
if (i - off < lower_check_bound)
lower_check_bound = i - off;
}
}
}
}
}
return result;
}
#endif
/*
* Return the number of window lines occupied by buffer line "lnum".
*/
int
plines(lnum)
linenr_T lnum;
{
return plines_win(curwin, lnum, TRUE);
}
int
plines_win(wp, lnum, winheight)
win_T *wp;
linenr_T lnum;
int winheight; /* when TRUE limit to window height */
{
#if defined(FEAT_DIFF) || defined(PROTO)
/* Check for filler lines above this buffer line. When folded the result
* is one line anyway. */
return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
}
int
plines_nofill(lnum)
linenr_T lnum;
{
return plines_win_nofill(curwin, lnum, TRUE);
}
int
plines_win_nofill(wp, lnum, winheight)
win_T *wp;
linenr_T lnum;
int winheight; /* when TRUE limit to window height */
{
#endif
int lines;
if (!wp->w_p_wrap)
return 1;
#ifdef FEAT_VERTSPLIT
if (wp->w_width == 0)
return 1;
#endif
#ifdef FEAT_FOLDING
/* A folded lines is handled just like an empty line. */
/* NOTE: Caller must handle lines that are MAYBE folded. */
if (lineFolded(wp, lnum) == TRUE)
return 1;
#endif
lines = plines_win_nofold(wp, lnum);
if (winheight > 0 && lines > wp->w_height)
return (int)wp->w_height;
return lines;
}
/*
* Return number of window lines physical line "lnum" will occupy in window
* "wp". Does not care about folding, 'wrap' or 'diff'.
*/
int
plines_win_nofold(wp, lnum)
win_T *wp;
linenr_T lnum;
{
char_u *s;
long col;
int width;
s = ml_get_buf(wp->w_buffer, lnum, FALSE);
if (*s == NUL) /* empty line */
return 1;
col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
/*
* If list mode is on, then the '$' at the end of the line may take up one
* extra column.
*/
if (wp->w_p_list && lcs_eol != NUL)
col += 1;
/*
* Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
*/
width = W_WIDTH(wp) - win_col_off(wp);
if (width <= 0)
return 32000;
if (col <= width)
return 1;
col -= width;
width += win_col_off2(wp);
return (col + (width - 1)) / width + 1;
}
/*
* Like plines_win(), but only reports the number of physical screen lines
* used from the start of the line to the given column number.
*/
int
plines_win_col(wp, lnum, column)
win_T *wp;
linenr_T lnum;
long column;
{
long col;
char_u *s;
int lines = 0;
int width;
#ifdef FEAT_DIFF
/* Check for filler lines above this buffer line. When folded the result
* is one line anyway. */
lines = diff_check_fill(wp, lnum);
#endif
if (!wp->w_p_wrap)
return lines + 1;
#ifdef FEAT_VERTSPLIT
if (wp->w_width == 0)
return lines + 1;
#endif
s = ml_get_buf(wp->w_buffer, lnum, FALSE);
col = 0;
while (*s != NUL && --column >= 0)
{
col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
mb_ptr_adv(s);
}
/*
* If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
* INSERT mode, then col must be adjusted so that it represents the last
* screen position of the TAB. This only fixes an error when the TAB wraps
* from one screen line to the next (when 'columns' is not a multiple of
* 'ts') -- webb.
*/
if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
/*
* Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
*/
width = W_WIDTH(wp) - win_col_off(wp);
if (width <= 0)
return 9999;
lines += 1;
if (col > width)
lines += (col - width) / (width + win_col_off2(wp)) + 1;
return lines;
}
int
plines_m_win(wp, first, last)
win_T *wp;
linenr_T first, last;
{
int count = 0;
while (first <= last)
{
#ifdef FEAT_FOLDING
int x;
/* Check if there are any really folded lines, but also included lines
* that are maybe folded. */
x = foldedCount(wp, first, NULL);
if (x > 0)
{
++count; /* count 1 for "+-- folded" line */
first += x;
}
else
#endif
{
#ifdef FEAT_DIFF
if (first == wp->w_topline)
count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
else
#endif
count += plines_win(wp, first, TRUE);
++first;
}
}
return (count);
}
#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
/*
* Insert string "p" at the cursor position. Stops at a NUL byte.
* Handles Replace mode and multi-byte characters.
*/
void
ins_bytes(p)
char_u *p;
{
ins_bytes_len(p, (int)STRLEN(p));
}
#endif
#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
|| defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
/*
* Insert string "p" with length "len" at the cursor position.
* Handles Replace mode and multi-byte characters.
*/
void
ins_bytes_len(p, len)
char_u *p;
int len;
{
int i;
# ifdef FEAT_MBYTE
int n;
if (has_mbyte)
for (i = 0; i < len; i += n)
{
if (enc_utf8)
/* avoid reading past p[len] */
n = utfc_ptr2len_len(p + i, len - i);
else
n = (*mb_ptr2len)(p + i);
ins_char_bytes(p + i, n);
}
else
# endif
for (i = 0; i < len; ++i)
ins_char(p[i]);
}
#endif
/*
* Insert or replace a single character at the cursor position.
* When in REPLACE or VREPLACE mode, replace any existing character.
* Caller must have prepared for undo.
* For multi-byte characters we get the whole character, the caller must
* convert bytes to a character.
*/
void
ins_char(c)
int c;
{
#if defined(FEAT_MBYTE) || defined(PROTO)
char_u buf[MB_MAXBYTES + 1];
int n;
n = (*mb_char2bytes)(c, buf);
/* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
* Happens for CTRL-Vu9900. */
if (buf[0] == 0)
buf[0] = '\n';
ins_char_bytes(buf, n);
}
void
ins_char_bytes(buf, charlen)
char_u *buf;
int charlen;
{
int c = buf[0];
#endif
int newlen; /* nr of bytes inserted */
int oldlen; /* nr of bytes deleted (0 when not replacing) */
char_u *p;
char_u *newp;
char_u *oldp;
int linelen; /* length of old line including NUL */
colnr_T col;
linenr_T lnum = curwin->w_cursor.lnum;
int i;
#ifdef FEAT_VIRTUALEDIT
/* Break tabs if needed. */
if (virtual_active() && curwin->w_cursor.coladd > 0)
coladvance_force(getviscol());
#endif
col = curwin->w_cursor.col;
oldp = ml_get(lnum);
linelen = (int)STRLEN(oldp) + 1;
/* The lengths default to the values for when not replacing. */
oldlen = 0;
#ifdef FEAT_MBYTE
newlen = charlen;
#else
newlen = 1;
#endif
if (State & REPLACE_FLAG)
{
#ifdef FEAT_VREPLACE
if (State & VREPLACE_FLAG)
{
colnr_T new_vcol = 0; /* init for GCC */
colnr_T vcol;
int old_list;
#ifndef FEAT_MBYTE
char_u buf[2];
#endif
/*
* Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
* Returns the old value of list, so when finished,
* curwin->w_p_list should be set back to this.
*/
old_list = curwin->w_p_list;
if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
curwin->w_p_list = FALSE;
/*
* In virtual replace mode each character may replace one or more
* characters (zero if it's a TAB). Count the number of bytes to
* be deleted to make room for the new character, counting screen
* cells. May result in adding spaces to fill a gap.
*/
getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
#ifndef FEAT_MBYTE
buf[0] = c;
buf[1] = NUL;
#endif
new_vcol = vcol + chartabsize(buf, vcol);
while (oldp[col + oldlen] != NUL && vcol < new_vcol)
{
vcol += chartabsize(oldp + col + oldlen, vcol);
/* Don't need to remove a TAB that takes us to the right
* position. */
if (vcol > new_vcol && oldp[col + oldlen] == TAB)
break;
#ifdef FEAT_MBYTE
oldlen += (*mb_ptr2len)(oldp + col + oldlen);
#else
++oldlen;
#endif
/* Deleted a bit too much, insert spaces. */
if (vcol > new_vcol)
newlen += vcol - new_vcol;
}
curwin->w_p_list = old_list;
}
else
#endif
if (oldp[col] != NUL)
{
/* normal replace */
#ifdef FEAT_MBYTE
oldlen = (*mb_ptr2len)(oldp + col);
#else
oldlen = 1;
#endif
}
/* Push the replaced bytes onto the replace stack, so that they can be
* put back when BS is used. The bytes of a multi-byte character are
* done the other way around, so that the first byte is popped off
* first (it tells the byte length of the character). */
replace_push(NUL);
for (i = 0; i < oldlen; ++i)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
i += replace_push_mb(oldp + col + i) - 1;
else
#endif
replace_push(oldp[col + i]);
}
}
newp = alloc_check((unsigned)(linelen + newlen - oldlen));
if (newp == NULL)
return;
/* Copy bytes before the cursor. */
if (col > 0)
mch_memmove(newp, oldp, (size_t)col);
/* Copy bytes after the changed character(s). */
p = newp + col;
mch_memmove(p + newlen, oldp + col + oldlen,
(size_t)(linelen - col - oldlen));
/* Insert or overwrite the new character. */
#ifdef FEAT_MBYTE
mch_memmove(p, buf, charlen);
i = charlen;
#else
*p = c;
i = 1;
#endif
/* Fill with spaces when necessary. */
while (i < newlen)
p[i++] = ' ';
/* Replace the line in the buffer. */
ml_replace(lnum, newp, FALSE);
/* mark the buffer as changed and prepare for displaying */
changed_bytes(lnum, col);
/*
* If we're in Insert or Replace mode and 'showmatch' is set, then briefly
* show the match for right parens and braces.
*/
if (p_sm && (State & INSERT)
&& msg_silent == 0
#ifdef FEAT_MBYTE
&& charlen == 1
#endif
#ifdef FEAT_INS_EXPAND
&& !ins_compl_active()
#endif
)
showmatch(c);
#ifdef FEAT_RIGHTLEFT
if (!p_ri || (State & REPLACE_FLAG))
#endif
{
/* Normal insert: move cursor right */
#ifdef FEAT_MBYTE
curwin->w_cursor.col += charlen;
#else
++curwin->w_cursor.col;
#endif
}
/*
* TODO: should try to update w_row here, to avoid recomputing it later.
*/
}
/*
* Insert a string at the cursor position.
* Note: Does NOT handle Replace mode.
* Caller must have prepared for undo.
*/
void
ins_str(s)
char_u *s;
{
char_u *oldp, *newp;
int newlen = (int)STRLEN(s);
int oldlen;
colnr_T col;
linenr_T lnum = curwin->w_cursor.lnum;
#ifdef FEAT_VIRTUALEDIT
if (virtual_active() && curwin->w_cursor.coladd > 0)
coladvance_force(getviscol());
#endif
col = curwin->w_cursor.col;
oldp = ml_get(lnum);
oldlen = (int)STRLEN(oldp);
newp = alloc_check((unsigned)(oldlen + newlen + 1));
if (newp == NULL)
return;
if (col > 0)
mch_memmove(newp, oldp, (size_t)col);
mch_memmove(newp + col, s, (size_t)newlen);
mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
ml_replace(lnum, newp, FALSE);
changed_bytes(lnum, col);
curwin->w_cursor.col += newlen;
}
/*
* Delete one character under the cursor.
* If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
* Caller must have prepared for undo.
*
* return FAIL for failure, OK otherwise
*/
int
del_char(fixpos)
int fixpos;
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Make sure the cursor is at the start of a character. */
mb_adjust_cursor();
if (*ml_get_cursor() == NUL)
return FAIL;
return del_chars(1L, fixpos);
}
#endif
return del_bytes(1L, fixpos, TRUE);
}
#if defined(FEAT_MBYTE) || defined(PROTO)
/*
* Like del_bytes(), but delete characters instead of bytes.
*/
int
del_chars(count, fixpos)
long count;
int fixpos;
{
long bytes = 0;
long i;
char_u *p;
int l;
p = ml_get_cursor();
for (i = 0; i < count && *p != NUL; ++i)
{
l = (*mb_ptr2len)(p);
bytes += l;
p += l;
}
return del_bytes(bytes, fixpos, TRUE);
}
#endif
/*
* Delete "count" bytes under the cursor.
* If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
* Caller must have prepared for undo.
*
* return FAIL for failure, OK otherwise
*/
int
del_bytes(count, fixpos_arg, use_delcombine)
long count;
int fixpos_arg;
int use_delcombine UNUSED; /* 'delcombine' option applies */
{
char_u *oldp, *newp;
colnr_T oldlen;
linenr_T lnum = curwin->w_cursor.lnum;
colnr_T col = curwin->w_cursor.col;
int was_alloced;
long movelen;
int fixpos = fixpos_arg;
oldp = ml_get(lnum);
oldlen = (int)STRLEN(oldp);
/*
* Can't do anything when the cursor is on the NUL after the line.
*/
if (col >= oldlen)
return FAIL;
#ifdef FEAT_MBYTE
/* If 'delcombine' is set and deleting (less than) one character, only
* delete the last combining character. */
if (p_deco && use_delcombine && enc_utf8
&& utfc_ptr2len(oldp + col) >= count)
{
int cc[MAX_MCO];
int n;
(void)utfc_ptr2char(oldp + col, cc);
if (cc[0] != NUL)
{
/* Find the last composing char, there can be several. */
n = col;
do
{
col = n;
count = utf_ptr2len(oldp + n);
n += count;
} while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
fixpos = 0;
}
}
#endif
/*
* When count is too big, reduce it.
*/
movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
if (movelen <= 1)
{
/*
* If we just took off the last character of a non-blank line, and
* fixpos is TRUE, we don't want to end up positioned at the NUL,
* unless "restart_edit" is set or 'virtualedit' contains "onemore".
*/
if (col > 0 && fixpos && restart_edit == 0
#ifdef FEAT_VIRTUALEDIT
&& (ve_flags & VE_ONEMORE) == 0
#endif
)
{
--curwin->w_cursor.col;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_MBYTE
if (has_mbyte)
curwin->w_cursor.col -=
(*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
#endif
}
count = oldlen - col;
movelen = 1;
}
/*
* If the old line has been allocated the deletion can be done in the
* existing line. Otherwise a new line has to be allocated
* Can't do this when using Netbeans, because we would need to invoke
* netbeans_removed(), which deallocates the line. Let ml_replace() take
* care of notifying Netbeans.
*/
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active())
was_alloced = FALSE;
else
#endif
was_alloced = ml_line_alloced(); /* check if oldp was allocated */
if (was_alloced)
newp = oldp; /* use same allocated memory */
else
{ /* need to allocate a new line */
newp = alloc((unsigned)(oldlen + 1 - count));
if (newp == NULL)
return FAIL;
mch_memmove(newp, oldp, (size_t)col);
}
mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
if (!was_alloced)
ml_replace(lnum, newp, FALSE);
/* mark the buffer as changed and prepare for displaying */
changed_bytes(lnum, curwin->w_cursor.col);
return OK;
}
/*
* Delete from cursor to end of line.
* Caller must have prepared for undo.
*
* return FAIL for failure, OK otherwise
*/
int
truncate_line(fixpos)
int fixpos; /* if TRUE fix the cursor position when done */
{
char_u *newp;
linenr_T lnum = curwin->w_cursor.lnum;
colnr_T col = curwin->w_cursor.col;
if (col == 0)
newp = vim_strsave((char_u *)"");
else
newp = vim_strnsave(ml_get(lnum), col);
if (newp == NULL)
return FAIL;
ml_replace(lnum, newp, FALSE);
/* mark the buffer as changed and prepare for displaying */
changed_bytes(lnum, curwin->w_cursor.col);
/*
* If "fixpos" is TRUE we don't want to end up positioned at the NUL.
*/
if (fixpos && curwin->w_cursor.col > 0)
--curwin->w_cursor.col;
return OK;
}
/*
* Delete "nlines" lines at the cursor.
* Saves the lines for undo first if "undo" is TRUE.
*/
void
del_lines(nlines, undo)
long nlines; /* number of lines to delete */
int undo; /* if TRUE, prepare for undo */
{
long n;
linenr_T first = curwin->w_cursor.lnum;
if (nlines <= 0)
return;
/* save the deleted lines for undo */
if (undo && u_savedel(first, nlines) == FAIL)
return;
for (n = 0; n < nlines; )
{
if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
break;
ml_delete(first, TRUE);
++n;
/* If we delete the last line in the file, stop */
if (first > curbuf->b_ml.ml_line_count)
break;
}
/* Correct the cursor position before calling deleted_lines_mark(), it may
* trigger a callback to display the cursor. */
curwin->w_cursor.col = 0;
check_cursor_lnum();
/* adjust marks, mark the buffer as changed and prepare for displaying */
deleted_lines_mark(first, n);
}
int
gchar_pos(pos)
pos_T *pos;
{
char_u *ptr = ml_get_pos(pos);
#ifdef FEAT_MBYTE
if (has_mbyte)
return (*mb_ptr2char)(ptr);
#endif
return (int)*ptr;
}
int
gchar_cursor()
{
#ifdef FEAT_MBYTE
if (has_mbyte)
return (*mb_ptr2char)(ml_get_cursor());
#endif
return (int)*ml_get_cursor();
}
/*
* Write a character at the current cursor position.
* It is directly written into the block.
*/
void
pchar_cursor(c)
int c;
{
*(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
+ curwin->w_cursor.col) = c;
}
/*
* When extra == 0: Return TRUE if the cursor is before or on the first
* non-blank in the line.
* When extra == 1: Return TRUE if the cursor is before the first non-blank in
* the line.
*/
int
inindent(extra)
int extra;
{
char_u *ptr;
colnr_T col;
for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
++ptr;
if (col >= curwin->w_cursor.col + extra)
return TRUE;
else
return FALSE;
}
/*
* Skip to next part of an option argument: Skip space and comma.
*/
char_u *
skip_to_option_part(p)
char_u *p;
{
if (*p == ',')
++p;
while (*p == ' ')
++p;
return p;
}
/*
* Call this function when something in the current buffer is changed.
*
* Most often called through changed_bytes() and changed_lines(), which also
* mark the area of the display to be redrawn.
*
* Careful: may trigger autocommands that reload the buffer.
*/
void
changed()
{
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
/* The text of the preediting area is inserted, but this doesn't
* mean a change of the buffer yet. That is delayed until the
* text is committed. (this means preedit becomes empty) */
if (im_is_preediting() && !xim_changed_while_preediting)
return;
xim_changed_while_preediting = FALSE;
#endif
if (!curbuf->b_changed)
{
int save_msg_scroll = msg_scroll;
/* Give a warning about changing a read-only file. This may also
* check-out the file, thus change "curbuf"! */
change_warning(0);
/* Create a swap file if that is wanted.
* Don't do this for "nofile" and "nowrite" buffer types. */
if (curbuf->b_may_swap
#ifdef FEAT_QUICKFIX
&& !bt_dontwrite(curbuf)
#endif
)
{
ml_open_file(curbuf);
/* The ml_open_file() can cause an ATTENTION message.
* Wait two seconds, to make sure the user reads this unexpected
* message. Since we could be anywhere, call wait_return() now,
* and don't let the emsg() set msg_scroll. */
if (need_wait_return && emsg_silent == 0)
{
out_flush();
ui_delay(2000L, TRUE);
wait_return(TRUE);
msg_scroll = save_msg_scroll;
}
}
changed_int();
}
++curbuf->b_changedtick;
}
/*
* Internal part of changed(), no user interaction.
*/
void
changed_int()
{
curbuf->b_changed = TRUE;
ml_setflags(curbuf);
#ifdef FEAT_WINDOWS
check_status(curbuf);
redraw_tabline = TRUE;
#endif
#ifdef FEAT_TITLE
need_maketitle = TRUE; /* set window title later */
#endif
}
static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
/*
* Changed bytes within a single line for the current buffer.
* - marks the windows on this buffer to be redisplayed
* - marks the buffer changed by calling changed()
* - invalidates cached values
* Careful: may trigger autocommands that reload the buffer.
*/
void
changed_bytes(lnum, col)
linenr_T lnum;
colnr_T col;
{
changedOneline(curbuf, lnum);
changed_common(lnum, col, lnum + 1, 0L);
#ifdef FEAT_DIFF
/* Diff highlighting in other diff windows may need to be updated too. */
if (curwin->w_p_diff)
{
win_T *wp;
linenr_T wlnum;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_p_diff && wp != curwin)
{
redraw_win_later(wp, VALID);
wlnum = diff_lnum_win(lnum, wp);
if (wlnum > 0)
changedOneline(wp->w_buffer, wlnum);
}
}
#endif
}
static void
changedOneline(buf, lnum)
buf_T *buf;
linenr_T lnum;
{
if (buf->b_mod_set)
{
/* find the maximum area that must be redisplayed */
if (lnum < buf->b_mod_top)
buf->b_mod_top = lnum;
else if (lnum >= buf->b_mod_bot)
buf->b_mod_bot = lnum + 1;
}
else
{
/* set the area that must be redisplayed to one line */
buf->b_mod_set = TRUE;
buf->b_mod_top = lnum;
buf->b_mod_bot = lnum + 1;
buf->b_mod_xlines = 0;
}
}
/*
* Appended "count" lines below line "lnum" in the current buffer.
* Must be called AFTER the change and after mark_adjust().
* Takes care of marking the buffer to be redrawn and sets the changed flag.
*/
void
appended_lines(lnum, count)
linenr_T lnum;
long count;
{
changed_lines(lnum + 1, 0, lnum + 1, count);
}
/*
* Like appended_lines(), but adjust marks first.
*/
void
appended_lines_mark(lnum, count)
linenr_T lnum;
long count;
{
mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
changed_lines(lnum + 1, 0, lnum + 1, count);
}
/*
* Deleted "count" lines at line "lnum" in the current buffer.
* Must be called AFTER the change and after mark_adjust().
* Takes care of marking the buffer to be redrawn and sets the changed flag.
*/
void
deleted_lines(lnum, count)
linenr_T lnum;
long count;
{
changed_lines(lnum, 0, lnum + count, -count);
}
/*
* Like deleted_lines(), but adjust marks first.
* Make sure the cursor is on a valid line before calling, a GUI callback may
* be triggered to display the cursor.
*/
void
deleted_lines_mark(lnum, count)
linenr_T lnum;
long count;
{
mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
changed_lines(lnum, 0, lnum + count, -count);
}
/*
* Changed lines for the current buffer.
* Must be called AFTER the change and after mark_adjust().
* - mark the buffer changed by calling changed()
* - mark the windows on this buffer to be redisplayed
* - invalidate cached values
* "lnum" is the first line that needs displaying, "lnume" the first line
* below the changed lines (BEFORE the change).
* When only inserting lines, "lnum" and "lnume" are equal.
* Takes care of calling changed() and updating b_mod_*.
* Careful: may trigger autocommands that reload the buffer.
*/
void
changed_lines(lnum, col, lnume, xtra)
linenr_T lnum; /* first line with change */
colnr_T col; /* column in first line with change */
linenr_T lnume; /* line below last changed line */
long xtra; /* number of extra lines (negative when deleting) */
{
changed_lines_buf(curbuf, lnum, lnume, xtra);
#ifdef FEAT_DIFF
if (xtra == 0 && curwin->w_p_diff)
{
/* When the number of lines doesn't change then mark_adjust() isn't
* called and other diff buffers still need to be marked for
* displaying. */
win_T *wp;
linenr_T wlnum;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_p_diff && wp != curwin)
{
redraw_win_later(wp, VALID);
wlnum = diff_lnum_win(lnum, wp);
if (wlnum > 0)
changed_lines_buf(wp->w_buffer, wlnum,
lnume - lnum + wlnum, 0L);
}
}
#endif
changed_common(lnum, col, lnume, xtra);
}
static void
changed_lines_buf(buf, lnum, lnume, xtra)
buf_T *buf;
linenr_T lnum; /* first line with change */
linenr_T lnume; /* line below last changed line */
long xtra; /* number of extra lines (negative when deleting) */
{
if (buf->b_mod_set)
{
/* find the maximum area that must be redisplayed */
if (lnum < buf->b_mod_top)
buf->b_mod_top = lnum;
if (lnum < buf->b_mod_bot)
{
/* adjust old bot position for xtra lines */
buf->b_mod_bot += xtra;
if (buf->b_mod_bot < lnum)
buf->b_mod_bot = lnum;
}
if (lnume + xtra > buf->b_mod_bot)
buf->b_mod_bot = lnume + xtra;
buf->b_mod_xlines += xtra;
}
else
{
/* set the area that must be redisplayed */
buf->b_mod_set = TRUE;
buf->b_mod_top = lnum;
buf->b_mod_bot = lnume + xtra;
buf->b_mod_xlines = xtra;
}
}
/*
* Common code for when a change is was made.
* See changed_lines() for the arguments.
* Careful: may trigger autocommands that reload the buffer.
*/
static void
changed_common(lnum, col, lnume, xtra)
linenr_T lnum;
colnr_T col;
linenr_T lnume;
long xtra;
{
win_T *wp;
#ifdef FEAT_WINDOWS
tabpage_T *tp;
#endif
int i;
#ifdef FEAT_JUMPLIST
int cols;
pos_T *p;
int add;
#endif
/* mark the buffer as modified */
changed();
/* set the '. mark */
if (!cmdmod.keepjumps)
{
curbuf->b_last_change.lnum = lnum;
curbuf->b_last_change.col = col;
#ifdef FEAT_JUMPLIST
/* Create a new entry if a new undo-able change was started or we
* don't have an entry yet. */
if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
{
if (curbuf->b_changelistlen == 0)
add = TRUE;
else
{
/* Don't create a new entry when the line number is the same
* as the last one and the column is not too far away. Avoids
* creating many entries for typing "xxxxx". */
p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
if (p->lnum != lnum)
add = TRUE;
else
{
cols = comp_textwidth(FALSE);
if (cols == 0)
cols = 79;
add = (p->col + cols < col || col + cols < p->col);
}
}
if (add)
{
/* This is the first of a new sequence of undo-able changes
* and it's at some distance of the last change. Use a new
* position in the changelist. */
curbuf->b_new_change = FALSE;
if (curbuf->b_changelistlen == JUMPLISTSIZE)
{
/* changelist is full: remove oldest entry */
curbuf->b_changelistlen = JUMPLISTSIZE - 1;
mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
sizeof(pos_T) * (JUMPLISTSIZE - 1));
FOR_ALL_TAB_WINDOWS(tp, wp)
{
/* Correct position in changelist for other windows on
* this buffer. */
if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
--wp->w_changelistidx;
}
}
FOR_ALL_TAB_WINDOWS(tp, wp)
{
/* For other windows, if the position in the changelist is
* at the end it stays at the end. */
if (wp->w_buffer == curbuf
&& wp->w_changelistidx == curbuf->b_changelistlen)
++wp->w_changelistidx;
}
++curbuf->b_changelistlen;
}
}
curbuf->b_changelist[curbuf->b_changelistlen - 1] =
curbuf->b_last_change;
/* The current window is always after the last change, so that "g,"
* takes you back to it. */
curwin->w_changelistidx = curbuf->b_changelistlen;
#endif
}
FOR_ALL_TAB_WINDOWS(tp, wp)
{
if (wp->w_buffer == curbuf)
{
/* Mark this window to be redrawn later. */
if (wp->w_redr_type < VALID)
wp->w_redr_type = VALID;
/* Check if a change in the buffer has invalidated the cached
* values for the cursor. */
#ifdef FEAT_FOLDING
/*
* Update the folds for this window. Can't postpone this, because
* a following operator might work on the whole fold: ">>dd".
*/
foldUpdate(wp, lnum, lnume + xtra - 1);
/* The change may cause lines above or below the change to become
* included in a fold. Set lnum/lnume to the first/last line that
* might be displayed differently.
* Set w_cline_folded here as an efficient way to update it when
* inserting lines just above a closed fold. */
i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
if (wp->w_cursor.lnum == lnum)
wp->w_cline_folded = i;
i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
if (wp->w_cursor.lnum == lnume)
wp->w_cline_folded = i;
/* If the changed line is in a range of previously folded lines,
* compare with the first line in that range. */
if (wp->w_cursor.lnum <= lnum)
{
i = find_wl_entry(wp, lnum);
if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
changed_line_abv_curs_win(wp);
}
#endif
if (wp->w_cursor.lnum > lnum)
changed_line_abv_curs_win(wp);
else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
changed_cline_bef_curs_win(wp);
if (wp->w_botline >= lnum)
{
/* Assume that botline doesn't change (inserted lines make
* other lines scroll down below botline). */
approximate_botline_win(wp);
}
/* Check if any w_lines[] entries have become invalid.
* For entries below the change: Correct the lnums for
* inserted/deleted lines. Makes it possible to stop displaying
* after the change. */
for (i = 0; i < wp->w_lines_valid; ++i)
if (wp->w_lines[i].wl_valid)
{
if (wp->w_lines[i].wl_lnum >= lnum)
{
if (wp->w_lines[i].wl_lnum < lnume)
{
/* line included in change */
wp->w_lines[i].wl_valid = FALSE;
}
else if (xtra != 0)
{
/* line below change */
wp->w_lines[i].wl_lnum += xtra;
#ifdef FEAT_FOLDING
wp->w_lines[i].wl_lastlnum += xtra;
#endif
}
}
#ifdef FEAT_FOLDING
else if (wp->w_lines[i].wl_lastlnum >= lnum)
{
/* change somewhere inside this range of folded lines,
* may need to be redrawn */
wp->w_lines[i].wl_valid = FALSE;
}
#endif
}
#ifdef FEAT_FOLDING
/* Take care of side effects for setting w_topline when folds have
* changed. Esp. when the buffer was changed in another window. */
if (hasAnyFolding(wp))
set_topline(wp, wp->w_topline);
#endif
}
}
/* Call update_screen() later, which checks out what needs to be redrawn,
* since it notices b_mod_set and then uses b_mod_*. */
if (must_redraw < VALID)
must_redraw = VALID;
#ifdef FEAT_AUTOCMD
/* when the cursor line is changed always trigger CursorMoved */
if (lnum <= curwin->w_cursor.lnum
&& lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
last_cursormoved.lnum = 0;
#endif
}
/*
* unchanged() is called when the changed flag must be reset for buffer 'buf'
*/
void
unchanged(buf, ff)
buf_T *buf;
int ff; /* also reset 'fileformat' */
{
if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
{
buf->b_changed = 0;
ml_setflags(buf);
if (ff)
save_file_ff(buf);
#ifdef FEAT_WINDOWS
check_status(buf);
redraw_tabline = TRUE;
#endif
#ifdef FEAT_TITLE
need_maketitle = TRUE; /* set window title later */
#endif
}
++buf->b_changedtick;
#ifdef FEAT_NETBEANS_INTG
netbeans_unmodified(buf);
#endif
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* check_status: called when the status bars for the buffer 'buf'
* need to be updated
*/
void
check_status(buf)
buf_T *buf;
{
win_T *wp;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_buffer == buf && wp->w_status_height)
{
wp->w_redr_status = TRUE;
if (must_redraw < VALID)
must_redraw = VALID;
}
}
#endif
/*
* If the file is readonly, give a warning message with the first change.
* Don't do this for autocommands.
* Don't use emsg(), because it flushes the macro buffer.
* If we have undone all changes b_changed will be FALSE, but "b_did_warn"
* will be TRUE.
* Careful: may trigger autocommands that reload the buffer.
*/
void
change_warning(col)
int col; /* column for message; non-zero when in insert
mode and 'showmode' is on */
{
static char *w_readonly = N_("W10: Warning: Changing a readonly file");
if (curbuf->b_did_warn == FALSE
&& curbufIsChanged() == 0
#ifdef FEAT_AUTOCMD
&& !autocmd_busy
#endif
&& curbuf->b_p_ro)
{
#ifdef FEAT_AUTOCMD
++curbuf_lock;
apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
--curbuf_lock;
if (!curbuf->b_p_ro)
return;
#endif
/*
* Do what msg() does, but with a column offset if the warning should
* be after the mode message.
*/
msg_start();
if (msg_row == Rows - 1)
msg_col = col;
msg_source(hl_attr(HLF_W));
MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
#ifdef FEAT_EVAL
set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
#endif
msg_clr_eos();
(void)msg_end();
if (msg_silent == 0 && !silent_mode)
{
out_flush();
ui_delay(1000L, TRUE); /* give the user time to think about it */
}
curbuf->b_did_warn = TRUE;
redraw_cmdline = FALSE; /* don't redraw and erase the message */
if (msg_row < Rows - 1)
showmode();
}
}
/*
* Ask for a reply from the user, a 'y' or a 'n'.
* No other characters are accepted, the message is repeated until a valid
* reply is entered or CTRL-C is hit.
* If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
* from any buffers but directly from the user.
*
* return the 'y' or 'n'
*/
int
ask_yesno(str, direct)
char_u *str;
int direct;
{
int r = ' ';
int save_State = State;
if (exiting) /* put terminal in raw mode for this question */
settmode(TMODE_RAW);
++no_wait_return;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
State = CONFIRM; /* mouse behaves like with :confirm */
#ifdef FEAT_MOUSE
setmouse(); /* disables mouse for xterm */
#endif
++no_mapping;
++allow_keys; /* no mapping here, but recognize keys */
while (r != 'y' && r != 'n')
{
/* same highlighting as for wait_return */
smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
if (direct)
r = get_keystroke();
else
r = plain_vgetc();
if (r == Ctrl_C || r == ESC)
r = 'n';
msg_putchar(r); /* show what you typed */
out_flush();
}
--no_wait_return;
State = save_State;
#ifdef FEAT_MOUSE
setmouse();
#endif
--no_mapping;
--allow_keys;
return r;
}
/*
* Get a key stroke directly from the user.
* Ignores mouse clicks and scrollbar events, except a click for the left
* button (used at the more prompt).
* Doesn't use vgetc(), because it syncs undo and eats mapped characters.
* Disadvantage: typeahead is ignored.
* Translates the interrupt character for unix to ESC.
*/
int
get_keystroke()
{
char_u *buf = NULL;
int buflen = 150;
int maxlen;
int len = 0;
int n;
int save_mapped_ctrl_c = mapped_ctrl_c;
int waited = 0;
mapped_ctrl_c = FALSE; /* mappings are not used here */
for (;;)
{
cursor_on();
out_flush();
/* Leave some room for check_termcode() to insert a key code into (max
* 5 chars plus NUL). And fix_input_buffer() can triple the number of
* bytes. */
maxlen = (buflen - 6 - len) / 3;
if (buf == NULL)
buf = alloc(buflen);
else if (maxlen < 10)
{
/* Need some more space. This might happen when receiving a long
* escape sequence. */
buflen += 100;
buf = vim_realloc(buf, buflen);
maxlen = (buflen - 6 - len) / 3;
}
if (buf == NULL)
{
do_outofmem_msg((long_u)buflen);
return ESC; /* panic! */
}
/* First time: blocking wait. Second time: wait up to 100ms for a
* terminal code to complete. */
n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
if (n > 0)
{
/* Replace zero and CSI by a special key code. */
n = fix_input_buffer(buf + len, n, FALSE);
len += n;
waited = 0;
}
else if (len > 0)
++waited; /* keep track of the waiting time */
/* Incomplete termcode and not timed out yet: get more characters */
if ((n = check_termcode(1, buf, buflen, &len)) < 0
&& (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
continue;
if (n == KEYLEN_REMOVED) /* key code removed */
{
if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
{
/* Redrawing was postponed, do it now. */
update_screen(0);
setcursor(); /* put cursor back where it belongs */
}
continue;
}
if (n > 0) /* found a termcode: adjust length */
len = n;
if (len == 0) /* nothing typed yet */
continue;
/* Handle modifier and/or special key code. */
n = buf[0];
if (n == K_SPECIAL)
{
n = TO_SPECIAL(buf[1], buf[2]);
if (buf[1] == KS_MODIFIER
|| n == K_IGNORE
#ifdef FEAT_MOUSE
|| n == K_LEFTMOUSE_NM
|| n == K_LEFTDRAG
|| n == K_LEFTRELEASE
|| n == K_LEFTRELEASE_NM
|| n == K_MIDDLEMOUSE
|| n == K_MIDDLEDRAG
|| n == K_MIDDLERELEASE
|| n == K_RIGHTMOUSE
|| n == K_RIGHTDRAG
|| n == K_RIGHTRELEASE
|| n == K_MOUSEDOWN
|| n == K_MOUSEUP
|| n == K_MOUSELEFT
|| n == K_MOUSERIGHT
|| n == K_X1MOUSE
|| n == K_X1DRAG
|| n == K_X1RELEASE
|| n == K_X2MOUSE
|| n == K_X2DRAG
|| n == K_X2RELEASE
# ifdef FEAT_GUI
|| n == K_VER_SCROLLBAR
|| n == K_HOR_SCROLLBAR
# endif
#endif
)
{
if (buf[1] == KS_MODIFIER)
mod_mask = buf[2];
len -= 3;
if (len > 0)
mch_memmove(buf, buf + 3, (size_t)len);
continue;
}
break;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
{
if (MB_BYTE2LEN(n) > len)
continue; /* more bytes to get */
buf[len >= buflen ? buflen - 1 : len] = NUL;
n = (*mb_ptr2char)(buf);
}
#endif
#ifdef UNIX
if (n == intr_char)
n = ESC;
#endif
break;
}
vim_free(buf);
mapped_ctrl_c = save_mapped_ctrl_c;
return n;
}
/*
* Get a number from the user.
* When "mouse_used" is not NULL allow using the mouse.
*/
int
get_number(colon, mouse_used)
int colon; /* allow colon to abort */
int *mouse_used;
{
int n = 0;
int c;
int typed = 0;
if (mouse_used != NULL)
*mouse_used = FALSE;
/* When not printing messages, the user won't know what to type, return a
* zero (as if CR was hit). */
if (msg_silent != 0)
return 0;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
++no_mapping;
++allow_keys; /* no mapping here, but recognize keys */
for (;;)
{
windgoto(msg_row, msg_col);
c = safe_vgetc();
if (VIM_ISDIGIT(c))
{
n = n * 10 + c - '0';
msg_putchar(c);
++typed;
}
else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
{
if (typed > 0)
{
MSG_PUTS("\b \b");
--typed;
}
n /= 10;
}
#ifdef FEAT_MOUSE
else if (mouse_used != NULL && c == K_LEFTMOUSE)
{
*mouse_used = TRUE;
n = mouse_row + 1;
break;
}
#endif
else if (n == 0 && c == ':' && colon)
{
stuffcharReadbuff(':');
if (!exmode_active)
cmdline_row = msg_row;
skip_redraw = TRUE; /* skip redraw once */
do_redraw = FALSE;
break;
}
else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
break;
}
--no_mapping;
--allow_keys;
return n;
}
/*
* Ask the user to enter a number.
* When "mouse_used" is not NULL allow using the mouse and in that case return
* the line number.
*/
int
prompt_for_number(mouse_used)
int *mouse_used;
{
int i;
int save_cmdline_row;
int save_State;
/* When using ":silent" assume that <CR> was entered. */
if (mouse_used != NULL)
MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
else
MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
/* Set the state such that text can be selected/copied/pasted and we still
* get mouse events. */
save_cmdline_row = cmdline_row;
cmdline_row = 0;
save_State = State;
State = CMDLINE;
i = get_number(TRUE, mouse_used);
if (KeyTyped)
{
/* don't call wait_return() now */
/* msg_putchar('\n'); */
cmdline_row = msg_row - 1;
need_wait_return = FALSE;
msg_didany = FALSE;
msg_didout = FALSE;
}
else
cmdline_row = save_cmdline_row;
State = save_State;
return i;
}
void
msgmore(n)
long n;
{
long pn;
if (global_busy /* no messages now, wait until global is finished */
|| !messaging()) /* 'lazyredraw' set, don't do messages now */
return;
/* We don't want to overwrite another important message, but do overwrite
* a previous "more lines" or "fewer lines" message, so that "5dd" and
* then "put" reports the last action. */
if (keep_msg != NULL && !keep_msg_more)
return;
if (n > 0)
pn = n;
else
pn = -n;
if (pn > p_report)
{
if (pn == 1)
{
if (n > 0)
vim_strncpy(msg_buf, (char_u *)_("1 more line"),
MSG_BUF_LEN - 1);
else
vim_strncpy(msg_buf, (char_u *)_("1 line less"),
MSG_BUF_LEN - 1);
}
else
{
if (n > 0)
vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
_("%ld more lines"), pn);
else
vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
_("%ld fewer lines"), pn);
}
if (got_int)
vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
if (msg(msg_buf))
{
set_keep_msg(msg_buf, 0);
keep_msg_more = TRUE;
}
}
}
/*
* flush map and typeahead buffers and give a warning for an error
*/
void
beep_flush()
{
if (emsg_silent == 0)
{
flush_buffers(FALSE);
vim_beep();
}
}
/*
* give a warning for an error
*/
void
vim_beep()
{
if (emsg_silent == 0)
{
if (p_vb
#ifdef FEAT_GUI
/* While the GUI is starting up the termcap is set for the GUI
* but the output still goes to a terminal. */
&& !(gui.in_use && gui.starting)
#endif
)
{
out_str(T_VB);
}
else
{
#ifdef MSDOS
/*
* The number of beeps outputted is reduced to avoid having to wait
* for all the beeps to finish. This is only a problem on systems
* where the beeps don't overlap.
*/
if (beep_count == 0 || beep_count == 10)
{
out_char(BELL);
beep_count = 1;
}
else
++beep_count;
#else
out_char(BELL);
#endif
}
/* When 'verbose' is set and we are sourcing a script or executing a
* function give the user a hint where the beep comes from. */
if (vim_strchr(p_debug, 'e') != NULL)
{
msg_source(hl_attr(HLF_W));
msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
}
}
}
/*
* To get the "real" home directory:
* - get value of $HOME
* For Unix:
* - go to that directory
* - do mch_dirname() to get the real name of that directory.
* This also works with mounts and links.
* Don't do this for MS-DOS, it will change the "current dir" for a drive.
*/
static char_u *homedir = NULL;
void
init_homedir()
{
char_u *var;
/* In case we are called a second time (when 'encoding' changes). */
vim_free(homedir);
homedir = NULL;
#ifdef VMS
var = mch_getenv((char_u *)"SYS$LOGIN");
#else
var = mch_getenv((char_u *)"HOME");
#endif
if (var != NULL && *var == NUL) /* empty is same as not set */
var = NULL;
#ifdef WIN3264
/*
* Weird but true: $HOME may contain an indirect reference to another
* variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
* when $HOME is being set.
*/
if (var != NULL && *var == '%')
{
char_u *p;
char_u *exp;
p = vim_strchr(var + 1, '%');
if (p != NULL)
{
vim_strncpy(NameBuff, var + 1, p - (var + 1));
exp = mch_getenv(NameBuff);
if (exp != NULL && *exp != NUL
&& STRLEN(exp) + STRLEN(p) < MAXPATHL)
{
vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
var = NameBuff;
/* Also set $HOME, it's needed for _viminfo. */
vim_setenv((char_u *)"HOME", NameBuff);
}
}
}
/*
* Typically, $HOME is not defined on Windows, unless the user has
* specifically defined it for Vim's sake. However, on Windows NT
* platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
* each user. Try constructing $HOME from these.
*/
if (var == NULL)
{
char_u *homedrive, *homepath;
homedrive = mch_getenv((char_u *)"HOMEDRIVE");
homepath = mch_getenv((char_u *)"HOMEPATH");
if (homepath == NULL || *homepath == NUL)
homepath = "\\";
if (homedrive != NULL
&& STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
{
sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
if (NameBuff[0] != NUL)
{
var = NameBuff;
/* Also set $HOME, it's needed for _viminfo. */
vim_setenv((char_u *)"HOME", NameBuff);
}
}
}
# if defined(FEAT_MBYTE)
if (enc_utf8 && var != NULL)
{
int len;
char_u *pp = NULL;
/* Convert from active codepage to UTF-8. Other conversions are
* not done, because they would fail for non-ASCII characters. */
acp_to_enc(var, (int)STRLEN(var), &pp, &len);
if (pp != NULL)
{
homedir = pp;
return;
}
}
# endif
#endif
#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
/*
* Default home dir is C:/
* Best assumption we can make in such a situation.
*/
if (var == NULL)
var = "C:/";
#endif
if (var != NULL)
{
#ifdef UNIX
/*
* Change to the directory and get the actual path. This resolves
* links. Don't do it when we can't return.
*/
if (mch_dirname(NameBuff, MAXPATHL) == OK
&& mch_chdir((char *)NameBuff) == 0)
{
if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
var = IObuff;
if (mch_chdir((char *)NameBuff) != 0)
EMSG(_(e_prev_dir));
}
#endif
homedir = vim_strsave(var);
}
}
#if defined(EXITFREE) || defined(PROTO)
void
free_homedir()
{
vim_free(homedir);
}
#endif
/*
* Call expand_env() and store the result in an allocated string.
* This is not very memory efficient, this expects the result to be freed
* again soon.
*/
char_u *
expand_env_save(src)
char_u *src;
{
return expand_env_save_opt(src, FALSE);
}
/*
* Idem, but when "one" is TRUE handle the string as one file name, only
* expand "~" at the start.
*/
char_u *
expand_env_save_opt(src, one)
char_u *src;
int one;
{
char_u *p;
p = alloc(MAXPATHL);
if (p != NULL)
expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
return p;
}
/*
* Expand environment variable with path name.
* "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
* Skips over "\ ", "\~" and "\$" (not for Win32 though).
* If anything fails no expansion is done and dst equals src.
*/
void
expand_env(src, dst, dstlen)
char_u *src; /* input string e.g. "$HOME/vim.hlp" */
char_u *dst; /* where to put the result */
int dstlen; /* maximum length of the result */
{
expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
}
void
expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
char_u *dst; /* where to put the result */
int dstlen; /* maximum length of the result */
int esc; /* escape spaces in expanded variables */
int one; /* "srcp" is one file name */
char_u *startstr; /* start again after this (can be NULL) */
{
char_u *src;
char_u *tail;
int c;
char_u *var;
int copy_char;
int mustfree; /* var was allocated, need to free it later */
int at_start = TRUE; /* at start of a name */
int startstr_len = 0;
if (startstr != NULL)
startstr_len = (int)STRLEN(startstr);
src = skipwhite(srcp);
--dstlen; /* leave one char space for "\," */
while (*src && dstlen > 0)
{
copy_char = TRUE;
if ((*src == '$'
#ifdef VMS
&& at_start
#endif
)
#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
|| *src == '%'
#endif
|| (*src == '~' && at_start))
{
mustfree = FALSE;
/*
* The variable name is copied into dst temporarily, because it may
* be a string in read-only memory and a NUL needs to be appended.
*/
if (*src != '~') /* environment var */
{
tail = src + 1;
var = dst;
c = dstlen - 1;
#ifdef UNIX
/* Unix has ${var-name} type environment vars */
if (*tail == '{' && !vim_isIDc('{'))
{
tail++; /* ignore '{' */
while (c-- > 0 && *tail && *tail != '}')
*var++ = *tail++;
}
else
#endif
{
while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
|| (*src == '%' && *tail != '%')
#endif
))
{
#ifdef OS2 /* env vars only in uppercase */
*var++ = TOUPPER_LOC(*tail);
tail++; /* toupper() may be a macro! */
#else
*var++ = *tail++;
#endif
}
}
#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
# ifdef UNIX
if (src[1] == '{' && *tail != '}')
# else
if (*src == '%' && *tail != '%')
# endif
var = NULL;
else
{
# ifdef UNIX
if (src[1] == '{')
# else
if (*src == '%')
#endif
++tail;
#endif
*var = NUL;
var = vim_getenv(dst, &mustfree);
#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
}
#endif
}
/* home directory */
else if ( src[1] == NUL
|| vim_ispathsep(src[1])
|| vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
{
var = homedir;
tail = src + 1;
}
else /* user directory */
{
#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
/*
* Copy ~user to dst[], so we can put a NUL after it.
*/
tail = src;
var = dst;
c = dstlen - 1;
while ( c-- > 0
&& *tail
&& vim_isfilec(*tail)
&& !vim_ispathsep(*tail))
*var++ = *tail++;
*var = NUL;
# ifdef UNIX
/*
* If the system supports getpwnam(), use it.
* Otherwise, or if getpwnam() fails, the shell is used to
* expand ~user. This is slower and may fail if the shell
* does not support ~user (old versions of /bin/sh).
*/
# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
{
struct passwd *pw;
/* Note: memory allocated by getpwnam() is never freed.
* Calling endpwent() apparently doesn't help. */
pw = getpwnam((char *)dst + 1);
if (pw != NULL)
var = (char_u *)pw->pw_dir;
else
var = NULL;
}
if (var == NULL)
# endif
{
expand_T xpc;
ExpandInit(&xpc);
xpc.xp_context = EXPAND_FILES;
var = ExpandOne(&xpc, dst, NULL,
WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
mustfree = TRUE;
}
# else /* !UNIX, thus VMS */
/*
* USER_HOME is a comma-separated list of
* directories to search for the user account in.
*/
{
char_u test[MAXPATHL], paths[MAXPATHL];
char_u *path, *next_path, *ptr;
struct stat st;
STRCPY(paths, USER_HOME);
next_path = paths;
while (*next_path)
{
for (path = next_path; *next_path && *next_path != ',';
next_path++);
if (*next_path)
*next_path++ = NUL;
STRCPY(test, path);
STRCAT(test, "/");
STRCAT(test, dst + 1);
if (mch_stat(test, &st) == 0)
{
var = alloc(STRLEN(test) + 1);
STRCPY(var, test);
mustfree = TRUE;
break;
}
}
}
# endif /* UNIX */
#else
/* cannot expand user's home directory, so don't try */
var = NULL;
tail = (char_u *)""; /* for gcc */
#endif /* UNIX || VMS */
}
#ifdef BACKSLASH_IN_FILENAME
/* If 'shellslash' is set change backslashes to forward slashes.
* Can't use slash_adjust(), p_ssl may be set temporarily. */
if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
{
char_u *p = vim_strsave(var);
if (p != NULL)
{
if (mustfree)
vim_free(var);
var = p;
mustfree = TRUE;
forward_slash(var);
}
}
#endif
/* If "var" contains white space, escape it with a backslash.
* Required for ":e ~/tt" when $HOME includes a space. */
if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
{
char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
if (p != NULL)
{
if (mustfree)
vim_free(var);
var = p;
mustfree = TRUE;
}
}
if (var != NULL && *var != NUL
&& (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
{
STRCPY(dst, var);
dstlen -= (int)STRLEN(var);
c = (int)STRLEN(var);
/* if var[] ends in a path separator and tail[] starts
* with it, skip a character */
if (*var != NUL && after_pathsep(dst, dst + c)
#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
&& dst[-1] != ':'
#endif
&& vim_ispathsep(*tail))
++tail;
dst += c;
src = tail;
copy_char = FALSE;
}
if (mustfree)
vim_free(var);
}
if (copy_char) /* copy at least one char */
{
/*
* Recognize the start of a new name, for '~'.
* Don't do this when "one" is TRUE, to avoid expanding "~" in
* ":edit foo ~ foo".
*/
at_start = FALSE;
if (src[0] == '\\' && src[1] != NUL)
{
*dst++ = *src++;
--dstlen;
}
else if ((src[0] == ' ' || src[0] == ',') && !one)
at_start = TRUE;
*dst++ = *src++;
--dstlen;
if (startstr != NULL && src - startstr_len >= srcp
&& STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
at_start = TRUE;
}
}
*dst = NUL;
}
/*
* Vim's version of getenv().
* Special handling of $HOME, $VIM and $VIMRUNTIME.
* Also does ACP to 'enc' conversion for Win32.
* "mustfree" is set to TRUE when returned is allocated, it must be
* initialized to FALSE by the caller.
*/
char_u *
vim_getenv(name, mustfree)
char_u *name;
int *mustfree;
{
char_u *p;
char_u *pend;
int vimruntime;
#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
/* use "C:/" when $HOME is not set */
if (STRCMP(name, "HOME") == 0)
return homedir;
#endif
p = mch_getenv(name);
if (p != NULL && *p == NUL) /* empty is the same as not set */
p = NULL;
if (p != NULL)
{
#if defined(FEAT_MBYTE) && defined(WIN3264)
if (enc_utf8)
{
int len;
char_u *pp = NULL;
/* Convert from active codepage to UTF-8. Other conversions are
* not done, because they would fail for non-ASCII characters. */
acp_to_enc(p, (int)STRLEN(p), &pp, &len);
if (pp != NULL)
{
p = pp;
*mustfree = TRUE;
}
}
#endif
return p;
}
vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
if (!vimruntime && STRCMP(name, "VIM") != 0)
return NULL;
/*
* When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
* Don't do this when default_vimruntime_dir is non-empty.
*/
if (vimruntime
#ifdef HAVE_PATHDEF
&& *default_vimruntime_dir == NUL
#endif
)
{
p = mch_getenv((char_u *)"VIM");
if (p != NULL && *p == NUL) /* empty is the same as not set */
p = NULL;
if (p != NULL)
{
p = vim_version_dir(p);
if (p != NULL)
*mustfree = TRUE;
else
p = mch_getenv((char_u *)"VIM");
#if defined(FEAT_MBYTE) && defined(WIN3264)
if (enc_utf8)
{
int len;
char_u *pp = NULL;
/* Convert from active codepage to UTF-8. Other conversions
* are not done, because they would fail for non-ASCII
* characters. */
acp_to_enc(p, (int)STRLEN(p), &pp, &len);
if (pp != NULL)
{
if (*mustfree)
vim_free(p);
p = pp;
*mustfree = TRUE;
}
}
#endif
}
}
/*
* When expanding $VIM or $VIMRUNTIME fails, try using:
* - the directory name from 'helpfile' (unless it contains '$')
* - the executable name from argv[0]
*/
if (p == NULL)
{
if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
p = p_hf;
#ifdef USE_EXE_NAME
/*
* Use the name of the executable, obtained from argv[0].
*/
else
p = exe_name;
#endif
if (p != NULL)
{
/* remove the file name */
pend = gettail(p);
/* remove "doc/" from 'helpfile', if present */
if (p == p_hf)
pend = remove_tail(p, pend, (char_u *)"doc");
#ifdef USE_EXE_NAME
# ifdef MACOS_X
/* remove "MacOS" from exe_name and add "Resources/vim" */
if (p == exe_name)
{
char_u *pend1;
char_u *pnew;
pend1 = remove_tail(p, pend, (char_u *)"MacOS");
if (pend1 != pend)
{
pnew = alloc((unsigned)(pend1 - p) + 15);
if (pnew != NULL)
{
STRNCPY(pnew, p, (pend1 - p));
STRCPY(pnew + (pend1 - p), "Resources/vim");
p = pnew;
pend = p + STRLEN(p);
}
}
}
# endif
/* remove "src/" from exe_name, if present */
if (p == exe_name)
pend = remove_tail(p, pend, (char_u *)"src");
#endif
/* for $VIM, remove "runtime/" or "vim54/", if present */
if (!vimruntime)
{
pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
}
/* remove trailing path separator */
#ifndef MACOS_CLASSIC
/* With MacOS path (with colons) the final colon is required */
/* to avoid confusion between absolute and relative path */
if (pend > p && after_pathsep(p, pend))
--pend;
#endif
#ifdef MACOS_X
if (p == exe_name || p == p_hf)
#endif
/* check that the result is a directory name */
p = vim_strnsave(p, (int)(pend - p));
if (p != NULL && !mch_isdir(p))
{
vim_free(p);
p = NULL;
}
else
{
#ifdef USE_EXE_NAME
/* may add "/vim54" or "/runtime" if it exists */
if (vimruntime && (pend = vim_version_dir(p)) != NULL)
{
vim_free(p);
p = pend;
}
#endif
*mustfree = TRUE;
}
}
}
#ifdef HAVE_PATHDEF
/* When there is a pathdef.c file we can use default_vim_dir and
* default_vimruntime_dir */
if (p == NULL)
{
/* Only use default_vimruntime_dir when it is not empty */
if (vimruntime && *default_vimruntime_dir != NUL)
{
p = default_vimruntime_dir;
*mustfree = FALSE;
}
else if (*default_vim_dir != NUL)
{
if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
*mustfree = TRUE;
else
{
p = default_vim_dir;
*mustfree = FALSE;
}
}
}
#endif
/*
* Set the environment variable, so that the new value can be found fast
* next time, and others can also use it (e.g. Perl).
*/
if (p != NULL)
{
if (vimruntime)
{
vim_setenv((char_u *)"VIMRUNTIME", p);
didset_vimruntime = TRUE;
}
else
{
vim_setenv((char_u *)"VIM", p);
didset_vim = TRUE;
}
}
return p;
}
/*
* Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
* Return NULL if not, return its name in allocated memory otherwise.
*/
static char_u *
vim_version_dir(vimdir)
char_u *vimdir;
{
char_u *p;
if (vimdir == NULL || *vimdir == NUL)
return NULL;
p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
if (p != NULL && mch_isdir(p))
return p;
vim_free(p);
p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
if (p != NULL && mch_isdir(p))
return p;
vim_free(p);
return NULL;
}
/*
* If the string between "p" and "pend" ends in "name/", return "pend" minus
* the length of "name/". Otherwise return "pend".
*/
static char_u *
remove_tail(p, pend, name)
char_u *p;
char_u *pend;
char_u *name;
{
int len = (int)STRLEN(name) + 1;
char_u *newend = pend - len;
if (newend >= p
&& fnamencmp(newend, name, len - 1) == 0
&& (newend == p || after_pathsep(p, newend)))
return newend;
return pend;
}
/*
* Our portable version of setenv.
*/
void
vim_setenv(name, val)
char_u *name;
char_u *val;
{
#ifdef HAVE_SETENV
mch_setenv((char *)name, (char *)val, 1);
#else
char_u *envbuf;
/*
* Putenv does not copy the string, it has to remain
* valid. The allocated memory will never be freed.
*/
envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
if (envbuf != NULL)
{
sprintf((char *)envbuf, "%s=%s", name, val);
putenv((char *)envbuf);
}
#endif
#ifdef FEAT_GETTEXT
/*
* When setting $VIMRUNTIME adjust the directory to find message
* translations to $VIMRUNTIME/lang.
*/
if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
{
char_u *buf = concat_str(val, (char_u *)"/lang");
if (buf != NULL)
{
bindtextdomain(VIMPACKAGE, (char *)buf);
vim_free(buf);
}
}
#endif
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Function given to ExpandGeneric() to obtain an environment variable name.
*/
char_u *
get_env_name(xp, idx)
expand_T *xp UNUSED;
int idx;
{
# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
/*
* No environ[] on the Amiga and on the Mac (using MPW).
*/
return NULL;
# else
# ifndef __WIN32__
/* Borland C++ 5.2 has this in a header file. */
extern char **environ;
# endif
# define ENVNAMELEN 100
static char_u name[ENVNAMELEN];
char_u *str;
int n;
str = (char_u *)environ[idx];
if (str == NULL)
return NULL;
for (n = 0; n < ENVNAMELEN - 1; ++n)
{
if (str[n] == '=' || str[n] == NUL)
break;
name[n] = str[n];
}
name[n] = NUL;
return name;
# endif
}
#endif
/*
* Replace home directory by "~" in each space or comma separated file name in
* 'src'.
* If anything fails (except when out of space) dst equals src.
*/
void
home_replace(buf, src, dst, dstlen, one)
buf_T *buf; /* when not NULL, check for help files */
char_u *src; /* input file name */
char_u *dst; /* where to put the result */
int dstlen; /* maximum length of the result */
int one; /* if TRUE, only replace one file name, include
spaces and commas in the file name. */
{
size_t dirlen = 0, envlen = 0;
size_t len;
char_u *homedir_env, *homedir_env_orig;
char_u *p;
if (src == NULL)
{
*dst = NUL;
return;
}
/*
* If the file is a help file, remove the path completely.
*/
if (buf != NULL && buf->b_help)
{
STRCPY(dst, gettail(src));
return;
}
/*
* We check both the value of the $HOME environment variable and the
* "real" home directory.
*/
if (homedir != NULL)
dirlen = STRLEN(homedir);
#ifdef VMS
homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
#else
homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
#endif
#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
if (vim_strchr(homedir_env, '~') != NULL)
{
int usedlen = 0;
int flen;
char_u *fbuf = NULL;
flen = (int)STRLEN(homedir_env);
(void)modify_fname((char_u *)":p", &usedlen,
&homedir_env, &fbuf, &flen);
flen = (int)STRLEN(homedir_env);
if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
/* Remove the trailing / that is added to a directory. */
homedir_env[flen - 1] = NUL;
}
#endif
if (homedir_env != NULL && *homedir_env == NUL)
homedir_env = NULL;
if (homedir_env != NULL)
envlen = STRLEN(homedir_env);
if (!one)
src = skipwhite(src);
while (*src && dstlen > 0)
{
/*
* Here we are at the beginning of a file name.
* First, check to see if the beginning of the file name matches
* $HOME or the "real" home directory. Check that there is a '/'
* after the match (so that if e.g. the file is "/home/pieter/bla",
* and the home directory is "/home/piet", the file does not end up
* as "~er/bla" (which would seem to indicate the file "bla" in user
* er's home directory)).
*/
p = homedir;
len = dirlen;
for (;;)
{
if ( len
&& fnamencmp(src, p, len) == 0
&& (vim_ispathsep(src[len])
|| (!one && (src[len] == ',' || src[len] == ' '))
|| src[len] == NUL))
{
src += len;
if (--dstlen > 0)
*dst++ = '~';
/*
* If it's just the home directory, add "/".
*/
if (!vim_ispathsep(src[0]) && --dstlen > 0)
*dst++ = '/';
break;
}
if (p == homedir_env)
break;
p = homedir_env;
len = envlen;
}
/* if (!one) skip to separator: space or comma */
while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
*dst++ = *src++;
/* skip separator */
while ((*src == ' ' || *src == ',') && --dstlen > 0)
*dst++ = *src++;
}
/* if (dstlen == 0) out of space, what to do??? */
*dst = NUL;
if (homedir_env != homedir_env_orig)
vim_free(homedir_env);
}
/*
* Like home_replace, store the replaced string in allocated memory.
* When something fails, NULL is returned.
*/
char_u *
home_replace_save(buf, src)
buf_T *buf; /* when not NULL, check for help files */
char_u *src; /* input file name */
{
char_u *dst;
unsigned len;
len = 3; /* space for "~/" and trailing NUL */
if (src != NULL) /* just in case */
len += (unsigned)STRLEN(src);
dst = alloc(len);
if (dst != NULL)
home_replace(buf, src, dst, len, TRUE);
return dst;
}
/*
* Compare two file names and return:
* FPC_SAME if they both exist and are the same file.
* FPC_SAMEX if they both don't exist and have the same file name.
* FPC_DIFF if they both exist and are different files.
* FPC_NOTX if they both don't exist.
* FPC_DIFFX if one of them doesn't exist.
* For the first name environment variables are expanded
*/
int
fullpathcmp(s1, s2, checkname)
char_u *s1, *s2;
int checkname; /* when both don't exist, check file names */
{
#ifdef UNIX
char_u exp1[MAXPATHL];
char_u full1[MAXPATHL];
char_u full2[MAXPATHL];
struct stat st1, st2;
int r1, r2;
expand_env(s1, exp1, MAXPATHL);
r1 = mch_stat((char *)exp1, &st1);
r2 = mch_stat((char *)s2, &st2);
if (r1 != 0 && r2 != 0)
{
/* if mch_stat() doesn't work, may compare the names */
if (checkname)
{
if (fnamecmp(exp1, s2) == 0)
return FPC_SAMEX;
r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
return FPC_SAMEX;
}
return FPC_NOTX;
}
if (r1 != 0 || r2 != 0)
return FPC_DIFFX;
if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
return FPC_SAME;
return FPC_DIFF;
#else
char_u *exp1; /* expanded s1 */
char_u *full1; /* full path of s1 */
char_u *full2; /* full path of s2 */
int retval = FPC_DIFF;
int r1, r2;
/* allocate one buffer to store three paths (alloc()/free() is slow!) */
if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
{
full1 = exp1 + MAXPATHL;
full2 = full1 + MAXPATHL;
expand_env(s1, exp1, MAXPATHL);
r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
/* If vim_FullName() fails, the file probably doesn't exist. */
if (r1 != OK && r2 != OK)
{
if (checkname && fnamecmp(exp1, s2) == 0)
retval = FPC_SAMEX;
else
retval = FPC_NOTX;
}
else if (r1 != OK || r2 != OK)
retval = FPC_DIFFX;
else if (fnamecmp(full1, full2))
retval = FPC_DIFF;
else
retval = FPC_SAME;
vim_free(exp1);
}
return retval;
#endif
}
/*
* Get the tail of a path: the file name.
* When the path ends in a path separator the tail is the NUL after it.
* Fail safe: never returns NULL.
*/
char_u *
gettail(fname)
char_u *fname;
{
char_u *p1, *p2;
if (fname == NULL)
return (char_u *)"";
for (p1 = p2 = fname; *p2; ) /* find last part of path */
{
if (vim_ispathsep(*p2))
p1 = p2 + 1;
mb_ptr_adv(p2);
}
return p1;
}
#if defined(FEAT_SEARCHPATH)
static char_u *gettail_dir __ARGS((char_u *fname));
/*
* Return the end of the directory name, on the first path
* separator:
* "/path/file", "/path/dir/", "/path//dir", "/file"
* ^ ^ ^ ^
*/
static char_u *
gettail_dir(fname)
char_u *fname;
{
char_u *dir_end = fname;
char_u *next_dir_end = fname;
int look_for_sep = TRUE;
char_u *p;
for (p = fname; *p != NUL; )
{
if (vim_ispathsep(*p))
{
if (look_for_sep)
{
next_dir_end = p;
look_for_sep = FALSE;
}
}
else
{
if (!look_for_sep)
dir_end = next_dir_end;
look_for_sep = TRUE;
}
mb_ptr_adv(p);
}
return dir_end;
}
#endif
/*
* Get pointer to tail of "fname", including path separators. Putting a NUL
* here leaves the directory name. Takes care of "c:/" and "//".
* Always returns a valid pointer.
*/
char_u *
gettail_sep(fname)
char_u *fname;
{
char_u *p;
char_u *t;
p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
t = gettail(fname);
while (t > p && after_pathsep(fname, t))
--t;
#ifdef VMS
/* path separator is part of the path */
++t;
#endif
return t;
}
/*
* get the next path component (just after the next path separator).
*/
char_u *
getnextcomp(fname)
char_u *fname;
{
while (*fname && !vim_ispathsep(*fname))
mb_ptr_adv(fname);
if (*fname)
++fname;
return fname;
}
/*
* Get a pointer to one character past the head of a path name.
* Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
* If there is no head, path is returned.
*/
char_u *
get_past_head(path)
char_u *path;
{
char_u *retval;
#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
/* may skip "c:" */
if (isalpha(path[0]) && path[1] == ':')
retval = path + 2;
else
retval = path;
#else
# if defined(AMIGA)
/* may skip "label:" */
retval = vim_strchr(path, ':');
if (retval == NULL)
retval = path;
# else /* Unix */
retval = path;
# endif
#endif
while (vim_ispathsep(*retval))
++retval;
return retval;
}
/*
* return TRUE if 'c' is a path separator.
*/
int
vim_ispathsep(c)
int c;
{
#ifdef UNIX
return (c == '/'); /* UNIX has ':' inside file names */
#else
# ifdef BACKSLASH_IN_FILENAME
return (c == ':' || c == '/' || c == '\\');
# else
# ifdef VMS
/* server"user passwd"::device:[full.path.name]fname.extension;version" */
return (c == ':' || c == '[' || c == ']' || c == '/'
|| c == '<' || c == '>' || c == '"' );
# else
return (c == ':' || c == '/');
# endif /* VMS */
# endif
#endif
}
#if defined(FEAT_SEARCHPATH) || defined(PROTO)
/*
* return TRUE if 'c' is a path list separator.
*/
int
vim_ispathlistsep(c)
int c;
{
#ifdef UNIX
return (c == ':');
#else
return (c == ';'); /* might not be right for every system... */
#endif
}
#endif
#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
|| defined(FEAT_EVAL) || defined(PROTO)
/*
* Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
* It's done in-place.
*/
void
shorten_dir(str)
char_u *str;
{
char_u *tail, *s, *d;
int skip = FALSE;
tail = gettail(str);
d = str;
for (s = str; ; ++s)
{
if (s >= tail) /* copy the whole tail */
{
*d++ = *s;
if (*s == NUL)
break;
}
else if (vim_ispathsep(*s)) /* copy '/' and next char */
{
*d++ = *s;
skip = FALSE;
}
else if (!skip)
{
*d++ = *s; /* copy next char */
if (*s != '~' && *s != '.') /* and leading "~" and "." */
skip = TRUE;
# ifdef FEAT_MBYTE
if (has_mbyte)
{
int l = mb_ptr2len(s);
while (--l > 0)
*d++ = *++s;
}
# endif
}
}
}
#endif
/*
* Return TRUE if the directory of "fname" exists, FALSE otherwise.
* Also returns TRUE if there is no directory name.
* "fname" must be writable!.
*/
int
dir_of_file_exists(fname)
char_u *fname;
{
char_u *p;
int c;
int retval;
p = gettail_sep(fname);
if (p == fname)
return TRUE;
c = *p;
*p = NUL;
retval = mch_isdir(fname);
*p = c;
return retval;
}
#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
|| defined(PROTO)
/*
* Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
*/
int
vim_fnamecmp(x, y)
char_u *x, *y;
{
return vim_fnamencmp(x, y, MAXPATHL);
}
int
vim_fnamencmp(x, y, len)
char_u *x, *y;
size_t len;
{
while (len > 0 && *x && *y)
{
if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
&& !(*x == '/' && *y == '\\')
&& !(*x == '\\' && *y == '/'))
break;
++x;
++y;
--len;
}
if (len == 0)
return 0;
return (*x - *y);
}
#endif
/*
* Concatenate file names fname1 and fname2 into allocated memory.
* Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
*/
char_u *
concat_fnames(fname1, fname2, sep)
char_u *fname1;
char_u *fname2;
int sep;
{
char_u *dest;
dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
if (dest != NULL)
{
STRCPY(dest, fname1);
if (sep)
add_pathsep(dest);
STRCAT(dest, fname2);
}
return dest;
}
/*
* Concatenate two strings and return the result in allocated memory.
* Returns NULL when out of memory.
*/
char_u *
concat_str(str1, str2)
char_u *str1;
char_u *str2;
{
char_u *dest;
size_t l = STRLEN(str1);
dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
if (dest != NULL)
{
STRCPY(dest, str1);
STRCPY(dest + l, str2);
}
return dest;
}
/*
* Add a path separator to a file name, unless it already ends in a path
* separator.
*/
void
add_pathsep(p)
char_u *p;
{
if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
STRCAT(p, PATHSEPSTR);
}
/*
* FullName_save - Make an allocated copy of a full file name.
* Returns NULL when out of memory.
*/
char_u *
FullName_save(fname, force)
char_u *fname;
int force; /* force expansion, even when it already looks
* like a full path name */
{
char_u *buf;
char_u *new_fname = NULL;
if (fname == NULL)
return NULL;
buf = alloc((unsigned)MAXPATHL);
if (buf != NULL)
{
if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
new_fname = vim_strsave(buf);
else
new_fname = vim_strsave(fname);
vim_free(buf);
}
return new_fname;
}
#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
static char_u *skip_string __ARGS((char_u *p));
/*
* Find the start of a comment, not knowing if we are in a comment right now.
* Search starts at w_cursor.lnum and goes backwards.
*/
pos_T *
find_start_comment(ind_maxcomment) /* XXX */
int ind_maxcomment;
{
pos_T *pos;
char_u *line;
char_u *p;
int cur_maxcomment = ind_maxcomment;
for (;;)
{
pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
if (pos == NULL)
break;
/*
* Check if the comment start we found is inside a string.
* If it is then restrict the search to below this line and try again.
*/
line = ml_get(pos->lnum);
for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
p = skip_string(p);
if ((colnr_T)(p - line) <= pos->col)
break;
cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
if (cur_maxcomment <= 0)
{
pos = NULL;
break;
}
}
return pos;
}
/*
* Skip to the end of a "string" and a 'c' character.
* If there is no string or character, return argument unmodified.
*/
static char_u *
skip_string(p)
char_u *p;
{
int i;
/*
* We loop, because strings may be concatenated: "date""time".
*/
for ( ; ; ++p)
{
if (p[0] == '\'') /* 'c' or '\n' or '\000' */
{
if (!p[1]) /* ' at end of line */
break;
i = 2;
if (p[1] == '\\') /* '\n' or '\000' */
{
++i;
while (vim_isdigit(p[i - 1])) /* '\000' */
++i;
}
if (p[i] == '\'') /* check for trailing ' */
{
p += i;
continue;
}
}
else if (p[0] == '"') /* start of string */
{
for (++p; p[0]; ++p)
{
if (p[0] == '\\' && p[1] != NUL)
++p;
else if (p[0] == '"') /* end of string */
break;
}
if (p[0] == '"')
continue;
}
break; /* no string found */
}
if (!*p)
--p; /* backup from NUL */
return p;
}
#endif /* FEAT_CINDENT || FEAT_SYN_HL */
#if defined(FEAT_CINDENT) || defined(PROTO)
/*
* Do C or expression indenting on the current line.
*/
void
do_c_expr_indent()
{
# ifdef FEAT_EVAL
if (*curbuf->b_p_inde != NUL)
fixthisline(get_expr_indent);
else
# endif
fixthisline(get_c_indent);
}
/*
* Functions for C-indenting.
* Most of this originally comes from Eric Fischer.
*/
/*
* Below "XXX" means that this function may unlock the current line.
*/
static char_u *cin_skipcomment __ARGS((char_u *));
static int cin_nocode __ARGS((char_u *));
static pos_T *find_line_comment __ARGS((void));
static int cin_islabel_skip __ARGS((char_u **));
static int cin_isdefault __ARGS((char_u *));
static char_u *after_label __ARGS((char_u *l));
static int get_indent_nolabel __ARGS((linenr_T lnum));
static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
static int cin_first_id_amount __ARGS((void));
static int cin_get_equal_amount __ARGS((linenr_T lnum));
static int cin_ispreproc __ARGS((char_u *));
static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
static int cin_iscomment __ARGS((char_u *));
static int cin_islinecomment __ARGS((char_u *));
static int cin_isterminated __ARGS((char_u *, int, int));
static int cin_isinit __ARGS((void));
static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
static int cin_isif __ARGS((char_u *));
static int cin_iselse __ARGS((char_u *));
static int cin_isdo __ARGS((char_u *));
static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
static int cin_isbreak __ARGS((char_u *));
static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
static int cin_skip2pos __ARGS((pos_T *trypos));
static pos_T *find_start_brace __ARGS((int));
static pos_T *find_match_paren __ARGS((int, int));
static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
static int find_last_paren __ARGS((char_u *l, int start, int end));
static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
static int cin_is_cpp_namespace __ARGS((char_u *));
static int ind_hash_comment = 0; /* # starts a comment */
/*
* Skip over white space and C comments within the line.
* Also skip over Perl/shell comments if desired.
*/
static char_u *
cin_skipcomment(s)
char_u *s;
{
while (*s)
{
char_u *prev_s = s;
s = skipwhite(s);
/* Perl/shell # comment comment continues until eol. Require a space
* before # to avoid recognizing $#array. */
if (ind_hash_comment != 0 && s != prev_s && *s == '#')
{
s += STRLEN(s);
break;
}
if (*s != '/')
break;
++s;
if (*s == '/') /* slash-slash comment continues till eol */
{
s += STRLEN(s);
break;
}
if (*s != '*')
break;
for (++s; *s; ++s) /* skip slash-star comment */
if (s[0] == '*' && s[1] == '/')
{
s += 2;
break;
}
}
return s;
}
/*
* Return TRUE if there is no code at *s. White space and comments are
* not considered code.
*/
static int
cin_nocode(s)
char_u *s;
{
return *cin_skipcomment(s) == NUL;
}
/*
* Check previous lines for a "//" line comment, skipping over blank lines.
*/
static pos_T *
find_line_comment() /* XXX */
{
static pos_T pos;
char_u *line;
char_u *p;
pos = curwin->w_cursor;
while (--pos.lnum > 0)
{
line = ml_get(pos.lnum);
p = skipwhite(line);
if (cin_islinecomment(p))
{
pos.col = (int)(p - line);
return &pos;
}
if (*p != NUL)
break;
}
return NULL;
}
/*
* Check if string matches "label:"; move to character after ':' if true.
*/
static int
cin_islabel_skip(s)
char_u **s;
{
if (!vim_isIDc(**s)) /* need at least one ID character */
return FALSE;
while (vim_isIDc(**s))
(*s)++;
*s = cin_skipcomment(*s);
/* "::" is not a label, it's C++ */
return (**s == ':' && *++*s != ':');
}
/*
* Recognize a label: "label:".
* Note: curwin->w_cursor must be where we are looking for the label.
*/
int
cin_islabel(ind_maxcomment) /* XXX */
int ind_maxcomment;
{
char_u *s;
s = cin_skipcomment(ml_get_curline());
/*
* Exclude "default" from labels, since it should be indented
* like a switch label. Same for C++ scope declarations.
*/
if (cin_isdefault(s))
return FALSE;
if (cin_isscopedecl(s))
return FALSE;
if (cin_islabel_skip(&s))
{
/*
* Only accept a label if the previous line is terminated or is a case
* label.
*/
pos_T cursor_save;
pos_T *trypos;
char_u *line;
cursor_save = curwin->w_cursor;
while (curwin->w_cursor.lnum > 1)
{
--curwin->w_cursor.lnum;
/*
* If we're in a comment now, skip to the start of the comment.
*/
curwin->w_cursor.col = 0;
if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
curwin->w_cursor = *trypos;
line = ml_get_curline();
if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
continue;
if (*(line = cin_skipcomment(line)) == NUL)
continue;
curwin->w_cursor = cursor_save;
if (cin_isterminated(line, TRUE, FALSE)
|| cin_isscopedecl(line)
|| cin_iscase(line, TRUE)
|| (cin_islabel_skip(&line) && cin_nocode(line)))
return TRUE;
return FALSE;
}
curwin->w_cursor = cursor_save;
return TRUE; /* label at start of file??? */
}
return FALSE;
}
/*
* Recognize structure initialization and enumerations.
* Q&D-Implementation:
* check for "=" at end or "[typedef] enum" at beginning of line.
*/
static int
cin_isinit(void)
{
char_u *s;
s = cin_skipcomment(ml_get_curline());
if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
s = cin_skipcomment(s + 7);
if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
s = cin_skipcomment(s + 6);
if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
return TRUE;
if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
return TRUE;
return FALSE;
}
/*
* Recognize a switch label: "case .*:" or "default:".
*/
int
cin_iscase(s, strict)
char_u *s;
int strict; /* Allow relaxed check of case statement for JS */
{
s = cin_skipcomment(s);
if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
{
for (s += 4; *s; ++s)
{
s = cin_skipcomment(s);
if (*s == ':')
{
if (s[1] == ':') /* skip over "::" for C++ */
++s;
else
return TRUE;
}
if (*s == '\'' && s[1] && s[2] == '\'')
s += 2; /* skip over ':' */
else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
return FALSE; /* stop at comment */
else if (*s == '"')
{
/* JS etc. */
if (strict)
return FALSE; /* stop at string */
else
return TRUE;
}
}
return FALSE;
}
if (cin_isdefault(s))
return TRUE;
return FALSE;
}
/*
* Recognize a "default" switch label.
*/
static int
cin_isdefault(s)
char_u *s;
{
return (STRNCMP(s, "default", 7) == 0
&& *(s = cin_skipcomment(s + 7)) == ':'
&& s[1] != ':');
}
/*
* Recognize a "public/private/protected" scope declaration label.
*/
int
cin_isscopedecl(s)
char_u *s;
{
int i;
s = cin_skipcomment(s);
if (STRNCMP(s, "public", 6) == 0)
i = 6;
else if (STRNCMP(s, "protected", 9) == 0)
i = 9;
else if (STRNCMP(s, "private", 7) == 0)
i = 7;
else
return FALSE;
return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
}
/* Maximum number of lines to search back for a "namespace" line. */
#define FIND_NAMESPACE_LIM 20
/*
* Recognize a "namespace" scope declaration.
*/
static int
cin_is_cpp_namespace(s)
char_u *s;
{
char_u *p;
int has_name = FALSE;
s = cin_skipcomment(s);
if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
{
p = cin_skipcomment(skipwhite(s + 9));
while (*p != NUL)
{
if (vim_iswhite(*p))
{
has_name = TRUE; /* found end of a name */
p = cin_skipcomment(skipwhite(p));
}
else if (*p == '{')
{
break;
}
else if (vim_iswordc(*p))
{
if (has_name)
return FALSE; /* word character after skipping past name */
++p;
}
else
{
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
/*
* Return a pointer to the first non-empty non-comment character after a ':'.
* Return NULL if not found.
* case 234: a = b;
* ^
*/
static char_u *
after_label(l)
char_u *l;
{
for ( ; *l; ++l)
{
if (*l == ':')
{
if (l[1] == ':') /* skip over "::" for C++ */
++l;
else if (!cin_iscase(l + 1, FALSE))
break;
}
else if (*l == '\'' && l[1] && l[2] == '\'')
l += 2; /* skip over 'x' */
}
if (*l == NUL)
return NULL;
l = cin_skipcomment(l + 1);
if (*l == NUL)
return NULL;
return l;
}
/*
* Get indent of line "lnum", skipping a label.
* Return 0 if there is nothing after the label.
*/
static int
get_indent_nolabel(lnum) /* XXX */
linenr_T lnum;
{
char_u *l;
pos_T fp;
colnr_T col;
char_u *p;
l = ml_get(lnum);
p = after_label(l);
if (p == NULL)
return 0;
fp.col = (colnr_T)(p - l);
fp.lnum = lnum;
getvcol(curwin, &fp, &col, NULL, NULL);
return (int)col;
}
/*
* Find indent for line "lnum", ignoring any case or jump label.
* Also return a pointer to the text (after the label) in "pp".
* label: if (asdf && asdfasdf)
* ^
*/
static int
skip_label(lnum, pp, ind_maxcomment)
linenr_T lnum;
char_u **pp;
int ind_maxcomment;
{
char_u *l;
int amount;
pos_T cursor_save;
cursor_save = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
l = ml_get_curline();
/* XXX */
if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
|| cin_islabel(ind_maxcomment))
{
amount = get_indent_nolabel(lnum);
l = after_label(ml_get_curline());
if (l == NULL) /* just in case */
l = ml_get_curline();
}
else
{
amount = get_indent();
l = ml_get_curline();
}
*pp = l;
curwin->w_cursor = cursor_save;
return amount;
}
/*
* Return the indent of the first variable name after a type in a declaration.
* int a, indent of "a"
* static struct foo b, indent of "b"
* enum bla c, indent of "c"
* Returns zero when it doesn't look like a declaration.
*/
static int
cin_first_id_amount()
{
char_u *line, *p, *s;
int len;
pos_T fp;
colnr_T col;
line = ml_get_curline();
p = skipwhite(line);
len = (int)(skiptowhite(p) - p);
if (len == 6 && STRNCMP(p, "static", 6) == 0)
{
p = skipwhite(p + 6);
len = (int)(skiptowhite(p) - p);
}
if (len == 6 && STRNCMP(p, "struct", 6) == 0)
p = skipwhite(p + 6);
else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
p = skipwhite(p + 4);
else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
|| (len == 6 && STRNCMP(p, "signed", 6) == 0))
{
s = skipwhite(p + len);
if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
|| (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
|| (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
|| (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
p = s;
}
for (len = 0; vim_isIDc(p[len]); ++len)
;
if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
return 0;
p = skipwhite(p + len);
fp.lnum = curwin->w_cursor.lnum;
fp.col = (colnr_T)(p - line);
getvcol(curwin, &fp, &col, NULL, NULL);
return (int)col;
}
/*
* Return the indent of the first non-blank after an equal sign.
* char *foo = "here";
* Return zero if no (useful) equal sign found.
* Return -1 if the line above "lnum" ends in a backslash.
* foo = "asdf\
* asdf\
* here";
*/
static int
cin_get_equal_amount(lnum)
linenr_T lnum;
{
char_u *line;
char_u *s;
colnr_T col;
pos_T fp;
if (lnum > 1)
{
line = ml_get(lnum - 1);
if (*line != NUL && line[STRLEN(line) - 1] == '\\')
return -1;
}
line = s = ml_get(lnum);
while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
{
if (cin_iscomment(s)) /* ignore comments */
s = cin_skipcomment(s);
else
++s;
}
if (*s != '=')
return 0;
s = skipwhite(s + 1);
if (cin_nocode(s))
return 0;
if (*s == '"') /* nice alignment for continued strings */
++s;
fp.lnum = lnum;
fp.col = (colnr_T)(s - line);
getvcol(curwin, &fp, &col, NULL, NULL);
return (int)col;
}
/*
* Recognize a preprocessor statement: Any line that starts with '#'.
*/
static int
cin_ispreproc(s)
char_u *s;
{
if (*skipwhite(s) == '#')
return TRUE;
return FALSE;
}
/*
* Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
* continuation line of a preprocessor statement. Decrease "*lnump" to the
* start and return the line in "*pp".
*/
static int
cin_ispreproc_cont(pp, lnump)
char_u **pp;
linenr_T *lnump;
{
char_u *line = *pp;
linenr_T lnum = *lnump;
int retval = FALSE;
for (;;)
{
if (cin_ispreproc(line))
{
retval = TRUE;
*lnump = lnum;
break;
}
if (lnum == 1)
break;
line = ml_get(--lnum);
if (*line == NUL || line[STRLEN(line) - 1] != '\\')
break;
}
if (lnum != *lnump)
*pp = ml_get(*lnump);
return retval;
}
/*
* Recognize the start of a C or C++ comment.
*/
static int
cin_iscomment(p)
char_u *p;
{
return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
}
/*
* Recognize the start of a "//" comment.
*/
static int
cin_islinecomment(p)
char_u *p;
{
return (p[0] == '/' && p[1] == '/');
}
/*
* Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
* '}'.
* Don't consider "} else" a terminated line.
* If a line begins with an "else", only consider it terminated if no unmatched
* opening braces follow (handle "else { foo();" correctly).
* Return the character terminating the line (ending char's have precedence if
* both apply in order to determine initializations).
*/
static int
cin_isterminated(s, incl_open, incl_comma)
char_u *s;
int incl_open; /* include '{' at the end as terminator */
int incl_comma; /* recognize a trailing comma */
{
char_u found_start = 0;
unsigned n_open = 0;
int is_else = FALSE;
s = cin_skipcomment(s);
if (*s == '{' || (*s == '}' && !cin_iselse(s)))
found_start = *s;
if (!found_start)
is_else = cin_iselse(s);
while (*s)
{
/* skip over comments, "" strings and 'c'haracters */
s = skip_string(cin_skipcomment(s));
if (*s == '}' && n_open > 0)
--n_open;
if ((!is_else || n_open == 0)
&& (*s == ';' || *s == '}' || (incl_comma && *s == ','))
&& cin_nocode(s + 1))
return *s;
else if (*s == '{')
{
if (incl_open && cin_nocode(s + 1))
return *s;
else
++n_open;
}
if (*s)
s++;
}
return found_start;
}
/*
* Recognize the basic picture of a function declaration -- it needs to
* have an open paren somewhere and a close paren at the end of the line and
* no semicolons anywhere.
* When a line ends in a comma we continue looking in the next line.
* "sp" points to a string with the line. When looking at other lines it must
* be restored to the line. When it's NULL fetch lines here.
* "lnum" is where we start looking.
* "min_lnum" is the line before which we will not be looking.
*/
static int
cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
char_u **sp;
linenr_T first_lnum;
linenr_T min_lnum;
int ind_maxparen;
int ind_maxcomment;
{
char_u *s;
linenr_T lnum = first_lnum;
int retval = FALSE;
pos_T *trypos;
int just_started = TRUE;
if (sp == NULL)
s = ml_get(lnum);
else
s = *sp;
if (find_last_paren(s, '(', ')')
&& (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
{
lnum = trypos->lnum;
if (lnum < min_lnum)
return FALSE;
s = ml_get(lnum);
}
/* Ignore line starting with #. */
if (cin_ispreproc(s))
return FALSE;
while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
{
if (cin_iscomment(s)) /* ignore comments */
s = cin_skipcomment(s);
else
++s;
}
if (*s != '(')
return FALSE; /* ';', ' or " before any () or no '(' */
while (*s && *s != ';' && *s != '\'' && *s != '"')
{
if (*s == ')' && cin_nocode(s + 1))
{
/* ')' at the end: may have found a match
* Check for he previous line not to end in a backslash:
* #if defined(x) && \
* defined(y)
*/
lnum = first_lnum - 1;
s = ml_get(lnum);
if (*s == NUL || s[STRLEN(s) - 1] != '\\')
retval = TRUE;
goto done;
}
if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
{
int comma = (*s == ',');
/* ',' at the end: continue looking in the next line.
* At the end: check for ',' in the next line, for this style:
* func(arg1
* , arg2) */
for (;;)
{
if (lnum >= curbuf->b_ml.ml_line_count)
break;
s = ml_get(++lnum);
if (!cin_ispreproc(s))
break;
}
if (lnum >= curbuf->b_ml.ml_line_count)
break;
/* Require a comma at end of the line or a comma or ')' at the
* start of next line. */
s = skipwhite(s);
if (!just_started && (!comma && *s != ',' && *s != ')'))
break;
just_started = FALSE;
}
else if (cin_iscomment(s)) /* ignore comments */
s = cin_skipcomment(s);
else
{
++s;
just_started = FALSE;
}
}
done:
if (lnum != first_lnum && sp != NULL)
*sp = ml_get(first_lnum);
return retval;
}
static int
cin_isif(p)
char_u *p;
{
return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
}
static int
cin_iselse(p)
char_u *p;
{
if (*p == '}') /* accept "} else" */
p = cin_skipcomment(p + 1);
return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
}
static int
cin_isdo(p)
char_u *p;
{
return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
}
/*
* Check if this is a "while" that should have a matching "do".
* We only accept a "while (condition) ;", with only white space between the
* ')' and ';'. The condition may be spread over several lines.
*/
static int
cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
char_u *p;
linenr_T lnum;
int ind_maxparen;
{
pos_T cursor_save;
pos_T *trypos;
int retval = FALSE;
p = cin_skipcomment(p);
if (*p == '}') /* accept "} while (cond);" */
p = cin_skipcomment(p + 1);
if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
{
cursor_save = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
curwin->w_cursor.col = 0;
p = ml_get_curline();
while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
{
++p;
++curwin->w_cursor.col;
}
if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
&& *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
retval = TRUE;
curwin->w_cursor = cursor_save;
}
return retval;
}
/*
* Check whether in "p" there is an "if", "for" or "while" before "*poffset".
* Return 0 if there is none.
* Otherwise return !0 and update "*poffset" to point to the place where the
* string was found.
*/
static int
cin_is_if_for_while_before_offset(line, poffset)
char_u *line;
int *poffset;
{
int offset = *poffset;
if (offset-- < 2)
return 0;
while (offset > 2 && vim_iswhite(line[offset]))
--offset;
offset -= 1;
if (!STRNCMP(line + offset, "if", 2))
goto probablyFound;
if (offset >= 1)
{
offset -= 1;
if (!STRNCMP(line + offset, "for", 3))
goto probablyFound;
if (offset >= 2)
{
offset -= 2;
if (!STRNCMP(line + offset, "while", 5))
goto probablyFound;
}
}
return 0;
probablyFound:
if (!offset || !vim_isIDc(line[offset - 1]))
{
*poffset = offset;
return 1;
}
return 0;
}
/*
* Return TRUE if we are at the end of a do-while.
* do
* nothing;
* while (foo
* && bar); <-- here
* Adjust the cursor to the line with "while".
*/
static int
cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
int terminated;
int ind_maxparen;
int ind_maxcomment;
{
char_u *line;
char_u *p;
char_u *s;
pos_T *trypos;
int i;
if (terminated != ';') /* there must be a ';' at the end */
return FALSE;
p = line = ml_get_curline();
while (*p != NUL)
{
p = cin_skipcomment(p);
if (*p == ')')
{
s = skipwhite(p + 1);
if (*s == ';' && cin_nocode(s + 1))
{
/* Found ");" at end of the line, now check there is "while"
* before the matching '('. XXX */
i = (int)(p - line);
curwin->w_cursor.col = i;
trypos = find_match_paren(ind_maxparen, ind_maxcomment);
if (trypos != NULL)
{
s = cin_skipcomment(ml_get(trypos->lnum));
if (*s == '}') /* accept "} while (cond);" */
s = cin_skipcomment(s + 1);
if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
{
curwin->w_cursor.lnum = trypos->lnum;
return TRUE;
}
}
/* Searching may have made "line" invalid, get it again. */
line = ml_get_curline();
p = line + i;
}
}
if (*p != NUL)
++p;
}
return FALSE;
}
static int
cin_isbreak(p)
char_u *p;
{
return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
}
/*
* Find the position of a C++ base-class declaration or
* constructor-initialization. eg:
*
* class MyClass :
* baseClass <-- here
* class MyClass : public baseClass,
* anotherBaseClass <-- here (should probably lineup ??)
* MyClass::MyClass(...) :
* baseClass(...) <-- here (constructor-initialization)
*
* This is a lot of guessing. Watch out for "cond ? func() : foo".
*/
static int
cin_is_cpp_baseclass(col)
colnr_T *col; /* return: column to align with */
{
char_u *s;
int class_or_struct, lookfor_ctor_init, cpp_base_class;
linenr_T lnum = curwin->w_cursor.lnum;
char_u *line = ml_get_curline();
*col = 0;
s = skipwhite(line);
if (*s == '#') /* skip #define FOO x ? (x) : x */
return FALSE;
s = cin_skipcomment(s);
if (*s == NUL)
return FALSE;
cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
/* Search for a line starting with '#', empty, ending in ';' or containing
* '{' or '}' and start below it. This handles the following situations:
* a = cond ?
* func() :
* asdf;
* func::foo()
* : something
* {}
* Foo::Foo (int one, int two)
* : something(4),
* somethingelse(3)
* {}
*/
while (lnum > 1)
{
line = ml_get(lnum - 1);
s = skipwhite(line);
if (*s == '#' || *s == NUL)
break;
while (*s != NUL)
{
s = cin_skipcomment(s);
if (*s == '{' || *s == '}'
|| (*s == ';' && cin_nocode(s + 1)))
break;
if (*s != NUL)
++s;
}
if (*s != NUL)
break;
--lnum;
}
line = ml_get(lnum);
s = cin_skipcomment(line);
for (;;)
{
if (*s == NUL)
{
if (lnum == curwin->w_cursor.lnum)
break;
/* Continue in the cursor line. */
line = ml_get(++lnum);
s = cin_skipcomment(line);
if (*s == NUL)
continue;
}
if (s[0] == '"')
s = skip_string(s) + 1;
else if (s[0] == ':')
{
if (s[1] == ':')
{
/* skip double colon. It can't be a constructor
* initialization any more */
lookfor_ctor_init = FALSE;
s = cin_skipcomment(s + 2);
}
else if (lookfor_ctor_init || class_or_struct)
{
/* we have something found, that looks like the start of
* cpp-base-class-declaration or constructor-initialization */
cpp_base_class = TRUE;
lookfor_ctor_init = class_or_struct = FALSE;
*col = 0;
s = cin_skipcomment(s + 1);
}
else
s = cin_skipcomment(s + 1);
}
else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
|| (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
{
class_or_struct = TRUE;
lookfor_ctor_init = FALSE;
if (*s == 'c')
s = cin_skipcomment(s + 5);
else
s = cin_skipcomment(s + 6);
}
else
{
if (s[0] == '{' || s[0] == '}' || s[0] == ';')
{
cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
}
else if (s[0] == ')')
{
/* Constructor-initialization is assumed if we come across
* something like "):" */
class_or_struct = FALSE;
lookfor_ctor_init = TRUE;
}
else if (s[0] == '?')
{
/* Avoid seeing '() :' after '?' as constructor init. */
return FALSE;
}
else if (!vim_isIDc(s[0]))
{
/* if it is not an identifier, we are wrong */
class_or_struct = FALSE;
lookfor_ctor_init = FALSE;
}
else if (*col == 0)
{
/* it can't be a constructor-initialization any more */
lookfor_ctor_init = FALSE;
/* the first statement starts here: lineup with this one... */
if (cpp_base_class)
*col = (colnr_T)(s - line);
}
/* When the line ends in a comma don't align with it. */
if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
*col = 0;
s = cin_skipcomment(s + 1);
}
}
return cpp_base_class;
}
static int
get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
int col;
int ind_maxparen;
int ind_maxcomment;
int ind_cpp_baseclass;
{
int amount;
colnr_T vcol;
pos_T *trypos;
if (col == 0)
{
amount = get_indent();
if (find_last_paren(ml_get_curline(), '(', ')')
&& (trypos = find_match_paren(ind_maxparen,
ind_maxcomment)) != NULL)
amount = get_indent_lnum(trypos->lnum); /* XXX */
if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
amount += ind_cpp_baseclass;
}
else
{
curwin->w_cursor.col = col;
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
amount = (int)vcol;
}
if (amount < ind_cpp_baseclass)
amount = ind_cpp_baseclass;
return amount;
}
/*
* Return TRUE if string "s" ends with the string "find", possibly followed by
* white space and comments. Skip strings and comments.
* Ignore "ignore" after "find" if it's not NULL.
*/
static int
cin_ends_in(s, find, ignore)
char_u *s;
char_u *find;
char_u *ignore;
{
char_u *p = s;
char_u *r;
int len = (int)STRLEN(find);
while (*p != NUL)
{
p = cin_skipcomment(p);
if (STRNCMP(p, find, len) == 0)
{
r = skipwhite(p + len);
if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
r = skipwhite(r + STRLEN(ignore));
if (cin_nocode(r))
return TRUE;
}
if (*p != NUL)
++p;
}
return FALSE;
}
/*
* Skip strings, chars and comments until at or past "trypos".
* Return the column found.
*/
static int
cin_skip2pos(trypos)
pos_T *trypos;
{
char_u *line;
char_u *p;
p = line = ml_get(trypos->lnum);
while (*p && (colnr_T)(p - line) < trypos->col)
{
if (cin_iscomment(p))
p = cin_skipcomment(p);
else
{
p = skip_string(p);
++p;
}
}
return (int)(p - line);
}
/*
* Find the '{' at the start of the block we are in.
* Return NULL if no match found.
* Ignore a '{' that is in a comment, makes indenting the next three lines
* work. */
/* foo() */
/* { */
/* } */
static pos_T *
find_start_brace(ind_maxcomment) /* XXX */
int ind_maxcomment;
{
pos_T cursor_save;
pos_T *trypos;
pos_T *pos;
static pos_T pos_copy;
cursor_save = curwin->w_cursor;
while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
{
pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
trypos = &pos_copy;
curwin->w_cursor = *trypos;
pos = NULL;
/* ignore the { if it's in a // or / * * / comment */
if ((colnr_T)cin_skip2pos(trypos) == trypos->col
&& (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
break;
if (pos != NULL)
curwin->w_cursor.lnum = pos->lnum;
}
curwin->w_cursor = cursor_save;
return trypos;
}
/*
* Find the matching '(', failing if it is in a comment.
* Return NULL if no match found.
*/
static pos_T *
find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
int ind_maxparen;
int ind_maxcomment;
{
pos_T cursor_save;
pos_T *trypos;
static pos_T pos_copy;
cursor_save = curwin->w_cursor;
if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
{
/* check if the ( is in a // comment */
if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
trypos = NULL;
else
{
pos_copy = *trypos; /* copy trypos, findmatch will change it */
trypos = &pos_copy;
curwin->w_cursor = *trypos;
if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
trypos = NULL;
}
}
curwin->w_cursor = cursor_save;
return trypos;
}
/*
* Return ind_maxparen corrected for the difference in line number between the
* cursor position and "startpos". This makes sure that searching for a
* matching paren above the cursor line doesn't find a match because of
* looking a few lines further.
*/
static int
corr_ind_maxparen(ind_maxparen, startpos)
int ind_maxparen;
pos_T *startpos;
{
long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
if (n > 0 && n < ind_maxparen / 2)
return ind_maxparen - (int)n;
return ind_maxparen;
}
/*
* Set w_cursor.col to the column number of the last unmatched ')' or '{' in
* line "l". "l" must point to the start of the line.
*/
static int
find_last_paren(l, start, end)
char_u *l;
int start, end;
{
int i;
int retval = FALSE;
int open_count = 0;
curwin->w_cursor.col = 0; /* default is start of line */
for (i = 0; l[i] != NUL; i++)
{
i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
if (l[i] == start)
++open_count;
else if (l[i] == end)
{
if (open_count > 0)
--open_count;
else
{
curwin->w_cursor.col = i;
retval = TRUE;
}
}
}
return retval;
}
int
get_c_indent()
{
/*
* spaces from a block's opening brace the prevailing indent for that
* block should be
*/
int ind_level = curbuf->b_p_sw;
/*
* spaces from the edge of the line an open brace that's at the end of a
* line is imagined to be.
*/
int ind_open_imag = 0;
/*
* spaces from the prevailing indent for a line that is not preceded by
* an opening brace.
*/
int ind_no_brace = 0;
/*
* column where the first { of a function should be located }
*/
int ind_first_open = 0;
/*
* spaces from the prevailing indent a leftmost open brace should be
* located
*/
int ind_open_extra = 0;
/*
* spaces from the matching open brace (real location for one at the left
* edge; imaginary location from one that ends a line) the matching close
* brace should be located
*/
int ind_close_extra = 0;
/*
* spaces from the edge of the line an open brace sitting in the leftmost
* column is imagined to be
*/
int ind_open_left_imag = 0;
/*
* Spaces jump labels should be shifted to the left if N is non-negative,
* otherwise the jump label will be put to column 1.
*/
int ind_jump_label = -1;
/*
* spaces from the switch() indent a "case xx" label should be located
*/
int ind_case = curbuf->b_p_sw;
/*
* spaces from the "case xx:" code after a switch() should be located
*/
int ind_case_code = curbuf->b_p_sw;
/*
* lineup break at end of case in switch() with case label
*/
int ind_case_break = 0;
/*
* spaces from the class declaration indent a scope declaration label
* should be located
*/
int ind_scopedecl = curbuf->b_p_sw;
/*
* spaces from the scope declaration label code should be located
*/
int ind_scopedecl_code = curbuf->b_p_sw;
/*
* amount K&R-style parameters should be indented
*/
int ind_param = curbuf->b_p_sw;
/*
* amount a function type spec should be indented
*/
int ind_func_type = curbuf->b_p_sw;
/*
* amount a cpp base class declaration or constructor initialization
* should be indented
*/
int ind_cpp_baseclass = curbuf->b_p_sw;
/*
* additional spaces beyond the prevailing indent a continuation line
* should be located
*/
int ind_continuation = curbuf->b_p_sw;
/*
* spaces from the indent of the line with an unclosed parentheses
*/
int ind_unclosed = curbuf->b_p_sw * 2;
/*
* spaces from the indent of the line with an unclosed parentheses, which
* itself is also unclosed
*/
int ind_unclosed2 = curbuf->b_p_sw;
/*
* suppress ignoring spaces from the indent of a line starting with an
* unclosed parentheses.
*/
int ind_unclosed_noignore = 0;
/*
* If the opening paren is the last nonwhite character on the line, and
* ind_unclosed_wrapped is nonzero, use this indent relative to the outer
* context (for very long lines).
*/
int ind_unclosed_wrapped = 0;
/*
* suppress ignoring white space when lining up with the character after
* an unclosed parentheses.
*/
int ind_unclosed_whiteok = 0;
/*
* indent a closing parentheses under the line start of the matching
* opening parentheses.
*/
int ind_matching_paren = 0;
/*
* indent a closing parentheses under the previous line.
*/
int ind_paren_prev = 0;
/*
* Extra indent for comments.
*/
int ind_comment = 0;
/*
* spaces from the comment opener when there is nothing after it.
*/
int ind_in_comment = 3;
/*
* boolean: if non-zero, use ind_in_comment even if there is something
* after the comment opener.
*/
int ind_in_comment2 = 0;
/*
* max lines to search for an open paren
*/
int ind_maxparen = 20;
/*
* max lines to search for an open comment
*/
int ind_maxcomment = 70;
/*
* handle braces for java code
*/
int ind_java = 0;
/*
* not to confuse JS object properties with labels
*/
int ind_js = 0;
/*
* handle blocked cases correctly
*/
int ind_keep_case_label = 0;
/*
* handle C++ namespace
*/
int ind_cpp_namespace = 0;
/*
* handle continuation lines containing conditions of if(), for() and
* while()
*/
int ind_if_for_while = 0;
pos_T cur_curpos;
int amount;
int scope_amount;
int cur_amount = MAXCOL;
colnr_T col;
char_u *theline;
char_u *linecopy;
pos_T *trypos;
pos_T *tryposBrace = NULL;
pos_T our_paren_pos;
char_u *start;
int start_brace;
#define BRACE_IN_COL0 1 /* '{' is in column 0 */
#define BRACE_AT_START 2 /* '{' is at start of line */
#define BRACE_AT_END 3 /* '{' is at end of line */
linenr_T ourscope;
char_u *l;
char_u *look;
char_u terminated;
int lookfor;
#define LOOKFOR_INITIAL 0
#define LOOKFOR_IF 1
#define LOOKFOR_DO 2
#define LOOKFOR_CASE 3
#define LOOKFOR_ANY 4
#define LOOKFOR_TERM 5
#define LOOKFOR_UNTERM 6
#define LOOKFOR_SCOPEDECL 7
#define LOOKFOR_NOBREAK 8
#define LOOKFOR_CPP_BASECLASS 9
#define LOOKFOR_ENUM_OR_INIT 10
int whilelevel;
linenr_T lnum;
char_u *options;
char_u *digits;
int fraction = 0; /* init for GCC */
int divider;
int n;
int iscase;
int lookfor_break;
int lookfor_cpp_namespace = FALSE;
int cont_amount = 0; /* amount for continuation line */
int original_line_islabel;
int added_to_amount = 0;
for (options = curbuf->b_p_cino; *options; )
{
l = options++;
if (*options == '-')
++options;
digits = options; /* remember where the digits start */
n = getdigits(&options);
divider = 0;
if (*options == '.') /* ".5s" means a fraction */
{
fraction = atol((char *)++options);
while (VIM_ISDIGIT(*options))
{
++options;
if (divider)
divider *= 10;
else
divider = 10;
}
}
if (*options == 's') /* "2s" means two times 'shiftwidth' */
{
if (options == digits)
n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
else
{
n *= curbuf->b_p_sw;
if (divider)
n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
}
++options;
}
if (l[1] == '-')
n = -n;
/* When adding an entry here, also update the default 'cinoptions' in
* doc/indent.txt, and add explanation for it! */
switch (*l)
{
case '>': ind_level = n; break;
case 'e': ind_open_imag = n; break;
case 'n': ind_no_brace = n; break;
case 'f': ind_first_open = n; break;
case '{': ind_open_extra = n; break;
case '}': ind_close_extra = n; break;
case '^': ind_open_left_imag = n; break;
case 'L': ind_jump_label = n; break;
case ':': ind_case = n; break;
case '=': ind_case_code = n; break;
case 'b': ind_case_break = n; break;
case 'p': ind_param = n; break;
case 't': ind_func_type = n; break;
case '/': ind_comment = n; break;
case 'c': ind_in_comment = n; break;
case 'C': ind_in_comment2 = n; break;
case 'i': ind_cpp_baseclass = n; break;
case '+': ind_continuation = n; break;
case '(': ind_unclosed = n; break;
case 'u': ind_unclosed2 = n; break;
case 'U': ind_unclosed_noignore = n; break;
case 'W': ind_unclosed_wrapped = n; break;
case 'w': ind_unclosed_whiteok = n; break;
case 'm': ind_matching_paren = n; break;
case 'M': ind_paren_prev = n; break;
case ')': ind_maxparen = n; break;
case '*': ind_maxcomment = n; break;
case 'g': ind_scopedecl = n; break;
case 'h': ind_scopedecl_code = n; break;
case 'j': ind_java = n; break;
case 'J': ind_js = n; break;
case 'l': ind_keep_case_label = n; break;
case '#': ind_hash_comment = n; break;
case 'N': ind_cpp_namespace = n; break;
case 'k': ind_if_for_while = n; break;
}
if (*options == ',')
++options;
}
/* remember where the cursor was when we started */
cur_curpos = curwin->w_cursor;
/* if we are at line 1 0 is fine, right? */
if (cur_curpos.lnum == 1)
return 0;
/* Get a copy of the current contents of the line.
* This is required, because only the most recent line obtained with
* ml_get is valid! */
linecopy = vim_strsave(ml_get(cur_curpos.lnum));
if (linecopy == NULL)
return 0;
/*
* In insert mode and the cursor is on a ')' truncate the line at the
* cursor position. We don't want to line up with the matching '(' when
* inserting new stuff.
* For unknown reasons the cursor might be past the end of the line, thus
* check for that.
*/
if ((State & INSERT)
&& curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
&& linecopy[curwin->w_cursor.col] == ')')
linecopy[curwin->w_cursor.col] = NUL;
theline = skipwhite(linecopy);
/* move the cursor to the start of the line */
curwin->w_cursor.col = 0;
original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
/*
* #defines and so on always go at the left when included in 'cinkeys'.
*/
if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
{
amount = 0;
}
/*
* Is it a non-case label? Then that goes at the left margin too unless:
* - JS flag is set.
* - 'L' item has a positive value.
*/
else if (original_line_islabel && !ind_js && ind_jump_label < 0)
{
amount = 0;
}
/*
* If we're inside a "//" comment and there is a "//" comment in a
* previous line, lineup with that one.
*/
else if (cin_islinecomment(theline)
&& (trypos = find_line_comment()) != NULL) /* XXX */
{
/* find how indented the line beginning the comment is */
getvcol(curwin, trypos, &col, NULL, NULL);
amount = col;
}
/*
* If we're inside a comment and not looking at the start of the
* comment, try using the 'comments' option.
*/
else if (!cin_iscomment(theline)
&& (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
{
int lead_start_len = 2;
int lead_middle_len = 1;
char_u lead_start[COM_MAX_LEN]; /* start-comment string */
char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
char_u lead_end[COM_MAX_LEN]; /* end-comment string */
char_u *p;
int start_align = 0;
int start_off = 0;
int done = FALSE;
/* find how indented the line beginning the comment is */
getvcol(curwin, trypos, &col, NULL, NULL);
amount = col;
*lead_start = NUL;
*lead_middle = NUL;
p = curbuf->b_p_com;
while (*p != NUL)
{
int align = 0;
int off = 0;
int what = 0;
while (*p != NUL && *p != ':')
{
if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
what = *p++;
else if (*p == COM_LEFT || *p == COM_RIGHT)
align = *p++;
else if (VIM_ISDIGIT(*p) || *p == '-')
off = getdigits(&p);
else
++p;
}
if (*p == ':')
++p;
(void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
if (what == COM_START)
{
STRCPY(lead_start, lead_end);
lead_start_len = (int)STRLEN(lead_start);
start_off = off;
start_align = align;
}
else if (what == COM_MIDDLE)
{
STRCPY(lead_middle, lead_end);
lead_middle_len = (int)STRLEN(lead_middle);
}
else if (what == COM_END)
{
/* If our line starts with the middle comment string, line it
* up with the comment opener per the 'comments' option. */
if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
&& STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
{
done = TRUE;
if (curwin->w_cursor.lnum > 1)
{
/* If the start comment string matches in the previous
* line, use the indent of that line plus offset. If
* the middle comment string matches in the previous
* line, use the indent of that line. XXX */
look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
if (STRNCMP(look, lead_start, lead_start_len) == 0)
amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
else if (STRNCMP(look, lead_middle,
lead_middle_len) == 0)
{
amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
break;
}
/* If the start comment string doesn't match with the
* start of the comment, skip this entry. XXX */
else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
lead_start, lead_start_len) != 0)
continue;
}
if (start_off != 0)
amount += start_off;
else if (start_align == COM_RIGHT)
amount += vim_strsize(lead_start)
- vim_strsize(lead_middle);
break;
}
/* If our line starts with the end comment string, line it up
* with the middle comment */
if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
&& STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
{
amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
/* XXX */
if (off != 0)
amount += off;
else if (align == COM_RIGHT)
amount += vim_strsize(lead_start)
- vim_strsize(lead_middle);
done = TRUE;
break;
}
}
}
/* If our line starts with an asterisk, line up with the
* asterisk in the comment opener; otherwise, line up
* with the first character of the comment text.
*/
if (done)
;
else if (theline[0] == '*')
amount += 1;
else
{
/*
* If we are more than one line away from the comment opener, take
* the indent of the previous non-empty line. If 'cino' has "CO"
* and we are just below the comment opener and there are any
* white characters after it line up with the text after it;
* otherwise, add the amount specified by "c" in 'cino'
*/
amount = -1;
for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
{
if (linewhite(lnum)) /* skip blank lines */
continue;
amount = get_indent_lnum(lnum); /* XXX */
break;
}
if (amount == -1) /* use the comment opener */
{
if (!ind_in_comment2)
{
start = ml_get(trypos->lnum);
look = start + trypos->col + 2; /* skip / and * */
if (*look != NUL) /* if something after it */
trypos->col = (colnr_T)(skipwhite(look) - start);
}
getvcol(curwin, trypos, &col, NULL, NULL);
amount = col;
if (ind_in_comment2 || *look == NUL)
amount += ind_in_comment;
}
}
}
/*
* Are we inside parentheses or braces?
*/ /* XXX */
else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
&& ind_java == 0)
|| (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
|| trypos != NULL)
{
if (trypos != NULL && tryposBrace != NULL)
{
/* Both an unmatched '(' and '{' is found. Use the one which is
* closer to the current cursor position, set the other to NULL. */
if (trypos->lnum != tryposBrace->lnum
? trypos->lnum < tryposBrace->lnum
: trypos->col < tryposBrace->col)
trypos = NULL;
else
tryposBrace = NULL;
}
if (trypos != NULL)
{
/*
* If the matching paren is more than one line away, use the indent of
* a previous non-empty line that matches the same paren.
*/
if (theline[0] == ')' && ind_paren_prev)
{
/* Line up with the start of the matching paren line. */
amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
}
else
{
amount = -1;
our_paren_pos = *trypos;
for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
{
l = skipwhite(ml_get(lnum));
if (cin_nocode(l)) /* skip comment lines */
continue;
if (cin_ispreproc_cont(&l, &lnum))
continue; /* ignore #define, #if, etc. */
curwin->w_cursor.lnum = lnum;
/* Skip a comment. XXX */
if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
{
lnum = trypos->lnum + 1;
continue;
}
/* XXX */
if ((trypos = find_match_paren(
corr_ind_maxparen(ind_maxparen, &cur_curpos),
ind_maxcomment)) != NULL
&& trypos->lnum == our_paren_pos.lnum
&& trypos->col == our_paren_pos.col)
{
amount = get_indent_lnum(lnum); /* XXX */
if (theline[0] == ')')
{
if (our_paren_pos.lnum != lnum
&& cur_amount > amount)
cur_amount = amount;
amount = -1;
}
break;
}
}
}
/*
* Line up with line where the matching paren is. XXX
* If the line starts with a '(' or the indent for unclosed
* parentheses is zero, line up with the unclosed parentheses.
*/
if (amount == -1)
{
int ignore_paren_col = 0;
int is_if_for_while = 0;
if (ind_if_for_while)
{
/* Look for the outermost opening parenthesis on this line
* and check whether it belongs to an "if", "for" or "while". */
pos_T cursor_save = curwin->w_cursor;
pos_T outermost;
char_u *line;
trypos = &our_paren_pos;
do {
outermost = *trypos;
curwin->w_cursor.lnum = outermost.lnum;
curwin->w_cursor.col = outermost.col;
trypos = find_match_paren(ind_maxparen, ind_maxcomment);
} while (trypos && trypos->lnum == outermost.lnum);
curwin->w_cursor = cursor_save;
line = ml_get(outermost.lnum);
is_if_for_while =
cin_is_if_for_while_before_offset(line, &outermost.col);
}
amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
look = skipwhite(look);
if (*look == '(')
{
linenr_T save_lnum = curwin->w_cursor.lnum;
char_u *line;
int look_col;
/* Ignore a '(' in front of the line that has a match before
* our matching '('. */
curwin->w_cursor.lnum = our_paren_pos.lnum;
line = ml_get_curline();
look_col = (int)(look - line);
curwin->w_cursor.col = look_col + 1;
if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
!= NULL
&& trypos->lnum == our_paren_pos.lnum
&& trypos->col < our_paren_pos.col)
ignore_paren_col = trypos->col + 1;
curwin->w_cursor.lnum = save_lnum;
look = ml_get(our_paren_pos.lnum) + look_col;
}
if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
|| (!ind_unclosed_noignore && *look == '('
&& ignore_paren_col == 0))
{
/*
* If we're looking at a close paren, line up right there;
* otherwise, line up with the next (non-white) character.
* When ind_unclosed_wrapped is set and the matching paren is
* the last nonwhite character of the line, use either the
* indent of the current line or the indentation of the next
* outer paren and add ind_unclosed_wrapped (for very long
* lines).
*/
if (theline[0] != ')')
{
cur_amount = MAXCOL;
l = ml_get(our_paren_pos.lnum);
if (ind_unclosed_wrapped
&& cin_ends_in(l, (char_u *)"(", NULL))
{
/* look for opening unmatched paren, indent one level
* for each additional level */
n = 1;
for (col = 0; col < our_paren_pos.col; ++col)
{
switch (l[col])
{
case '(':
case '{': ++n;
break;
case ')':
case '}': if (n > 1)
--n;
break;
}
}
our_paren_pos.col = 0;
amount += n * ind_unclosed_wrapped;
}
else if (ind_unclosed_whiteok)
our_paren_pos.col++;
else
{
col = our_paren_pos.col + 1;
while (vim_iswhite(l[col]))
col++;
if (l[col] != NUL) /* In case of trailing space */
our_paren_pos.col = col;
else
our_paren_pos.col++;
}
}
/*
* Find how indented the paren is, or the character after it
* if we did the above "if".
*/
if (our_paren_pos.col > 0)
{
getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
if (cur_amount > (int)col)
cur_amount = col;
}
}
if (theline[0] == ')' && ind_matching_paren)
{
/* Line up with the start of the matching paren line. */
}
else if ((ind_unclosed == 0 && is_if_for_while == 0)
|| (!ind_unclosed_noignore
&& *look == '(' && ignore_paren_col == 0))
{
if (cur_amount != MAXCOL)
amount = cur_amount;
}
else
{
/* Add ind_unclosed2 for each '(' before our matching one, but
* ignore (void) before the line (ignore_paren_col). */
col = our_paren_pos.col;
while ((int)our_paren_pos.col > ignore_paren_col)
{
--our_paren_pos.col;
switch (*ml_get_pos(&our_paren_pos))
{
case '(': amount += ind_unclosed2;
col = our_paren_pos.col;
break;
case ')': amount -= ind_unclosed2;
col = MAXCOL;
break;
}
}
/* Use ind_unclosed once, when the first '(' is not inside
* braces */
if (col == MAXCOL)
amount += ind_unclosed;
else
{
curwin->w_cursor.lnum = our_paren_pos.lnum;
curwin->w_cursor.col = col;
if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
amount += ind_unclosed2;
else
{
if (is_if_for_while)
amount += ind_if_for_while;
else
amount += ind_unclosed;
}
}
/*
* For a line starting with ')' use the minimum of the two
* positions, to avoid giving it more indent than the previous
* lines:
* func_long_name( if (x
* arg && yy
* ) ^ not here ) ^ not here
*/
if (cur_amount < amount)
amount = cur_amount;
}
}
/* add extra indent for a comment */
if (cin_iscomment(theline))
amount += ind_comment;
}
/*
* Are we at least inside braces, then?
*/
else
{
trypos = tryposBrace;
ourscope = trypos->lnum;
start = ml_get(ourscope);
/*
* Now figure out how indented the line is in general.
* If the brace was at the start of the line, we use that;
* otherwise, check out the indentation of the line as
* a whole and then add the "imaginary indent" to that.
*/
look = skipwhite(start);
if (*look == '{')
{
getvcol(curwin, trypos, &col, NULL, NULL);
amount = col;
if (*start == '{')
start_brace = BRACE_IN_COL0;
else
start_brace = BRACE_AT_START;
}
else
{
/*
* that opening brace might have been on a continuation
* line. if so, find the start of the line.
*/
curwin->w_cursor.lnum = ourscope;
/*
* position the cursor over the rightmost paren, so that
* matching it will take us back to the start of the line.
*/
lnum = ourscope;
if (find_last_paren(start, '(', ')')
&& (trypos = find_match_paren(ind_maxparen,
ind_maxcomment)) != NULL)
lnum = trypos->lnum;
/*
* It could have been something like
* case 1: if (asdf &&
* ldfd) {
* }
*/
if (ind_js || (ind_keep_case_label
&& cin_iscase(skipwhite(ml_get_curline()), FALSE)))
amount = get_indent();
else
amount = skip_label(lnum, &l, ind_maxcomment);
start_brace = BRACE_AT_END;
}
/*
* if we're looking at a closing brace, that's where
* we want to be. otherwise, add the amount of room
* that an indent is supposed to be.
*/
if (theline[0] == '}')
{
/*
* they may want closing braces to line up with something
* other than the open brace. indulge them, if so.
*/
amount += ind_close_extra;
}
else
{
/*
* If we're looking at an "else", try to find an "if"
* to match it with.
* If we're looking at a "while", try to find a "do"
* to match it with.
*/
lookfor = LOOKFOR_INITIAL;
if (cin_iselse(theline))
lookfor = LOOKFOR_IF;
else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
/* XXX */
lookfor = LOOKFOR_DO;
if (lookfor != LOOKFOR_INITIAL)
{
curwin->w_cursor.lnum = cur_curpos.lnum;
if (find_match(lookfor, ourscope, ind_maxparen,
ind_maxcomment) == OK)
{
amount = get_indent(); /* XXX */
goto theend;
}
}
/*
* We get here if we are not on an "while-of-do" or "else" (or
* failed to find a matching "if").
* Search backwards for something to line up with.
* First set amount for when we don't find anything.
*/
/*
* if the '{' is _really_ at the left margin, use the imaginary
* location of a left-margin brace. Otherwise, correct the
* location for ind_open_extra.
*/
if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
{
amount = ind_open_left_imag;
lookfor_cpp_namespace = TRUE;
}
else if (start_brace == BRACE_AT_START &&
lookfor_cpp_namespace) /* '{' is at start */
{
lookfor_cpp_namespace = TRUE;
}
else
{
if (start_brace == BRACE_AT_END) /* '{' is at end of line */
{
amount += ind_open_imag;
l = skipwhite(ml_get_curline());
if (cin_is_cpp_namespace(l))
amount += ind_cpp_namespace;
}
else
{
/* Compensate for adding ind_open_extra later. */
amount -= ind_open_extra;
if (amount < 0)
amount = 0;
}
}
lookfor_break = FALSE;
if (cin_iscase(theline, FALSE)) /* it's a switch() label */
{
lookfor = LOOKFOR_CASE; /* find a previous switch() label */
amount += ind_case;
}
else if (cin_isscopedecl(theline)) /* private:, ... */
{
lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
amount += ind_scopedecl;
}
else
{
if (ind_case_break && cin_isbreak(theline)) /* break; ... */
lookfor_break = TRUE;
lookfor = LOOKFOR_INITIAL;
amount += ind_level; /* ind_level from start of block */
}
scope_amount = amount;
whilelevel = 0;
/*
* Search backwards. If we find something we recognize, line up
* with that.
*
* if we're looking at an open brace, indent
* the usual amount relative to the conditional
* that opens the block.
*/
curwin->w_cursor = cur_curpos;
for (;;)
{
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
/*
* If we went all the way back to the start of our scope, line
* up with it.
*/
if (curwin->w_cursor.lnum <= ourscope)
{
/* we reached end of scope:
* if looking for a enum or structure initialization
* go further back:
* if it is an initializer (enum xxx or xxx =), then
* don't add ind_continuation, otherwise it is a variable
* declaration:
* int x,
* here; <-- add ind_continuation
*/
if (lookfor == LOOKFOR_ENUM_OR_INIT)
{
if (curwin->w_cursor.lnum == 0
|| curwin->w_cursor.lnum
< ourscope - ind_maxparen)
{
/* nothing found (abuse ind_maxparen as limit)
* assume terminated line (i.e. a variable
* initialization) */
if (cont_amount > 0)
amount = cont_amount;
else if (!ind_js)
amount += ind_continuation;
break;
}
l = ml_get_curline();
/*
* If we're in a comment now, skip to the start of the
* comment.
*/
trypos = find_start_comment(ind_maxcomment);
if (trypos != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
continue;
}
/*
* Skip preprocessor directives and blank lines.
*/
if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
continue;
if (cin_nocode(l))
continue;
terminated = cin_isterminated(l, FALSE, TRUE);
/*
* If we are at top level and the line looks like a
* function declaration, we are done
* (it's a variable declaration).
*/
if (start_brace != BRACE_IN_COL0
|| !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
0, ind_maxparen, ind_maxcomment))
{
/* if the line is terminated with another ','
* it is a continued variable initialization.
* don't add extra indent.
* TODO: does not work, if a function
* declaration is split over multiple lines:
* cin_isfuncdecl returns FALSE then.
*/
if (terminated == ',')
break;
/* if it es a enum declaration or an assignment,
* we are done.
*/
if (terminated != ';' && cin_isinit())
break;
/* nothing useful found */
if (terminated == 0 || terminated == '{')
continue;
}
if (terminated != ';')
{
/* Skip parens and braces. Position the cursor
* over the rightmost paren, so that matching it
* will take us back to the start of the line.
*/ /* XXX */
trypos = NULL;
if (find_last_paren(l, '(', ')'))
trypos = find_match_paren(ind_maxparen,
ind_maxcomment);
if (trypos == NULL && find_last_paren(l, '{', '}'))
trypos = find_start_brace(ind_maxcomment);
if (trypos != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
continue;
}
}
/* it's a variable declaration, add indentation
* like in
* int a,
* b;
*/
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
}
else if (lookfor == LOOKFOR_UNTERM)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
}
else
{
if (lookfor != LOOKFOR_TERM
&& lookfor != LOOKFOR_CPP_BASECLASS)
{
amount = scope_amount;
if (theline[0] == '{')
{
amount += ind_open_extra;
added_to_amount = ind_open_extra;
}
}
if (lookfor_cpp_namespace)
{
/*
* Looking for C++ namespace, need to look further
* back.
*/
if (curwin->w_cursor.lnum == ourscope)
continue;
if (curwin->w_cursor.lnum == 0
|| curwin->w_cursor.lnum
< ourscope - FIND_NAMESPACE_LIM)
break;
l = ml_get_curline();
/* If we're in a comment now, skip to the start of
* the comment. */
trypos = find_start_comment(ind_maxcomment);
if (trypos != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
continue;
}
/* Skip preprocessor directives and blank lines. */
if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
continue;
/* Finally the actual check for "namespace". */
if (cin_is_cpp_namespace(l))
{
amount += ind_cpp_namespace - added_to_amount;
break;
}
if (cin_nocode(l))
continue;
}
}
break;
}
/*
* If we're in a comment now, skip to the start of the comment.
*/ /* XXX */
if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
continue;
}
l = ml_get_curline();
/*
* If this is a switch() label, may line up relative to that.
* If this is a C++ scope declaration, do the same.
*/
iscase = cin_iscase(l, FALSE);
if (iscase || cin_isscopedecl(l))
{
/* we are only looking for cpp base class
* declaration/initialization any longer */
if (lookfor == LOOKFOR_CPP_BASECLASS)
break;
/* When looking for a "do" we are not interested in
* labels. */
if (whilelevel > 0)
continue;
/*
* case xx:
* c = 99 + <- this indent plus continuation
*-> here;
*/
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
break;
}
/*
* case xx: <- line up with this case
* x = 333;
* case yy:
*/
if ( (iscase && lookfor == LOOKFOR_CASE)
|| (iscase && lookfor_break)
|| (!iscase && lookfor == LOOKFOR_SCOPEDECL))
{
/*
* Check that this case label is not for another
* switch()
*/ /* XXX */
if ((trypos = find_start_brace(ind_maxcomment)) ==
NULL || trypos->lnum == ourscope)
{
amount = get_indent(); /* XXX */
break;
}
continue;
}
n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
/*
* case xx: if (cond) <- line up with this if
* y = y + 1;
* -> s = 99;
*
* case xx:
* if (cond) <- line up with this line
* y = y + 1;
* -> s = 99;
*/
if (lookfor == LOOKFOR_TERM)
{
if (n)
amount = n;
if (!lookfor_break)
break;
}
/*
* case xx: x = x + 1; <- line up with this x
* -> y = y + 1;
*
* case xx: if (cond) <- line up with this if
* -> y = y + 1;
*/
if (n)
{
amount = n;
l = after_label(ml_get_curline());
if (l != NULL && cin_is_cinword(l))
{
if (theline[0] == '{')
amount += ind_open_extra;
else
amount += ind_level + ind_no_brace;
}
break;
}
/*
* Try to get the indent of a statement before the switch
* label. If nothing is found, line up relative to the
* switch label.
* break; <- may line up with this line
* case xx:
* -> y = 1;
*/
scope_amount = get_indent() + (iscase /* XXX */
? ind_case_code : ind_scopedecl_code);
lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
continue;
}
/*
* Looking for a switch() label or C++ scope declaration,
* ignore other lines, skip {}-blocks.
*/
if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
{
if (find_last_paren(l, '{', '}') && (trypos =
find_start_brace(ind_maxcomment)) != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
}
continue;
}
/*
* Ignore jump labels with nothing after them.
*/
if (!ind_js && cin_islabel(ind_maxcomment))
{
l = after_label(ml_get_curline());
if (l == NULL || cin_nocode(l))
continue;
}
/*
* Ignore #defines, #if, etc.
* Ignore comment and empty lines.
* (need to get the line again, cin_islabel() may have
* unlocked it)
*/
l = ml_get_curline();
if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
|| cin_nocode(l))
continue;
/*
* Are we at the start of a cpp base class declaration or
* constructor initialization?
*/ /* XXX */
n = FALSE;
if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
{
n = cin_is_cpp_baseclass(&col);
l = ml_get_curline();
}
if (n)
{
if (lookfor == LOOKFOR_UNTERM)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
}
else if (theline[0] == '{')
{
/* Need to find start of the declaration. */
lookfor = LOOKFOR_UNTERM;
ind_continuation = 0;
continue;
}
else
/* XXX */
amount = get_baseclass_amount(col, ind_maxparen,
ind_maxcomment, ind_cpp_baseclass);
break;
}
else if (lookfor == LOOKFOR_CPP_BASECLASS)
{
/* only look, whether there is a cpp base class
* declaration or initialization before the opening brace.
*/
if (cin_isterminated(l, TRUE, FALSE))
break;
else
continue;
}
/*
* What happens next depends on the line being terminated.
* If terminated with a ',' only consider it terminating if
* there is another unterminated statement behind, eg:
* 123,
* sizeof
* here
* Otherwise check whether it is a enumeration or structure
* initialisation (not indented) or a variable declaration
* (indented).
*/
terminated = cin_isterminated(l, FALSE, TRUE);
if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
&& terminated == ','))
{
/*
* if we're in the middle of a paren thing,
* go back to the line that starts it so
* we can get the right prevailing indent
* if ( foo &&
* bar )
*/
/*
* position the cursor over the rightmost paren, so that
* matching it will take us back to the start of the line.
*/
(void)find_last_paren(l, '(', ')');
trypos = find_match_paren(
corr_ind_maxparen(ind_maxparen, &cur_curpos),
ind_maxcomment);
/*
* If we are looking for ',', we also look for matching
* braces.
*/
if (trypos == NULL && terminated == ','
&& find_last_paren(l, '{', '}'))
trypos = find_start_brace(ind_maxcomment);
if (trypos != NULL)
{
/*
* Check if we are on a case label now. This is
* handled above.
* case xx: if ( asdf &&
* asdf)
*/
curwin->w_cursor = *trypos;
l = ml_get_curline();
if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
{
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
continue;
}
}
/*
* Skip over continuation lines to find the one to get the
* indent from
* char *usethis = "bla\
* bla",
* here;
*/
if (terminated == ',')
{
while (curwin->w_cursor.lnum > 1)
{
l = ml_get(curwin->w_cursor.lnum - 1);
if (*l == NUL || l[STRLEN(l) - 1] != '\\')
break;
--curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
}
}
/*
* Get indent and pointer to text for current line,
* ignoring any jump label. XXX
*/
if (!ind_js)
cur_amount = skip_label(curwin->w_cursor.lnum,
&l, ind_maxcomment);
else
cur_amount = get_indent();
/*
* If this is just above the line we are indenting, and it
* starts with a '{', line it up with this line.
* while (not)
* -> {
* }
*/
if (terminated != ',' && lookfor != LOOKFOR_TERM
&& theline[0] == '{')
{
amount = cur_amount;
/*
* Only add ind_open_extra when the current line
* doesn't start with a '{', which must have a match
* in the same line (scope is the same). Probably:
* { 1, 2 },
* -> { 3, 4 }
*/
if (*skipwhite(l) != '{')
amount += ind_open_extra;
if (ind_cpp_baseclass)
{
/* have to look back, whether it is a cpp base
* class declaration or initialization */
lookfor = LOOKFOR_CPP_BASECLASS;
continue;
}
break;
}
/*
* Check if we are after an "if", "while", etc.
* Also allow " } else".
*/
if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
{
/*
* Found an unterminated line after an if (), line up
* with the last one.
* if (cond)
* 100 +
* -> here;
*/
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
break;
}
/*
* If this is just above the line we are indenting, we
* are finished.
* while (not)
* -> here;
* Otherwise this indent can be used when the line
* before this is terminated.
* yyy;
* if (stat)
* while (not)
* xxx;
* -> here;
*/
amount = cur_amount;
if (theline[0] == '{')
amount += ind_open_extra;
if (lookfor != LOOKFOR_TERM)
{
amount += ind_level + ind_no_brace;
break;
}
/*
* Special trick: when expecting the while () after a
* do, line up with the while()
* do
* x = 1;
* -> here
*/
l = skipwhite(ml_get_curline());
if (cin_isdo(l))
{
if (whilelevel == 0)
break;
--whilelevel;
}
/*
* When searching for a terminated line, don't use the
* one between the "if" and the matching "else".
* Need to use the scope of this "else". XXX
* If whilelevel != 0 continue looking for a "do {".
*/
if (cin_iselse(l) && whilelevel == 0)
{
/* If we're looking at "} else", let's make sure we
* find the opening brace of the enclosing scope,
* not the one from "if () {". */
if (*l == '}')
curwin->w_cursor.col =
(colnr_T)(l - ml_get_curline()) + 1;
if ((trypos = find_start_brace(ind_maxcomment))
== NULL
|| find_match(LOOKFOR_IF, trypos->lnum,
ind_maxparen, ind_maxcomment) == FAIL)
break;
}
}
/*
* If we're below an unterminated line that is not an
* "if" or something, we may line up with this line or
* add something for a continuation line, depending on
* the line before this one.
*/
else
{
/*
* Found two unterminated lines on a row, line up with
* the last one.
* c = 99 +
* 100 +
* -> here;
*/
if (lookfor == LOOKFOR_UNTERM)
{
/* When line ends in a comma add extra indent */
if (terminated == ',')
amount += ind_continuation;
break;
}
if (lookfor == LOOKFOR_ENUM_OR_INIT)
{
/* Found two lines ending in ',', lineup with the
* lowest one, but check for cpp base class
* declaration/initialization, if it is an
* opening brace or we are looking just for
* enumerations/initializations. */
if (terminated == ',')
{
if (ind_cpp_baseclass == 0)
break;
lookfor = LOOKFOR_CPP_BASECLASS;
continue;
}
/* Ignore unterminated lines in between, but
* reduce indent. */
if (amount > cur_amount)
amount = cur_amount;
}
else
{
/*
* Found first unterminated line on a row, may
* line up with this line, remember its indent
* 100 +
* -> here;
*/
amount = cur_amount;
/*
* If previous line ends in ',', check whether we
* are in an initialization or enum
* struct xxx =
* {
* sizeof a,
* 124 };
* or a normal possible continuation line.
* but only, of no other statement has been found
* yet.
*/
if (lookfor == LOOKFOR_INITIAL && terminated == ',')
{
lookfor = LOOKFOR_ENUM_OR_INIT;
cont_amount = cin_first_id_amount();
}
else
{
if (lookfor == LOOKFOR_INITIAL
&& *l != NUL
&& l[STRLEN(l) - 1] == '\\')
/* XXX */
cont_amount = cin_get_equal_amount(
curwin->w_cursor.lnum);
if (lookfor != LOOKFOR_TERM)
lookfor = LOOKFOR_UNTERM;
}
}
}
}
/*
* Check if we are after a while (cond);
* If so: Ignore until the matching "do".
*/
/* XXX */
else if (cin_iswhileofdo_end(terminated, ind_maxparen,
ind_maxcomment))
{
/*
* Found an unterminated line after a while ();, line up
* with the last one.
* while (cond);
* 100 + <- line up with this one
* -> here;
*/
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
break;
}
if (whilelevel == 0)
{
lookfor = LOOKFOR_TERM;
amount = get_indent(); /* XXX */
if (theline[0] == '{')
amount += ind_open_extra;
}
++whilelevel;
}
/*
* We are after a "normal" statement.
* If we had another statement we can stop now and use the
* indent of that other statement.
* Otherwise the indent of the current statement may be used,
* search backwards for the next "normal" statement.
*/
else
{
/*
* Skip single break line, if before a switch label. It
* may be lined up with the case label.
*/
if (lookfor == LOOKFOR_NOBREAK
&& cin_isbreak(skipwhite(ml_get_curline())))
{
lookfor = LOOKFOR_ANY;
continue;
}
/*
* Handle "do {" line.
*/
if (whilelevel > 0)
{
l = cin_skipcomment(ml_get_curline());
if (cin_isdo(l))
{
amount = get_indent(); /* XXX */
--whilelevel;
continue;
}
}
/*
* Found a terminated line above an unterminated line. Add
* the amount for a continuation line.
* x = 1;
* y = foo +
* -> here;
* or
* int x = 1;
* int foo,
* -> here;
*/
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT)
{
if (cont_amount > 0)
amount = cont_amount;
else
amount += ind_continuation;
break;
}
/*
* Found a terminated line above a terminated line or "if"
* etc. line. Use the amount of the line below us.
* x = 1; x = 1;
* if (asdf) y = 2;
* while (asdf) ->here;
* here;
* ->foo;
*/
if (lookfor == LOOKFOR_TERM)
{
if (!lookfor_break && whilelevel == 0)
break;
}
/*
* First line above the one we're indenting is terminated.
* To know what needs to be done look further backward for
* a terminated line.
*/
else
{
/*
* position the cursor over the rightmost paren, so
* that matching it will take us back to the start of
* the line. Helps for:
* func(asdr,
* asdfasdf);
* here;
*/
term_again:
l = ml_get_curline();
if (find_last_paren(l, '(', ')')
&& (trypos = find_match_paren(ind_maxparen,
ind_maxcomment)) != NULL)
{
/*
* Check if we are on a case label now. This is
* handled above.
* case xx: if ( asdf &&
* asdf)
*/
curwin->w_cursor = *trypos;
l = ml_get_curline();
if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
{
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
continue;
}
}
/* When aligning with the case statement, don't align
* with a statement after it.
* case 1: { <-- don't use this { position
* stat;
* }
* case 2:
* stat;
* }
*/
iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
/*
* Get indent and pointer to text for current line,
* ignoring any jump label.
*/
amount = skip_label(curwin->w_cursor.lnum,
&l, ind_maxcomment);
if (theline[0] == '{')
amount += ind_open_extra;
/* See remark above: "Only add ind_open_extra.." */
l = skipwhite(l);
if (*l == '{')
amount -= ind_open_extra;
lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
/*
* When a terminated line starts with "else" skip to
* the matching "if":
* else 3;
* indent this;
* Need to use the scope of this "else". XXX
* If whilelevel != 0 continue looking for a "do {".
*/
if (lookfor == LOOKFOR_TERM
&& *l != '}'
&& cin_iselse(l)
&& whilelevel == 0)
{
if ((trypos = find_start_brace(ind_maxcomment))
== NULL
|| find_match(LOOKFOR_IF, trypos->lnum,
ind_maxparen, ind_maxcomment) == FAIL)
break;
continue;
}
/*
* If we're at the end of a block, skip to the start of
* that block.
*/
l = ml_get_curline();
if (find_last_paren(l, '{', '}')
&& (trypos = find_start_brace(ind_maxcomment))
!= NULL) /* XXX */
{
curwin->w_cursor = *trypos;
/* if not "else {" check for terminated again */
/* but skip block for "} else {" */
l = cin_skipcomment(ml_get_curline());
if (*l == '}' || !cin_iselse(l))
goto term_again;
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
}
}
}
}
}
}
/* add extra indent for a comment */
if (cin_iscomment(theline))
amount += ind_comment;
/* subtract extra left-shift for jump labels */
if (ind_jump_label > 0 && original_line_islabel)
amount -= ind_jump_label;
}
/*
* ok -- we're not inside any sort of structure at all!
*
* this means we're at the top level, and everything should
* basically just match where the previous line is, except
* for the lines immediately following a function declaration,
* which are K&R-style parameters and need to be indented.
*/
else
{
/*
* if our line starts with an open brace, forget about any
* prevailing indent and make sure it looks like the start
* of a function
*/
if (theline[0] == '{')
{
amount = ind_first_open;
}
/*
* If the NEXT line is a function declaration, the current
* line needs to be indented as a function type spec.
* Don't do this if the current line looks like a comment or if the
* current line is terminated, ie. ends in ';', or if the current line
* contains { or }: "void f() {\n if (1)"
*/
else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
&& !cin_nocode(theline)
&& vim_strchr(theline, '{') == NULL
&& vim_strchr(theline, '}') == NULL
&& !cin_ends_in(theline, (char_u *)":", NULL)
&& !cin_ends_in(theline, (char_u *)",", NULL)
&& cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
cur_curpos.lnum + 1,
ind_maxparen, ind_maxcomment)
&& !cin_isterminated(theline, FALSE, TRUE))
{
amount = ind_func_type;
}
else
{
amount = 0;
curwin->w_cursor = cur_curpos;
/* search backwards until we find something we recognize */
while (curwin->w_cursor.lnum > 1)
{
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
l = ml_get_curline();
/*
* If we're in a comment now, skip to the start of the comment.
*/ /* XXX */
if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
{
curwin->w_cursor.lnum = trypos->lnum + 1;
curwin->w_cursor.col = 0;
continue;
}
/*
* Are we at the start of a cpp base class declaration or
* constructor initialization?
*/ /* XXX */
n = FALSE;
if (ind_cpp_baseclass != 0 && theline[0] != '{')
{
n = cin_is_cpp_baseclass(&col);
l = ml_get_curline();
}
if (n)
{
/* XXX */
amount = get_baseclass_amount(col, ind_maxparen,
ind_maxcomment, ind_cpp_baseclass);
break;
}
/*
* Skip preprocessor directives and blank lines.
*/
if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
continue;
if (cin_nocode(l))
continue;
/*
* If the previous line ends in ',', use one level of
* indentation:
* int foo,
* bar;
* do this before checking for '}' in case of eg.
* enum foobar
* {
* ...
* } foo,
* bar;
*/
n = 0;
if (cin_ends_in(l, (char_u *)",", NULL)
|| (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
{
/* take us back to opening paren */
if (find_last_paren(l, '(', ')')
&& (trypos = find_match_paren(ind_maxparen,
ind_maxcomment)) != NULL)
curwin->w_cursor = *trypos;
/* For a line ending in ',' that is a continuation line go
* back to the first line with a backslash:
* char *foo = "bla\
* bla",
* here;
*/
while (n == 0 && curwin->w_cursor.lnum > 1)
{
l = ml_get(curwin->w_cursor.lnum - 1);
if (*l == NUL || l[STRLEN(l) - 1] != '\\')
break;
--curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
}
amount = get_indent(); /* XXX */
if (amount == 0)
amount = cin_first_id_amount();
if (amount == 0)
amount = ind_continuation;
break;
}
/*
* If the line looks like a function declaration, and we're
* not in a comment, put it the left margin.
*/
if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
ind_maxparen, ind_maxcomment)) /* XXX */
break;
l = ml_get_curline();
/*
* Finding the closing '}' of a previous function. Put
* current line at the left margin. For when 'cino' has "fs".
*/
if (*skipwhite(l) == '}')
break;
/* (matching {)
* If the previous line ends on '};' (maybe followed by
* comments) align at column 0. For example:
* char *string_array[] = { "foo",
* / * x * / "b};ar" }; / * foobar * /
*/
if (cin_ends_in(l, (char_u *)"};", NULL))
break;
/*
* Find a line only has a semicolon that belongs to a previous
* line ending in '}', e.g. before an #endif. Don't increase
* indent then.
*/
if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
{
pos_T curpos_save = curwin->w_cursor;
while (curwin->w_cursor.lnum > 1)
{
look = ml_get(--curwin->w_cursor.lnum);
if (!(cin_nocode(look) || cin_ispreproc_cont(
&look, &curwin->w_cursor.lnum)))
break;
}
if (curwin->w_cursor.lnum > 0
&& cin_ends_in(look, (char_u *)"}", NULL))
break;
curwin->w_cursor = curpos_save;
}
/*
* If the PREVIOUS line is a function declaration, the current
* line (and the ones that follow) needs to be indented as
* parameters.
*/
if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
ind_maxparen, ind_maxcomment))
{
amount = ind_param;
break;
}
/*
* If the previous line ends in ';' and the line before the
* previous line ends in ',' or '\', ident to column zero:
* int foo,
* bar;
* indent_to_0 here;
*/
if (cin_ends_in(l, (char_u *)";", NULL))
{
l = ml_get(curwin->w_cursor.lnum - 1);
if (cin_ends_in(l, (char_u *)",", NULL)
|| (*l != NUL && l[STRLEN(l) - 1] == '\\'))
break;
l = ml_get_curline();
}
/*
* Doesn't look like anything interesting -- so just
* use the indent of this line.
*
* Position the cursor over the rightmost paren, so that
* matching it will take us back to the start of the line.
*/
find_last_paren(l, '(', ')');
if ((trypos = find_match_paren(ind_maxparen,
ind_maxcomment)) != NULL)
curwin->w_cursor = *trypos;
amount = get_indent(); /* XXX */
break;
}
/* add extra indent for a comment */
if (cin_iscomment(theline))
amount += ind_comment;
/* add extra indent if the previous line ended in a backslash:
* "asdfasdf\
* here";
* char *foo = "asdf\
* here";
*/
if (cur_curpos.lnum > 1)
{
l = ml_get(cur_curpos.lnum - 1);
if (*l != NUL && l[STRLEN(l) - 1] == '\\')
{
cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
if (cur_amount > 0)
amount = cur_amount;
else if (cur_amount == 0)
amount += ind_continuation;
}
}
}
}
theend:
/* put the cursor back where it belongs */
curwin->w_cursor = cur_curpos;
vim_free(linecopy);
if (amount < 0)
return 0;
return amount;
}
static int
find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
int lookfor;
linenr_T ourscope;
int ind_maxparen;
int ind_maxcomment;
{
char_u *look;
pos_T *theirscope;
char_u *mightbeif;
int elselevel;
int whilelevel;
if (lookfor == LOOKFOR_IF)
{
elselevel = 1;
whilelevel = 0;
}
else
{
elselevel = 0;
whilelevel = 1;
}
curwin->w_cursor.col = 0;
while (curwin->w_cursor.lnum > ourscope + 1)
{
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
look = cin_skipcomment(ml_get_curline());
if (cin_iselse(look)
|| cin_isif(look)
|| cin_isdo(look) /* XXX */
|| cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
{
/*
* if we've gone outside the braces entirely,
* we must be out of scope...
*/
theirscope = find_start_brace(ind_maxcomment); /* XXX */
if (theirscope == NULL)
break;
/*
* and if the brace enclosing this is further
* back than the one enclosing the else, we're
* out of luck too.
*/
if (theirscope->lnum < ourscope)
break;
/*
* and if they're enclosed in a *deeper* brace,
* then we can ignore it because it's in a
* different scope...
*/
if (theirscope->lnum > ourscope)
continue;
/*
* if it was an "else" (that's not an "else if")
* then we need to go back to another if, so
* increment elselevel
*/
look = cin_skipcomment(ml_get_curline());
if (cin_iselse(look))
{
mightbeif = cin_skipcomment(look + 4);
if (!cin_isif(mightbeif))
++elselevel;
continue;
}
/*
* if it was a "while" then we need to go back to
* another "do", so increment whilelevel. XXX
*/
if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
{
++whilelevel;
continue;
}
/* If it's an "if" decrement elselevel */
look = cin_skipcomment(ml_get_curline());
if (cin_isif(look))
{
elselevel--;
/*
* When looking for an "if" ignore "while"s that
* get in the way.
*/
if (elselevel == 0 && lookfor == LOOKFOR_IF)
whilelevel = 0;
}
/* If it's a "do" decrement whilelevel */
if (cin_isdo(look))
whilelevel--;
/*
* if we've used up all the elses, then
* this must be the if that we want!
* match the indent level of that if.
*/
if (elselevel <= 0 && whilelevel <= 0)
{
return OK;
}
}
}
return FAIL;
}
# if defined(FEAT_EVAL) || defined(PROTO)
/*
* Get indent level from 'indentexpr'.
*/
int
get_expr_indent()
{
int indent;
pos_T pos;
int save_State;
int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
OPT_LOCAL);
pos = curwin->w_cursor;
set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
if (use_sandbox)
++sandbox;
++textlock;
indent = eval_to_number(curbuf->b_p_inde);
if (use_sandbox)
--sandbox;
--textlock;
/* Restore the cursor position so that 'indentexpr' doesn't need to.
* Pretend to be in Insert mode, allow cursor past end of line for "o"
* command. */
save_State = State;
State = INSERT;
curwin->w_cursor = pos;
check_cursor();
State = save_State;
/* If there is an error, just keep the current indent. */
if (indent < 0)
indent = get_indent();
return indent;
}
# endif
#endif /* FEAT_CINDENT */
#if defined(FEAT_LISP) || defined(PROTO)
static int lisp_match __ARGS((char_u *p));
static int
lisp_match(p)
char_u *p;
{
char_u buf[LSIZE];
int len;
char_u *word = p_lispwords;
while (*word != NUL)
{
(void)copy_option_part(&word, buf, LSIZE, ",");
len = (int)STRLEN(buf);
if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
return TRUE;
}
return FALSE;
}
/*
* When 'p' is present in 'cpoptions, a Vi compatible method is used.
* The incompatible newer method is quite a bit better at indenting
* code in lisp-like languages than the traditional one; it's still
* mostly heuristics however -- Dirk van Deun, dirk@rave.org
*
* TODO:
* Findmatch() should be adapted for lisp, also to make showmatch
* work correctly: now (v5.3) it seems all C/C++ oriented:
* - it does not recognize the #\( and #\) notations as character literals
* - it doesn't know about comments starting with a semicolon
* - it incorrectly interprets '(' as a character literal
* All this messes up get_lisp_indent in some rare cases.
* Update from Sergey Khorev:
* I tried to fix the first two issues.
*/
int
get_lisp_indent()
{
pos_T *pos, realpos, paren;
int amount;
char_u *that;
colnr_T col;
colnr_T firsttry;
int parencount, quotecount;
int vi_lisp;
/* Set vi_lisp to use the vi-compatible method */
vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
realpos = curwin->w_cursor;
curwin->w_cursor.col = 0;
if ((pos = findmatch(NULL, '(')) == NULL)
pos = findmatch(NULL, '[');
else
{
paren = *pos;
pos = findmatch(NULL, '[');
if (pos == NULL || ltp(pos, &paren))
pos = &paren;
}
if (pos != NULL)
{
/* Extra trick: Take the indent of the first previous non-white
* line that is at the same () level. */
amount = -1;
parencount = 0;
while (--curwin->w_cursor.lnum >= pos->lnum)
{
if (linewhite(curwin->w_cursor.lnum))
continue;
for (that = ml_get_curline(); *that != NUL; ++that)
{
if (*that == ';')
{
while (*(that + 1) != NUL)
++that;
continue;
}
if (*that == '\\')
{
if (*(that + 1) != NUL)
++that;
continue;
}
if (*that == '"' && *(that + 1) != NUL)
{
while (*++that && *that != '"')
{
/* skipping escaped characters in the string */
if (*that == '\\')
{
if (*++that == NUL)
break;
if (that[1] == NUL)
{
++that;
break;
}
}
}
}
if (*that == '(' || *that == '[')
++parencount;
else if (*that == ')' || *that == ']')
--parencount;
}
if (parencount == 0)
{
amount = get_indent();
break;
}
}
if (amount == -1)
{
curwin->w_cursor.lnum = pos->lnum;
curwin->w_cursor.col = pos->col;
col = pos->col;
that = ml_get_curline();
if (vi_lisp && get_indent() == 0)
amount = 2;
else
{
amount = 0;
while (*that && col)
{
amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
col--;
}
/*
* Some keywords require "body" indenting rules (the
* non-standard-lisp ones are Scheme special forms):
*
* (let ((a 1)) instead (let ((a 1))
* (...)) of (...))
*/
if (!vi_lisp && (*that == '(' || *that == '[')
&& lisp_match(that + 1))
amount += 2;
else
{
that++;
amount++;
firsttry = amount;
while (vim_iswhite(*that))
{
amount += lbr_chartabsize(that, (colnr_T)amount);
++that;
}
if (*that && *that != ';') /* not a comment line */
{
/* test *that != '(' to accommodate first let/do
* argument if it is more than one line */
if (!vi_lisp && *that != '(' && *that != '[')
firsttry++;
parencount = 0;
quotecount = 0;
if (vi_lisp
|| (*that != '"'
&& *that != '\''
&& *that != '#'
&& (*that < '0' || *that > '9')))
{
while (*that
&& (!vim_iswhite(*that)
|| quotecount
|| parencount)
&& (!((*that == '(' || *that == '[')
&& !quotecount
&& !parencount
&& vi_lisp)))
{
if (*that == '"')
quotecount = !quotecount;
if ((*that == '(' || *that == '[')
&& !quotecount)
++parencount;
if ((*that == ')' || *that == ']')
&& !quotecount)
--parencount;
if (*that == '\\' && *(that+1) != NUL)
amount += lbr_chartabsize_adv(&that,
(colnr_T)amount);
amount += lbr_chartabsize_adv(&that,
(colnr_T)amount);
}
}
while (vim_iswhite(*that))
{
amount += lbr_chartabsize(that, (colnr_T)amount);
that++;
}
if (!*that || *that == ';')
amount = firsttry;
}
}
}
}
}
else
amount = 0; /* no matching '(' or '[' found, use zero indent */
curwin->w_cursor = realpos;
return amount;
}
#endif /* FEAT_LISP */
void
prepare_to_exit()
{
#if defined(SIGHUP) && defined(SIG_IGN)
/* Ignore SIGHUP, because a dropped connection causes a read error, which
* makes Vim exit and then handling SIGHUP causes various reentrance
* problems. */
signal(SIGHUP, SIG_IGN);
#endif
#ifdef FEAT_GUI
if (gui.in_use)
{
gui.dying = TRUE;
out_trash(); /* trash any pending output */
}
else
#endif
{
windgoto((int)Rows - 1, 0);
/*
* Switch terminal mode back now, so messages end up on the "normal"
* screen (if there are two screens).
*/
settmode(TMODE_COOK);
#ifdef WIN3264
if (can_end_termcap_mode(FALSE) == TRUE)
#endif
stoptermcap();
out_flush();
}
}
/*
* Preserve files and exit.
* When called IObuff must contain a message.
*/
void
preserve_exit()
{
buf_T *buf;
prepare_to_exit();
/* Setting this will prevent free() calls. That avoids calling free()
* recursively when free() was invoked with a bad pointer. */
really_exiting = TRUE;
out_str(IObuff);
screen_start(); /* don't know where cursor is now */
out_flush();
ml_close_notmod(); /* close all not-modified buffers */
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
{
if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
{
OUT_STR(_("Vim: preserving files...\n"));
screen_start(); /* don't know where cursor is now */
out_flush();
ml_sync_all(FALSE, FALSE); /* preserve all swap files */
break;
}
}
ml_close_all(FALSE); /* close all memfiles, without deleting */
OUT_STR(_("Vim: Finished.\n"));
getout(1);
}
/*
* return TRUE if "fname" exists.
*/
int
vim_fexists(fname)
char_u *fname;
{
struct stat st;
if (mch_stat((char *)fname, &st))
return FALSE;
return TRUE;
}
/*
* Check for CTRL-C pressed, but only once in a while.
* Should be used instead of ui_breakcheck() for functions that check for
* each line in the file. Calling ui_breakcheck() each time takes too much
* time, because it can be a system call.
*/
#ifndef BREAKCHECK_SKIP
# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
# define BREAKCHECK_SKIP 200
# else
# define BREAKCHECK_SKIP 32
# endif
#endif
static int breakcheck_count = 0;
void
line_breakcheck()
{
if (++breakcheck_count >= BREAKCHECK_SKIP)
{
breakcheck_count = 0;
ui_breakcheck();
}
}
/*
* Like line_breakcheck() but check 10 times less often.
*/
void
fast_breakcheck()
{
if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
{
breakcheck_count = 0;
ui_breakcheck();
}
}
/*
* Invoke expand_wildcards() for one pattern.
* Expand items like "%:h" before the expansion.
* Returns OK or FAIL.
*/
int
expand_wildcards_eval(pat, num_file, file, flags)
char_u **pat; /* pointer to input pattern */
int *num_file; /* resulting number of files */
char_u ***file; /* array of resulting files */
int flags; /* EW_DIR, etc. */
{
int ret = FAIL;
char_u *eval_pat = NULL;
char_u *exp_pat = *pat;
char_u *ignored_msg;
int usedlen;
if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
{
++emsg_off;
eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
NULL, &ignored_msg, NULL);
--emsg_off;
if (eval_pat != NULL)
exp_pat = concat_str(eval_pat, exp_pat + usedlen);
}
if (exp_pat != NULL)
ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
if (eval_pat != NULL)
{
vim_free(exp_pat);
vim_free(eval_pat);
}
return ret;
}
/*
* Expand wildcards. Calls gen_expand_wildcards() and removes files matching
* 'wildignore'.
* Returns OK or FAIL. When FAIL then "num_file" won't be set.
*/
int
expand_wildcards(num_pat, pat, num_file, file, flags)
int num_pat; /* number of input patterns */
char_u **pat; /* array of input patterns */
int *num_file; /* resulting number of files */
char_u ***file; /* array of resulting files */
int flags; /* EW_DIR, etc. */
{
int retval;
int i, j;
char_u *p;
int non_suf_match; /* number without matching suffix */
retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
/* When keeping all matches, return here */
if ((flags & EW_KEEPALL) || retval == FAIL)
return retval;
#ifdef FEAT_WILDIGN
/*
* Remove names that match 'wildignore'.
*/
if (*p_wig)
{
char_u *ffname;
/* check all files in (*file)[] */
for (i = 0; i < *num_file; ++i)
{
ffname = FullName_save((*file)[i], FALSE);
if (ffname == NULL) /* out of memory */
break;
# ifdef VMS
vms_remove_version(ffname);
# endif
if (match_file_list(p_wig, (*file)[i], ffname))
{
/* remove this matching file from the list */
vim_free((*file)[i]);
for (j = i; j + 1 < *num_file; ++j)
(*file)[j] = (*file)[j + 1];
--*num_file;
--i;
}
vim_free(ffname);
}
}
#endif
/*
* Move the names where 'suffixes' match to the end.
*/
if (*num_file > 1)
{
non_suf_match = 0;
for (i = 0; i < *num_file; ++i)
{
if (!match_suffix((*file)[i]))
{
/*
* Move the name without matching suffix to the front
* of the list.
*/
p = (*file)[i];
for (j = i; j > non_suf_match; --j)
(*file)[j] = (*file)[j - 1];
(*file)[non_suf_match++] = p;
}
}
}
return retval;
}
/*
* Return TRUE if "fname" matches with an entry in 'suffixes'.
*/
int
match_suffix(fname)
char_u *fname;
{
int fnamelen, setsuflen;
char_u *setsuf;
#define MAXSUFLEN 30 /* maximum length of a file suffix */
char_u suf_buf[MAXSUFLEN];
fnamelen = (int)STRLEN(fname);
setsuflen = 0;
for (setsuf = p_su; *setsuf; )
{
setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
if (setsuflen == 0)
{
char_u *tail = gettail(fname);
/* empty entry: match name without a '.' */
if (vim_strchr(tail, '.') == NULL)
{
setsuflen = 1;
break;
}
}
else
{
if (fnamelen >= setsuflen
&& fnamencmp(suf_buf, fname + fnamelen - setsuflen,
(size_t)setsuflen) == 0)
break;
setsuflen = 0;
}
}
return (setsuflen != 0);
}
#if !defined(NO_EXPANDPATH) || defined(PROTO)
# ifdef VIM_BACKTICK
static int vim_backtick __ARGS((char_u *p));
static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
# endif
# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
/*
* File name expansion code for MS-DOS, Win16 and Win32. It's here because
* it's shared between these systems.
*/
# if defined(DJGPP) || defined(PROTO)
# define _cdecl /* DJGPP doesn't have this */
# else
# ifdef __BORLANDC__
# define _cdecl _RTLENTRYF
# endif
# endif
/*
* comparison function for qsort in dos_expandpath()
*/
static int _cdecl
pstrcmp(const void *a, const void *b)
{
return (pathcmp(*(char **)a, *(char **)b, -1));
}
# ifndef WIN3264
static void
namelowcpy(
char_u *d,
char_u *s)
{
# ifdef DJGPP
if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
while (*s)
*d++ = *s++;
else
# endif
while (*s)
*d++ = TOLOWER_LOC(*s++);
*d = NUL;
}
# endif
/*
* Recursively expand one path component into all matching files and/or
* directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
* Return the number of matches found.
* "path" has backslashes before chars that are not to be expanded, starting
* at "path[wildoff]".
* Return the number of matches found.
* NOTE: much of this is identical to unix_expandpath(), keep in sync!
*/
static int
dos_expandpath(
garray_T *gap,
char_u *path,
int wildoff,
int flags, /* EW_* flags */
int didstar) /* expanded "**" once already */
{
char_u *buf;
char_u *path_end;
char_u *p, *s, *e;
int start_len = gap->ga_len;
char_u *pat;
regmatch_T regmatch;
int starts_with_dot;
int matches;
int len;
int starstar = FALSE;
static int stardepth = 0; /* depth for "**" expansion */
#ifdef WIN3264
WIN32_FIND_DATA fb;
HANDLE hFind = (HANDLE)0;
# ifdef FEAT_MBYTE
WIN32_FIND_DATAW wfb;
WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
# endif
#else
struct ffblk fb;
#endif
char_u *matchname;
int ok;
/* Expanding "**" may take a long time, check for CTRL-C. */
if (stardepth > 0)
{
ui_breakcheck();
if (got_int)
return 0;
}
/* make room for file name */
buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
if (buf == NULL)
return 0;
/*
* Find the first part in the path name that contains a wildcard or a ~1.
* Copy it into buf, including the preceding characters.
*/
p = buf;
s = buf;
e = NULL;
path_end = path;
while (*path_end != NUL)
{
/* May ignore a wildcard that has a backslash before it; it will
* be removed by rem_backslash() or file_pat_to_reg_pat() below. */
if (path_end >= path + wildoff && rem_backslash(path_end))
*p++ = *path_end++;
else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
{
if (e != NULL)
break;
s = p + 1;
}
else if (path_end >= path + wildoff
&& vim_strchr((char_u *)"*?[~", *path_end) != NULL)
e = p;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
len = (*mb_ptr2len)(path_end);
STRNCPY(p, path_end, len);
p += len;
path_end += len;
}
else
#endif
*p++ = *path_end++;
}
e = p;
*e = NUL;
/* now we have one wildcard component between s and e */
/* Remove backslashes between "wildoff" and the start of the wildcard
* component. */
for (p = buf + wildoff; p < s; ++p)
if (rem_backslash(p))
{
STRMOVE(p, p + 1);
--e;
--s;
}
/* Check for "**" between "s" and "e". */
for (p = s; p < e; ++p)
if (p[0] == '*' && p[1] == '*')
starstar = TRUE;
starts_with_dot = (*s == '.');
pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
if (pat == NULL)
{
vim_free(buf);
return 0;
}
/* compile the regexp into a program */
if (flags & (EW_NOERROR | EW_NOTWILD))
++emsg_silent;
regmatch.rm_ic = TRUE; /* Always ignore case */
regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
if (flags & (EW_NOERROR | EW_NOTWILD))
--emsg_silent;
vim_free(pat);
if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
{
vim_free(buf);
return 0;
}
/* remember the pattern or file name being looked for */
matchname = vim_strsave(s);
/* If "**" is by itself, this is the first time we encounter it and more
* is following then find matches without any directory. */
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/')
{
STRCPY(s, path_end + 1);
++stardepth;
(void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
--stardepth;
}
/* Scan all files in the directory with "dir/ *.*" */
STRCPY(s, "*.*");
#ifdef WIN3264
# ifdef FEAT_MBYTE
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
/* The active codepage differs from 'encoding'. Attempt using the
* wide function. If it fails because it is not implemented fall back
* to the non-wide version (for Windows 98) */
wn = enc_to_utf16(buf, NULL);
if (wn != NULL)
{
hFind = FindFirstFileW(wn, &wfb);
if (hFind == INVALID_HANDLE_VALUE
&& GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
vim_free(wn);
wn = NULL;
}
}
}
if (wn == NULL)
# endif
hFind = FindFirstFile(buf, &fb);
ok = (hFind != INVALID_HANDLE_VALUE);
#else
/* If we are expanding wildcards we try both files and directories */
ok = (findfirst((char *)buf, &fb,
(*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
#endif
while (ok)
{
#ifdef WIN3264
# ifdef FEAT_MBYTE
if (wn != NULL)
p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
else
# endif
p = (char_u *)fb.cFileName;
#else
p = (char_u *)fb.ff_name;
#endif
/* Ignore entries starting with a dot, unless when asked for. Accept
* all entries found with "matchname". */
if ((p[0] != '.' || starts_with_dot)
&& (matchname == NULL
|| (regmatch.regprog != NULL
&& vim_regexec(®match, p, (colnr_T)0))
|| ((flags & EW_NOTWILD)
&& fnamencmp(path + (s - buf), p, e - s) == 0)))
{
#ifdef WIN3264
STRCPY(s, p);
#else
namelowcpy(s, p);
#endif
len = (int)STRLEN(buf);
if (starstar && stardepth < 100)
{
/* For "**" in the pattern first go deeper in the tree to
* find matches. */
STRCPY(buf + len, "/**");
STRCPY(buf + len + 3, path_end);
++stardepth;
(void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
--stardepth;
}
STRCPY(buf + len, path_end);
if (mch_has_exp_wildcard(path_end))
{
/* need to expand another component of the path */
/* remove backslashes for the remaining components only */
(void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
}
else
{
/* no more wildcards, check if there is a match */
/* remove backslashes for the remaining components only */
if (*path_end != 0)
backslash_halve(buf + len + 1);
if (mch_getperm(buf) >= 0) /* add existing file */
addfile(gap, buf, flags);
}
}
#ifdef WIN3264
# ifdef FEAT_MBYTE
if (wn != NULL)
{
vim_free(p);
ok = FindNextFileW(hFind, &wfb);
}
else
# endif
ok = FindNextFile(hFind, &fb);
#else
ok = (findnext(&fb) == 0);
#endif
/* If no more matches and no match was used, try expanding the name
* itself. Finds the long name of a short filename. */
if (!ok && matchname != NULL && gap->ga_len == start_len)
{
STRCPY(s, matchname);
#ifdef WIN3264
FindClose(hFind);
# ifdef FEAT_MBYTE
if (wn != NULL)
{
vim_free(wn);
wn = enc_to_utf16(buf, NULL);
if (wn != NULL)
hFind = FindFirstFileW(wn, &wfb);
}
if (wn == NULL)
# endif
hFind = FindFirstFile(buf, &fb);
ok = (hFind != INVALID_HANDLE_VALUE);
#else
ok = (findfirst((char *)buf, &fb,
(*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
#endif
vim_free(matchname);
matchname = NULL;
}
}
#ifdef WIN3264
FindClose(hFind);
# ifdef FEAT_MBYTE
vim_free(wn);
# endif
#endif
vim_free(buf);
vim_free(regmatch.regprog);
vim_free(matchname);
matches = gap->ga_len - start_len;
if (matches > 0)
qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
sizeof(char_u *), pstrcmp);
return matches;
}
int
mch_expandpath(
garray_T *gap,
char_u *path,
int flags) /* EW_* flags */
{
return dos_expandpath(gap, path, 0, flags, FALSE);
}
# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
|| defined(PROTO)
/*
* Unix style wildcard expansion code.
* It's here because it's used both for Unix and Mac.
*/
static int pstrcmp __ARGS((const void *, const void *));
static int
pstrcmp(a, b)
const void *a, *b;
{
return (pathcmp(*(char **)a, *(char **)b, -1));
}
/*
* Recursively expand one path component into all matching files and/or
* directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
* "path" has backslashes before chars that are not to be expanded, starting
* at "path + wildoff".
* Return the number of matches found.
* NOTE: much of this is identical to dos_expandpath(), keep in sync!
*/
int
unix_expandpath(gap, path, wildoff, flags, didstar)
garray_T *gap;
char_u *path;
int wildoff;
int flags; /* EW_* flags */
int didstar; /* expanded "**" once already */
{
char_u *buf;
char_u *path_end;
char_u *p, *s, *e;
int start_len = gap->ga_len;
char_u *pat;
regmatch_T regmatch;
int starts_with_dot;
int matches;
int len;
int starstar = FALSE;
static int stardepth = 0; /* depth for "**" expansion */
DIR *dirp;
struct dirent *dp;
/* Expanding "**" may take a long time, check for CTRL-C. */
if (stardepth > 0)
{
ui_breakcheck();
if (got_int)
return 0;
}
/* make room for file name */
buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
if (buf == NULL)
return 0;
/*
* Find the first part in the path name that contains a wildcard.
* When EW_ICASE is set every letter is considered to be a wildcard.
* Copy it into "buf", including the preceding characters.
*/
p = buf;
s = buf;
e = NULL;
path_end = path;
while (*path_end != NUL)
{
/* May ignore a wildcard that has a backslash before it; it will
* be removed by rem_backslash() or file_pat_to_reg_pat() below. */
if (path_end >= path + wildoff && rem_backslash(path_end))
*p++ = *path_end++;
else if (*path_end == '/')
{
if (e != NULL)
break;
s = p + 1;
}
else if (path_end >= path + wildoff
&& (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
#ifndef CASE_INSENSITIVE_FILENAME
|| ((flags & EW_ICASE)
&& isalpha(PTR2CHAR(path_end)))
#endif
))
e = p;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
len = (*mb_ptr2len)(path_end);
STRNCPY(p, path_end, len);
p += len;
path_end += len;
}
else
#endif
*p++ = *path_end++;
}
e = p;
*e = NUL;
/* Now we have one wildcard component between "s" and "e". */
/* Remove backslashes between "wildoff" and the start of the wildcard
* component. */
for (p = buf + wildoff; p < s; ++p)
if (rem_backslash(p))
{
STRMOVE(p, p + 1);
--e;
--s;
}
/* Check for "**" between "s" and "e". */
for (p = s; p < e; ++p)
if (p[0] == '*' && p[1] == '*')
starstar = TRUE;
/* convert the file pattern to a regexp pattern */
starts_with_dot = (*s == '.');
pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
if (pat == NULL)
{
vim_free(buf);
return 0;
}
/* compile the regexp into a program */
#ifdef CASE_INSENSITIVE_FILENAME
regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
#else
if (flags & EW_ICASE)
regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
else
regmatch.rm_ic = FALSE; /* Don't ignore case */
#endif
if (flags & (EW_NOERROR | EW_NOTWILD))
++emsg_silent;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
if (flags & (EW_NOERROR | EW_NOTWILD))
--emsg_silent;
vim_free(pat);
if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
{
vim_free(buf);
return 0;
}
/* If "**" is by itself, this is the first time we encounter it and more
* is following then find matches without any directory. */
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/')
{
STRCPY(s, path_end + 1);
++stardepth;
(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
--stardepth;
}
/* open the directory for scanning */
*s = NUL;
dirp = opendir(*buf == NUL ? "." : (char *)buf);
/* Find all matching entries */
if (dirp != NULL)
{
for (;;)
{
dp = readdir(dirp);
if (dp == NULL)
break;
if ((dp->d_name[0] != '.' || starts_with_dot)
&& ((regmatch.regprog != NULL && vim_regexec(®match,
(char_u *)dp->d_name, (colnr_T)0))
|| ((flags & EW_NOTWILD)
&& fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
{
STRCPY(s, dp->d_name);
len = STRLEN(buf);
if (starstar && stardepth < 100)
{
/* For "**" in the pattern first go deeper in the tree to
* find matches. */
STRCPY(buf + len, "/**");
STRCPY(buf + len + 3, path_end);
++stardepth;
(void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
--stardepth;
}
STRCPY(buf + len, path_end);
if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
{
/* need to expand another component of the path */
/* remove backslashes for the remaining components only */
(void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
}
else
{
/* no more wildcards, check if there is a match */
/* remove backslashes for the remaining components only */
if (*path_end != NUL)
backslash_halve(buf + len + 1);
if (mch_getperm(buf) >= 0) /* add existing file */
{
#ifdef MACOS_CONVERT
size_t precomp_len = STRLEN(buf)+1;
char_u *precomp_buf =
mac_precompose_path(buf, precomp_len, &precomp_len);
if (precomp_buf)
{
mch_memmove(buf, precomp_buf, precomp_len);
vim_free(precomp_buf);
}
#endif
addfile(gap, buf, flags);
}
}
}
}
closedir(dirp);
}
vim_free(buf);
vim_free(regmatch.regprog);
matches = gap->ga_len - start_len;
if (matches > 0)
qsort(((char_u **)gap->ga_data) + start_len, matches,
sizeof(char_u *), pstrcmp);
return matches;
}
#endif
#if defined(FEAT_SEARCHPATH)
static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
/*
* Moves "*psep" back to the previous path separator in "path".
* Returns FAIL is "*psep" ends up at the beginning of "path".
*/
static int
find_previous_pathsep(path, psep)
char_u *path;
char_u **psep;
{
/* skip the current separator */
if (*psep > path && vim_ispathsep(**psep))
--*psep;
/* find the previous separator */
while (*psep > path)
{
if (vim_ispathsep(**psep))
return OK;
mb_ptr_back(path, *psep);
}
return FAIL;
}
/*
* Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
* "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
*/
static int
is_unique(maybe_unique, gap, i)
char_u *maybe_unique;
garray_T *gap;
int i;
{
int j;
int candidate_len;
int other_path_len;
char_u **other_paths = (char_u **)gap->ga_data;
char_u *rival;
for (j = 0; j < gap->ga_len; j++)
{
if (j == i)
continue; /* don't compare it with itself */
candidate_len = (int)STRLEN(maybe_unique);
other_path_len = (int)STRLEN(other_paths[j]);
if (other_path_len < candidate_len)
continue; /* it's different when it's shorter */
rival = other_paths[j] + other_path_len - candidate_len;
if (fnamecmp(maybe_unique, rival) == 0
&& (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
return FALSE; /* match */
}
return TRUE; /* no match found */
}
/*
* Split the 'path' option into an array of strings in garray_T. Relative
* paths are expanded to their equivalent fullpath. This includes the "."
* (relative to current buffer directory) and empty path (relative to current
* directory) notations.
*
* TODO: handle upward search (;) and path limiter (**N) notations by
* expanding each into their equivalent path(s).
*/
static void
expand_path_option(curdir, gap)
char_u *curdir;
garray_T *gap;
{
char_u *path_option = *curbuf->b_p_path == NUL
? p_path : curbuf->b_p_path;
char_u *buf;
char_u *p;
int len;
if ((buf = alloc((int)MAXPATHL)) == NULL)
return;
while (*path_option != NUL)
{
copy_option_part(&path_option, buf, MAXPATHL, " ,");
if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
{
/* Relative to current buffer:
* "/path/file" + "." -> "/path/"
* "/path/file" + "./subdir" -> "/path/subdir" */
if (curbuf->b_ffname == NULL)
continue;
p = gettail(curbuf->b_ffname);
len = (int)(p - curbuf->b_ffname);
if (len + (int)STRLEN(buf) >= MAXPATHL)
continue;
if (buf[1] == NUL)
buf[len] = NUL;
else
STRMOVE(buf + len, buf + 2);
mch_memmove(buf, curbuf->b_ffname, len);
simplify_filename(buf);
}
else if (buf[0] == NUL)
/* relative to current directory */
STRCPY(buf, curdir);
else if (path_with_url(buf))
/* URL can't be used here */
continue;
else if (!mch_isFullName(buf))
{
/* Expand relative path to their full path equivalent */
len = (int)STRLEN(curdir);
if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
continue;
STRMOVE(buf + len + 1, buf);
STRCPY(buf, curdir);
buf[len] = PATHSEP;
simplify_filename(buf);
}
if (ga_grow(gap, 1) == FAIL)
break;
p = vim_strsave(buf);
if (p == NULL)
break;
((char_u **)gap->ga_data)[gap->ga_len++] = p;
}
vim_free(buf);
}
/*
* Returns a pointer to the file or directory name in "fname" that matches the
* longest path in "ga"p, or NULL if there is no match. For example:
*
* path: /foo/bar/baz
* fname: /foo/bar/baz/quux.txt
* returns: ^this
*/
static char_u *
get_path_cutoff(fname, gap)
char_u *fname;
garray_T *gap;
{
int i;
int maxlen = 0;
char_u **path_part = (char_u **)gap->ga_data;
char_u *cutoff = NULL;
for (i = 0; i < gap->ga_len; i++)
{
int j = 0;
while ((fname[j] == path_part[i][j]
# if defined(MSWIN) || defined(MSDOS)
|| (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
#endif
) && fname[j] != NUL && path_part[i][j] != NUL)
j++;
if (j > maxlen)
{
maxlen = j;
cutoff = &fname[j];
}
}
/* skip to the file or directory name */
if (cutoff != NULL)
while (vim_ispathsep(*cutoff))
mb_ptr_adv(cutoff);
return cutoff;
}
/*
* Sorts, removes duplicates and modifies all the fullpath names in "gap" so
* that they are unique with respect to each other while conserving the part
* that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
*/
static void
uniquefy_paths(gap, pattern)
garray_T *gap;
char_u *pattern;
{
int i;
int len;
char_u **fnames = (char_u **)gap->ga_data;
int sort_again = FALSE;
char_u *pat;
char_u *file_pattern;
char_u *curdir;
regmatch_T regmatch;
garray_T path_ga;
char_u **in_curdir = NULL;
char_u *short_name;
remove_duplicates(gap);
ga_init2(&path_ga, (int)sizeof(char_u *), 1);
/*
* We need to prepend a '*' at the beginning of file_pattern so that the
* regex matches anywhere in the path. FIXME: is this valid for all
* possible patterns?
*/
len = (int)STRLEN(pattern);
file_pattern = alloc(len + 2);
if (file_pattern == NULL)
return;
file_pattern[0] = '*';
file_pattern[1] = NUL;
STRCAT(file_pattern, pattern);
pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
vim_free(file_pattern);
if (pat == NULL)
return;
regmatch.rm_ic = TRUE; /* always ignore case */
regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
vim_free(pat);
if (regmatch.regprog == NULL)
return;
if ((curdir = alloc((int)(MAXPATHL))) == NULL)
goto theend;
mch_dirname(curdir, MAXPATHL);
expand_path_option(curdir, &path_ga);
in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
if (in_curdir == NULL)
goto theend;
for (i = 0; i < gap->ga_len && !got_int; i++)
{
char_u *path = fnames[i];
int is_in_curdir;
char_u *dir_end = gettail_dir(path);
char_u *pathsep_p;
char_u *path_cutoff;
len = (int)STRLEN(path);
is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
&& curdir[dir_end - path] == NUL;
if (is_in_curdir)
in_curdir[i] = vim_strsave(path);
/* Shorten the filename while maintaining its uniqueness */
path_cutoff = get_path_cutoff(path, &path_ga);
/* we start at the end of the path */
pathsep_p = path + len - 1;
while (find_previous_pathsep(path, &pathsep_p))
if (vim_regexec(®match, pathsep_p + 1, (colnr_T)0)
&& is_unique(pathsep_p + 1, gap, i)
&& path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
{
sort_again = TRUE;
mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
break;
}
if (mch_isFullName(path))
{
/*
* Last resort: shorten relative to curdir if possible.
* 'possible' means:
* 1. It is under the current directory.
* 2. The result is actually shorter than the original.
*
* Before curdir After
* /foo/bar/file.txt /foo/bar ./file.txt
* c:\foo\bar\file.txt c:\foo\bar .\file.txt
* /file.txt / /file.txt
* c:\file.txt c:\ .\file.txt
*/
short_name = shorten_fname(path, curdir);
if (short_name != NULL && short_name > path + 1
#if defined(MSWIN) || defined(MSDOS)
/* On windows,
* shorten_fname("c:\a\a.txt", "c:\a\b")
* returns "\a\a.txt", which is not really the short
* name, hence: */
&& !vim_ispathsep(*short_name)
#endif
)
{
STRCPY(path, ".");
add_pathsep(path);
STRMOVE(path + STRLEN(path), short_name);
}
}
ui_breakcheck();
}
/* Shorten filenames in /in/current/directory/{filename} */
for (i = 0; i < gap->ga_len && !got_int; i++)
{
char_u *rel_path;
char_u *path = in_curdir[i];
if (path == NULL)
continue;
/* If the {filename} is not unique, change it to ./{filename}.
* Else reduce it to {filename} */
short_name = shorten_fname(path, curdir);
if (short_name == NULL)
short_name = path;
if (is_unique(short_name, gap, i))
{
STRCPY(fnames[i], short_name);
continue;
}
rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
if (rel_path == NULL)
goto theend;
STRCPY(rel_path, ".");
add_pathsep(rel_path);
STRCAT(rel_path, short_name);
vim_free(fnames[i]);
fnames[i] = rel_path;
sort_again = TRUE;
ui_breakcheck();
}
theend:
vim_free(curdir);
if (in_curdir != NULL)
{
for (i = 0; i < gap->ga_len; i++)
vim_free(in_curdir[i]);
vim_free(in_curdir);
}
ga_clear_strings(&path_ga);
vim_free(regmatch.regprog);
if (sort_again)
remove_duplicates(gap);
}
/*
* Calls globpath() with 'path' values for the given pattern and stores the
* result in "gap".
* Returns the total number of matches.
*/
static int
expand_in_path(gap, pattern, flags)
garray_T *gap;
char_u *pattern;
int flags; /* EW_* flags */
{
char_u *curdir;
garray_T path_ga;
char_u *files = NULL;
char_u *s; /* start */
char_u *e; /* end */
char_u *paths = NULL;
if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
return 0;
mch_dirname(curdir, MAXPATHL);
ga_init2(&path_ga, (int)sizeof(char_u *), 1);
expand_path_option(curdir, &path_ga);
vim_free(curdir);
if (path_ga.ga_len == 0)
return 0;
paths = ga_concat_strings(&path_ga);
ga_clear_strings(&path_ga);
if (paths == NULL)
return 0;
files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
vim_free(paths);
if (files == NULL)
return 0;
/* Copy each path in files into gap */
s = e = files;
while (*s != NUL)
{
while (*e != '\n' && *e != NUL)
e++;
if (*e == NUL)
{
addfile(gap, s, flags);
break;
}
else
{
/* *e is '\n' */
*e = NUL;
addfile(gap, s, flags);
e++;
s = e;
}
}
vim_free(files);
return gap->ga_len;
}
#endif
#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Sort "gap" and remove duplicate entries. "gap" is expected to contain a
* list of file names in allocated memory.
*/
void
remove_duplicates(gap)
garray_T *gap;
{
int i;
int j;
char_u **fnames = (char_u **)gap->ga_data;
sort_strings(fnames, gap->ga_len);
for (i = gap->ga_len - 1; i > 0; --i)
if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
{
vim_free(fnames[i]);
for (j = i + 1; j < gap->ga_len; ++j)
fnames[j - 1] = fnames[j];
--gap->ga_len;
}
}
#endif
/*
* Generic wildcard expansion code.
*
* Characters in "pat" that should not be expanded must be preceded with a
* backslash. E.g., "/path\ with\ spaces/my\*star*"
*
* Return FAIL when no single file was found. In this case "num_file" is not
* set, and "file" may contain an error message.
* Return OK when some files found. "num_file" is set to the number of
* matches, "file" to the array of matches. Call FreeWild() later.
*/
int
gen_expand_wildcards(num_pat, pat, num_file, file, flags)
int num_pat; /* number of input patterns */
char_u **pat; /* array of input patterns */
int *num_file; /* resulting number of files */
char_u ***file; /* array of resulting files */
int flags; /* EW_* flags */
{
int i;
garray_T ga;
char_u *p;
static int recursive = FALSE;
int add_pat;
#if defined(FEAT_SEARCHPATH)
int did_expand_in_path = FALSE;
#endif
/*
* expand_env() is called to expand things like "~user". If this fails,
* it calls ExpandOne(), which brings us back here. In this case, always
* call the machine specific expansion function, if possible. Otherwise,
* return FAIL.
*/
if (recursive)
#ifdef SPECIAL_WILDCHAR
return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
#else
return FAIL;
#endif
#ifdef SPECIAL_WILDCHAR
/*
* If there are any special wildcard characters which we cannot handle
* here, call machine specific function for all the expansion. This
* avoids starting the shell for each argument separately.
* For `=expr` do use the internal function.
*/
for (i = 0; i < num_pat; i++)
{
if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
# ifdef VIM_BACKTICK
&& !(vim_backtick(pat[i]) && pat[i][1] == '=')
# endif
)
return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
}
#endif
recursive = TRUE;
/*
* The matching file names are stored in a growarray. Init it empty.
*/
ga_init2(&ga, (int)sizeof(char_u *), 30);
for (i = 0; i < num_pat; ++i)
{
add_pat = -1;
p = pat[i];
#ifdef VIM_BACKTICK
if (vim_backtick(p))
add_pat = expand_backtick(&ga, p, flags);
else
#endif
{
/*
* First expand environment variables, "~/" and "~user/".
*/
if (vim_strchr(p, '$') != NULL || *p == '~')
{
p = expand_env_save_opt(p, TRUE);
if (p == NULL)
p = pat[i];
#ifdef UNIX
/*
* On Unix, if expand_env() can't expand an environment
* variable, use the shell to do that. Discard previously
* found file names and start all over again.
*/
else if (vim_strchr(p, '$') != NULL || *p == '~')
{
vim_free(p);
ga_clear_strings(&ga);
i = mch_expand_wildcards(num_pat, pat, num_file, file,
flags);
recursive = FALSE;
return i;
}
#endif
}
/*
* If there are wildcards: Expand file names and add each match to
* the list. If there is no match, and EW_NOTFOUND is given, add
* the pattern.
* If there are no wildcards: Add the file name if it exists or
* when EW_NOTFOUND is given.
*/
if (mch_has_exp_wildcard(p))
{
#if defined(FEAT_SEARCHPATH)
if ((flags & EW_PATH)
&& !mch_isFullName(p)
&& !(p[0] == '.'
&& (vim_ispathsep(p[1])
|| (p[1] == '.' && vim_ispathsep(p[2]))))
)
{
/* :find completion where 'path' is used.
* Recursiveness is OK here. */
recursive = FALSE;
add_pat = expand_in_path(&ga, p, flags);
recursive = TRUE;
did_expand_in_path = TRUE;
}
else
#endif
add_pat = mch_expandpath(&ga, p, flags);
}
}
if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
{
char_u *t = backslash_halve_save(p);
#if defined(MACOS_CLASSIC)
slash_to_colon(t);
#endif
/* When EW_NOTFOUND is used, always add files and dirs. Makes
* "vim c:/" work. */
if (flags & EW_NOTFOUND)
addfile(&ga, t, flags | EW_DIR | EW_FILE);
else if (mch_getperm(t) >= 0)
addfile(&ga, t, flags);
vim_free(t);
}
#if defined(FEAT_SEARCHPATH)
if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
uniquefy_paths(&ga, p);
#endif
if (p != pat[i])
vim_free(p);
}
*num_file = ga.ga_len;
*file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
recursive = FALSE;
return (ga.ga_data != NULL) ? OK : FAIL;
}
# ifdef VIM_BACKTICK
/*
* Return TRUE if we can expand this backtick thing here.
*/
static int
vim_backtick(p)
char_u *p;
{
return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
}
/*
* Expand an item in `backticks` by executing it as a command.
* Currently only works when pat[] starts and ends with a `.
* Returns number of file names found.
*/
static int
expand_backtick(gap, pat, flags)
garray_T *gap;
char_u *pat;
int flags; /* EW_* flags */
{
char_u *p;
char_u *cmd;
char_u *buffer;
int cnt = 0;
int i;
/* Create the command: lop off the backticks. */
cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
if (cmd == NULL)
return 0;
#ifdef FEAT_EVAL
if (*cmd == '=') /* `={expr}`: Expand expression */
buffer = eval_to_string(cmd + 1, &p, TRUE);
else
#endif
buffer = get_cmd_output(cmd, NULL,
(flags & EW_SILENT) ? SHELL_SILENT : 0);
vim_free(cmd);
if (buffer == NULL)
return 0;
cmd = buffer;
while (*cmd != NUL)
{
cmd = skipwhite(cmd); /* skip over white space */
p = cmd;
while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
++p;
/* add an entry if it is not empty */
if (p > cmd)
{
i = *p;
*p = NUL;
addfile(gap, cmd, flags);
*p = i;
++cnt;
}
cmd = p;
while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
++cmd;
}
vim_free(buffer);
return cnt;
}
# endif /* VIM_BACKTICK */
/*
* Add a file to a file list. Accepted flags:
* EW_DIR add directories
* EW_FILE add files
* EW_EXEC add executable files
* EW_NOTFOUND add even when it doesn't exist
* EW_ADDSLASH add slash after directory name
*/
void
addfile(gap, f, flags)
garray_T *gap;
char_u *f; /* filename */
int flags;
{
char_u *p;
int isdir;
/* if the file/dir doesn't exist, may not add it */
if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
return;
#ifdef FNAME_ILLEGAL
/* if the file/dir contains illegal characters, don't add it */
if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
return;
#endif
isdir = mch_isdir(f);
if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
return;
/* If the file isn't executable, may not add it. Do accept directories. */
if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
return;
/* Make room for another item in the file list. */
if (ga_grow(gap, 1) == FAIL)
return;
p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
if (p == NULL)
return;
STRCPY(p, f);
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(p);
#endif
/*
* Append a slash or backslash after directory names if none is present.
*/
#ifndef DONT_ADD_PATHSEP_TO_DIR
if (isdir && (flags & EW_ADDSLASH))
add_pathsep(p);
#endif
((char_u **)gap->ga_data)[gap->ga_len++] = p;
}
#endif /* !NO_EXPANDPATH */
#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
#ifndef SEEK_SET
# define SEEK_SET 0
#endif
#ifndef SEEK_END
# define SEEK_END 2
#endif
/*
* Get the stdout of an external command.
* Returns an allocated string, or NULL for error.
*/
char_u *
get_cmd_output(cmd, infile, flags)
char_u *cmd;
char_u *infile; /* optional input file name */
int flags; /* can be SHELL_SILENT */
{
char_u *tempname;
char_u *command;
char_u *buffer = NULL;
int len;
int i = 0;
FILE *fd;
if (check_restricted() || check_secure())
return NULL;
/* get a name for the temp file */
if ((tempname = vim_tempname('o')) == NULL)
{
EMSG(_(e_notmp));
return NULL;
}
/* Add the redirection stuff */
command = make_filter_cmd(cmd, infile, tempname);
if (command == NULL)
goto done;
/*
* Call the shell to execute the command (errors are ignored).
* Don't check timestamps here.
*/
++no_check_timestamps;
call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
--no_check_timestamps;
vim_free(command);
/*
* read the names from the file into memory
*/
# ifdef VMS
/* created temporary file is not always readable as binary */
fd = mch_fopen((char *)tempname, "r");
# else
fd = mch_fopen((char *)tempname, READBIN);
# endif
if (fd == NULL)
{
EMSG2(_(e_notopen), tempname);
goto done;
}
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)
i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
fclose(fd);
mch_remove(tempname);
if (buffer == NULL)
goto done;
#ifdef VMS
len = i; /* VMS doesn't give us what we asked for... */
#endif
if (i != len)
{
EMSG2(_(e_notread), tempname);
vim_free(buffer);
buffer = NULL;
}
else
buffer[len] = NUL; /* make sure the buffer is terminated */
done:
vim_free(tempname);
return buffer;
}
#endif
/*
* Free the list of files returned by expand_wildcards() or other expansion
* functions.
*/
void
FreeWild(count, files)
int count;
char_u **files;
{
if (count <= 0 || files == NULL)
return;
#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
/*
* Is this still OK for when other functions than expand_wildcards() have
* been used???
*/
_fnexplodefree((char **)files);
#else
while (count--)
vim_free(files[count]);
vim_free(files);
#endif
}
/*
* Return TRUE when need to go to Insert mode because of 'insertmode'.
* Don't do this when still processing a command or a mapping.
* Don't do this when inside a ":normal" command.
*/
int
goto_im()
{
return (p_im && stuff_empty() && typebuf_typed());
}
| zyz2011-vim | src/misc1.c | C | gpl2 | 260,282 |
/* 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.
*/
#define EXTERN
#include "vim.h"
#ifdef SPAWNO
# include <spawno.h> /* special MS-DOS swapping library */
#endif
#ifdef __CYGWIN__
# ifndef WIN32
# include <cygwin/version.h>
# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
* cygwin_conv_path() */
# endif
# include <limits.h>
#endif
/* Maximum number of commands from + or -c arguments. */
#define MAX_ARG_CMDS 10
/* values for "window_layout" */
#define WIN_HOR 1 /* "-o" horizontally split windows */
#define WIN_VER 2 /* "-O" vertically split windows */
#define WIN_TABS 3 /* "-p" windows on tab pages */
/* Struct for various parameters passed between main() and other functions. */
typedef struct
{
int argc;
char **argv;
int evim_mode; /* started as "evim" */
char_u *use_vimrc; /* vimrc from -u argument */
int n_commands; /* no. of commands from + or -c */
char_u *commands[MAX_ARG_CMDS]; /* commands from + or -c arg. */
char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
int n_pre_commands; /* no. of commands from --cmd */
char_u *pre_commands[MAX_ARG_CMDS]; /* commands from --cmd argument */
int edit_type; /* type of editing to do */
char_u *tagname; /* tag from -t argument */
#ifdef FEAT_QUICKFIX
char_u *use_ef; /* 'errorfile' from -q argument */
#endif
int want_full_screen;
int stdout_isatty; /* is stdout a terminal? */
char_u *term; /* specified terminal name */
#ifdef FEAT_CRYPT
int ask_for_key; /* -x argument */
#endif
int no_swap_file; /* "-n" argument used */
#ifdef FEAT_EVAL
int use_debug_break_level;
#endif
#ifdef FEAT_WINDOWS
int window_count; /* number of windows to use */
int window_layout; /* 0, WIN_HOR, WIN_VER or WIN_TABS */
#endif
#ifdef FEAT_CLIENTSERVER
int serverArg; /* TRUE when argument for a server */
char_u *serverName_arg; /* cmdline arg for server name */
char_u *serverStr; /* remote server command */
char_u *serverStrEnc; /* encoding of serverStr */
char_u *servername; /* allocated name for our server */
#endif
#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
int literal; /* don't expand file names */
#endif
#ifdef MSWIN
int full_path; /* file name argument was full path */
#endif
#ifdef FEAT_DIFF
int diff_mode; /* start with 'diff' set */
#endif
} mparm_T;
/* Values for edit_type. */
#define EDIT_NONE 0 /* no edit type yet */
#define EDIT_FILE 1 /* file name argument[s] given, use argument list */
#define EDIT_STDIN 2 /* read file from stdin */
#define EDIT_TAG 3 /* tag name argument given, use tagname */
#define EDIT_QF 4 /* start in quickfix mode */
#if (defined(UNIX) || defined(VMS)) && !defined(NO_VIM_MAIN)
static int file_owned __ARGS((char *fname));
#endif
static void mainerr __ARGS((int, char_u *));
#ifndef NO_VIM_MAIN
static void main_msg __ARGS((char *s));
static void usage __ARGS((void));
static int get_number_arg __ARGS((char_u *p, int *idx, int def));
# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
static void init_locale __ARGS((void));
# endif
static void parse_command_name __ARGS((mparm_T *parmp));
static void early_arg_scan __ARGS((mparm_T *parmp));
static void command_line_scan __ARGS((mparm_T *parmp));
static void check_tty __ARGS((mparm_T *parmp));
static void read_stdin __ARGS((void));
static void create_windows __ARGS((mparm_T *parmp));
# ifdef FEAT_WINDOWS
static void edit_buffers __ARGS((mparm_T *parmp));
# endif
static void exe_pre_commands __ARGS((mparm_T *parmp));
static void exe_commands __ARGS((mparm_T *parmp));
static void source_startup_scripts __ARGS((mparm_T *parmp));
static void main_start_gui __ARGS((void));
# if defined(HAS_SWAP_EXISTS_ACTION)
static void check_swap_exists_action __ARGS((void));
# endif
# if defined(FEAT_CLIENTSERVER) || defined(PROTO)
static void exec_on_server __ARGS((mparm_T *parmp));
static void prepare_server __ARGS((mparm_T *parmp));
static void cmdsrv_main __ARGS((int *argc, char **argv, char_u *serverName_arg, char_u **serverStr));
static char_u *serverMakeName __ARGS((char_u *arg, char *cmd));
# endif
#endif
/*
* Different types of error messages.
*/
static char *(main_errors[]) =
{
N_("Unknown option argument"),
#define ME_UNKNOWN_OPTION 0
N_("Too many edit arguments"),
#define ME_TOO_MANY_ARGS 1
N_("Argument missing after"),
#define ME_ARG_MISSING 2
N_("Garbage after option argument"),
#define ME_GARBAGE 3
N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments"),
#define ME_EXTRA_CMD 4
N_("Invalid argument for"),
#define ME_INVALID_ARG 5
};
#ifndef NO_VIM_MAIN /* skip this for unittests */
#ifndef PROTO /* don't want a prototype for main() */
int
# ifdef VIMDLL
_export
# endif
# ifdef FEAT_GUI_MSWIN
# ifdef __BORLANDC__
_cdecl
# endif
VimMain
# else
main
# endif
(argc, argv)
int argc;
char **argv;
{
char_u *fname = NULL; /* file name from command line */
mparm_T params; /* various parameters passed between
* main() and other functions. */
#ifdef STARTUPTIME
int i;
#endif
/*
* Do any system-specific initialisations. These can NOT use IObuff or
* NameBuff. Thus emsg2() cannot be called!
*/
mch_early_init();
/* Many variables are in "params" so that we can pass them to invoked
* functions without a lot of arguments. "argc" and "argv" are also
* copied, so that they can be changed. */
vim_memset(¶ms, 0, sizeof(params));
params.argc = argc;
params.argv = argv;
params.want_full_screen = TRUE;
#ifdef FEAT_EVAL
params.use_debug_break_level = -1;
#endif
#ifdef FEAT_WINDOWS
params.window_count = -1;
#endif
#ifdef FEAT_TCL
vim_tcl_init(params.argv[0]);
#endif
#ifdef MEM_PROFILE
atexit(vim_mem_profile_dump);
#endif
#ifdef STARTUPTIME
for (i = 1; i < argc; ++i)
{
if (STRICMP(argv[i], "--startuptime") == 0 && i + 1 < argc)
{
time_fd = mch_fopen(argv[i + 1], "a");
TIME_MSG("--- VIM STARTING ---");
break;
}
}
#endif
starttime = time(NULL);
#ifdef __EMX__
_wildcard(¶ms.argc, ¶ms.argv);
#endif
#ifdef FEAT_MBYTE
(void)mb_init(); /* init mb_bytelen_tab[] to ones */
#endif
#ifdef FEAT_EVAL
eval_init(); /* init global variables */
#endif
#ifdef __QNXNTO__
qnx_init(); /* PhAttach() for clipboard, (and gui) */
#endif
#ifdef MAC_OS_CLASSIC
/* Prepare for possibly starting GUI sometime */
/* Macintosh needs this before any memory is allocated. */
gui_prepare(¶ms.argc, params.argv);
TIME_MSG("GUI prepared");
#endif
/* Init the table of Normal mode commands. */
init_normal_cmds();
#if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC)
make_version(); /* Construct the long version string. */
#endif
/*
* Allocate space for the generic buffers (needed for set_init_1() and
* EMSG2()).
*/
if ((IObuff = alloc(IOSIZE)) == NULL
|| (NameBuff = alloc(MAXPATHL)) == NULL)
mch_exit(0);
TIME_MSG("Allocated generic buffers");
#ifdef NBDEBUG
/* Wait a moment for debugging NetBeans. Must be after allocating
* NameBuff. */
nbdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL");
nbdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20);
TIME_MSG("NetBeans debug wait");
#endif
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
/*
* Setup to use the current locale (for ctype() and many other things).
* NOTE: Translated messages with encodings other than latin1 will not
* work until set_init_1() has been called!
*/
init_locale();
TIME_MSG("locale set");
#endif
#ifdef FEAT_GUI
gui.dofork = TRUE; /* default is to use fork() */
#endif
/*
* Do a first scan of the arguments in "argv[]":
* -display or --display
* --server...
* --socketid
* --windowid
*/
early_arg_scan(¶ms);
#ifdef FEAT_SUN_WORKSHOP
findYourself(params.argv[0]);
#endif
#if defined(FEAT_GUI) && !defined(MAC_OS_CLASSIC)
/* Prepare for possibly starting GUI sometime */
gui_prepare(¶ms.argc, params.argv);
TIME_MSG("GUI prepared");
#endif
#ifdef FEAT_CLIPBOARD
clip_init(FALSE); /* Initialise clipboard stuff */
TIME_MSG("clipboard setup");
#endif
/*
* Check if we have an interactive window.
* On the Amiga: If there is no window, we open one with a newcli command
* (needed for :! to * work). mch_check_win() will also handle the -d or
* -dev argument.
*/
params.stdout_isatty = (mch_check_win(params.argc, params.argv) != FAIL);
TIME_MSG("window checked");
/*
* Allocate the first window and buffer.
* Can't do anything without it, exit when it fails.
*/
if (win_alloc_first() == FAIL)
mch_exit(0);
init_yank(); /* init yank buffers */
alist_init(&global_alist); /* Init the argument list to empty. */
/*
* Set the default values for the options.
* NOTE: Non-latin1 translated messages are working only after this,
* because this is where "has_mbyte" will be set, which is used by
* msg_outtrans_len_attr().
* First find out the home directory, needed to expand "~" in options.
*/
init_homedir(); /* find real value of $HOME */
set_init_1();
TIME_MSG("inits 1");
#ifdef FEAT_EVAL
set_lang_var(); /* set v:lang and v:ctype */
#endif
#ifdef FEAT_CLIENTSERVER
/*
* Do the client-server stuff, unless "--servername ''" was used.
* This may exit Vim if the command was sent to the server.
*/
exec_on_server(¶ms);
#endif
/*
* Figure out the way to work from the command name argv[0].
* "vimdiff" starts diff mode, "rvim" sets "restricted", etc.
*/
parse_command_name(¶ms);
/*
* Process the command line arguments. File names are put in the global
* argument list "global_alist".
*/
command_line_scan(¶ms);
TIME_MSG("parsing arguments");
/*
* On some systems, when we compile with the GUI, we always use it. On Mac
* there is no terminal version, and on Windows we can't fork one off with
* :gui.
*/
#ifdef ALWAYS_USE_GUI
gui.starting = TRUE;
#else
# if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
/*
* Check if the GUI can be started. Reset gui.starting if not.
* Don't know about other systems, stay on the safe side and don't check.
*/
if (gui.starting)
{
if (gui_init_check() == FAIL)
{
gui.starting = FALSE;
/* When running "evim" or "gvim -y" we need the menus, exit if we
* don't have them. */
if (params.evim_mode)
mch_exit(1);
}
}
# endif
#endif
if (GARGCOUNT > 0)
{
#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
/*
* Expand wildcards in file names.
*/
if (!params.literal)
{
/* 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 *)":set isf+=(,)");
alist_expand(NULL, 0);
do_cmdline_cmd((char_u *)":set isf&");
}
#endif
fname = alist_name(&GARGLIST[0]);
}
#if defined(WIN32) && defined(FEAT_MBYTE)
{
extern void set_alist_count(void);
/* Remember the number of entries in the argument list. If it changes
* we don't react on setting 'encoding'. */
set_alist_count();
}
#endif
#ifdef MSWIN
if (GARGCOUNT == 1 && params.full_path)
{
/*
* If there is one filename, fully qualified, we have very probably
* been invoked from explorer, so change to the file's directory.
* Hint: to avoid this when typing a command use a forward slash.
* If the cd fails, it doesn't matter.
*/
(void)vim_chdirfile(fname);
}
#endif
TIME_MSG("expanding arguments");
#ifdef FEAT_DIFF
if (params.diff_mode && params.window_count == -1)
params.window_count = 0; /* open up to 3 windows */
#endif
/* Don't redraw until much later. */
++RedrawingDisabled;
/*
* When listing swap file names, don't do cursor positioning et. al.
*/
if (recoverymode && fname == NULL)
params.want_full_screen = FALSE;
/*
* When certain to start the GUI, don't check capabilities of terminal.
* For GTK we can't be sure, but when started from the desktop it doesn't
* make sense to try using a terminal.
*/
#if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
if (gui.starting
# ifdef FEAT_GUI_GTK
&& !isatty(2)
# endif
)
params.want_full_screen = FALSE;
#endif
#if defined(FEAT_GUI_MAC) && defined(MACOS_X_UNIX)
/* When the GUI is started from Finder, need to display messages in a
* message box. isatty(2) returns TRUE anyway, thus we need to check the
* name to know we're not started from a terminal. */
if (gui.starting && (!isatty(2) || strcmp("/dev/console", ttyname(2)) == 0))
{
params.want_full_screen = FALSE;
/* Avoid always using "/" as the current directory. Note that when
* started from Finder the arglist will be filled later in
* HandleODocAE() and "fname" will be NULL. */
if (getcwd((char *)NameBuff, MAXPATHL) != NULL
&& STRCMP(NameBuff, "/") == 0)
{
if (fname != NULL)
(void)vim_chdirfile(fname);
else
{
expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
vim_chdir(NameBuff);
}
}
}
#endif
/*
* mch_init() sets up the terminal (window) for use. This must be
* done after resetting full_screen, otherwise it may move the cursor
* (MSDOS).
* Note that we may use mch_exit() before mch_init()!
*/
mch_init();
TIME_MSG("shell init");
#ifdef USE_XSMP
/*
* For want of anywhere else to do it, try to connect to xsmp here.
* Fitting it in after gui_mch_init, but before gui_init (via termcapinit).
* Hijacking -X 'no X connection' to also disable XSMP connection as that
* has a similar delay upon failure.
* Only try if SESSION_MANAGER is set to something non-null.
*/
if (!x_no_connect)
{
char *p = getenv("SESSION_MANAGER");
if (p != NULL && *p != NUL)
{
xsmp_init();
TIME_MSG("xsmp init");
}
}
#endif
/*
* Print a warning if stdout is not a terminal.
*/
check_tty(¶ms);
/* This message comes before term inits, but after setting "silent_mode"
* when the input is not a tty. */
if (GARGCOUNT > 1 && !silent_mode)
printf(_("%d files to edit\n"), GARGCOUNT);
if (params.want_full_screen && !silent_mode)
{
termcapinit(params.term); /* set terminal name and get terminal
capabilities (will set full_screen) */
screen_start(); /* don't know where cursor is now */
TIME_MSG("Termcap init");
}
/*
* Set the default values for the options that use Rows and Columns.
*/
ui_get_shellsize(); /* inits Rows and Columns */
win_init_size();
#ifdef FEAT_DIFF
/* Set the 'diff' option now, so that it can be checked for in a .vimrc
* file. There is no buffer yet though. */
if (params.diff_mode)
diff_win_options(firstwin, FALSE);
#endif
cmdline_row = Rows - p_ch;
msg_row = cmdline_row;
screenalloc(FALSE); /* allocate screen buffers */
set_init_2();
TIME_MSG("inits 2");
msg_scroll = TRUE;
no_wait_return = TRUE;
init_mappings(); /* set up initial mappings */
init_highlight(TRUE, FALSE); /* set the default highlight groups */
TIME_MSG("init highlight");
#ifdef FEAT_EVAL
/* Set the break level after the terminal is initialized. */
debug_break_level = params.use_debug_break_level;
#endif
#ifdef FEAT_MZSCHEME
/*
* Newer version of MzScheme (Racket) require earlier (trampolined)
* initialisation via scheme_main_setup.
* Implement this by initialising it as early as possible
* and splitting off remaining Vim main into vim_main2
*/
{
/* Pack up preprocessed command line arguments.
* It is safe because Scheme does not access argc/argv. */
char *args[2];
args[0] = (char *)fname;
args[1] = (char *)¶ms;
return mzscheme_main(2, args);
}
}
int vim_main2(int argc, char **argv)
{
char_u *fname = (char_u *)argv[0];
mparm_T params;
memcpy(¶ms, argv[1], sizeof(params));
#endif
/* Execute --cmd arguments. */
exe_pre_commands(¶ms);
/* Source startup scripts. */
source_startup_scripts(¶ms);
#ifdef FEAT_EVAL
/*
* Read all the plugin files.
* Only when compiled with +eval, since most plugins need it.
*/
if (p_lpl)
{
# ifdef VMS /* Somehow VMS doesn't handle the "**". */
source_runtime((char_u *)"plugin/*.vim", TRUE);
# else
source_runtime((char_u *)"plugin/**/*.vim", TRUE);
# endif
TIME_MSG("loading plugins");
}
#endif
#ifdef FEAT_DIFF
/* Decide about window layout for diff mode after reading vimrc. */
if (params.diff_mode && params.window_layout == 0)
{
if (diffopt_horizontal())
params.window_layout = WIN_HOR; /* use horizontal split */
else
params.window_layout = WIN_VER; /* use vertical split */
}
#endif
/*
* Recovery mode without a file name: List swap files.
* This uses the 'dir' option, therefore it must be after the
* initializations.
*/
if (recoverymode && fname == NULL)
{
recover_names(NULL, TRUE, 0, NULL);
mch_exit(0);
}
/*
* Set a few option defaults after reading .vimrc files:
* 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
*/
set_init_3();
TIME_MSG("inits 3");
/*
* "-n" argument: Disable swap file by setting 'updatecount' to 0.
* Note that this overrides anything from a vimrc file.
*/
if (params.no_swap_file)
p_uc = 0;
#ifdef FEAT_FKMAP
if (curwin->w_p_rl && p_altkeymap)
{
p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
# ifdef FEAT_ARABIC
curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
# endif
p_fkmap = TRUE; /* Set the Farsi keymap mode */
}
#endif
#ifdef FEAT_GUI
if (gui.starting)
{
#if defined(UNIX) || defined(VMS)
/* When something caused a message from a vimrc script, need to output
* an extra newline before the shell prompt. */
if (did_emsg || msg_didout)
putchar('\n');
#endif
gui_start(); /* will set full_screen to TRUE */
TIME_MSG("starting GUI");
/* When running "evim" or "gvim -y" we need the menus, exit if we
* don't have them. */
if (!gui.in_use && params.evim_mode)
mch_exit(1);
}
#endif
#ifdef SPAWNO /* special MSDOS swapping library */
init_SPAWNO("", SWAP_ANY);
#endif
#ifdef FEAT_VIMINFO
/*
* Read in registers, history etc, but not marks, from the viminfo file.
* This is where v:oldfiles gets filled.
*/
if (*p_viminfo != NUL)
{
read_viminfo(NULL, VIF_WANT_INFO | VIF_GET_OLDFILES);
TIME_MSG("reading viminfo");
}
#endif
#ifdef FEAT_QUICKFIX
/*
* "-q errorfile": Load the error file now.
* If the error file can't be read, exit before doing anything else.
*/
if (params.edit_type == EDIT_QF)
{
if (params.use_ef != NULL)
set_string_option_direct((char_u *)"ef", -1,
params.use_ef, OPT_FREE, SID_CARG);
vim_snprintf((char *)IObuff, IOSIZE, "cfile %s", p_ef);
if (qf_init(NULL, p_ef, p_efm, TRUE, IObuff) < 0)
{
out_char('\n');
mch_exit(3);
}
TIME_MSG("reading errorfile");
}
#endif
/*
* Start putting things on the screen.
* Scroll screen down before drawing over it
* Clear screen now, so file message will not be cleared.
*/
starting = NO_BUFFERS;
no_wait_return = FALSE;
if (!exmode_active)
msg_scroll = FALSE;
#ifdef FEAT_GUI
/*
* This seems to be required to make callbacks to be called now, instead
* of after things have been put on the screen, which then may be deleted
* when getting a resize callback.
* For the Mac this handles putting files dropped on the Vim icon to
* global_alist.
*/
if (gui.in_use)
{
# ifdef FEAT_SUN_WORKSHOP
if (!usingSunWorkShop)
# endif
gui_wait_for_chars(50L);
TIME_MSG("GUI delay");
}
#endif
#if defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)
qnx_clip_init();
#endif
#if defined(MACOS_X) && defined(FEAT_CLIPBOARD)
clip_init(TRUE);
#endif
#ifdef FEAT_XCLIPBOARD
/* Start using the X clipboard, unless the GUI was started. */
# ifdef FEAT_GUI
if (!gui.in_use)
# endif
{
setup_term_clip();
TIME_MSG("setup clipboard");
}
#endif
#ifdef FEAT_CLIENTSERVER
/* Prepare for being a Vim server. */
prepare_server(¶ms);
#endif
/*
* If "-" argument given: Read file from stdin.
* Do this before starting Raw mode, because it may change things that the
* writing end of the pipe doesn't like, e.g., in case stdin and stderr
* are the same terminal: "cat | vim -".
* Using autocommands here may cause trouble...
*/
if (params.edit_type == EDIT_STDIN && !recoverymode)
read_stdin();
#if defined(UNIX) || defined(VMS)
/* When switching screens and something caused a message from a vimrc
* script, need to output an extra newline on exit. */
if ((did_emsg || msg_didout) && *T_TI != NUL)
newline_on_exit = TRUE;
#endif
/*
* When done something that is not allowed or error message call
* wait_return. This must be done before starttermcap(), because it may
* switch to another screen. It must be done after settmode(TMODE_RAW),
* because we want to react on a single key stroke.
* Call settmode and starttermcap here, so the T_KS and T_TI may be
* defined by termcapinit and redefined in .exrc.
*/
settmode(TMODE_RAW);
TIME_MSG("setting raw mode");
if (need_wait_return || msg_didany)
{
wait_return(TRUE);
TIME_MSG("waiting for return");
}
starttermcap(); /* start termcap if not done by wait_return() */
TIME_MSG("start termcap");
#ifdef FEAT_MOUSE
setmouse(); /* may start using the mouse */
#endif
if (scroll_region)
scroll_region_reset(); /* In case Rows changed */
scroll_start(); /* may scroll the screen to the right position */
/*
* Don't clear the screen when starting in Ex mode, unless using the GUI.
*/
if (exmode_active
#ifdef FEAT_GUI
&& !gui.in_use
#endif
)
must_redraw = CLEAR;
else
{
screenclear(); /* clear screen */
TIME_MSG("clearing screen");
}
#ifdef FEAT_CRYPT
if (params.ask_for_key)
{
(void)blowfish_self_test();
(void)get_crypt_key(TRUE, TRUE);
TIME_MSG("getting crypt key");
}
#endif
no_wait_return = TRUE;
/*
* Create the requested number of windows and edit buffers in them.
* Also does recovery if "recoverymode" set.
*/
create_windows(¶ms);
TIME_MSG("opening buffers");
#ifdef FEAT_EVAL
/* clear v:swapcommand */
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
#endif
/* Ex starts at last line of the file */
if (exmode_active)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
TIME_MSG("BufEnter autocommands");
#endif
setpcmark();
#ifdef FEAT_QUICKFIX
/*
* When started with "-q errorfile" jump to first error now.
*/
if (params.edit_type == EDIT_QF)
{
qf_jump(NULL, 0, 0, FALSE);
TIME_MSG("jump to first error");
}
#endif
#ifdef FEAT_WINDOWS
/*
* If opened more than one window, start editing files in the other
* windows.
*/
edit_buffers(¶ms);
#endif
#ifdef FEAT_DIFF
if (params.diff_mode)
{
win_T *wp;
/* set options in each window for "vimdiff". */
for (wp = firstwin; wp != NULL; wp = wp->w_next)
diff_win_options(wp, TRUE);
}
#endif
/*
* Shorten any of the filenames, but only when absolute.
*/
shorten_fnames(FALSE);
/*
* Need to jump to the tag before executing the '-c command'.
* Makes "vim -c '/return' -t main" work.
*/
if (params.tagname != NULL)
{
#if defined(HAS_SWAP_EXISTS_ACTION)
swap_exists_did_quit = FALSE;
#endif
vim_snprintf((char *)IObuff, IOSIZE, "ta %s", params.tagname);
do_cmdline_cmd(IObuff);
TIME_MSG("jumping to tag");
#if defined(HAS_SWAP_EXISTS_ACTION)
/* If the user doesn't want to edit the file then we quit here. */
if (swap_exists_did_quit)
getout(1);
#endif
}
/* Execute any "+", "-c" and "-S" arguments. */
if (params.n_commands > 0)
exe_commands(¶ms);
RedrawingDisabled = 0;
redraw_all_later(NOT_VALID);
no_wait_return = FALSE;
starting = 0;
#ifdef FEAT_TERMRESPONSE
/* Requesting the termresponse is postponed until here, so that a "-c q"
* argument doesn't make it appear in the shell Vim was started from. */
may_req_termresponse();
#endif
/* start in insert mode */
if (p_im)
need_start_insertmode = TRUE;
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
TIME_MSG("VimEnter autocommands");
#endif
#if defined(FEAT_EVAL) && defined(FEAT_CLIPBOARD)
/* Adjust default register name for "unnamed" in 'clipboard'. Can only be
* done after the clipboard is available and all initial commands that may
* modify the 'clipboard' setting have run; i.e. just before entering the
* main loop. */
{
int default_regname = 0;
adjust_clip_reg(&default_regname);
set_reg_var(default_regname);
}
#endif
#if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
/* When a startup script or session file setup for diff'ing and
* scrollbind, sync the scrollbind now. */
if (curwin->w_p_diff && curwin->w_p_scb)
{
update_topline();
check_scrollbind((linenr_T)0, 0L);
TIME_MSG("diff scrollbinding");
}
#endif
#if defined(WIN3264) && !defined(FEAT_GUI_W32)
mch_set_winsize_now(); /* Allow winsize changes from now on */
#endif
#if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
/* When tab pages were created, may need to update the tab pages line and
* scrollbars. This is skipped while creating them. */
if (first_tabpage->tp_next != NULL)
{
out_flush();
gui_init_which_components(NULL);
gui_update_scrollbars(TRUE);
}
need_mouse_correct = TRUE;
#endif
/* If ":startinsert" command used, stuff a dummy command to be able to
* call normal_cmd(), which will then start Insert mode. */
if (restart_edit != 0)
stuffcharReadbuff(K_NOP);
#ifdef FEAT_NETBEANS_INTG
if (netbeansArg != NULL && strncmp("-nb", netbeansArg, 3) == 0)
{
# ifdef FEAT_GUI
# if !defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK) \
&& !defined(FEAT_GUI_W32)
if (gui.in_use)
{
mch_errmsg(_("netbeans is not supported with this GUI\n"));
mch_exit(2);
}
# endif
# endif
/* Tell the client that it can start sending commands. */
netbeans_open(netbeansArg + 3, TRUE);
}
#endif
TIME_MSG("before starting main loop");
/*
* Call the main command loop. This never returns.
*/
main_loop(FALSE, FALSE);
return 0;
}
#endif /* PROTO */
#endif /* NO_VIM_MAIN */
/*
* Main loop: Execute Normal mode commands until exiting Vim.
* Also used to handle commands in the command-line window, until the window
* is closed.
* Also used to handle ":visual" command after ":global": execute Normal mode
* commands, return when entering Ex mode. "noexmode" is TRUE then.
*/
void
main_loop(cmdwin, noexmode)
int cmdwin; /* TRUE when working in the command-line window */
int noexmode; /* TRUE when return on entering Ex mode */
{
oparg_T oa; /* operator arguments */
int previous_got_int = FALSE; /* "got_int" was TRUE */
#ifdef FEAT_CONCEAL
linenr_T conceal_old_cursor_line = 0;
linenr_T conceal_new_cursor_line = 0;
int conceal_update_lines = FALSE;
#endif
#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
/* Setup to catch a terminating error from the X server. Just ignore
* it, restore the state and continue. This might not always work
* properly, but at least we don't exit unexpectedly when the X server
* exists while Vim is running in a console. */
if (!cmdwin && !noexmode && SETJMP(x_jump_env))
{
State = NORMAL;
# ifdef FEAT_VISUAL
VIsual_active = FALSE;
# endif
got_int = TRUE;
need_wait_return = FALSE;
global_busy = FALSE;
exmode_active = 0;
skip_redraw = FALSE;
RedrawingDisabled = 0;
no_wait_return = 0;
vgetc_busy = 0;
# ifdef FEAT_EVAL
emsg_skip = 0;
# endif
emsg_off = 0;
# ifdef FEAT_MOUSE
setmouse();
# endif
settmode(TMODE_RAW);
starttermcap();
scroll_start();
redraw_later_clear();
}
#endif
clear_oparg(&oa);
while (!cmdwin
#ifdef FEAT_CMDWIN
|| cmdwin_result == 0
#endif
)
{
if (stuff_empty())
{
did_check_timestamps = FALSE;
if (need_check_timestamps)
check_timestamps(FALSE);
if (need_wait_return) /* if wait_return still needed ... */
wait_return(FALSE); /* ... call it now */
if (need_start_insertmode && goto_im()
#ifdef FEAT_VISUAL
&& !VIsual_active
#endif
)
{
need_start_insertmode = FALSE;
stuffReadbuff((char_u *)"i"); /* start insert mode next */
/* skip the fileinfo message now, because it would be shown
* after insert mode finishes! */
need_fileinfo = FALSE;
}
}
/* Reset "got_int" now that we got back to the main loop. Except when
* inside a ":g/pat/cmd" command, then the "got_int" needs to abort
* the ":g" command.
* For ":g/pat/vi" we reset "got_int" when used once. When used
* a second time we go back to Ex mode and abort the ":g" command. */
if (got_int)
{
if (noexmode && global_busy && !exmode_active && previous_got_int)
{
/* Typed two CTRL-C in a row: go back to ex mode as if "Q" was
* used and keep "got_int" set, so that it aborts ":g". */
exmode_active = EXMODE_NORMAL;
State = NORMAL;
}
else if (!global_busy || !exmode_active)
{
if (!quit_more)
(void)vgetc(); /* flush all buffers */
got_int = FALSE;
}
previous_got_int = TRUE;
}
else
previous_got_int = FALSE;
if (!exmode_active)
msg_scroll = FALSE;
quit_more = FALSE;
/*
* If skip redraw is set (for ":" in wait_return()), don't redraw now.
* If there is nothing in the stuff_buffer or do_redraw is TRUE,
* update cursor and redraw.
*/
if (skip_redraw || exmode_active)
skip_redraw = FALSE;
else if (do_redraw || stuff_empty())
{
#if defined(FEAT_AUTOCMD) || defined(FEAT_CONCEAL)
/* Trigger CursorMoved if the cursor moved. */
if (!finish_op && (
# ifdef FEAT_AUTOCMD
has_cursormoved()
# 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_AUTOCMD
if (has_cursormoved())
apply_autocmds(EVENT_CURSORMOVED, 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 defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
/* Scroll-binding for diff mode may have been postponed until
* here. Avoids doing it for every change. */
if (diff_need_scrollbind)
{
check_scrollbind((linenr_T)0, 0L);
diff_need_scrollbind = FALSE;
}
#endif
#if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
/* Include a closed fold completely in the Visual area. */
foldAdjustVisual();
#endif
#ifdef FEAT_FOLDING
/*
* When 'foldclose' is set, apply 'foldlevel' to folds that don't
* contain the cursor.
* When 'foldopen' is "all", open the fold(s) under the cursor.
* This may mark the window for redrawing.
*/
if (hasAnyFolding(curwin) && !char_avail())
{
foldCheckClose();
if (fdo_flags & FDO_ALL)
foldOpenCursor();
}
#endif
/*
* Before redrawing, make sure w_topline is correct, and w_leftcol
* if lines don't wrap, and w_skipcol if lines wrap.
*/
update_topline();
validate_cursor();
#ifdef FEAT_VISUAL
if (VIsual_active)
update_curbuf(INVERTED);/* update inverted part */
else
#endif
if (must_redraw)
update_screen(0);
else if (redraw_cmdline || clear_cmdline)
showmode();
#ifdef FEAT_WINDOWS
redraw_statuslines();
#endif
#ifdef FEAT_TITLE
if (need_maketitle)
maketitle();
#endif
/* display message after redraw */
if (keep_msg != NULL)
{
char_u *p;
/* msg_attr_keep() will set keep_msg to NULL, must free the
* string here. */
p = keep_msg;
keep_msg = NULL;
msg_attr(p, keep_msg_attr);
vim_free(p);
}
if (need_fileinfo) /* show file info after redraw */
{
fileinfo(FALSE, TRUE, FALSE);
need_fileinfo = FALSE;
}
emsg_on_display = FALSE; /* can delete error message now */
did_emsg = FALSE;
msg_didany = FALSE; /* reset lines_left in msg_start() */
may_clear_sb_text(); /* clear scroll-back text on next msg */
showruler(FALSE);
# 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
&& conceal_old_cursor_line
<= curbuf->b_ml.ml_line_count)
update_single_line(curwin, conceal_old_cursor_line);
update_single_line(curwin, conceal_new_cursor_line);
curwin->w_valid &= ~VALID_CROW;
}
# endif
setcursor();
cursor_on();
do_redraw = FALSE;
#ifdef STARTUPTIME
/* Now that we have drawn the first screen all the startup stuff
* has been done, close any file for startup messages. */
if (time_fd != NULL)
{
TIME_MSG("first screen update");
TIME_MSG("--- VIM STARTED ---");
fclose(time_fd);
time_fd = NULL;
}
#endif
}
#ifdef FEAT_GUI
if (need_mouse_correct)
gui_mouse_correct();
#endif
/*
* Update w_curswant if w_set_curswant has been set.
* Postponed until here to avoid computing w_virtcol too often.
*/
update_curswant();
#ifdef FEAT_EVAL
/*
* May perform garbage collection when waiting for a character, but
* only at the very toplevel. Otherwise we may be using a List or
* Dict internally somewhere.
* "may_garbage_collect" is reset in vgetc() which is invoked through
* do_exmode() and normal_cmd().
*/
may_garbage_collect = (!cmdwin && !noexmode);
#endif
/*
* If we're invoked as ex, do a round of ex commands.
* Otherwise, get and execute a normal mode command.
*/
if (exmode_active)
{
if (noexmode) /* End of ":global/path/visual" commands */
return;
do_exmode(exmode_active == EXMODE_VIM);
}
else
normal_cmd(&oa, TRUE);
}
}
#if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO)
/*
* Exit, but leave behind swap files for modified buffers.
*/
void
getout_preserve_modified(exitval)
int exitval;
{
# if defined(SIGHUP) && defined(SIG_IGN)
/* Ignore SIGHUP, because a dropped connection causes a read error, which
* makes Vim exit and then handling SIGHUP causes various reentrance
* problems. */
signal(SIGHUP, SIG_IGN);
# endif
ml_close_notmod(); /* close all not-modified buffers */
ml_sync_all(FALSE, FALSE); /* preserve all swap files */
ml_close_all(FALSE); /* close all memfiles, without deleting */
getout(exitval); /* exit Vim properly */
}
#endif
/* Exit properly */
void
getout(exitval)
int exitval;
{
#ifdef FEAT_AUTOCMD
buf_T *buf;
win_T *wp;
tabpage_T *tp, *next_tp;
#endif
exiting = TRUE;
/* When running in Ex mode an error causes us to exit with a non-zero exit
* code. POSIX requires this, although it's not 100% clear from the
* standard. */
if (exmode_active)
exitval += ex_exitval;
/* Position the cursor on the last screen line, below all the text */
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
windgoto((int)Rows - 1, 0);
#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
/* Optionally print hashtable efficiency. */
hash_debug_results();
#endif
#ifdef FEAT_GUI
msg_didany = FALSE;
#endif
#ifdef FEAT_AUTOCMD
if (get_vim_var_nr(VV_DYING) <= 1)
{
/* Trigger BufWinLeave for all windows, but only once per buffer. */
# if defined FEAT_WINDOWS
for (tp = first_tabpage; tp != NULL; tp = next_tp)
{
next_tp = tp->tp_next;
for (wp = (tp == curtab)
? firstwin : tp->tp_firstwin; wp != NULL; wp = wp->w_next)
{
buf = wp->w_buffer;
if (buf->b_changedtick != -1)
{
apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname,
buf->b_fname, FALSE, buf);
buf->b_changedtick = -1; /* note that we did it already */
/* start all over, autocommands may mess up the lists */
next_tp = first_tabpage;
break;
}
}
}
# else
apply_autocmds(EVENT_BUFWINLEAVE, curbuf, curbuf->b_fname,
FALSE, curbuf);
# endif
/* Trigger BufUnload for buffers that are loaded */
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_ml.ml_mfp != NULL)
{
apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
FALSE, buf);
if (!buf_valid(buf)) /* autocmd may delete the buffer */
break;
}
apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
}
#endif
#ifdef FEAT_VIMINFO
if (*p_viminfo != NUL)
/* Write out the registers, history, marks etc, to the viminfo file */
write_viminfo(NULL, FALSE);
#endif
#ifdef FEAT_AUTOCMD
if (get_vim_var_nr(VV_DYING) <= 1)
apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
#endif
#ifdef FEAT_PROFILE
profile_dump();
#endif
if (did_emsg
#ifdef FEAT_GUI
|| (gui.in_use && msg_didany && p_verbose > 0)
#endif
)
{
/* give the user a chance to read the (error) message */
no_wait_return = FALSE;
wait_return(FALSE);
}
#ifdef FEAT_AUTOCMD
/* Position the cursor again, the autocommands may have moved it */
# ifdef FEAT_GUI
if (!gui.in_use)
# endif
windgoto((int)Rows - 1, 0);
#endif
#ifdef FEAT_LUA
lua_end();
#endif
#ifdef FEAT_MZSCHEME
mzscheme_end();
#endif
#ifdef FEAT_TCL
tcl_end();
#endif
#ifdef FEAT_RUBY
ruby_end();
#endif
#ifdef FEAT_PYTHON
python_end();
#endif
#ifdef FEAT_PYTHON3
python3_end();
#endif
#ifdef FEAT_PERL
perl_end();
#endif
#if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
iconv_end();
#endif
#ifdef FEAT_NETBEANS_INTG
netbeans_end();
#endif
#ifdef FEAT_CSCOPE
cs_end();
#endif
#ifdef FEAT_EVAL
if (garbage_collect_at_exit)
garbage_collect();
#endif
mch_exit(exitval);
}
#ifndef NO_VIM_MAIN
/*
* Get a (optional) count for a Vim argument.
*/
static int
get_number_arg(p, idx, def)
char_u *p; /* pointer to argument */
int *idx; /* index in argument, is incremented */
int def; /* default value */
{
if (vim_isdigit(p[*idx]))
{
def = atoi((char *)&(p[*idx]));
while (vim_isdigit(p[*idx]))
*idx = *idx + 1;
}
return def;
}
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
/*
* Setup to use the current locale (for ctype() and many other things).
*/
static void
init_locale()
{
setlocale(LC_ALL, "");
# ifdef FEAT_GUI_GTK
/* Tell Gtk not to change our locale settings. */
gtk_disable_setlocale();
# endif
# if defined(FEAT_FLOAT) && defined(LC_NUMERIC)
/* Make sure strtod() uses a decimal point, not a comma. */
setlocale(LC_NUMERIC, "C");
# endif
# 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
# ifdef FEAT_GETTEXT
{
int mustfree = FALSE;
char_u *p;
# ifdef DYNAMIC_GETTEXT
/* Initialize the gettext library */
dyn_libintl_init(NULL);
# endif
/* expand_env() doesn't work yet, because chartab[] is not initialized
* yet, call vim_getenv() directly */
p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
if (p != NULL && *p != NUL)
{
vim_snprintf((char *)NameBuff, MAXPATHL, "%s/lang", p);
bindtextdomain(VIMPACKAGE, (char *)NameBuff);
}
if (mustfree)
vim_free(p);
textdomain(VIMPACKAGE);
}
# endif
}
#endif
/*
* Check for: [r][e][g][vi|vim|view][diff][ex[im]]
* If the executable name starts with "r" we disable shell commands.
* If the next character is "e" we run in Easy mode.
* If the next character is "g" we run the GUI version.
* If the next characters are "view" we start in readonly mode.
* If the next characters are "diff" or "vimdiff" we start in diff mode.
* If the next characters are "ex" we start in Ex mode. If it's followed
* by "im" use improved Ex mode.
*/
static void
parse_command_name(parmp)
mparm_T *parmp;
{
char_u *initstr;
initstr = gettail((char_u *)parmp->argv[0]);
#ifdef MACOS_X_UNIX
/* An issue has been seen when launching Vim in such a way that
* $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
* executable or a symbolic link of it. Until this issue is resolved
* we prohibit the GUI from being used.
*/
if (STRCMP(initstr, parmp->argv[0]) == 0)
disallow_gui = TRUE;
/* TODO: On MacOS X default to gui if argv[0] ends in:
* /Vim.app/Contents/MacOS/Vim */
#endif
#ifdef FEAT_EVAL
set_vim_var_string(VV_PROGNAME, initstr, -1);
#endif
if (TOLOWER_ASC(initstr[0]) == 'r')
{
restricted = TRUE;
++initstr;
}
/* Use evim mode for "evim" and "egvim", not for "editor". */
if (TOLOWER_ASC(initstr[0]) == 'e'
&& (TOLOWER_ASC(initstr[1]) == 'v'
|| TOLOWER_ASC(initstr[1]) == 'g'))
{
#ifdef FEAT_GUI
gui.starting = TRUE;
#endif
parmp->evim_mode = TRUE;
++initstr;
}
/* "gvim" starts the GUI. Also accept "Gvim" for MS-Windows. */
if (TOLOWER_ASC(initstr[0]) == 'g')
{
main_start_gui();
#ifdef FEAT_GUI
++initstr;
#endif
}
if (STRNICMP(initstr, "view", 4) == 0)
{
readonlymode = TRUE;
curbuf->b_p_ro = TRUE;
p_uc = 10000; /* don't update very often */
initstr += 4;
}
else if (STRNICMP(initstr, "vim", 3) == 0)
initstr += 3;
/* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
if (STRICMP(initstr, "diff") == 0)
{
#ifdef FEAT_DIFF
parmp->diff_mode = TRUE;
#else
mch_errmsg(_("This Vim was not compiled with the diff feature."));
mch_errmsg("\n");
mch_exit(2);
#endif
}
if (STRNICMP(initstr, "ex", 2) == 0)
{
if (STRNICMP(initstr + 2, "im", 2) == 0)
exmode_active = EXMODE_VIM;
else
exmode_active = EXMODE_NORMAL;
change_compatible(TRUE); /* set 'compatible' */
}
}
/*
* Get the name of the display, before gui_prepare() removes it from
* argv[]. Used for the xterm-clipboard display.
*
* Also find the --server... arguments and --socketid and --windowid
*/
static void
early_arg_scan(parmp)
mparm_T *parmp UNUSED;
{
#if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER) \
|| !defined(FEAT_NETBEANS_INTG)
int argc = parmp->argc;
char **argv = parmp->argv;
int i;
for (i = 1; i < argc; i++)
{
if (STRCMP(argv[i], "--") == 0)
break;
# ifdef FEAT_XCLIPBOARD
else if (STRICMP(argv[i], "-display") == 0
# if defined(FEAT_GUI_GTK)
|| STRICMP(argv[i], "--display") == 0
# endif
)
{
if (i == argc - 1)
mainerr_arg_missing((char_u *)argv[i]);
xterm_display = argv[++i];
}
# endif
# ifdef FEAT_CLIENTSERVER
else if (STRICMP(argv[i], "--servername") == 0)
{
if (i == argc - 1)
mainerr_arg_missing((char_u *)argv[i]);
parmp->serverName_arg = (char_u *)argv[++i];
}
else if (STRICMP(argv[i], "--serverlist") == 0)
parmp->serverArg = TRUE;
else if (STRNICMP(argv[i], "--remote", 8) == 0)
{
parmp->serverArg = TRUE;
# ifdef FEAT_GUI
if (strstr(argv[i], "-wait") != 0)
/* don't fork() when starting the GUI to edit files ourself */
gui.dofork = FALSE;
# endif
}
# endif
# if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
# ifdef FEAT_GUI_W32
else if (STRICMP(argv[i], "--windowid") == 0)
# else
else if (STRICMP(argv[i], "--socketid") == 0)
# endif
{
long_u id;
int count;
if (i == argc - 1)
mainerr_arg_missing((char_u *)argv[i]);
if (STRNICMP(argv[i+1], "0x", 2) == 0)
count = sscanf(&(argv[i + 1][2]), SCANF_HEX_LONG_U, &id);
else
count = sscanf(argv[i + 1], SCANF_DECIMAL_LONG_U, &id);
if (count != 1)
mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
else
# ifdef FEAT_GUI_W32
win_socket_id = id;
# else
gtk_socket_id = id;
# endif
i++;
}
# endif
# ifdef FEAT_GUI_GTK
else if (STRICMP(argv[i], "--echo-wid") == 0)
echo_wid_arg = TRUE;
# endif
# ifndef FEAT_NETBEANS_INTG
else if (strncmp(argv[i], "-nb", (size_t)3) == 0)
{
mch_errmsg(_("'-nb' cannot be used: not enabled at compile time\n"));
mch_exit(2);
}
# endif
}
#endif
}
/*
* Scan the command line arguments.
*/
static void
command_line_scan(parmp)
mparm_T *parmp;
{
int argc = parmp->argc;
char **argv = parmp->argv;
int argv_idx; /* index in argv[n][] */
int had_minmin = FALSE; /* found "--" argument */
int want_argument; /* option argument with argument */
int c;
char_u *p = NULL;
long n;
--argc;
++argv;
argv_idx = 1; /* active option letter is argv[0][argv_idx] */
while (argc > 0)
{
/*
* "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
*/
if (argv[0][0] == '+' && !had_minmin)
{
if (parmp->n_commands >= MAX_ARG_CMDS)
mainerr(ME_EXTRA_CMD, NULL);
argv_idx = -1; /* skip to next argument */
if (argv[0][1] == NUL)
parmp->commands[parmp->n_commands++] = (char_u *)"$";
else
parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
}
/*
* Optional argument.
*/
else if (argv[0][0] == '-' && !had_minmin)
{
want_argument = FALSE;
c = argv[0][argv_idx++];
#ifdef VMS
/*
* VMS only uses upper case command lines. Interpret "-X" as "-x"
* and "-/X" as "-X".
*/
if (c == '/')
{
c = argv[0][argv_idx++];
c = TOUPPER_ASC(c);
}
else
c = TOLOWER_ASC(c);
#endif
switch (c)
{
case NUL: /* "vim -" read from stdin */
/* "ex -" silent mode */
if (exmode_active)
silent_mode = TRUE;
else
{
if (parmp->edit_type != EDIT_NONE)
mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
parmp->edit_type = EDIT_STDIN;
read_cmd_fd = 2; /* read from stderr instead of stdin */
}
argv_idx = -1; /* skip to next argument */
break;
case '-': /* "--" don't take any more option arguments */
/* "--help" give help message */
/* "--version" give version message */
/* "--literal" take files literally */
/* "--nofork" don't fork */
/* "--noplugin[s]" skip plugins */
/* "--cmd <cmd>" execute cmd before vimrc */
if (STRICMP(argv[0] + argv_idx, "help") == 0)
usage();
else if (STRICMP(argv[0] + argv_idx, "version") == 0)
{
Columns = 80; /* need to init Columns */
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
list_version();
msg_putchar('\n');
msg_didout = FALSE;
mch_exit(0);
}
else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
{
#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
parmp->literal = TRUE;
#endif
}
else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
{
#ifdef FEAT_GUI
gui.dofork = FALSE; /* don't fork() when starting GUI */
#endif
}
else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
p_lpl = FALSE;
else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
{
want_argument = TRUE;
argv_idx += 3;
}
else if (STRNICMP(argv[0] + argv_idx, "startuptime", 11) == 0)
{
want_argument = TRUE;
argv_idx += 11;
}
#ifdef FEAT_CLIENTSERVER
else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
; /* already processed -- no arg */
else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
|| STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
{
/* already processed -- snatch the following arg */
if (argc > 1)
{
--argc;
++argv;
}
}
#endif
#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
# ifdef FEAT_GUI_GTK
else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
# else
else if (STRNICMP(argv[0] + argv_idx, "windowid", 8) == 0)
# endif
{
/* already processed -- snatch the following arg */
if (argc > 1)
{
--argc;
++argv;
}
}
#endif
#ifdef FEAT_GUI_GTK
else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
{
/* already processed, skip */
}
#endif
else
{
if (argv[0][argv_idx])
mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
had_minmin = TRUE;
}
if (!want_argument)
argv_idx = -1; /* skip to next argument */
break;
case 'A': /* "-A" start in Arabic mode */
#ifdef FEAT_ARABIC
set_option_value((char_u *)"arabic", 1L, NULL, 0);
#else
mch_errmsg(_(e_noarabic));
mch_exit(2);
#endif
break;
case 'b': /* "-b" binary mode */
/* Needs to be effective before expanding file names, because
* for Win32 this makes us edit a shortcut file itself,
* instead of the file it links to. */
set_options_bin(curbuf->b_p_bin, 1, 0);
curbuf->b_p_bin = 1; /* binary file I/O */
break;
case 'C': /* "-C" Compatible */
change_compatible(TRUE);
break;
case 'e': /* "-e" Ex mode */
exmode_active = EXMODE_NORMAL;
break;
case 'E': /* "-E" Improved Ex mode */
exmode_active = EXMODE_VIM;
break;
case 'f': /* "-f" GUI: run in foreground. Amiga: open
window directly, not with newcli */
#ifdef FEAT_GUI
gui.dofork = FALSE; /* don't fork() when starting GUI */
#endif
break;
case 'g': /* "-g" start GUI */
main_start_gui();
break;
case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
#ifdef FEAT_FKMAP
p_fkmap = TRUE;
set_option_value((char_u *)"rl", 1L, NULL, 0);
#else
mch_errmsg(_(e_nofarsi));
mch_exit(2);
#endif
break;
case 'h': /* "-h" give help message */
#ifdef FEAT_GUI_GNOME
/* Tell usage() to exit for "gvim". */
gui.starting = FALSE;
#endif
usage();
break;
case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
#ifdef FEAT_RIGHTLEFT
p_hkmap = TRUE;
set_option_value((char_u *)"rl", 1L, NULL, 0);
#else
mch_errmsg(_(e_nohebrew));
mch_exit(2);
#endif
break;
case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
#ifdef FEAT_LISP
set_option_value((char_u *)"lisp", 1L, NULL, 0);
p_sm = TRUE;
#endif
break;
case 'M': /* "-M" no changes or writing of files */
reset_modifiable();
/* FALLTHROUGH */
case 'm': /* "-m" no writing of files */
p_write = FALSE;
break;
case 'y': /* "-y" easy mode */
#ifdef FEAT_GUI
gui.starting = TRUE; /* start GUI a bit later */
#endif
parmp->evim_mode = TRUE;
break;
case 'N': /* "-N" Nocompatible */
change_compatible(FALSE);
break;
case 'n': /* "-n" no swap file */
#ifdef FEAT_NETBEANS_INTG
/* checking for "-nb", netbeans parameters */
if (argv[0][argv_idx] == 'b')
{
netbeansArg = argv[0];
argv_idx = -1; /* skip to next argument */
}
else
#endif
parmp->no_swap_file = TRUE;
break;
case 'p': /* "-p[N]" open N tab pages */
#ifdef TARGET_API_MAC_OSX
/* For some reason on MacOS X, an argument like:
-psn_0_10223617 is passed in when invoke from Finder
or with the 'open' command */
if (argv[0][argv_idx] == 's')
{
argv_idx = -1; /* bypass full -psn */
main_start_gui();
break;
}
#endif
#ifdef FEAT_WINDOWS
/* default is 0: open window for each file */
parmp->window_count = get_number_arg((char_u *)argv[0],
&argv_idx, 0);
parmp->window_layout = WIN_TABS;
#endif
break;
case 'o': /* "-o[N]" open N horizontal split windows */
#ifdef FEAT_WINDOWS
/* default is 0: open window for each file */
parmp->window_count = get_number_arg((char_u *)argv[0],
&argv_idx, 0);
parmp->window_layout = WIN_HOR;
#endif
break;
case 'O': /* "-O[N]" open N vertical split windows */
#if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
/* default is 0: open window for each file */
parmp->window_count = get_number_arg((char_u *)argv[0],
&argv_idx, 0);
parmp->window_layout = WIN_VER;
#endif
break;
#ifdef FEAT_QUICKFIX
case 'q': /* "-q" QuickFix mode */
if (parmp->edit_type != EDIT_NONE)
mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
parmp->edit_type = EDIT_QF;
if (argv[0][argv_idx]) /* "-q{errorfile}" */
{
parmp->use_ef = (char_u *)argv[0] + argv_idx;
argv_idx = -1;
}
else if (argc > 1) /* "-q {errorfile}" */
want_argument = TRUE;
break;
#endif
case 'R': /* "-R" readonly mode */
readonlymode = TRUE;
curbuf->b_p_ro = TRUE;
p_uc = 10000; /* don't update very often */
break;
case 'r': /* "-r" recovery mode */
case 'L': /* "-L" recovery mode */
recoverymode = 1;
break;
case 's':
if (exmode_active) /* "-s" silent (batch) mode */
silent_mode = TRUE;
else /* "-s {scriptin}" read from script file */
want_argument = TRUE;
break;
case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
if (parmp->edit_type != EDIT_NONE)
mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
parmp->edit_type = EDIT_TAG;
if (argv[0][argv_idx]) /* "-t{tag}" */
{
parmp->tagname = (char_u *)argv[0] + argv_idx;
argv_idx = -1;
}
else /* "-t {tag}" */
want_argument = TRUE;
break;
#ifdef FEAT_EVAL
case 'D': /* "-D" Debugging */
parmp->use_debug_break_level = 9999;
break;
#endif
#ifdef FEAT_DIFF
case 'd': /* "-d" 'diff' */
# ifdef AMIGA
/* check for "-dev {device}" */
if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
want_argument = TRUE;
else
# endif
parmp->diff_mode = TRUE;
break;
#endif
case 'V': /* "-V{N}" Verbose level */
/* default is 10: a little bit verbose */
p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
if (argv[0][argv_idx] != NUL)
{
set_option_value((char_u *)"verbosefile", 0L,
(char_u *)argv[0] + argv_idx, 0);
argv_idx = (int)STRLEN(argv[0]);
}
break;
case 'v': /* "-v" Vi-mode (as if called "vi") */
exmode_active = 0;
#ifdef FEAT_GUI
gui.starting = FALSE; /* don't start GUI */
#endif
break;
case 'w': /* "-w{number}" set window height */
/* "-w {scriptout}" write to script */
if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
{
n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
set_option_value((char_u *)"window", n, NULL, 0);
break;
}
want_argument = TRUE;
break;
#ifdef FEAT_CRYPT
case 'x': /* "-x" encrypted reading/writing of files */
parmp->ask_for_key = TRUE;
break;
#endif
case 'X': /* "-X" don't connect to X server */
#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
x_no_connect = TRUE;
#endif
break;
case 'Z': /* "-Z" restricted mode */
restricted = TRUE;
break;
case 'c': /* "-c{command}" or "-c {command}" execute
command */
if (argv[0][argv_idx] != NUL)
{
if (parmp->n_commands >= MAX_ARG_CMDS)
mainerr(ME_EXTRA_CMD, NULL);
parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
+ argv_idx;
argv_idx = -1;
break;
}
/*FALLTHROUGH*/
case 'S': /* "-S {file}" execute Vim script */
case 'i': /* "-i {viminfo}" use for viminfo */
#ifndef FEAT_DIFF
case 'd': /* "-d {device}" device (for Amiga) */
#endif
case 'T': /* "-T {terminal}" terminal name */
case 'u': /* "-u {vimrc}" vim inits file */
case 'U': /* "-U {gvimrc}" gvim inits file */
case 'W': /* "-W {scriptout}" overwrite */
#ifdef FEAT_GUI_W32
case 'P': /* "-P {parent title}" MDI parent */
#endif
want_argument = TRUE;
break;
default:
mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
}
/*
* Handle option arguments with argument.
*/
if (want_argument)
{
/*
* Check for garbage immediately after the option letter.
*/
if (argv[0][argv_idx] != NUL)
mainerr(ME_GARBAGE, (char_u *)argv[0]);
--argc;
if (argc < 1 && c != 'S') /* -S has an optional argument */
mainerr_arg_missing((char_u *)argv[0]);
++argv;
argv_idx = -1;
switch (c)
{
case 'c': /* "-c {command}" execute command */
case 'S': /* "-S {file}" execute Vim script */
if (parmp->n_commands >= MAX_ARG_CMDS)
mainerr(ME_EXTRA_CMD, NULL);
if (c == 'S')
{
char *a;
if (argc < 1)
/* "-S" without argument: use default session file
* name. */
a = SESSION_FILE;
else if (argv[0][0] == '-')
{
/* "-S" followed by another option: use default
* session file name. */
a = SESSION_FILE;
++argc;
--argv;
}
else
a = argv[0];
p = alloc((unsigned)(STRLEN(a) + 4));
if (p == NULL)
mch_exit(2);
sprintf((char *)p, "so %s", a);
parmp->cmds_tofree[parmp->n_commands] = TRUE;
parmp->commands[parmp->n_commands++] = p;
}
else
parmp->commands[parmp->n_commands++] =
(char_u *)argv[0];
break;
case '-':
if (argv[-1][2] == 'c')
{
/* "--cmd {command}" execute command */
if (parmp->n_pre_commands >= MAX_ARG_CMDS)
mainerr(ME_EXTRA_CMD, NULL);
parmp->pre_commands[parmp->n_pre_commands++] =
(char_u *)argv[0];
}
/* "--startuptime <file>" already handled */
break;
/* case 'd': -d {device} is handled in mch_check_win() for the
* Amiga */
#ifdef FEAT_QUICKFIX
case 'q': /* "-q {errorfile}" QuickFix mode */
parmp->use_ef = (char_u *)argv[0];
break;
#endif
case 'i': /* "-i {viminfo}" use for viminfo */
use_viminfo = (char_u *)argv[0];
break;
case 's': /* "-s {scriptin}" read from script file */
if (scriptin[0] != NULL)
{
scripterror:
mch_errmsg(_("Attempt to open script file again: \""));
mch_errmsg(argv[-1]);
mch_errmsg(" ");
mch_errmsg(argv[0]);
mch_errmsg("\"\n");
mch_exit(2);
}
if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
{
mch_errmsg(_("Cannot open for reading: \""));
mch_errmsg(argv[0]);
mch_errmsg("\"\n");
mch_exit(2);
}
if (save_typebuf() == FAIL)
mch_exit(2); /* out of memory */
break;
case 't': /* "-t {tag}" */
parmp->tagname = (char_u *)argv[0];
break;
case 'T': /* "-T {terminal}" terminal name */
/*
* The -T term argument is always available and when
* HAVE_TERMLIB is supported it overrides the environment
* variable TERM.
*/
#ifdef FEAT_GUI
if (term_is_gui((char_u *)argv[0]))
gui.starting = TRUE; /* start GUI a bit later */
else
#endif
parmp->term = (char_u *)argv[0];
break;
case 'u': /* "-u {vimrc}" vim inits file */
parmp->use_vimrc = (char_u *)argv[0];
break;
case 'U': /* "-U {gvimrc}" gvim inits file */
#ifdef FEAT_GUI
use_gvimrc = (char_u *)argv[0];
#endif
break;
case 'w': /* "-w {nr}" 'window' value */
/* "-w {scriptout}" append to script file */
if (vim_isdigit(*((char_u *)argv[0])))
{
argv_idx = 0;
n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
set_option_value((char_u *)"window", n, NULL, 0);
argv_idx = -1;
break;
}
/*FALLTHROUGH*/
case 'W': /* "-W {scriptout}" overwrite script file */
if (scriptout != NULL)
goto scripterror;
if ((scriptout = mch_fopen(argv[0],
c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
{
mch_errmsg(_("Cannot open for script output: \""));
mch_errmsg(argv[0]);
mch_errmsg("\"\n");
mch_exit(2);
}
break;
#ifdef FEAT_GUI_W32
case 'P': /* "-P {parent title}" MDI parent */
gui_mch_set_parent(argv[0]);
break;
#endif
}
}
}
/*
* File name argument.
*/
else
{
argv_idx = -1; /* skip to next argument */
/* Check for only one type of editing. */
if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
parmp->edit_type = EDIT_FILE;
#ifdef MSWIN
/* Remember if the argument was a full path before changing
* slashes to backslashes. */
if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
parmp->full_path = TRUE;
#endif
/* Add the file to the global argument list. */
if (ga_grow(&global_alist.al_ga, 1) == FAIL
|| (p = vim_strsave((char_u *)argv[0])) == NULL)
mch_exit(2);
#ifdef FEAT_DIFF
if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
&& !mch_isdir(alist_name(&GARGLIST[0])))
{
char_u *r;
r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
if (r != NULL)
{
vim_free(p);
p = r;
}
}
#endif
#if defined(__CYGWIN32__) && !defined(WIN32)
/*
* If vim is invoked by non-Cygwin tools, convert away any
* DOS paths, so things like .swp files are created correctly.
* Look for evidence of non-Cygwin paths before we bother.
* This is only for when using the Unix files.
*/
if (strpbrk(p, "\\:") != NULL && !path_with_url(p))
{
char posix_path[PATH_MAX];
# if CYGWIN_VERSION_DLL_MAJOR >= 1007
cygwin_conv_path(CCP_WIN_A_TO_POSIX, p, posix_path, PATH_MAX);
# else
cygwin_conv_to_posix_path(p, posix_path);
# endif
vim_free(p);
p = vim_strsave(posix_path);
if (p == NULL)
mch_exit(2);
}
#endif
#ifdef USE_FNAME_CASE
/* Make the case of the file name match the actual file. */
fname_case(p, 0);
#endif
alist_add(&global_alist, p,
#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
parmp->literal ? 2 : 0 /* add buffer nr after exp. */
#else
2 /* add buffer number now and use curbuf */
#endif
);
#if defined(FEAT_MBYTE) && defined(WIN32)
{
/* Remember this argument has been added to the argument list.
* Needed when 'encoding' is changed. */
used_file_arg(argv[0], parmp->literal, parmp->full_path,
# ifdef FEAT_DIFF
parmp->diff_mode
# else
FALSE
# endif
);
}
#endif
}
/*
* If there are no more letters after the current "-", go to next
* argument. argv_idx is set to -1 when the current argument is to be
* skipped.
*/
if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
{
--argc;
++argv;
argv_idx = 1;
}
}
#ifdef FEAT_EVAL
/* If there is a "+123" or "-c" command, set v:swapcommand to the first
* one. */
if (parmp->n_commands > 0)
{
p = alloc((unsigned)STRLEN(parmp->commands[0]) + 3);
if (p != NULL)
{
sprintf((char *)p, ":%s\r", parmp->commands[0]);
set_vim_var_string(VV_SWAPCOMMAND, p, -1);
vim_free(p);
}
}
#endif
}
/*
* Print a warning if stdout is not a terminal.
* When starting in Ex mode and commands come from a file, set Silent mode.
*/
static void
check_tty(parmp)
mparm_T *parmp;
{
int input_isatty; /* is active input a terminal? */
input_isatty = mch_input_isatty();
if (exmode_active)
{
if (!input_isatty)
silent_mode = TRUE;
}
else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
#ifdef FEAT_GUI
/* don't want the delay when started from the desktop */
&& !gui.starting
#endif
)
{
#ifdef NBDEBUG
/*
* This shouldn't be necessary. But if I run netbeans with the log
* output coming to the console and XOpenDisplay fails, I get vim
* trying to start with input/output to my console tty. This fills my
* input buffer so fast I can't even kill the process in under 2
* minutes (and it beeps continuously the whole time :-)
*/
if (netbeans_active() && (!parmp->stdout_isatty || !input_isatty))
{
mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
exit(1);
}
#endif
if (!parmp->stdout_isatty)
mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
if (!input_isatty)
mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
out_flush();
if (scriptin[0] == NULL)
ui_delay(2000L, TRUE);
TIME_MSG("Warning delay");
}
}
/*
* Read text from stdin.
*/
static void
read_stdin()
{
int i;
#if defined(HAS_SWAP_EXISTS_ACTION)
/* When getting the ATTENTION prompt here, use a dialog */
swap_exists_action = SEA_DIALOG;
#endif
no_wait_return = TRUE;
i = msg_didany;
set_buflisted(TRUE);
(void)open_buffer(TRUE, NULL, 0); /* create memfile and read file */
no_wait_return = FALSE;
msg_didany = i;
TIME_MSG("reading stdin");
#if defined(HAS_SWAP_EXISTS_ACTION)
check_swap_exists_action();
#endif
#if !(defined(AMIGA) || defined(MACOS))
/*
* Close stdin and dup it from stderr. Required for GPM to work
* properly, and for running external commands.
* Is there any other system that cannot do this?
*/
close(0);
ignored = dup(2);
#endif
}
/*
* Create the requested number of windows and edit buffers in them.
* Also does recovery if "recoverymode" set.
*/
static void
create_windows(parmp)
mparm_T *parmp UNUSED;
{
#ifdef FEAT_WINDOWS
int dorewind;
int done = 0;
/*
* Create the number of windows that was requested.
*/
if (parmp->window_count == -1) /* was not set */
parmp->window_count = 1;
if (parmp->window_count == 0)
parmp->window_count = GARGCOUNT;
if (parmp->window_count > 1)
{
/* Don't change the windows if there was a command in .vimrc that
* already split some windows */
if (parmp->window_layout == 0)
parmp->window_layout = WIN_HOR;
if (parmp->window_layout == WIN_TABS)
{
parmp->window_count = make_tabpages(parmp->window_count);
TIME_MSG("making tab pages");
}
else if (firstwin->w_next == NULL)
{
parmp->window_count = make_windows(parmp->window_count,
parmp->window_layout == WIN_VER);
TIME_MSG("making windows");
}
else
parmp->window_count = win_count();
}
else
parmp->window_count = 1;
#endif
if (recoverymode) /* do recover */
{
msg_scroll = TRUE; /* scroll message up */
ml_recover();
if (curbuf->b_ml.ml_mfp == NULL) /* failed */
getout(1);
do_modelines(0); /* do modelines */
}
else
{
/*
* Open a buffer for windows that don't have one yet.
* Commands in the .vimrc might have loaded a file or split the window.
* Watch out for autocommands that delete a window.
*/
#ifdef FEAT_AUTOCMD
/*
* Don't execute Win/Buf Enter/Leave autocommands here
*/
++autocmd_no_enter;
++autocmd_no_leave;
#endif
#ifdef FEAT_WINDOWS
dorewind = TRUE;
while (done++ < 1000)
{
if (dorewind)
{
if (parmp->window_layout == WIN_TABS)
goto_tabpage(1);
else
curwin = firstwin;
}
else if (parmp->window_layout == WIN_TABS)
{
if (curtab->tp_next == NULL)
break;
goto_tabpage(0);
}
else
{
if (curwin->w_next == NULL)
break;
curwin = curwin->w_next;
}
dorewind = FALSE;
#endif
curbuf = curwin->w_buffer;
if (curbuf->b_ml.ml_mfp == NULL)
{
#ifdef FEAT_FOLDING
/* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
if (p_fdls >= 0)
curwin->w_p_fdl = p_fdls;
#endif
#if defined(HAS_SWAP_EXISTS_ACTION)
/* When getting the ATTENTION prompt here, use a dialog */
swap_exists_action = SEA_DIALOG;
#endif
set_buflisted(TRUE);
/* create memfile, read file */
(void)open_buffer(FALSE, NULL, 0);
#if defined(HAS_SWAP_EXISTS_ACTION)
if (swap_exists_action == SEA_QUIT)
{
if (got_int || only_one_window())
{
/* abort selected or quit and only one window */
did_emsg = FALSE; /* avoid hit-enter prompt */
getout(1);
}
/* We can't close the window, it would disturb what
* happens next. Clear the file name and set the arg
* index to -1 to delete it later. */
setfname(curbuf, NULL, NULL, FALSE);
curwin->w_arg_idx = -1;
swap_exists_action = SEA_NONE;
}
else
handle_swap_exists(NULL);
#endif
#ifdef FEAT_AUTOCMD
dorewind = TRUE; /* start again */
#endif
}
#ifdef FEAT_WINDOWS
ui_breakcheck();
if (got_int)
{
(void)vgetc(); /* only break the file loading, not the rest */
break;
}
}
#endif
#ifdef FEAT_WINDOWS
if (parmp->window_layout == WIN_TABS)
goto_tabpage(1);
else
curwin = firstwin;
curbuf = curwin->w_buffer;
#endif
#ifdef FEAT_AUTOCMD
--autocmd_no_enter;
--autocmd_no_leave;
#endif
}
}
#ifdef FEAT_WINDOWS
/*
* If opened more than one window, start editing files in the other
* windows. make_windows() has already opened the windows.
*/
static void
edit_buffers(parmp)
mparm_T *parmp;
{
int arg_idx; /* index in argument list */
int i;
int advance = TRUE;
# ifdef FEAT_AUTOCMD
/*
* Don't execute Win/Buf Enter/Leave autocommands here
*/
++autocmd_no_enter;
++autocmd_no_leave;
# endif
/* When w_arg_idx is -1 remove the window (see create_windows()). */
if (curwin->w_arg_idx == -1)
{
win_close(curwin, TRUE);
advance = FALSE;
}
arg_idx = 1;
for (i = 1; i < parmp->window_count; ++i)
{
/* When w_arg_idx is -1 remove the window (see create_windows()). */
if (curwin->w_arg_idx == -1)
{
++arg_idx;
win_close(curwin, TRUE);
advance = FALSE;
continue;
}
if (advance)
{
if (parmp->window_layout == WIN_TABS)
{
if (curtab->tp_next == NULL) /* just checking */
break;
goto_tabpage(0);
}
else
{
if (curwin->w_next == NULL) /* just checking */
break;
win_enter(curwin->w_next, FALSE);
}
}
advance = TRUE;
/* Only open the file if there is no file in this window yet (that can
* happen when .vimrc contains ":sall"). */
if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
{
curwin->w_arg_idx = arg_idx;
/* Edit file from arg list, if there is one. When "Quit" selected
* at the ATTENTION prompt close the window. */
# ifdef HAS_SWAP_EXISTS_ACTION
swap_exists_did_quit = FALSE;
# endif
(void)do_ecmd(0, arg_idx < GARGCOUNT
? alist_name(&GARGLIST[arg_idx]) : NULL,
NULL, NULL, ECMD_LASTL, ECMD_HIDE, curwin);
# ifdef HAS_SWAP_EXISTS_ACTION
if (swap_exists_did_quit)
{
/* abort or quit selected */
if (got_int || only_one_window())
{
/* abort selected and only one window */
did_emsg = FALSE; /* avoid hit-enter prompt */
getout(1);
}
win_close(curwin, TRUE);
advance = FALSE;
}
# endif
if (arg_idx == GARGCOUNT - 1)
arg_had_last = TRUE;
++arg_idx;
}
ui_breakcheck();
if (got_int)
{
(void)vgetc(); /* only break the file loading, not the rest */
break;
}
}
if (parmp->window_layout == WIN_TABS)
goto_tabpage(1);
# ifdef FEAT_AUTOCMD
--autocmd_no_enter;
# endif
win_enter(firstwin, FALSE); /* back to first window */
# ifdef FEAT_AUTOCMD
--autocmd_no_leave;
# endif
TIME_MSG("editing files in windows");
if (parmp->window_count > 1 && parmp->window_layout != WIN_TABS)
win_equal(curwin, FALSE, 'b'); /* adjust heights */
}
#endif /* FEAT_WINDOWS */
/*
* Execute the commands from --cmd arguments "cmds[cnt]".
*/
static void
exe_pre_commands(parmp)
mparm_T *parmp;
{
char_u **cmds = parmp->pre_commands;
int cnt = parmp->n_pre_commands;
int i;
if (cnt > 0)
{
curwin->w_cursor.lnum = 0; /* just in case.. */
sourcing_name = (char_u *)_("pre-vimrc command line");
# ifdef FEAT_EVAL
current_SID = SID_CMDARG;
# endif
for (i = 0; i < cnt; ++i)
do_cmdline_cmd(cmds[i]);
sourcing_name = NULL;
# ifdef FEAT_EVAL
current_SID = 0;
# endif
TIME_MSG("--cmd commands");
}
}
/*
* Execute "+", "-c" and "-S" arguments.
*/
static void
exe_commands(parmp)
mparm_T *parmp;
{
int i;
/*
* We start commands on line 0, make "vim +/pat file" match a
* pattern on line 1. But don't move the cursor when an autocommand
* with g`" was used.
*/
msg_scroll = TRUE;
if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
curwin->w_cursor.lnum = 0;
sourcing_name = (char_u *)"command line";
#ifdef FEAT_EVAL
current_SID = SID_CARG;
#endif
for (i = 0; i < parmp->n_commands; ++i)
{
do_cmdline_cmd(parmp->commands[i]);
if (parmp->cmds_tofree[i])
vim_free(parmp->commands[i]);
}
sourcing_name = NULL;
#ifdef FEAT_EVAL
current_SID = 0;
#endif
if (curwin->w_cursor.lnum == 0)
curwin->w_cursor.lnum = 1;
if (!exmode_active)
msg_scroll = FALSE;
#ifdef FEAT_QUICKFIX
/* When started with "-q errorfile" jump to first error again. */
if (parmp->edit_type == EDIT_QF)
qf_jump(NULL, 0, 0, FALSE);
#endif
TIME_MSG("executing command arguments");
}
/*
* Source startup scripts.
*/
static void
source_startup_scripts(parmp)
mparm_T *parmp;
{
int i;
/*
* For "evim" source evim.vim first of all, so that the user can overrule
* any things he doesn't like.
*/
if (parmp->evim_mode)
{
(void)do_source((char_u *)EVIM_FILE, FALSE, DOSO_NONE);
TIME_MSG("source evim file");
}
/*
* If -u argument given, use only the initializations from that file and
* nothing else.
*/
if (parmp->use_vimrc != NULL)
{
if (STRCMP(parmp->use_vimrc, "NONE") == 0
|| STRCMP(parmp->use_vimrc, "NORC") == 0)
{
#ifdef FEAT_GUI
if (use_gvimrc == NULL) /* don't load gvimrc either */
use_gvimrc = parmp->use_vimrc;
#endif
if (parmp->use_vimrc[2] == 'N')
p_lpl = FALSE; /* don't load plugins either */
}
else
{
if (do_source(parmp->use_vimrc, FALSE, DOSO_NONE) != OK)
EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
}
}
else if (!silent_mode)
{
#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
/*
* Get system wide defaults, if the file name is defined.
*/
#ifdef SYS_VIMRC_FILE
(void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, DOSO_NONE);
#endif
#ifdef MACOS_X
(void)do_source((char_u *)"$VIMRUNTIME/macmap.vim", FALSE, DOSO_NONE);
#endif
/*
* Try to read initialization commands from the following places:
* - environment variable VIMINIT
* - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
* - second user vimrc file ($VIM/.vimrc for Dos)
* - environment variable EXINIT
* - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
* - second user exrc file ($VIM/.exrc for Dos)
* The first that exists is used, the rest is ignored.
*/
if (process_env((char_u *)"VIMINIT", TRUE) != OK)
{
if (do_source((char_u *)USR_VIMRC_FILE, TRUE, DOSO_VIMRC) == FAIL
#ifdef USR_VIMRC_FILE2
&& do_source((char_u *)USR_VIMRC_FILE2, TRUE,
DOSO_VIMRC) == FAIL
#endif
#ifdef USR_VIMRC_FILE3
&& do_source((char_u *)USR_VIMRC_FILE3, TRUE,
DOSO_VIMRC) == FAIL
#endif
&& process_env((char_u *)"EXINIT", FALSE) == FAIL
&& do_source((char_u *)USR_EXRC_FILE, FALSE, DOSO_NONE) == FAIL)
{
#ifdef USR_EXRC_FILE2
(void)do_source((char_u *)USR_EXRC_FILE2, FALSE, DOSO_NONE);
#endif
}
}
/*
* Read initialization commands from ".vimrc" or ".exrc" in current
* directory. This is only done if the 'exrc' option is set.
* Because of security reasons we disallow shell and write commands
* now, except for unix if the file is owned by the user or 'secure'
* option has been reset in environment of global ".exrc" or ".vimrc".
* Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
* SYS_VIMRC_FILE.
*/
if (p_exrc)
{
#if defined(UNIX) || defined(VMS)
/* If ".vimrc" file is not owned by user, set 'secure' mode. */
if (!file_owned(VIMRC_FILE))
#endif
secure = p_secure;
i = FAIL;
if (fullpathcmp((char_u *)USR_VIMRC_FILE,
(char_u *)VIMRC_FILE, FALSE) != FPC_SAME
#ifdef USR_VIMRC_FILE2
&& fullpathcmp((char_u *)USR_VIMRC_FILE2,
(char_u *)VIMRC_FILE, FALSE) != FPC_SAME
#endif
#ifdef USR_VIMRC_FILE3
&& fullpathcmp((char_u *)USR_VIMRC_FILE3,
(char_u *)VIMRC_FILE, FALSE) != FPC_SAME
#endif
#ifdef SYS_VIMRC_FILE
&& fullpathcmp((char_u *)SYS_VIMRC_FILE,
(char_u *)VIMRC_FILE, FALSE) != FPC_SAME
#endif
)
i = do_source((char_u *)VIMRC_FILE, TRUE, DOSO_VIMRC);
if (i == FAIL)
{
#if defined(UNIX) || defined(VMS)
/* if ".exrc" is not owned by user set 'secure' mode */
if (!file_owned(EXRC_FILE))
secure = p_secure;
else
secure = 0;
#endif
if ( fullpathcmp((char_u *)USR_EXRC_FILE,
(char_u *)EXRC_FILE, FALSE) != FPC_SAME
#ifdef USR_EXRC_FILE2
&& fullpathcmp((char_u *)USR_EXRC_FILE2,
(char_u *)EXRC_FILE, FALSE) != FPC_SAME
#endif
)
(void)do_source((char_u *)EXRC_FILE, FALSE, DOSO_NONE);
}
}
if (secure == 2)
need_wait_return = TRUE;
secure = 0;
#ifdef AMIGA
proc->pr_WindowPtr = save_winptr;
#endif
}
TIME_MSG("sourcing vimrc file(s)");
}
/*
* Setup to start using the GUI. Exit with an error when not available.
*/
static void
main_start_gui()
{
#ifdef FEAT_GUI
gui.starting = TRUE; /* start GUI a bit later */
#else
mch_errmsg(_(e_nogvim));
mch_errmsg("\n");
mch_exit(2);
#endif
}
#endif /* NO_VIM_MAIN */
/*
* Get an environment variable, and execute it as Ex commands.
* Returns FAIL if the environment variable was not executed, OK otherwise.
*/
int
process_env(env, is_viminit)
char_u *env;
int is_viminit; /* when TRUE, called for VIMINIT */
{
char_u *initstr;
char_u *save_sourcing_name;
linenr_T save_sourcing_lnum;
#ifdef FEAT_EVAL
scid_T save_sid;
#endif
if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
{
if (is_viminit)
vimrc_found(NULL, NULL);
save_sourcing_name = sourcing_name;
save_sourcing_lnum = sourcing_lnum;
sourcing_name = env;
sourcing_lnum = 0;
#ifdef FEAT_EVAL
save_sid = current_SID;
current_SID = SID_ENV;
#endif
do_cmdline_cmd(initstr);
sourcing_name = save_sourcing_name;
sourcing_lnum = save_sourcing_lnum;
#ifdef FEAT_EVAL
current_SID = save_sid;;
#endif
return OK;
}
return FAIL;
}
#if (defined(UNIX) || defined(VMS)) && !defined(NO_VIM_MAIN)
/*
* Return TRUE if we are certain the user owns the file "fname".
* Used for ".vimrc" and ".exrc".
* Use both stat() and lstat() for extra security.
*/
static int
file_owned(fname)
char *fname;
{
struct stat s;
# ifdef UNIX
uid_t uid = getuid();
# else /* VMS */
uid_t uid = ((getgid() << 16) | getuid());
# endif
return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
# ifdef HAVE_LSTAT
|| mch_lstat(fname, &s) != 0 || s.st_uid != uid
# endif
);
}
#endif
/*
* Give an error message main_errors["n"] and exit.
*/
static void
mainerr(n, str)
int n; /* one of the ME_ defines */
char_u *str; /* extra argument or NULL */
{
#if defined(UNIX) || defined(__EMX__) || defined(VMS)
reset_signals(); /* kill us with CTRL-C here, if you like */
#endif
mch_errmsg(longVersion);
mch_errmsg("\n");
mch_errmsg(_(main_errors[n]));
if (str != NULL)
{
mch_errmsg(": \"");
mch_errmsg((char *)str);
mch_errmsg("\"");
}
mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
mch_exit(1);
}
void
mainerr_arg_missing(str)
char_u *str;
{
mainerr(ME_ARG_MISSING, str);
}
#ifndef NO_VIM_MAIN
/*
* print a message with three spaces prepended and '\n' appended.
*/
static void
main_msg(s)
char *s;
{
mch_msg(" ");
mch_msg(s);
mch_msg("\n");
}
/*
* Print messages for "vim -h" or "vim --help" and exit.
*/
static void
usage()
{
int i;
static char *(use[]) =
{
N_("[file ..] edit specified file(s)"),
N_("- read text from stdin"),
N_("-t tag edit file where tag is defined"),
#ifdef FEAT_QUICKFIX
N_("-q [errorfile] edit file with first error")
#endif
};
#if defined(UNIX) || defined(__EMX__) || defined(VMS)
reset_signals(); /* kill us with CTRL-C here, if you like */
#endif
mch_msg(longVersion);
mch_msg(_("\n\nusage:"));
for (i = 0; ; ++i)
{
mch_msg(_(" vim [arguments] "));
mch_msg(_(use[i]));
if (i == (sizeof(use) / sizeof(char_u *)) - 1)
break;
mch_msg(_("\n or:"));
}
#ifdef VMS
mch_msg(_("\nWhere case is ignored prepend / to make flag upper case"));
#endif
mch_msg(_("\n\nArguments:\n"));
main_msg(_("--\t\t\tOnly file names after this"));
#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
main_msg(_("--literal\t\tDon't expand wildcards"));
#endif
#ifdef FEAT_OLE
main_msg(_("-register\t\tRegister this gvim for OLE"));
main_msg(_("-unregister\t\tUnregister gvim for OLE"));
#endif
#ifdef FEAT_GUI
main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
#endif
main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
main_msg(_("-E\t\t\tImproved Ex mode"));
main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
#ifdef FEAT_DIFF
main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
#endif
main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
main_msg(_("-M\t\t\tModifications in text not allowed"));
main_msg(_("-b\t\t\tBinary mode"));
#ifdef FEAT_LISP
main_msg(_("-l\t\t\tLisp mode"));
#endif
main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
main_msg(_("-V[N][fname]\t\tBe verbose [level N] [log messages to fname]"));
#ifdef FEAT_EVAL
main_msg(_("-D\t\t\tDebugging mode"));
#endif
main_msg(_("-n\t\t\tNo swap file, use memory only"));
main_msg(_("-r\t\t\tList swap files and exit"));
main_msg(_("-r (with file name)\tRecover crashed session"));
main_msg(_("-L\t\t\tSame as -r"));
#ifdef AMIGA
main_msg(_("-f\t\t\tDon't use newcli to open window"));
main_msg(_("-dev <device>\t\tUse <device> for I/O"));
#endif
#ifdef FEAT_ARABIC
main_msg(_("-A\t\t\tstart in Arabic mode"));
#endif
#ifdef FEAT_RIGHTLEFT
main_msg(_("-H\t\t\tStart in Hebrew mode"));
#endif
#ifdef FEAT_FKMAP
main_msg(_("-F\t\t\tStart in Farsi mode"));
#endif
main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
#ifdef FEAT_GUI
main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
#endif
main_msg(_("--noplugin\t\tDon't load plugin scripts"));
#ifdef FEAT_WINDOWS
main_msg(_("-p[N]\t\tOpen N tab pages (default: one for each file)"));
main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
main_msg(_("-O[N]\t\tLike -o but split vertically"));
#endif
main_msg(_("+\t\t\tStart at end of file"));
main_msg(_("+<lnum>\t\tStart at line <lnum>"));
main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
#ifdef FEAT_CRYPT
main_msg(_("-x\t\t\tEdit encrypted files"));
#endif
#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
# if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
main_msg(_("-display <display>\tConnect vim to this particular X-server"));
# endif
main_msg(_("-X\t\t\tDo not connect to X server"));
#endif
#ifdef FEAT_CLIENTSERVER
main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
# ifdef FEAT_WINDOWS
main_msg(_("--remote-tab[-wait][-silent] <files> As --remote but use tab page per file"));
# endif
main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
main_msg(_("--serverlist\t\tList available Vim server names and exit"));
main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
#endif
#ifdef STARTUPTIME
main_msg(_("--startuptime <file>\tWrite startup timing messages to <file>"));
#endif
#ifdef FEAT_VIMINFO
main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
#endif
main_msg(_("-h or --help\tPrint Help (this message) and exit"));
main_msg(_("--version\t\tPrint version information and exit"));
#ifdef FEAT_GUI_X11
# ifdef FEAT_GUI_MOTIF
mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
# else
# ifdef FEAT_GUI_ATHENA
# ifdef FEAT_GUI_NEXTAW
mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
# else
mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
# endif
# endif
# endif
main_msg(_("-display <display>\tRun vim on <display>"));
main_msg(_("-iconic\t\tStart vim iconified"));
main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
main_msg(_("-boldfont <font>\tUse <font> for bold text"));
main_msg(_("-italicfont <font>\tUse <font> for italic text"));
main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
# ifdef FEAT_GUI_ATHENA
main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
# endif
main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
main_msg(_("-xrm <resource>\tSet the specified resource"));
#endif /* FEAT_GUI_X11 */
#ifdef FEAT_GUI_GTK
mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
main_msg(_("--role <role>\tSet a unique role to identify the main window"));
main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
main_msg(_("--echo-wid\t\tMake gvim echo the Window ID on stdout"));
#endif
#ifdef FEAT_GUI_W32
main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
main_msg(_("--windowid <HWND>\tOpen Vim inside another win32 widget"));
#endif
#ifdef FEAT_GUI_GNOME
/* Gnome gives extra messages for --help if we continue, but not for -h. */
if (gui.starting)
{
mch_msg("\n");
gui.dofork = FALSE;
}
else
#endif
mch_exit(0);
}
#if defined(HAS_SWAP_EXISTS_ACTION)
/*
* Check the result of the ATTENTION dialog:
* When "Quit" selected, exit Vim.
* When "Recover" selected, recover the file.
*/
static void
check_swap_exists_action()
{
if (swap_exists_action == SEA_QUIT)
getout(1);
handle_swap_exists(NULL);
}
#endif
#endif
#if defined(STARTUPTIME) || defined(PROTO)
static void time_diff __ARGS((struct timeval *then, struct timeval *now));
static struct timeval prev_timeval;
# ifdef WIN3264
/*
* Windows doesn't have gettimeofday(), although it does have struct timeval.
*/
static int
gettimeofday(struct timeval *tv, char *dummy)
{
long t = clock();
tv->tv_sec = t / CLOCKS_PER_SEC;
tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
return 0;
}
# endif
/*
* Save the previous time before doing something that could nest.
* set "*tv_rel" to the time elapsed so far.
*/
void
time_push(tv_rel, tv_start)
void *tv_rel, *tv_start;
{
*((struct timeval *)tv_rel) = prev_timeval;
gettimeofday(&prev_timeval, NULL);
((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
- ((struct timeval *)tv_rel)->tv_usec;
((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
- ((struct timeval *)tv_rel)->tv_sec;
if (((struct timeval *)tv_rel)->tv_usec < 0)
{
((struct timeval *)tv_rel)->tv_usec += 1000000;
--((struct timeval *)tv_rel)->tv_sec;
}
*(struct timeval *)tv_start = prev_timeval;
}
/*
* Compute the previous time after doing something that could nest.
* Subtract "*tp" from prev_timeval;
* Note: The arguments are (void *) to avoid trouble with systems that don't
* have struct timeval.
*/
void
time_pop(tp)
void *tp; /* actually (struct timeval *) */
{
prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
if (prev_timeval.tv_usec < 0)
{
prev_timeval.tv_usec += 1000000;
--prev_timeval.tv_sec;
}
}
static void
time_diff(then, now)
struct timeval *then;
struct timeval *now;
{
long usec;
long msec;
usec = now->tv_usec - then->tv_usec;
msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
usec = usec % 1000L;
fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
}
void
time_msg(mesg, tv_start)
char *mesg;
void *tv_start; /* only for do_source: start time; actually
(struct timeval *) */
{
static struct timeval start;
struct timeval now;
if (time_fd != NULL)
{
if (strstr(mesg, "STARTING") != NULL)
{
gettimeofday(&start, NULL);
prev_timeval = start;
fprintf(time_fd, "\n\ntimes in msec\n");
fprintf(time_fd, " clock self+sourced self: sourced script\n");
fprintf(time_fd, " clock elapsed: other lines\n\n");
}
gettimeofday(&now, NULL);
time_diff(&start, &now);
if (((struct timeval *)tv_start) != NULL)
{
fprintf(time_fd, " ");
time_diff(((struct timeval *)tv_start), &now);
}
fprintf(time_fd, " ");
time_diff(&prev_timeval, &now);
prev_timeval = now;
fprintf(time_fd, ": %s\n", mesg);
}
}
#endif
#if (defined(FEAT_CLIENTSERVER) && !defined(NO_VIM_MAIN)) || defined(PROTO)
/*
* Common code for the X command server and the Win32 command server.
*/
static char_u *build_drop_cmd __ARGS((int filec, char **filev, int tabs, int sendReply));
/*
* Do the client-server stuff, unless "--servername ''" was used.
*/
static void
exec_on_server(parmp)
mparm_T *parmp;
{
if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
{
# ifdef WIN32
/* Initialise the client/server messaging infrastructure. */
serverInitMessaging();
# endif
/*
* When a command server argument was found, execute it. This may
* exit Vim when it was successful. Otherwise it's executed further
* on. Remember the encoding used here in "serverStrEnc".
*/
if (parmp->serverArg)
{
cmdsrv_main(&parmp->argc, parmp->argv,
parmp->serverName_arg, &parmp->serverStr);
# ifdef FEAT_MBYTE
parmp->serverStrEnc = vim_strsave(p_enc);
# endif
}
/* If we're still running, get the name to register ourselves.
* On Win32 can register right now, for X11 need to setup the
* clipboard first, it's further down. */
parmp->servername = serverMakeName(parmp->serverName_arg,
parmp->argv[0]);
# ifdef WIN32
if (parmp->servername != NULL)
{
serverSetName(parmp->servername);
vim_free(parmp->servername);
}
# endif
}
}
/*
* Prepare for running as a Vim server.
*/
static void
prepare_server(parmp)
mparm_T *parmp;
{
# if defined(FEAT_X11)
/*
* Register for remote command execution with :serversend and --remote
* unless there was a -X or a --servername '' on the command line.
* Only register nongui-vim's with an explicit --servername argument.
* When running as root --servername is also required.
*/
if (X_DISPLAY != NULL && parmp->servername != NULL && (
# ifdef FEAT_GUI
(gui.in_use
# ifdef UNIX
&& getuid() != ROOT_UID
# endif
) ||
# endif
parmp->serverName_arg != NULL))
{
(void)serverRegisterName(X_DISPLAY, parmp->servername);
vim_free(parmp->servername);
TIME_MSG("register server name");
}
else
serverDelayedStartName = parmp->servername;
# endif
/*
* Execute command ourselves if we're here because the send failed (or
* else we would have exited above).
*/
if (parmp->serverStr != NULL)
{
char_u *p;
server_to_input_buf(serverConvert(parmp->serverStrEnc,
parmp->serverStr, &p));
vim_free(p);
}
}
static void
cmdsrv_main(argc, argv, serverName_arg, serverStr)
int *argc;
char **argv;
char_u *serverName_arg;
char_u **serverStr;
{
char_u *res;
int i;
char_u *sname;
int ret;
int didone = FALSE;
int exiterr = 0;
char **newArgV = argv + 1;
int newArgC = 1,
Argc = *argc;
int argtype;
#define ARGTYPE_OTHER 0
#define ARGTYPE_EDIT 1
#define ARGTYPE_EDIT_WAIT 2
#define ARGTYPE_SEND 3
int silent = FALSE;
int tabs = FALSE;
# ifndef FEAT_X11
HWND srv;
# else
Window srv;
setup_term_clip();
# endif
sname = serverMakeName(serverName_arg, argv[0]);
if (sname == NULL)
return;
/*
* Execute the command server related arguments and remove them
* from the argc/argv array; We may have to return into main()
*/
for (i = 1; i < Argc; i++)
{
res = NULL;
if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
{
for (; i < *argc; i++)
{
*newArgV++ = argv[i];
newArgC++;
}
break;
}
if (STRICMP(argv[i], "--remote-send") == 0)
argtype = ARGTYPE_SEND;
else if (STRNICMP(argv[i], "--remote", 8) == 0)
{
char *p = argv[i] + 8;
argtype = ARGTYPE_EDIT;
while (*p != NUL)
{
if (STRNICMP(p, "-wait", 5) == 0)
{
argtype = ARGTYPE_EDIT_WAIT;
p += 5;
}
else if (STRNICMP(p, "-silent", 7) == 0)
{
silent = TRUE;
p += 7;
}
else if (STRNICMP(p, "-tab", 4) == 0)
{
tabs = TRUE;
p += 4;
}
else
{
argtype = ARGTYPE_OTHER;
break;
}
}
}
else
argtype = ARGTYPE_OTHER;
if (argtype != ARGTYPE_OTHER)
{
if (i == *argc - 1)
mainerr_arg_missing((char_u *)argv[i]);
if (argtype == ARGTYPE_SEND)
{
*serverStr = (char_u *)argv[i + 1];
i++;
}
else
{
*serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
tabs, argtype == ARGTYPE_EDIT_WAIT);
if (*serverStr == NULL)
{
/* Probably out of memory, exit. */
didone = TRUE;
exiterr = 1;
break;
}
Argc = i;
}
# ifdef FEAT_X11
if (xterm_dpy == NULL)
{
mch_errmsg(_("No display"));
ret = -1;
}
else
ret = serverSendToVim(xterm_dpy, sname, *serverStr,
NULL, &srv, 0, 0, silent);
# else
/* Win32 always works? */
ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
# endif
if (ret < 0)
{
if (argtype == ARGTYPE_SEND)
{
/* Failed to send, abort. */
mch_errmsg(_(": Send failed.\n"));
didone = TRUE;
exiterr = 1;
}
else if (!silent)
/* Let vim start normally. */
mch_errmsg(_(": Send failed. Trying to execute locally\n"));
break;
}
# ifdef FEAT_GUI_W32
/* Guess that when the server name starts with "g" it's a GUI
* server, which we can bring to the foreground here.
* Foreground() in the server doesn't work very well. */
if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
SetForegroundWindow(srv);
# endif
/*
* For --remote-wait: Wait until the server did edit each
* file. Also detect that the server no longer runs.
*/
if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
{
int numFiles = *argc - i - 1;
int j;
char_u *done = alloc(numFiles);
char_u *p;
# ifdef FEAT_GUI_W32
NOTIFYICONDATA ni;
int count = 0;
extern HWND message_window;
# endif
if (numFiles > 0 && argv[i + 1][0] == '+')
/* Skip "+cmd" argument, don't wait for it to be edited. */
--numFiles;
# ifdef FEAT_GUI_W32
ni.cbSize = sizeof(ni);
ni.hWnd = message_window;
ni.uID = 0;
ni.uFlags = NIF_ICON|NIF_TIP;
ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
Shell_NotifyIcon(NIM_ADD, &ni);
# endif
/* Wait for all files to unload in remote */
vim_memset(done, 0, numFiles);
while (memchr(done, 0, numFiles) != NULL)
{
# ifdef WIN32
p = serverGetReply(srv, NULL, TRUE, TRUE);
if (p == NULL)
break;
# else
if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
break;
# endif
j = atoi((char *)p);
if (j >= 0 && j < numFiles)
{
# ifdef FEAT_GUI_W32
++count;
sprintf(ni.szTip, _("%d of %d edited"),
count, numFiles);
Shell_NotifyIcon(NIM_MODIFY, &ni);
# endif
done[j] = 1;
}
}
# ifdef FEAT_GUI_W32
Shell_NotifyIcon(NIM_DELETE, &ni);
# endif
}
}
else if (STRICMP(argv[i], "--remote-expr") == 0)
{
if (i == *argc - 1)
mainerr_arg_missing((char_u *)argv[i]);
# ifdef WIN32
/* Win32 always works? */
if (serverSendToVim(sname, (char_u *)argv[i + 1],
&res, NULL, 1, FALSE) < 0)
# else
if (xterm_dpy == NULL)
mch_errmsg(_("No display: Send expression failed.\n"));
else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
&res, NULL, 1, 1, FALSE) < 0)
# endif
{
if (res != NULL && *res != NUL)
{
/* Output error from remote */
mch_errmsg((char *)res);
vim_free(res);
res = NULL;
}
mch_errmsg(_(": Send expression failed.\n"));
}
}
else if (STRICMP(argv[i], "--serverlist") == 0)
{
# ifdef WIN32
/* Win32 always works? */
res = serverGetVimNames();
# else
if (xterm_dpy != NULL)
res = serverGetVimNames(xterm_dpy);
# endif
if (called_emsg)
mch_errmsg("\n");
}
else if (STRICMP(argv[i], "--servername") == 0)
{
/* Already processed. Take it out of the command line */
i++;
continue;
}
else
{
*newArgV++ = argv[i];
newArgC++;
continue;
}
didone = TRUE;
if (res != NULL && *res != NUL)
{
mch_msg((char *)res);
if (res[STRLEN(res) - 1] != '\n')
mch_msg("\n");
}
vim_free(res);
}
if (didone)
{
display_errors(); /* display any collected messages */
exit(exiterr); /* Mission accomplished - get out */
}
/* Return back into main() */
*argc = newArgC;
vim_free(sname);
}
/*
* Build a ":drop" command to send to a Vim server.
*/
static char_u *
build_drop_cmd(filec, filev, tabs, sendReply)
int filec;
char **filev;
int tabs; /* Use ":tab drop" instead of ":drop". */
int sendReply;
{
garray_T ga;
int i;
char_u *inicmd = NULL;
char_u *p;
char_u *cwd;
if (filec > 0 && filev[0][0] == '+')
{
inicmd = (char_u *)filev[0] + 1;
filev++;
filec--;
}
/* Check if we have at least one argument. */
if (filec <= 0)
mainerr_arg_missing((char_u *)filev[-1]);
/* Temporarily cd to the current directory to handle relative file names. */
cwd = alloc(MAXPATHL);
if (cwd == NULL)
return NULL;
if (mch_dirname(cwd, MAXPATHL) != OK)
{
vim_free(cwd);
return NULL;
}
p = vim_strsave_escaped_ext(cwd,
#ifdef BACKSLASH_IN_FILENAME
"", /* rem_backslash() will tell what chars to escape */
#else
PATH_ESC_CHARS,
#endif
'\\', TRUE);
vim_free(cwd);
if (p == NULL)
return NULL;
ga_init2(&ga, 1, 100);
ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
ga_concat(&ga, p);
vim_free(p);
/* Call inputsave() so that a prompt for an encryption key works. */
ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|");
if (tabs)
ga_concat(&ga, (char_u *)"tab ");
ga_concat(&ga, (char_u *)"drop");
for (i = 0; i < filec; i++)
{
/* On Unix the shell has already expanded the wildcards, don't want to
* do it again in the Vim server. On MS-Windows only escape
* non-wildcard characters. */
p = vim_strsave_escaped((char_u *)filev[i],
#ifdef UNIX
PATH_ESC_CHARS
#else
(char_u *)" \t%#"
#endif
);
if (p == NULL)
{
vim_free(ga.ga_data);
return NULL;
}
ga_concat(&ga, (char_u *)" ");
ga_concat(&ga, p);
vim_free(p);
}
ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
/* The :drop commands goes to Insert mode when 'insertmode' is set, use
* CTRL-\ CTRL-N again. */
ga_concat(&ga, (char_u *)"<C-\\><C-N>");
/* Switch back to the correct current directory (prior to temporary path
* switch) unless 'autochdir' is set, in which case it will already be
* correct after the :drop command. */
ga_concat(&ga, (char_u *)":if !exists('+acd')||!&acd|cd -|endif<CR>");
if (sendReply)
ga_concat(&ga, (char_u *)":call SetupRemoteReplies()<CR>");
ga_concat(&ga, (char_u *)":");
if (inicmd != NULL)
{
/* Can't use <CR> after "inicmd", because an "startinsert" would cause
* the following commands to be inserted as text. Use a "|",
* hopefully "inicmd" does allow this... */
ga_concat(&ga, inicmd);
ga_concat(&ga, (char_u *)"|");
}
/* Bring the window to the foreground, goto Insert mode when 'im' set and
* clear command line. */
ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
ga_append(&ga, NUL);
return ga.ga_data;
}
/*
* Make our basic server name: use the specified "arg" if given, otherwise use
* the tail of the command "cmd" we were started with.
* Return the name in allocated memory. This doesn't include a serial number.
*/
static char_u *
serverMakeName(arg, cmd)
char_u *arg;
char *cmd;
{
char_u *p;
if (arg != NULL && *arg != NUL)
p = vim_strsave_up(arg);
else
{
p = vim_strsave_up(gettail((char_u *)cmd));
/* Remove .exe or .bat from the name. */
if (p != NULL && vim_strchr(p, '.') != NULL)
*vim_strchr(p, '.') = NUL;
}
return p;
}
#endif /* FEAT_CLIENTSERVER */
#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
/*
* Replace termcodes such as <CR> and insert as key presses if there is room.
*/
void
server_to_input_buf(str)
char_u *str;
{
char_u *ptr = NULL;
char_u *cpo_save = p_cpo;
/* Set 'cpoptions' the way we want it.
* B set - backslashes are *not* treated specially
* k set - keycodes are *not* reverse-engineered
* < unset - <Key> sequences *are* interpreted
* The last but one parameter of replace_termcodes() is TRUE so that the
* <lt> sequence is recognised - needed for a real backslash.
*/
p_cpo = (char_u *)"Bk";
str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE, FALSE);
p_cpo = cpo_save;
if (*ptr != NUL) /* trailing CTRL-V results in nothing */
{
/*
* Add the string to the input stream.
* Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
*
* First clear typed characters from the typeahead buffer, there could
* be half a mapping there. Then append to the existing string, so
* that multiple commands from a client are concatenated.
*/
if (typebuf.tb_maplen < typebuf.tb_len)
del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
(void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
/* Let input_available() know we inserted text in the typeahead
* buffer. */
typebuf_was_filled = TRUE;
}
vim_free((char_u *)ptr);
}
/*
* Evaluate an expression that the client sent to a string.
* Handles disabling error messages and disables debugging, otherwise Vim
* hangs, waiting for "cont" to be typed.
*/
char_u *
eval_client_expr_to_string(expr)
char_u *expr;
{
char_u *res;
int save_dbl = debug_break_level;
int save_ro = redir_off;
debug_break_level = -1;
redir_off = 0;
++emsg_skip;
res = eval_to_string(expr, NULL, TRUE);
debug_break_level = save_dbl;
redir_off = save_ro;
--emsg_skip;
/* A client can tell us to redraw, but not to display the cursor, so do
* that here. */
setcursor();
out_flush();
#ifdef FEAT_GUI
if (gui.in_use)
gui_update_cursor(FALSE, FALSE);
#endif
return res;
}
/*
* If conversion is needed, convert "data" from "client_enc" to 'encoding' and
* return an allocated string. Otherwise return "data".
* "*tofree" is set to the result when it needs to be freed later.
*/
char_u *
serverConvert(client_enc, data, tofree)
char_u *client_enc UNUSED;
char_u *data;
char_u **tofree;
{
char_u *res = data;
*tofree = NULL;
# ifdef FEAT_MBYTE
if (client_enc != NULL && p_enc != NULL)
{
vimconv_T vimconv;
vimconv.vc_type = CONV_NONE;
if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
&& vimconv.vc_type != CONV_NONE)
{
res = string_convert(&vimconv, data, NULL);
if (res == NULL)
res = data;
else
*tofree = res;
}
convert_setup(&vimconv, NULL, NULL);
}
# endif
return res;
}
#endif
/*
* When FEAT_FKMAP is defined, also compile the Farsi source code.
*/
#if defined(FEAT_FKMAP) || defined(PROTO)
# include "farsi.c"
#endif
/*
* When FEAT_ARABIC is defined, also compile the Arabic source code.
*/
#if defined(FEAT_ARABIC) || defined(PROTO)
# include "arabic.c"
#endif
| zyz2011-vim | src/main.c | C | gpl2 | 107,178 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved by Bram Moolenaar
* this file by Vince Negri
*
* 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.
*/
/*
* vimrun.c - Tiny Win32 program to safely run an external command in a
* DOS console.
* This program is required to avoid that typing CTRL-C in the DOS
* console kills Vim. Now it only kills vimrun.
*/
#include <stdio.h>
#include <stdlib.h>
#ifndef __CYGWIN__
# include <conio.h>
#endif
#ifdef __BORLANDC__
extern char *
#ifdef _RTLDLL
__import
#endif
_oscmd;
# define _kbhit kbhit
# define _getch getch
#else
# ifdef __MINGW32__
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# else
# ifdef __CYGWIN__
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# define _getch getchar
# else
extern char *_acmdln;
# endif
# endif
#endif
int
main(void)
{
const char *p;
int retval;
int inquote = 0;
int silent = 0;
#ifdef __BORLANDC__
p = _oscmd;
#else
# if defined(__MINGW32__) || defined(__CYGWIN__)
p = (const char *)GetCommandLine();
# else
p = _acmdln;
# endif
#endif
/*
* Skip the executable name, which might be in "".
*/
while (*p)
{
if (*p == '"')
inquote = !inquote;
else if (!inquote && *p == ' ')
{
++p;
break;
}
++p;
}
/*
* "-s" argument: don't wait for a key hit.
*/
if (p[0] == '-' && p[1] == 's' && p[2] == ' ')
{
silent = 1;
p += 3;
while (*p == ' ')
++p;
}
/* Print the command, including quotes and redirection. */
puts(p);
/*
* Do it!
*/
retval = system(p);
if (retval == -1)
perror("vimrun system(): ");
else if (retval != 0)
printf("shell returned %d\n", retval);
if (!silent)
{
puts("Hit any key to close this window...");
#ifndef __CYGWIN__
while (_kbhit())
(void)_getch();
#endif
(void)_getch();
}
return retval;
}
| zyz2011-vim | src/vimrun.c | C | gpl2 | 2,144 |
$!
$! OS_VMS_FIX.COM
$! Copyright (C) 2000, Stephen P. Wall
$!
$! Filter files for "#if" line continuations using a '\' and convert
$! them to use comments for the continuation. Necessary for VAXC - it
$! doesn't understand the '\'.
$!
$! Yes, this is honkin' ugly code, but I deliberately avoided
$! if ...
$! then
$! ....
$! endif
$! and call/subroutine/endsubroutine constructs, because I can still
$! remember when DCL didn't have them, and I wanted this to be as
$! portable as possible, so... If you want to structure it nicer for
$! your own use, please feel free to do so. However, please only
$! distribute it in it's original form.
$!
$! I wrote it in DCL for portability and ease of use - a C version
$! would definitely run faster, but then I'd have to deal with compiler
$! differences, and users would have to deal with configuring and
$! building it. With DCL, it runs out-of-the-box.
$!
$! Note that if you use this from a VMS system to modify files on a
$! mounted network drive, f$search() may return only the first matching
$! file when it tries to resolve wildcards. I have been unable to find
$! a way around this. Either copy the files to a local disk, or specify
$! each file individually (Keep in mind if you do this that VMS limits
$! you to eight parameters, so you'll only be able to filter eight files
$! at a time).
$!
$! Ideas...
$! - Use 'search filespec "#","if","\"/mat=and' to quickly eliminate
$! files that definitely don't need filtering. This should speed
$! things up considerable. Reading and writing every line from every
$! file takes quite a bit of time...
$! - Error handling isn't great. Come up with something better....
$!
$! E-mail addresses:
$! Steve Wall hitched97@velnet.com
$! Zoltan Arpadffy arpadffy@polarhome.com
$! John W. Hamill jhamill3@ford.com
$!
$! Modification History:
$! 13Jul00 SWall Initial Version
$! 14Jul00 ZArpadffy Display usage
$! 06Mar01 JHamill Ctrl-M problem fix
$!
$! If no parameters, or "-h" for a parameter, print usage and exit
$
$ all = "''p1'''p2'''p3'''p4'''p5'''p6'''p7'''p8'"
$ if (all .nes. "") .and. (p1 .nes. "-h") .and. (p1 .nes. "-H") then goto startup
$
$ write sys$output "OS_VMS_FIX - DECC->VAXC pre-processor directive convert script"
$ write sys$output "Usage: @OS_VMS_FIX <filename_1> <filename_2> <...>"
$ write sys$output " @OS_VMS_FIX <filename with wildcard> <...>"
$ write sys$output ""
$ write sys$output "Example: @OS_VMS_FIX *.c *.h [.proto]*.pro"
$ write sys$output "Please note, you can define up to 8 parameters."
$ write sys$output ""
$ exit
$
$! Create an FDL file to convert VFC format files to Stream_LF.
$! VMS OPEN/WRITE command creates VFC files. When VFC files are read
$! out under unix, they appear to have binary data embedded in them.
$! To be friendly, we'll convert them to Stream_LF, which reads just
$! file on unix.
$
$startup:
$ on control_y then goto stopfdl
$ open/write fdl []convert.fdl
$ write fdl "SYSTEM"
$ write fdl " SOURCE VAX/VMS"
$ write fdl "FILE"
$ write fdl " ORGANIZATION SEQUENTIAL"
$ write fdl "RECORD"
$ write fdl " BLOCK_SPAN YES"
$ write fdl " CARRIAGE_CONTROL CARRIAGE_RETURN"
$ write fdl " FORMAT STREAM"
$ write fdl " SIZE 0"
$ close fdl
$ on control_y then goto endparamloop
$
$! Some symbols for use later on...
$
$ spc = ""
$ spc[0,8] = 32
$ tab = ""
$ tab[0,8] = 9
$
$! Scan all positional arguments, do wildcard expansion, and call the
$! filter routine on each resulting filename.
$
$ cnt = 0
$paramloop:
$ cnt = cnt + 1
$
$! VMS only allows command line parameters P1 - P8, so stop after
$! processing 8 arguments.
$
$ if cnt .eq. 9 then goto endparamloop
$
$! Skip any empty parameter.
$
$ if P'cnt' .eqs. "" then goto paramloop
$
$! Got a parameter - do wildcard expansion.
$
$ arg = f$parse(P'cnt')
$ write sys$output "Parsing ''arg'..."
$ last = ""
$fileloop:
$ file = f$search(arg, 1)
$
$! f$search() returns "" after the last of multiple matches.
$
$ if file .eqs. "" then goto endfileloop
$
$! Strip the version number.
$
$ file = f$parse(file,,,"DEVICE") + f$parse(file,,,"DIRECTORY") + -
f$parse(file,,,"NAME") + f$parse(file,,,"TYPE")
$
$! f$search() returns the same filename over and over if there are no
$! wildcards in it.
$
$ if file .eqs. last then goto endfileloop
$ last = file
$
$! Got a valid file - filter it.
$
$ gosub filter
$
$! Reset our error handling.
$
$ on control_y then goto endparamloop
$
$! See if there's another matching filename.
$
$ goto fileloop
$endfileloop:
$
$! Check for another parameter.
$
$ goto paramloop
$endparamloop:
$
$! Finished - delete the FDL file.
$
$ delete []convert.fdl;
$
$! So long, and thanks for all the fish...
$
$ exit
$
$
$! User aborted with Control-Y during creation of FDL file.
$! Close the file, delete it, and exit with an error status.
$
$stopfdl:
$ close fdl
$ delete []convert.fdl;
$ exit %X10000000
$
$
$! Filter a file.
$
$filter:
$ write sys$output "Filtering ''file'..."
$
$! Get a temporary filename from the subroutine parameter.
$
$ tmp = f$parse(file,,,"DEVICE") + f$parse(file,,,"DIRECTORY") + -
"tmp_" + f$parse(file,,,"NAME") + f$parse(file,,,"TYPE")
$ on control_y then goto aborted
$ open /read input 'file'
$ open /write output 'tmp'
$ changed = 0
$readloop:
$ read/end_of_file=endreadloop/error=readlooperror input line
$
$! Get the first 3 non-blank character on the line.
$
$ start = f$extract(0,3,f$edit(line,"COLLAPSE,LOWERCASE"))
$
$! If the line doesn't start with some form of "#if", just write it to
$! the temp file.
$
$ if start .nes. "#if" then goto writeit
$chkbkslsh:
$
$! See if the line ends in a backslash. If not, write it to the temp file.
$
$ if f$extract(f$length(line)-1,1,line) .nes. "\" then goto writeit
$
$! Ok, got a line that needs to be modified. Mark this file as changed,
$! then replace the backslash at the end with the beginning of a comment
$! (/*), and write it to the temp file.
$
$ changed = 1
$ line = f$extract(0,f$length(line)-1,line) + "/*"
$ write/symbol output line
$
$! Get another line from the input.
$
$ read/end_of_file=endreadloop/error=readlooperror input line
$
$! Grab all the blank space from the beginning of the line.
$
$ spaces = ""
$spaceloop:
$ if (f$extract(0,1,line) .nes. spc) .and. (f$extract(0,1,line) .nes. tab) -
then goto endspaceloop
$ spaces = spaces + f$extract(0,1,line)
$ line = f$extract(1,f$length(line)-1,line)
$ goto spaceloop
$endspaceloop:
$
$! Stick an end-comment (*/) after the leading blanks, then go back and
$! check for a trailing backslash again, to catch code that continues
$! across multiple lines.
$
$ line = spaces + "*/ " + line
$ goto chkbkslsh
$
$! Write the current line, (will either be an untouched line, or the
$! last line of a continuation) to the temp file, and go back to look
$! for more input.
$!
$writeit:
$ write/symbol output line
$ goto readloop
$
$! Hit EOF. Close the input & output, and if the file was marked as
$! changed, convert it from VMS VFC format, to the more common Stream_LF
$! format, so it doesn't show up full of garbage if someone tries to
$! edit it on another OS.
$!
$endreadloop:
$ close input
$ close output
$ if changed .eq. 0 then goto nocopy
$ convert 'tmp' 'file' /fdl=[]convert.fdl
$nocopy:
$ delete 'tmp';
$
$! Exit this subroutine.
$
$ goto endfunc
$
$! Got a read error. Say so, and trash the temp file.
$
$readlooperror:
$ write sys$error "Error processing file ''file'"
$ goto errorend
$
$! Got an interrupt. Say so, and trash the temp file.
$
$aborted:
$ write sys$error "Aborted while processing file ''file'"
$
$! Common code for read errors and interrupts.
$
$errorend:
$ close input
$ close output
$ delete 'tmp';
$ return %X10000000
$
$! End of filter subroutine.
$
$endfunc:
$ return
$
$! EOF
| zyz2011-vim | src/os_vms_fix.com | DIGITAL Command Language | gpl2 | 7,771 |
/* vi:set ts=8 sts=4 sw=4: */
/* MODIFIED ATHENA SCROLLBAR (USING ARROWHEADS AT ENDS OF TRAVEL) */
/* Modifications Copyright 1992 by Mitch Trachtenberg */
/* Rights, permissions, and disclaimer of warranty are as in the */
/* DEC and MIT notice below. See usage warning in .c file. */
/*
* $XConsortium: ScrollbarP.h,v 1.3 94/04/17 20:12:42 jim Exp $
*/
/***********************************************************
Copyright (c) 1987, 1988 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
All Rights Reserved
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 Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL 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.
******************************************************************/
#ifndef _Scrollbar_h
#define _Scrollbar_h
/****************************************************************
*
* Scrollbar Widget
*
****************************************************************/
#include <X11/IntrinsicP.h>
#include <X11/Xaw/SimpleP.h>
#include <X11/Xmu/Converters.h>
/*
* Most things we need are in StringDefs.h
*/
#define XtCMinimumThumb "MinimumThumb"
#define XtCShown "Shown"
#define XtCTopOfThumb "TopOfThumb"
#define XtCMaxOfThumb "MaxOfThumb"
#define XtCShadowWidth "ShadowWidth"
#define XtCTopShadowPixel "TopShadowPixel"
#define XtCBottomShadowPixel "BottomShadowPixel"
#define XtCLimitThumb "LimitThumb"
#define XtNminimumThumb "minimumThumb"
#define XtNtopOfThumb "topOfThumb"
#define XtNmaxOfThumb "maxOfThumb"
#define XtNshadowWidth "shadowWidth"
#define XtNtopShadowPixel "topShadowPixel"
#define XtNbottomShadowPixel "bottomShadowPixel"
#define XtNlimitThumb "limitThumb"
typedef struct _ScrollbarRec *ScrollbarWidget;
typedef struct _ScrollbarClassRec *ScrollbarWidgetClass;
extern WidgetClass vim_scrollbarWidgetClass;
extern void vim_XawScrollbarSetThumb __ARGS((Widget, double, double, double));
typedef struct
{
/* public */
Pixel foreground; /* thumb foreground color */
XtOrientation orientation; /* horizontal or vertical */
XtCallbackList scrollProc; /* proportional scroll */
XtCallbackList thumbProc; /* jump (to position) scroll */
XtCallbackList jumpProc; /* same as thumbProc but pass data by ref */
Pixmap thumb; /* thumb color */
float top; /* What percent is above the win's top */
float shown; /* What percent is shown in the win */
float max; /* Maximum value for top */
Dimension length; /* either height or width */
Dimension thickness; /* either width or height */
Dimension min_thumb; /* minimum size for the thumb. */
/* private */
XtIntervalId timer_id; /* autorepeat timer; remove on destruction */
char scroll_mode; /* see below */
float scroll_off; /* offset from event to top of thumb */
GC gc; /* a (shared) gc */
Position topLoc; /* Pixel that corresponds to top */
Dimension shownLength; /* Num pixels corresponding to shown */
/* From 3d widget */
Dimension shadow_width;
Pixel top_shadow_pixel;
Pixel bot_shadow_pixel;
Bool limit_thumb; /* limit thumb to inside scrollbar */
int top_shadow_contrast;
int bot_shadow_contrast;
GC top_shadow_GC;
GC bot_shadow_GC;
} ScrollbarPart;
#define SMODE_NONE 0
#define SMODE_CONT 1
#define SMODE_PAGE_UP 2
#define SMODE_PAGE_DOWN 3
#define SMODE_LINE_UP 4
#define SMODE_LINE_DOWN 5
#define ONE_LINE_DATA 1
#define ONE_PAGE_DATA 10
#define END_PAGE_DATA 9999
typedef struct _ScrollbarRec {
CorePart core;
SimplePart simple;
ScrollbarPart scrollbar;
} ScrollbarRec;
typedef struct {int empty;} ScrollbarClassPart;
typedef struct _ScrollbarClassRec {
CoreClassPart core_class;
SimpleClassPart simple_class;
ScrollbarClassPart scrollbar_class;
} ScrollbarClassRec;
extern ScrollbarClassRec vim_scrollbarClassRec;
#endif /* _Scrollbar_h */
| zyz2011-vim | src/gui_at_sb.h | C | gpl2 | 5,938 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read a list of people who contributed.
* 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"
static int path_is_url __ARGS((char_u *p));
#if defined(FEAT_WINDOWS) || defined(PROTO)
static void win_init __ARGS((win_T *newp, win_T *oldp, int flags));
static void win_init_some __ARGS((win_T *newp, win_T *oldp));
static void frame_comp_pos __ARGS((frame_T *topfrp, int *row, int *col));
static void frame_setheight __ARGS((frame_T *curfrp, int height));
#ifdef FEAT_VERTSPLIT
static void frame_setwidth __ARGS((frame_T *curfrp, int width));
#endif
static void win_exchange __ARGS((long));
static void win_rotate __ARGS((int, int));
static void win_totop __ARGS((int size, int flags));
static void win_equal_rec __ARGS((win_T *next_curwin, int current, frame_T *topfr, int dir, int col, int row, int width, int height));
static int last_window __ARGS((void));
static int close_last_window_tabpage __ARGS((win_T *win, int free_buf, tabpage_T *prev_curtab));
static win_T *win_free_mem __ARGS((win_T *win, int *dirp, tabpage_T *tp));
static frame_T *win_altframe __ARGS((win_T *win, tabpage_T *tp));
static tabpage_T *alt_tabpage __ARGS((void));
static win_T *frame2win __ARGS((frame_T *frp));
static int frame_has_win __ARGS((frame_T *frp, win_T *wp));
static void frame_new_height __ARGS((frame_T *topfrp, int height, int topfirst, int wfh));
static int frame_fixed_height __ARGS((frame_T *frp));
#ifdef FEAT_VERTSPLIT
static int frame_fixed_width __ARGS((frame_T *frp));
static void frame_add_statusline __ARGS((frame_T *frp));
static void frame_new_width __ARGS((frame_T *topfrp, int width, int leftfirst, int wfw));
static void frame_add_vsep __ARGS((frame_T *frp));
static int frame_minwidth __ARGS((frame_T *topfrp, win_T *next_curwin));
static void frame_fix_width __ARGS((win_T *wp));
#endif
#endif
static int win_alloc_firstwin __ARGS((win_T *oldwin));
static void new_frame __ARGS((win_T *wp));
#if defined(FEAT_WINDOWS) || defined(PROTO)
static tabpage_T *alloc_tabpage __ARGS((void));
static int leave_tabpage __ARGS((buf_T *new_curbuf));
static void enter_tabpage __ARGS((tabpage_T *tp, buf_T *old_curbuf, int trigger_autocmds));
static void frame_fix_height __ARGS((win_T *wp));
static int frame_minheight __ARGS((frame_T *topfrp, win_T *next_curwin));
static void win_enter_ext __ARGS((win_T *wp, int undo_sync, int no_curwin));
static void win_free __ARGS((win_T *wp, tabpage_T *tp));
static void frame_append __ARGS((frame_T *after, frame_T *frp));
static void frame_insert __ARGS((frame_T *before, frame_T *frp));
static void frame_remove __ARGS((frame_T *frp));
#ifdef FEAT_VERTSPLIT
static void win_new_width __ARGS((win_T *wp, int width));
static void win_goto_ver __ARGS((int up, long count));
static void win_goto_hor __ARGS((int left, long count));
#endif
static void frame_add_height __ARGS((frame_T *frp, int n));
static void last_status_rec __ARGS((frame_T *fr, int statusline));
static void make_snapshot_rec __ARGS((frame_T *fr, frame_T **frp));
static void clear_snapshot __ARGS((tabpage_T *tp, int idx));
static void clear_snapshot_rec __ARGS((frame_T *fr));
static int check_snapshot_rec __ARGS((frame_T *sn, frame_T *fr));
static win_T *restore_snapshot_rec __ARGS((frame_T *sn, frame_T *fr));
#endif /* FEAT_WINDOWS */
static win_T *win_alloc __ARGS((win_T *after, int hidden));
static void set_fraction __ARGS((win_T *wp));
static void win_new_height __ARGS((win_T *wp, int height));
#define URL_SLASH 1 /* path_is_url() has found "://" */
#define URL_BACKSLASH 2 /* path_is_url() has found ":\\" */
#define NOWIN (win_T *)-1 /* non-existing window */
#ifdef FEAT_WINDOWS
# define ROWS_AVAIL (Rows - p_ch - tabline_height())
#else
# define ROWS_AVAIL (Rows - p_ch)
#endif
#if defined(FEAT_WINDOWS) || defined(PROTO)
static char *m_onlyone = N_("Already only one window");
/*
* all CTRL-W window commands are handled here, called from normal_cmd().
*/
void
do_window(nchar, Prenum, xchar)
int nchar;
long Prenum;
int xchar; /* extra char from ":wincmd gx" or NUL */
{
long Prenum1;
win_T *wp;
#if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID)
char_u *ptr;
linenr_T lnum = -1;
#endif
#ifdef FEAT_FIND_ID
int type = FIND_DEFINE;
int len;
#endif
char_u cbuf[40];
if (Prenum == 0)
Prenum1 = 1;
else
Prenum1 = Prenum;
#ifdef FEAT_CMDWIN
# define CHECK_CMDWIN if (cmdwin_type != 0) { EMSG(_(e_cmdwin)); break; }
#else
# define CHECK_CMDWIN
#endif
switch (nchar)
{
/* split current window in two parts, horizontally */
case 'S':
case Ctrl_S:
case 's':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
#ifdef FEAT_QUICKFIX
/* When splitting the quickfix window open a new buffer in it,
* don't replicate the quickfix buffer. */
if (bt_quickfix(curbuf))
goto newwindow;
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_split((int)Prenum, 0);
break;
#ifdef FEAT_VERTSPLIT
/* split current window in two parts, vertically */
case Ctrl_V:
case 'v':
CHECK_CMDWIN
# ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
# endif
# ifdef FEAT_QUICKFIX
/* When splitting the quickfix window open a new buffer in it,
* don't replicate the quickfix buffer. */
if (bt_quickfix(curbuf))
goto newwindow;
# endif
# ifdef FEAT_GUI
need_mouse_correct = TRUE;
# endif
win_split((int)Prenum, WSP_VERT);
break;
#endif
/* split current window and edit alternate file */
case Ctrl_HAT:
case '^':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
STRCPY(cbuf, "split #");
if (Prenum)
vim_snprintf((char *)cbuf + 7, sizeof(cbuf) - 7,
"%ld", Prenum);
do_cmdline_cmd(cbuf);
break;
/* open new window */
case Ctrl_N:
case 'n':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
#ifdef FEAT_QUICKFIX
newwindow:
#endif
if (Prenum)
/* window height */
vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, "%ld", Prenum);
else
cbuf[0] = NUL;
#if defined(FEAT_VERTSPLIT) && defined(FEAT_QUICKFIX)
if (nchar == 'v' || nchar == Ctrl_V)
STRCAT(cbuf, "v");
#endif
STRCAT(cbuf, "new");
do_cmdline_cmd(cbuf);
break;
/* quit current window */
case Ctrl_Q:
case 'q':
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
do_cmdline_cmd((char_u *)"quit");
break;
/* close current window */
case Ctrl_C:
case 'c':
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
do_cmdline_cmd((char_u *)"close");
break;
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
/* close preview window */
case Ctrl_Z:
case 'z':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
do_cmdline_cmd((char_u *)"pclose");
break;
/* cursor to preview window */
case 'P':
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_p_pvw)
break;
if (wp == NULL)
EMSG(_("E441: There is no preview window"));
else
win_goto(wp);
break;
#endif
/* close all but current window */
case Ctrl_O:
case 'o':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
do_cmdline_cmd((char_u *)"only");
break;
/* cursor to next window with wrap around */
case Ctrl_W:
case 'w':
/* cursor to previous window with wrap around */
case 'W':
CHECK_CMDWIN
if (firstwin == lastwin && Prenum != 1) /* just one window */
beep_flush();
else
{
if (Prenum) /* go to specified window */
{
for (wp = firstwin; --Prenum > 0; )
{
if (wp->w_next == NULL)
break;
else
wp = wp->w_next;
}
}
else
{
if (nchar == 'W') /* go to previous window */
{
wp = curwin->w_prev;
if (wp == NULL)
wp = lastwin; /* wrap around */
}
else /* go to next window */
{
wp = curwin->w_next;
if (wp == NULL)
wp = firstwin; /* wrap around */
}
}
win_goto(wp);
}
break;
/* cursor to window below */
case 'j':
case K_DOWN:
case Ctrl_J:
CHECK_CMDWIN
#ifdef FEAT_VERTSPLIT
win_goto_ver(FALSE, Prenum1);
#else
for (wp = curwin; wp->w_next != NULL && Prenum1-- > 0;
wp = wp->w_next)
;
win_goto(wp);
#endif
break;
/* cursor to window above */
case 'k':
case K_UP:
case Ctrl_K:
CHECK_CMDWIN
#ifdef FEAT_VERTSPLIT
win_goto_ver(TRUE, Prenum1);
#else
for (wp = curwin; wp->w_prev != NULL && Prenum1-- > 0;
wp = wp->w_prev)
;
win_goto(wp);
#endif
break;
#ifdef FEAT_VERTSPLIT
/* cursor to left window */
case 'h':
case K_LEFT:
case Ctrl_H:
case K_BS:
CHECK_CMDWIN
win_goto_hor(TRUE, Prenum1);
break;
/* cursor to right window */
case 'l':
case K_RIGHT:
case Ctrl_L:
CHECK_CMDWIN
win_goto_hor(FALSE, Prenum1);
break;
#endif
/* move window to new tab page */
case 'T':
if (one_window())
MSG(_(m_onlyone));
else
{
tabpage_T *oldtab = curtab;
tabpage_T *newtab;
/* First create a new tab with the window, then go back to
* the old tab and close the window there. */
wp = curwin;
if (win_new_tabpage((int)Prenum) == OK
&& valid_tabpage(oldtab))
{
newtab = curtab;
goto_tabpage_tp(oldtab, TRUE);
if (curwin == wp)
win_close(curwin, FALSE);
if (valid_tabpage(newtab))
goto_tabpage_tp(newtab, TRUE);
}
}
break;
/* cursor to top-left window */
case 't':
case Ctrl_T:
win_goto(firstwin);
break;
/* cursor to bottom-right window */
case 'b':
case Ctrl_B:
win_goto(lastwin);
break;
/* cursor to last accessed (previous) window */
case 'p':
case Ctrl_P:
if (prevwin == NULL)
beep_flush();
else
win_goto(prevwin);
break;
/* exchange current and next window */
case 'x':
case Ctrl_X:
CHECK_CMDWIN
win_exchange(Prenum);
break;
/* rotate windows downwards */
case Ctrl_R:
case 'r':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
win_rotate(FALSE, (int)Prenum1); /* downwards */
break;
/* rotate windows upwards */
case 'R':
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
win_rotate(TRUE, (int)Prenum1); /* upwards */
break;
/* move window to the very top/bottom/left/right */
case 'K':
case 'J':
#ifdef FEAT_VERTSPLIT
case 'H':
case 'L':
#endif
CHECK_CMDWIN
win_totop((int)Prenum,
((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)
| ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT));
break;
/* make all windows the same height */
case '=':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_equal(NULL, FALSE, 'b');
break;
/* increase current window height */
case '+':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(curwin->w_height + (int)Prenum1);
break;
/* decrease current window height */
case '-':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(curwin->w_height - (int)Prenum1);
break;
/* set current window height */
case Ctrl__:
case '_':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(Prenum ? (int)Prenum : 9999);
break;
#ifdef FEAT_VERTSPLIT
/* increase current window width */
case '>':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(curwin->w_width + (int)Prenum1);
break;
/* decrease current window width */
case '<':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(curwin->w_width - (int)Prenum1);
break;
/* set current window width */
case '|':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(Prenum != 0 ? (int)Prenum : 9999);
break;
#endif
/* jump to tag and split window if tag exists (in preview window) */
#if defined(FEAT_QUICKFIX)
case '}':
CHECK_CMDWIN
if (Prenum)
g_do_tagpreview = Prenum;
else
g_do_tagpreview = p_pvh;
/*FALLTHROUGH*/
#endif
case ']':
case Ctrl_RSB:
CHECK_CMDWIN
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
if (Prenum)
postponed_split = Prenum;
else
postponed_split = -1;
/* Execute the command right here, required when
* "wincmd ]" was used in a function. */
do_nv_ident(Ctrl_RSB, NUL);
break;
#ifdef FEAT_SEARCHPATH
/* edit file name under cursor in a new window */
case 'f':
case 'F':
case Ctrl_F:
wingotofile:
CHECK_CMDWIN
ptr = grab_file_name(Prenum1, &lnum);
if (ptr != NULL)
{
# ifdef FEAT_GUI
need_mouse_correct = TRUE;
# endif
setpcmark();
if (win_split(0, 0) == OK)
{
RESET_BINDING(curwin);
(void)do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL,
ECMD_HIDE, NULL);
if (nchar == 'F' && lnum >= 0)
{
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_SOL | BL_FIX);
}
}
vim_free(ptr);
}
break;
#endif
#ifdef FEAT_FIND_ID
/* Go to the first occurrence of the identifier under cursor along path in a
* new window -- webb
*/
case 'i': /* Go to any match */
case Ctrl_I:
type = FIND_ANY;
/* FALLTHROUGH */
case 'd': /* Go to definition, using 'define' */
case Ctrl_D:
CHECK_CMDWIN
if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
break;
find_pattern_in_path(ptr, 0, len, TRUE,
Prenum == 0 ? TRUE : FALSE, type,
Prenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM);
curwin->w_set_curswant = TRUE;
break;
#endif
case K_KENTER:
case CAR:
#if defined(FEAT_QUICKFIX)
/*
* In a quickfix window a <CR> jumps to the error under the
* cursor in a new window.
*/
if (bt_quickfix(curbuf))
{
sprintf((char *)cbuf, "split +%ld%s",
(long)curwin->w_cursor.lnum,
(curwin->w_llist_ref == NULL) ? "cc" : "ll");
do_cmdline_cmd(cbuf);
}
#endif
break;
/* CTRL-W g extended commands */
case 'g':
case Ctrl_G:
CHECK_CMDWIN
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
++no_mapping;
++allow_keys; /* no mapping for xchar, but allow key codes */
if (xchar == NUL)
xchar = plain_vgetc();
LANGMAP_ADJUST(xchar, TRUE);
--no_mapping;
--allow_keys;
#ifdef FEAT_CMDL_INFO
(void)add_to_showcmd(xchar);
#endif
switch (xchar)
{
#if defined(FEAT_QUICKFIX)
case '}':
xchar = Ctrl_RSB;
if (Prenum)
g_do_tagpreview = Prenum;
else
g_do_tagpreview = p_pvh;
/*FALLTHROUGH*/
#endif
case ']':
case Ctrl_RSB:
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
if (Prenum)
postponed_split = Prenum;
else
postponed_split = -1;
/* Execute the command right here, required when
* "wincmd g}" was used in a function. */
do_nv_ident('g', xchar);
break;
#ifdef FEAT_SEARCHPATH
case 'f': /* CTRL-W gf: "gf" in a new tab page */
case 'F': /* CTRL-W gF: "gF" in a new tab page */
cmdmod.tab = tabpage_index(curtab) + 1;
nchar = xchar;
goto wingotofile;
#endif
default:
beep_flush();
break;
}
break;
default: beep_flush();
break;
}
}
/*
* split the current window, implements CTRL-W s and :split
*
* "size" is the height or width for the new window, 0 to use half of current
* height or width.
*
* "flags":
* WSP_ROOM: require enough room for new window
* WSP_VERT: vertical split.
* WSP_TOP: open window at the top-left of the shell (help window).
* WSP_BOT: open window at the bottom-right of the shell (quickfix window).
* WSP_HELP: creating the help window, keep layout snapshot
*
* return FAIL for failure, OK otherwise
*/
int
win_split(size, flags)
int size;
int flags;
{
/* When the ":tab" modifier was used open a new tab page instead. */
if (may_open_tabpage() == OK)
return OK;
/* Add flags from ":vertical", ":topleft" and ":botright". */
flags |= cmdmod.split;
if ((flags & WSP_TOP) && (flags & WSP_BOT))
{
EMSG(_("E442: Can't split topleft and botright at the same time"));
return FAIL;
}
/* When creating the help window make a snapshot of the window layout.
* Otherwise clear the snapshot, it's now invalid. */
if (flags & WSP_HELP)
make_snapshot(SNAP_HELP_IDX);
else
clear_snapshot(curtab, SNAP_HELP_IDX);
return win_split_ins(size, flags, NULL, 0);
}
/*
* When "new_wp" is NULL: split the current window in two.
* When "new_wp" is not NULL: insert this window at the far
* top/left/right/bottom.
* return FAIL for failure, OK otherwise
*/
int
win_split_ins(size, flags, new_wp, dir)
int size;
int flags;
win_T *new_wp;
int dir;
{
win_T *wp = new_wp;
win_T *oldwin;
int new_size = size;
int i;
int need_status = 0;
int do_equal = FALSE;
int needed;
int available;
int oldwin_height = 0;
int layout;
frame_T *frp, *curfrp;
int before;
if (flags & WSP_TOP)
oldwin = firstwin;
else if (flags & WSP_BOT)
oldwin = lastwin;
else
oldwin = curwin;
/* add a status line when p_ls == 1 and splitting the first window */
if (lastwin == firstwin && p_ls == 1 && oldwin->w_status_height == 0)
{
if (oldwin->w_height <= p_wmh && new_wp == NULL)
{
EMSG(_(e_noroom));
return FAIL;
}
need_status = STATUS_HEIGHT;
}
#ifdef FEAT_GUI
/* May be needed for the scrollbars that are going to change. */
if (gui.in_use)
out_flush();
#endif
#ifdef FEAT_VERTSPLIT
if (flags & WSP_VERT)
{
layout = FR_ROW;
/*
* Check if we are able to split the current window and compute its
* width.
*/
needed = p_wmw + 1;
if (flags & WSP_ROOM)
needed += p_wiw - p_wmw;
if (p_ea || (flags & (WSP_BOT | WSP_TOP)))
{
available = topframe->fr_width;
needed += frame_minwidth(topframe, NULL);
}
else
available = oldwin->w_width;
if (available < needed && new_wp == NULL)
{
EMSG(_(e_noroom));
return FAIL;
}
if (new_size == 0)
new_size = oldwin->w_width / 2;
if (new_size > oldwin->w_width - p_wmw - 1)
new_size = oldwin->w_width - p_wmw - 1;
if (new_size < p_wmw)
new_size = p_wmw;
/* if it doesn't fit in the current window, need win_equal() */
if (oldwin->w_width - new_size - 1 < p_wmw)
do_equal = TRUE;
/* We don't like to take lines for the new window from a
* 'winfixwidth' window. Take them from a window to the left or right
* instead, if possible. */
if (oldwin->w_p_wfw)
win_setwidth_win(oldwin->w_width + new_size, oldwin);
/* Only make all windows the same width if one of them (except oldwin)
* is wider than one of the split windows. */
if (!do_equal && p_ea && size == 0 && *p_ead != 'v'
&& oldwin->w_frame->fr_parent != NULL)
{
frp = oldwin->w_frame->fr_parent->fr_child;
while (frp != NULL)
{
if (frp->fr_win != oldwin && frp->fr_win != NULL
&& (frp->fr_win->w_width > new_size
|| frp->fr_win->w_width > oldwin->w_width
- new_size - STATUS_HEIGHT))
{
do_equal = TRUE;
break;
}
frp = frp->fr_next;
}
}
}
else
#endif
{
layout = FR_COL;
/*
* Check if we are able to split the current window and compute its
* height.
*/
needed = p_wmh + STATUS_HEIGHT + need_status;
if (flags & WSP_ROOM)
needed += p_wh - p_wmh;
if (p_ea || (flags & (WSP_BOT | WSP_TOP)))
{
available = topframe->fr_height;
needed += frame_minheight(topframe, NULL);
}
else
{
available = oldwin->w_height;
needed += p_wmh;
}
if (available < needed && new_wp == NULL)
{
EMSG(_(e_noroom));
return FAIL;
}
oldwin_height = oldwin->w_height;
if (need_status)
{
oldwin->w_status_height = STATUS_HEIGHT;
oldwin_height -= STATUS_HEIGHT;
}
if (new_size == 0)
new_size = oldwin_height / 2;
if (new_size > oldwin_height - p_wmh - STATUS_HEIGHT)
new_size = oldwin_height - p_wmh - STATUS_HEIGHT;
if (new_size < p_wmh)
new_size = p_wmh;
/* if it doesn't fit in the current window, need win_equal() */
if (oldwin_height - new_size - STATUS_HEIGHT < p_wmh)
do_equal = TRUE;
/* We don't like to take lines for the new window from a
* 'winfixheight' window. Take them from a window above or below
* instead, if possible. */
if (oldwin->w_p_wfh)
{
win_setheight_win(oldwin->w_height + new_size + STATUS_HEIGHT,
oldwin);
oldwin_height = oldwin->w_height;
if (need_status)
oldwin_height -= STATUS_HEIGHT;
}
/* Only make all windows the same height if one of them (except oldwin)
* is higher than one of the split windows. */
if (!do_equal && p_ea && size == 0
#ifdef FEAT_VERTSPLIT
&& *p_ead != 'h'
#endif
&& oldwin->w_frame->fr_parent != NULL)
{
frp = oldwin->w_frame->fr_parent->fr_child;
while (frp != NULL)
{
if (frp->fr_win != oldwin && frp->fr_win != NULL
&& (frp->fr_win->w_height > new_size
|| frp->fr_win->w_height > oldwin_height - new_size
- STATUS_HEIGHT))
{
do_equal = TRUE;
break;
}
frp = frp->fr_next;
}
}
}
/*
* allocate new window structure and link it in the window list
*/
if ((flags & WSP_TOP) == 0
&& ((flags & WSP_BOT)
|| (flags & WSP_BELOW)
|| (!(flags & WSP_ABOVE)
&& (
#ifdef FEAT_VERTSPLIT
(flags & WSP_VERT) ? p_spr :
#endif
p_sb))))
{
/* new window below/right of current one */
if (new_wp == NULL)
wp = win_alloc(oldwin, FALSE);
else
win_append(oldwin, wp);
}
else
{
if (new_wp == NULL)
wp = win_alloc(oldwin->w_prev, FALSE);
else
win_append(oldwin->w_prev, wp);
}
if (new_wp == NULL)
{
if (wp == NULL)
return FAIL;
new_frame(wp);
if (wp->w_frame == NULL)
{
win_free(wp, NULL);
return FAIL;
}
/* make the contents of the new window the same as the current one */
win_init(wp, curwin, flags);
}
/*
* Reorganise the tree of frames to insert the new window.
*/
if (flags & (WSP_TOP | WSP_BOT))
{
#ifdef FEAT_VERTSPLIT
if ((topframe->fr_layout == FR_COL && (flags & WSP_VERT) == 0)
|| (topframe->fr_layout == FR_ROW && (flags & WSP_VERT) != 0))
#else
if (topframe->fr_layout == FR_COL)
#endif
{
curfrp = topframe->fr_child;
if (flags & WSP_BOT)
while (curfrp->fr_next != NULL)
curfrp = curfrp->fr_next;
}
else
curfrp = topframe;
before = (flags & WSP_TOP);
}
else
{
curfrp = oldwin->w_frame;
if (flags & WSP_BELOW)
before = FALSE;
else if (flags & WSP_ABOVE)
before = TRUE;
else
#ifdef FEAT_VERTSPLIT
if (flags & WSP_VERT)
before = !p_spr;
else
#endif
before = !p_sb;
}
if (curfrp->fr_parent == NULL || curfrp->fr_parent->fr_layout != layout)
{
/* Need to create a new frame in the tree to make a branch. */
frp = (frame_T *)alloc_clear((unsigned)sizeof(frame_T));
*frp = *curfrp;
curfrp->fr_layout = layout;
frp->fr_parent = curfrp;
frp->fr_next = NULL;
frp->fr_prev = NULL;
curfrp->fr_child = frp;
curfrp->fr_win = NULL;
curfrp = frp;
if (frp->fr_win != NULL)
oldwin->w_frame = frp;
else
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
frp->fr_parent = curfrp;
}
if (new_wp == NULL)
frp = wp->w_frame;
else
frp = new_wp->w_frame;
frp->fr_parent = curfrp->fr_parent;
/* Insert the new frame at the right place in the frame list. */
if (before)
frame_insert(curfrp, frp);
else
frame_append(curfrp, frp);
/* Set w_fraction now so that the cursor keeps the same relative
* vertical position. */
if (oldwin->w_height > 0)
set_fraction(oldwin);
wp->w_fraction = oldwin->w_fraction;
#ifdef FEAT_VERTSPLIT
if (flags & WSP_VERT)
{
wp->w_p_scr = curwin->w_p_scr;
if (need_status)
{
win_new_height(oldwin, oldwin->w_height - 1);
oldwin->w_status_height = need_status;
}
if (flags & (WSP_TOP | WSP_BOT))
{
/* set height and row of new window to full height */
wp->w_winrow = tabline_height();
win_new_height(wp, curfrp->fr_height - (p_ls > 0));
wp->w_status_height = (p_ls > 0);
}
else
{
/* height and row of new window is same as current window */
wp->w_winrow = oldwin->w_winrow;
win_new_height(wp, oldwin->w_height);
wp->w_status_height = oldwin->w_status_height;
}
frp->fr_height = curfrp->fr_height;
/* "new_size" of the current window goes to the new window, use
* one column for the vertical separator */
win_new_width(wp, new_size);
if (before)
wp->w_vsep_width = 1;
else
{
wp->w_vsep_width = oldwin->w_vsep_width;
oldwin->w_vsep_width = 1;
}
if (flags & (WSP_TOP | WSP_BOT))
{
if (flags & WSP_BOT)
frame_add_vsep(curfrp);
/* Set width of neighbor frame */
frame_new_width(curfrp, curfrp->fr_width
- (new_size + ((flags & WSP_TOP) != 0)), flags & WSP_TOP,
FALSE);
}
else
win_new_width(oldwin, oldwin->w_width - (new_size + 1));
if (before) /* new window left of current one */
{
wp->w_wincol = oldwin->w_wincol;
oldwin->w_wincol += new_size + 1;
}
else /* new window right of current one */
wp->w_wincol = oldwin->w_wincol + oldwin->w_width + 1;
frame_fix_width(oldwin);
frame_fix_width(wp);
}
else
#endif
{
/* width and column of new window is same as current window */
#ifdef FEAT_VERTSPLIT
if (flags & (WSP_TOP | WSP_BOT))
{
wp->w_wincol = 0;
win_new_width(wp, Columns);
wp->w_vsep_width = 0;
}
else
{
wp->w_wincol = oldwin->w_wincol;
win_new_width(wp, oldwin->w_width);
wp->w_vsep_width = oldwin->w_vsep_width;
}
frp->fr_width = curfrp->fr_width;
#endif
/* "new_size" of the current window goes to the new window, use
* one row for the status line */
win_new_height(wp, new_size);
if (flags & (WSP_TOP | WSP_BOT))
frame_new_height(curfrp, curfrp->fr_height
- (new_size + STATUS_HEIGHT), flags & WSP_TOP, FALSE);
else
win_new_height(oldwin, oldwin_height - (new_size + STATUS_HEIGHT));
if (before) /* new window above current one */
{
wp->w_winrow = oldwin->w_winrow;
wp->w_status_height = STATUS_HEIGHT;
oldwin->w_winrow += wp->w_height + STATUS_HEIGHT;
}
else /* new window below current one */
{
wp->w_winrow = oldwin->w_winrow + oldwin->w_height + STATUS_HEIGHT;
wp->w_status_height = oldwin->w_status_height;
oldwin->w_status_height = STATUS_HEIGHT;
}
#ifdef FEAT_VERTSPLIT
if (flags & WSP_BOT)
frame_add_statusline(curfrp);
#endif
frame_fix_height(wp);
frame_fix_height(oldwin);
}
if (flags & (WSP_TOP | WSP_BOT))
(void)win_comp_pos();
/*
* Both windows need redrawing
*/
redraw_win_later(wp, NOT_VALID);
wp->w_redr_status = TRUE;
redraw_win_later(oldwin, NOT_VALID);
oldwin->w_redr_status = TRUE;
if (need_status)
{
msg_row = Rows - 1;
msg_col = sc_col;
msg_clr_eos_force(); /* Old command/ruler may still be there */
comp_col();
msg_row = Rows - 1;
msg_col = 0; /* put position back at start of line */
}
/*
* equalize the window sizes.
*/
if (do_equal || dir != 0)
win_equal(wp, TRUE,
#ifdef FEAT_VERTSPLIT
(flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h')
: dir == 'h' ? 'b' :
#endif
'v');
/* Don't change the window height/width to 'winheight' / 'winwidth' if a
* size was given. */
#ifdef FEAT_VERTSPLIT
if (flags & WSP_VERT)
{
i = p_wiw;
if (size != 0)
p_wiw = size;
# ifdef FEAT_GUI
/* When 'guioptions' includes 'L' or 'R' may have to add scrollbars. */
if (gui.in_use)
gui_init_which_components(NULL);
# endif
}
else
#endif
{
i = p_wh;
if (size != 0)
p_wh = size;
}
/*
* make the new window the current window
*/
win_enter(wp, FALSE);
#ifdef FEAT_VERTSPLIT
if (flags & WSP_VERT)
p_wiw = i;
else
#endif
p_wh = i;
return OK;
}
/*
* Initialize window "newp" from window "oldp".
* Used when splitting a window and when creating a new tab page.
* The windows will both edit the same buffer.
* WSP_NEWLOC may be specified in flags to prevent the location list from
* being copied.
*/
static void
win_init(newp, oldp, flags)
win_T *newp;
win_T *oldp;
int flags UNUSED;
{
int i;
newp->w_buffer = oldp->w_buffer;
#ifdef FEAT_SYN_HL
newp->w_s = &(oldp->w_buffer->b_s);
#endif
oldp->w_buffer->b_nwindows++;
newp->w_cursor = oldp->w_cursor;
newp->w_valid = 0;
newp->w_curswant = oldp->w_curswant;
newp->w_set_curswant = oldp->w_set_curswant;
newp->w_topline = oldp->w_topline;
#ifdef FEAT_DIFF
newp->w_topfill = oldp->w_topfill;
#endif
newp->w_leftcol = oldp->w_leftcol;
newp->w_pcmark = oldp->w_pcmark;
newp->w_prev_pcmark = oldp->w_prev_pcmark;
newp->w_alt_fnum = oldp->w_alt_fnum;
newp->w_wrow = oldp->w_wrow;
newp->w_fraction = oldp->w_fraction;
newp->w_prev_fraction_row = oldp->w_prev_fraction_row;
#ifdef FEAT_JUMPLIST
copy_jumplist(oldp, newp);
#endif
#ifdef FEAT_QUICKFIX
if (flags & WSP_NEWLOC)
{
/* Don't copy the location list. */
newp->w_llist = NULL;
newp->w_llist_ref = NULL;
}
else
copy_loclist(oldp, newp);
#endif
if (oldp->w_localdir != NULL)
newp->w_localdir = vim_strsave(oldp->w_localdir);
/* copy tagstack and folds */
for (i = 0; i < oldp->w_tagstacklen; i++)
{
newp->w_tagstack[i] = oldp->w_tagstack[i];
if (newp->w_tagstack[i].tagname != NULL)
newp->w_tagstack[i].tagname =
vim_strsave(newp->w_tagstack[i].tagname);
}
newp->w_tagstackidx = oldp->w_tagstackidx;
newp->w_tagstacklen = oldp->w_tagstacklen;
#ifdef FEAT_FOLDING
copyFoldingState(oldp, newp);
#endif
win_init_some(newp, oldp);
#ifdef FEAT_SYN_HL
check_colorcolumn(newp);
#endif
}
/*
* Initialize window "newp" from window"old".
* Only the essential things are copied.
*/
static void
win_init_some(newp, oldp)
win_T *newp;
win_T *oldp;
{
/* Use the same argument list. */
newp->w_alist = oldp->w_alist;
++newp->w_alist->al_refcount;
newp->w_arg_idx = oldp->w_arg_idx;
/* copy options from existing window */
win_copy_options(oldp, newp);
}
#endif /* FEAT_WINDOWS */
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Check if "win" is a pointer to an existing window.
*/
int
win_valid(win)
win_T *win;
{
win_T *wp;
if (win == NULL)
return FALSE;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp == win)
return TRUE;
return FALSE;
}
/*
* Return the number of windows.
*/
int
win_count()
{
win_T *wp;
int count = 0;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
++count;
return count;
}
/*
* Make "count" windows on the screen.
* Return actual number of windows on the screen.
* Must be called when there is just one window, filling the whole screen
* (excluding the command line).
*/
int
make_windows(count, vertical)
int count;
int vertical UNUSED; /* split windows vertically if TRUE */
{
int maxcount;
int todo;
#ifdef FEAT_VERTSPLIT
if (vertical)
{
/* Each windows needs at least 'winminwidth' lines and a separator
* column. */
maxcount = (curwin->w_width + curwin->w_vsep_width
- (p_wiw - p_wmw)) / (p_wmw + 1);
}
else
#endif
{
/* Each window needs at least 'winminheight' lines and a status line. */
maxcount = (curwin->w_height + curwin->w_status_height
- (p_wh - p_wmh)) / (p_wmh + STATUS_HEIGHT);
}
if (maxcount < 2)
maxcount = 2;
if (count > maxcount)
count = maxcount;
/*
* add status line now, otherwise first window will be too big
*/
if (count > 1)
last_status(TRUE);
#ifdef FEAT_AUTOCMD
/*
* Don't execute autocommands while creating the windows. Must do that
* when putting the buffers in the windows.
*/
block_autocmds();
#endif
/* todo is number of windows left to create */
for (todo = count - 1; todo > 0; --todo)
#ifdef FEAT_VERTSPLIT
if (vertical)
{
if (win_split(curwin->w_width - (curwin->w_width - todo)
/ (todo + 1) - 1, WSP_VERT | WSP_ABOVE) == FAIL)
break;
}
else
#endif
{
if (win_split(curwin->w_height - (curwin->w_height - todo
* STATUS_HEIGHT) / (todo + 1)
- STATUS_HEIGHT, WSP_ABOVE) == FAIL)
break;
}
#ifdef FEAT_AUTOCMD
unblock_autocmds();
#endif
/* return actual number of windows */
return (count - todo);
}
/*
* Exchange current and next window
*/
static void
win_exchange(Prenum)
long Prenum;
{
frame_T *frp;
frame_T *frp2;
win_T *wp;
win_T *wp2;
int temp;
if (lastwin == firstwin) /* just one window */
{
beep_flush();
return;
}
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
/*
* find window to exchange with
*/
if (Prenum)
{
frp = curwin->w_frame->fr_parent->fr_child;
while (frp != NULL && --Prenum > 0)
frp = frp->fr_next;
}
else if (curwin->w_frame->fr_next != NULL) /* Swap with next */
frp = curwin->w_frame->fr_next;
else /* Swap last window in row/col with previous */
frp = curwin->w_frame->fr_prev;
/* We can only exchange a window with another window, not with a frame
* containing windows. */
if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin)
return;
wp = frp->fr_win;
/*
* 1. remove curwin from the list. Remember after which window it was in wp2
* 2. insert curwin before wp in the list
* if wp != wp2
* 3. remove wp from the list
* 4. insert wp after wp2
* 5. exchange the status line height and vsep width.
*/
wp2 = curwin->w_prev;
frp2 = curwin->w_frame->fr_prev;
if (wp->w_prev != curwin)
{
win_remove(curwin, NULL);
frame_remove(curwin->w_frame);
win_append(wp->w_prev, curwin);
frame_insert(frp, curwin->w_frame);
}
if (wp != wp2)
{
win_remove(wp, NULL);
frame_remove(wp->w_frame);
win_append(wp2, wp);
if (frp2 == NULL)
frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame);
else
frame_append(frp2, wp->w_frame);
}
temp = curwin->w_status_height;
curwin->w_status_height = wp->w_status_height;
wp->w_status_height = temp;
#ifdef FEAT_VERTSPLIT
temp = curwin->w_vsep_width;
curwin->w_vsep_width = wp->w_vsep_width;
wp->w_vsep_width = temp;
/* If the windows are not in the same frame, exchange the sizes to avoid
* messing up the window layout. Otherwise fix the frame sizes. */
if (curwin->w_frame->fr_parent != wp->w_frame->fr_parent)
{
temp = curwin->w_height;
curwin->w_height = wp->w_height;
wp->w_height = temp;
temp = curwin->w_width;
curwin->w_width = wp->w_width;
wp->w_width = temp;
}
else
{
frame_fix_height(curwin);
frame_fix_height(wp);
frame_fix_width(curwin);
frame_fix_width(wp);
}
#endif
(void)win_comp_pos(); /* recompute window positions */
win_enter(wp, TRUE);
redraw_later(CLEAR);
}
/*
* rotate windows: if upwards TRUE the second window becomes the first one
* if upwards FALSE the first window becomes the second one
*/
static void
win_rotate(upwards, count)
int upwards;
int count;
{
win_T *wp1;
win_T *wp2;
frame_T *frp;
int n;
if (firstwin == lastwin) /* nothing to do */
{
beep_flush();
return;
}
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
#ifdef FEAT_VERTSPLIT
/* Check if all frames in this row/col have one window. */
for (frp = curwin->w_frame->fr_parent->fr_child; frp != NULL;
frp = frp->fr_next)
if (frp->fr_win == NULL)
{
EMSG(_("E443: Cannot rotate when another window is split"));
return;
}
#endif
while (count--)
{
if (upwards) /* first window becomes last window */
{
/* remove first window/frame from the list */
frp = curwin->w_frame->fr_parent->fr_child;
wp1 = frp->fr_win;
win_remove(wp1, NULL);
frame_remove(frp);
/* find last frame and append removed window/frame after it */
for ( ; frp->fr_next != NULL; frp = frp->fr_next)
;
win_append(frp->fr_win, wp1);
frame_append(frp, wp1->w_frame);
wp2 = frp->fr_win; /* previously last window */
}
else /* last window becomes first window */
{
/* find last window/frame in the list and remove it */
for (frp = curwin->w_frame; frp->fr_next != NULL;
frp = frp->fr_next)
;
wp1 = frp->fr_win;
wp2 = wp1->w_prev; /* will become last window */
win_remove(wp1, NULL);
frame_remove(frp);
/* append the removed window/frame before the first in the list */
win_append(frp->fr_parent->fr_child->fr_win->w_prev, wp1);
frame_insert(frp->fr_parent->fr_child, frp);
}
/* exchange status height and vsep width of old and new last window */
n = wp2->w_status_height;
wp2->w_status_height = wp1->w_status_height;
wp1->w_status_height = n;
frame_fix_height(wp1);
frame_fix_height(wp2);
#ifdef FEAT_VERTSPLIT
n = wp2->w_vsep_width;
wp2->w_vsep_width = wp1->w_vsep_width;
wp1->w_vsep_width = n;
frame_fix_width(wp1);
frame_fix_width(wp2);
#endif
/* recompute w_winrow and w_wincol for all windows */
(void)win_comp_pos();
}
redraw_later(CLEAR);
}
/*
* Move the current window to the very top/bottom/left/right of the screen.
*/
static void
win_totop(size, flags)
int size;
int flags;
{
int dir;
int height = curwin->w_height;
if (lastwin == firstwin)
{
beep_flush();
return;
}
/* Remove the window and frame from the tree of frames. */
(void)winframe_remove(curwin, &dir, NULL);
win_remove(curwin, NULL);
last_status(FALSE); /* may need to remove last status line */
(void)win_comp_pos(); /* recompute window positions */
/* Split a window on the desired side and put the window there. */
(void)win_split_ins(size, flags, curwin, dir);
if (!(flags & WSP_VERT))
{
win_setheight(height);
if (p_ea)
win_equal(curwin, TRUE, 'v');
}
#if defined(FEAT_GUI) && defined(FEAT_VERTSPLIT)
/* When 'guioptions' includes 'L' or 'R' may have to remove or add
* scrollbars. Have to update them anyway. */
gui_may_update_scrollbars();
#endif
}
/*
* Move window "win1" to below/right of "win2" and make "win1" the current
* window. Only works within the same frame!
*/
void
win_move_after(win1, win2)
win_T *win1, *win2;
{
int height;
/* check if the arguments are reasonable */
if (win1 == win2)
return;
/* check if there is something to do */
if (win2->w_next != win1)
{
/* may need move the status line/vertical separator of the last window
* */
if (win1 == lastwin)
{
height = win1->w_prev->w_status_height;
win1->w_prev->w_status_height = win1->w_status_height;
win1->w_status_height = height;
#ifdef FEAT_VERTSPLIT
if (win1->w_prev->w_vsep_width == 1)
{
/* Remove the vertical separator from the last-but-one window,
* add it to the last window. Adjust the frame widths. */
win1->w_prev->w_vsep_width = 0;
win1->w_prev->w_frame->fr_width -= 1;
win1->w_vsep_width = 1;
win1->w_frame->fr_width += 1;
}
#endif
}
else if (win2 == lastwin)
{
height = win1->w_status_height;
win1->w_status_height = win2->w_status_height;
win2->w_status_height = height;
#ifdef FEAT_VERTSPLIT
if (win1->w_vsep_width == 1)
{
/* Remove the vertical separator from win1, add it to the last
* window, win2. Adjust the frame widths. */
win2->w_vsep_width = 1;
win2->w_frame->fr_width += 1;
win1->w_vsep_width = 0;
win1->w_frame->fr_width -= 1;
}
#endif
}
win_remove(win1, NULL);
frame_remove(win1->w_frame);
win_append(win2, win1);
frame_append(win2->w_frame, win1->w_frame);
(void)win_comp_pos(); /* recompute w_winrow for all windows */
redraw_later(NOT_VALID);
}
win_enter(win1, FALSE);
}
/*
* Make all windows the same height.
* 'next_curwin' will soon be the current window, make sure it has enough
* rows.
*/
void
win_equal(next_curwin, current, dir)
win_T *next_curwin; /* pointer to current window to be or NULL */
int current; /* do only frame with current window */
int dir; /* 'v' for vertically, 'h' for horizontally,
'b' for both, 0 for using p_ead */
{
if (dir == 0)
#ifdef FEAT_VERTSPLIT
dir = *p_ead;
#else
dir = 'b';
#endif
win_equal_rec(next_curwin == NULL ? curwin : next_curwin, current,
topframe, dir, 0, tabline_height(),
(int)Columns, topframe->fr_height);
}
/*
* Set a frame to a new position and height, spreading the available room
* equally over contained frames.
* The window "next_curwin" (if not NULL) should at least get the size from
* 'winheight' and 'winwidth' if possible.
*/
static void
win_equal_rec(next_curwin, current, topfr, dir, col, row, width, height)
win_T *next_curwin; /* pointer to current window to be or NULL */
int current; /* do only frame with current window */
frame_T *topfr; /* frame to set size off */
int dir; /* 'v', 'h' or 'b', see win_equal() */
int col; /* horizontal position for frame */
int row; /* vertical position for frame */
int width; /* new width of frame */
int height; /* new height of frame */
{
int n, m;
int extra_sep = 0;
int wincount, totwincount = 0;
frame_T *fr;
int next_curwin_size = 0;
int room = 0;
int new_size;
int has_next_curwin = 0;
int hnc;
if (topfr->fr_layout == FR_LEAF)
{
/* Set the width/height of this frame.
* Redraw when size or position changes */
if (topfr->fr_height != height || topfr->fr_win->w_winrow != row
#ifdef FEAT_VERTSPLIT
|| topfr->fr_width != width || topfr->fr_win->w_wincol != col
#endif
)
{
topfr->fr_win->w_winrow = row;
frame_new_height(topfr, height, FALSE, FALSE);
#ifdef FEAT_VERTSPLIT
topfr->fr_win->w_wincol = col;
frame_new_width(topfr, width, FALSE, FALSE);
#endif
redraw_all_later(CLEAR);
}
}
#ifdef FEAT_VERTSPLIT
else if (topfr->fr_layout == FR_ROW)
{
topfr->fr_width = width;
topfr->fr_height = height;
if (dir != 'v') /* equalize frame widths */
{
/* Compute the maximum number of windows horizontally in this
* frame. */
n = frame_minwidth(topfr, NOWIN);
/* add one for the rightmost window, it doesn't have a separator */
if (col + width == Columns)
extra_sep = 1;
else
extra_sep = 0;
totwincount = (n + extra_sep) / (p_wmw + 1);
has_next_curwin = frame_has_win(topfr, next_curwin);
/*
* Compute width for "next_curwin" window and room available for
* other windows.
* "m" is the minimal width when counting p_wiw for "next_curwin".
*/
m = frame_minwidth(topfr, next_curwin);
room = width - m;
if (room < 0)
{
next_curwin_size = p_wiw + room;
room = 0;
}
else
{
next_curwin_size = -1;
for (fr = topfr->fr_child; fr != NULL; fr = fr->fr_next)
{
/* If 'winfixwidth' set keep the window width if
* possible.
* Watch out for this window being the next_curwin. */
if (frame_fixed_width(fr))
{
n = frame_minwidth(fr, NOWIN);
new_size = fr->fr_width;
if (frame_has_win(fr, next_curwin))
{
room += p_wiw - p_wmw;
next_curwin_size = 0;
if (new_size < p_wiw)
new_size = p_wiw;
}
else
/* These windows don't use up room. */
totwincount -= (n + (fr->fr_next == NULL
? extra_sep : 0)) / (p_wmw + 1);
room -= new_size - n;
if (room < 0)
{
new_size += room;
room = 0;
}
fr->fr_newwidth = new_size;
}
}
if (next_curwin_size == -1)
{
if (!has_next_curwin)
next_curwin_size = 0;
else if (totwincount > 1
&& (room + (totwincount - 2))
/ (totwincount - 1) > p_wiw)
{
/* Can make all windows wider than 'winwidth', spread
* the room equally. */
next_curwin_size = (room + p_wiw
+ (totwincount - 1) * p_wmw
+ (totwincount - 1)) / totwincount;
room -= next_curwin_size - p_wiw;
}
else
next_curwin_size = p_wiw;
}
}
if (has_next_curwin)
--totwincount; /* don't count curwin */
}
for (fr = topfr->fr_child; fr != NULL; fr = fr->fr_next)
{
n = m = 0;
wincount = 1;
if (fr->fr_next == NULL)
/* last frame gets all that remains (avoid roundoff error) */
new_size = width;
else if (dir == 'v')
new_size = fr->fr_width;
else if (frame_fixed_width(fr))
{
new_size = fr->fr_newwidth;
wincount = 0; /* doesn't count as a sizeable window */
}
else
{
/* Compute the maximum number of windows horiz. in "fr". */
n = frame_minwidth(fr, NOWIN);
wincount = (n + (fr->fr_next == NULL ? extra_sep : 0))
/ (p_wmw + 1);
m = frame_minwidth(fr, next_curwin);
if (has_next_curwin)
hnc = frame_has_win(fr, next_curwin);
else
hnc = FALSE;
if (hnc) /* don't count next_curwin */
--wincount;
if (totwincount == 0)
new_size = room;
else
new_size = (wincount * room + ((unsigned)totwincount >> 1))
/ totwincount;
if (hnc) /* add next_curwin size */
{
next_curwin_size -= p_wiw - (m - n);
new_size += next_curwin_size;
room -= new_size - next_curwin_size;
}
else
room -= new_size;
new_size += n;
}
/* Skip frame that is full width when splitting or closing a
* window, unless equalizing all frames. */
if (!current || dir != 'v' || topfr->fr_parent != NULL
|| (new_size != fr->fr_width)
|| frame_has_win(fr, next_curwin))
win_equal_rec(next_curwin, current, fr, dir, col, row,
new_size, height);
col += new_size;
width -= new_size;
totwincount -= wincount;
}
}
#endif
else /* topfr->fr_layout == FR_COL */
{
#ifdef FEAT_VERTSPLIT
topfr->fr_width = width;
#endif
topfr->fr_height = height;
if (dir != 'h') /* equalize frame heights */
{
/* Compute maximum number of windows vertically in this frame. */
n = frame_minheight(topfr, NOWIN);
/* add one for the bottom window if it doesn't have a statusline */
if (row + height == cmdline_row && p_ls == 0)
extra_sep = 1;
else
extra_sep = 0;
totwincount = (n + extra_sep) / (p_wmh + 1);
has_next_curwin = frame_has_win(topfr, next_curwin);
/*
* Compute height for "next_curwin" window and room available for
* other windows.
* "m" is the minimal height when counting p_wh for "next_curwin".
*/
m = frame_minheight(topfr, next_curwin);
room = height - m;
if (room < 0)
{
/* The room is less then 'winheight', use all space for the
* current window. */
next_curwin_size = p_wh + room;
room = 0;
}
else
{
next_curwin_size = -1;
for (fr = topfr->fr_child; fr != NULL; fr = fr->fr_next)
{
/* If 'winfixheight' set keep the window height if
* possible.
* Watch out for this window being the next_curwin. */
if (frame_fixed_height(fr))
{
n = frame_minheight(fr, NOWIN);
new_size = fr->fr_height;
if (frame_has_win(fr, next_curwin))
{
room += p_wh - p_wmh;
next_curwin_size = 0;
if (new_size < p_wh)
new_size = p_wh;
}
else
/* These windows don't use up room. */
totwincount -= (n + (fr->fr_next == NULL
? extra_sep : 0)) / (p_wmh + 1);
room -= new_size - n;
if (room < 0)
{
new_size += room;
room = 0;
}
fr->fr_newheight = new_size;
}
}
if (next_curwin_size == -1)
{
if (!has_next_curwin)
next_curwin_size = 0;
else if (totwincount > 1
&& (room + (totwincount - 2))
/ (totwincount - 1) > p_wh)
{
/* can make all windows higher than 'winheight',
* spread the room equally. */
next_curwin_size = (room + p_wh
+ (totwincount - 1) * p_wmh
+ (totwincount - 1)) / totwincount;
room -= next_curwin_size - p_wh;
}
else
next_curwin_size = p_wh;
}
}
if (has_next_curwin)
--totwincount; /* don't count curwin */
}
for (fr = topfr->fr_child; fr != NULL; fr = fr->fr_next)
{
n = m = 0;
wincount = 1;
if (fr->fr_next == NULL)
/* last frame gets all that remains (avoid roundoff error) */
new_size = height;
else if (dir == 'h')
new_size = fr->fr_height;
else if (frame_fixed_height(fr))
{
new_size = fr->fr_newheight;
wincount = 0; /* doesn't count as a sizeable window */
}
else
{
/* Compute the maximum number of windows vert. in "fr". */
n = frame_minheight(fr, NOWIN);
wincount = (n + (fr->fr_next == NULL ? extra_sep : 0))
/ (p_wmh + 1);
m = frame_minheight(fr, next_curwin);
if (has_next_curwin)
hnc = frame_has_win(fr, next_curwin);
else
hnc = FALSE;
if (hnc) /* don't count next_curwin */
--wincount;
if (totwincount == 0)
new_size = room;
else
new_size = (wincount * room + ((unsigned)totwincount >> 1))
/ totwincount;
if (hnc) /* add next_curwin size */
{
next_curwin_size -= p_wh - (m - n);
new_size += next_curwin_size;
room -= new_size - next_curwin_size;
}
else
room -= new_size;
new_size += n;
}
/* Skip frame that is full width when splitting or closing a
* window, unless equalizing all frames. */
if (!current || dir != 'h' || topfr->fr_parent != NULL
|| (new_size != fr->fr_height)
|| frame_has_win(fr, next_curwin))
win_equal_rec(next_curwin, current, fr, dir, col, row,
width, new_size);
row += new_size;
height -= new_size;
totwincount -= wincount;
}
}
}
/*
* close all windows for buffer 'buf'
*/
void
close_windows(buf, keep_curwin)
buf_T *buf;
int keep_curwin; /* don't close "curwin" */
{
win_T *wp;
tabpage_T *tp, *nexttp;
int h = tabline_height();
++RedrawingDisabled;
for (wp = firstwin; wp != NULL && lastwin != firstwin; )
{
if (wp->w_buffer == buf && (!keep_curwin || wp != curwin)
#ifdef FEAT_AUTOCMD
&& !(wp->w_closing || wp->w_buffer->b_closing)
#endif
)
{
win_close(wp, FALSE);
/* Start all over, autocommands may change the window layout. */
wp = firstwin;
}
else
wp = wp->w_next;
}
/* Also check windows in other tab pages. */
for (tp = first_tabpage; tp != NULL; tp = nexttp)
{
nexttp = tp->tp_next;
if (tp != curtab)
for (wp = tp->tp_firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_buffer == buf
#ifdef FEAT_AUTOCMD
&& !(wp->w_closing || wp->w_buffer->b_closing)
#endif
)
{
win_close_othertab(wp, FALSE, tp);
/* Start all over, the tab page may be closed and
* autocommands may change the window layout. */
nexttp = first_tabpage;
break;
}
}
--RedrawingDisabled;
if (h != tabline_height())
shell_new_rows();
}
/*
* Return TRUE if the current window is the only window that exists (ignoring
* "aucmd_win").
* Returns FALSE if there is a window, possibly in another tab page.
*/
static int
last_window()
{
return (one_window() && first_tabpage->tp_next == NULL);
}
/*
* Return TRUE if there is only one window other than "aucmd_win" in the
* current tab page.
*/
int
one_window()
{
#ifdef FEAT_AUTOCMD
win_T *wp;
int seen_one = FALSE;
FOR_ALL_WINDOWS(wp)
{
if (wp != aucmd_win)
{
if (seen_one)
return FALSE;
seen_one = TRUE;
}
}
return TRUE;
#else
return firstwin == lastwin;
#endif
}
/*
* Close the possibly last window in a tab page.
* Returns TRUE when the window was closed already.
*/
static int
close_last_window_tabpage(win, free_buf, prev_curtab)
win_T *win;
int free_buf;
tabpage_T *prev_curtab;
{
if (firstwin == lastwin)
{
/*
* Closing the last window in a tab page. First go to another tab
* page and then close the window and the tab page. This avoids that
* curwin and curtab are invalid while we are freeing memory, they may
* be used in GUI events.
* Don't trigger autocommands yet, they may use wrong values, so do
* that below.
*/
goto_tabpage_tp(alt_tabpage(), FALSE);
redraw_tabline = TRUE;
/* Safety check: Autocommands may have closed the window when jumping
* to the other tab page. */
if (valid_tabpage(prev_curtab) && prev_curtab->tp_firstwin == win)
{
int h = tabline_height();
win_close_othertab(win, free_buf, prev_curtab);
if (h != tabline_height())
shell_new_rows();
}
/* Since goto_tabpage_tp above did not trigger *Enter autocommands, do
* that now. */
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
#endif
return TRUE;
}
return FALSE;
}
/*
* Close window "win". Only works for the current tab page.
* If "free_buf" is TRUE related buffer may be unloaded.
*
* Called by :quit, :close, :xit, :wq and findtag().
*/
void
win_close(win, free_buf)
win_T *win;
int free_buf;
{
win_T *wp;
#ifdef FEAT_AUTOCMD
int other_buffer = FALSE;
#endif
int close_curwin = FALSE;
int dir;
int help_window = FALSE;
tabpage_T *prev_curtab = curtab;
if (last_window())
{
EMSG(_("E444: Cannot close last window"));
return;
}
#ifdef FEAT_AUTOCMD
if (win->w_closing || win->w_buffer->b_closing)
return; /* window is already being closed */
if (win == aucmd_win)
{
EMSG(_("E813: Cannot close autocmd window"));
return;
}
if ((firstwin == aucmd_win || lastwin == aucmd_win) && one_window())
{
EMSG(_("E814: Cannot close window, only autocmd window would remain"));
return;
}
#endif
/* When closing the last window in a tab page first go to another tab page
* and then close the window and the tab page to avoid that curwin and
* curtab are invalid while we are freeing memory. */
if (close_last_window_tabpage(win, free_buf, prev_curtab))
return;
/* When closing the help window, try restoring a snapshot after closing
* the window. Otherwise clear the snapshot, it's now invalid. */
if (win->w_buffer != NULL && win->w_buffer->b_help)
help_window = TRUE;
else
clear_snapshot(curtab, SNAP_HELP_IDX);
#ifdef FEAT_AUTOCMD
if (win == curwin)
{
/*
* Guess which window is going to be the new current window.
* This may change because of the autocommands (sigh).
*/
wp = frame2win(win_altframe(win, NULL));
/*
* Be careful: If autocommands delete the window or cause this window
* to be the last one left, return now.
*/
if (wp->w_buffer != curbuf)
{
other_buffer = TRUE;
win->w_closing = TRUE;
apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
if (!win_valid(win))
return;
win->w_closing = FALSE;
if (last_window())
return;
}
win->w_closing = TRUE;
apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
if (!win_valid(win))
return;
win->w_closing = FALSE;
if (last_window())
return;
# ifdef FEAT_EVAL
/* autocmds may abort script processing */
if (aborting())
return;
# endif
}
#endif
#ifdef FEAT_GUI
/* Avoid trouble with scrollbars that are going to be deleted in
* win_free(). */
if (gui.in_use)
out_flush();
#endif
#ifdef FEAT_SYN_HL
/* Free independent synblock before the buffer is freed. */
if (win->w_buffer != NULL)
reset_synblock(win);
#endif
/*
* Close the link to the buffer.
*/
if (win->w_buffer != NULL)
{
#ifdef FEAT_AUTOCMD
win->w_closing = TRUE;
#endif
close_buffer(win, win->w_buffer, free_buf ? DOBUF_UNLOAD : 0, FALSE);
#ifdef FEAT_AUTOCMD
if (win_valid(win))
win->w_closing = FALSE;
#endif
}
/* Autocommands may have closed the window already, or closed the only
* other window or moved to another tab page. */
if (!win_valid(win) || last_window() || curtab != prev_curtab
|| close_last_window_tabpage(win, free_buf, prev_curtab))
return;
/* Free the memory used for the window and get the window that received
* the screen space. */
wp = win_free_mem(win, &dir, NULL);
/* Make sure curwin isn't invalid. It can cause severe trouble when
* printing an error message. For win_equal() curbuf needs to be valid
* too. */
if (win == curwin)
{
curwin = wp;
#ifdef FEAT_QUICKFIX
if (wp->w_p_pvw || bt_quickfix(wp->w_buffer))
{
/*
* If the cursor goes to the preview or the quickfix window, try
* finding another window to go to.
*/
for (;;)
{
if (wp->w_next == NULL)
wp = firstwin;
else
wp = wp->w_next;
if (wp == curwin)
break;
if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer))
{
curwin = wp;
break;
}
}
}
#endif
curbuf = curwin->w_buffer;
close_curwin = TRUE;
}
if (p_ea
#ifdef FEAT_VERTSPLIT
&& (*p_ead == 'b' || *p_ead == dir)
#endif
)
win_equal(curwin, TRUE,
#ifdef FEAT_VERTSPLIT
dir
#else
0
#endif
);
else
win_comp_pos();
if (close_curwin)
{
win_enter_ext(wp, FALSE, TRUE);
#ifdef FEAT_AUTOCMD
if (other_buffer)
/* careful: after this wp and win may be invalid! */
apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
#endif
}
/*
* If last window has a status line now and we don't want one,
* remove the status line.
*/
last_status(FALSE);
/* After closing the help window, try restoring the window layout from
* before it was opened. */
if (help_window)
restore_snapshot(SNAP_HELP_IDX, close_curwin);
#if defined(FEAT_GUI) && defined(FEAT_VERTSPLIT)
/* When 'guioptions' includes 'L' or 'R' may have to remove scrollbars. */
if (gui.in_use && !win_hasvertsplit())
gui_init_which_components(NULL);
#endif
redraw_all_later(NOT_VALID);
}
/*
* Close window "win" in tab page "tp", which is not the current tab page.
* This may be the last window in that tab page and result in closing the tab,
* thus "tp" may become invalid!
* Caller must check if buffer is hidden and whether the tabline needs to be
* updated.
*/
void
win_close_othertab(win, free_buf, tp)
win_T *win;
int free_buf;
tabpage_T *tp;
{
win_T *wp;
int dir;
tabpage_T *ptp = NULL;
int free_tp = FALSE;
#ifdef FEAT_AUTOCMD
if (win->w_closing || win->w_buffer->b_closing)
return; /* window is already being closed */
#endif
/* Close the link to the buffer. */
close_buffer(win, win->w_buffer, free_buf ? DOBUF_UNLOAD : 0, FALSE);
/* Careful: Autocommands may have closed the tab page or made it the
* current tab page. */
for (ptp = first_tabpage; ptp != NULL && ptp != tp; ptp = ptp->tp_next)
;
if (ptp == NULL || tp == curtab)
return;
/* Autocommands may have closed the window already. */
for (wp = tp->tp_firstwin; wp != NULL && wp != win; wp = wp->w_next)
;
if (wp == NULL)
return;
/* When closing the last window in a tab page remove the tab page. */
if (tp == NULL ? firstwin == lastwin : tp->tp_firstwin == tp->tp_lastwin)
{
if (tp == first_tabpage)
first_tabpage = tp->tp_next;
else
{
for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tp;
ptp = ptp->tp_next)
;
if (ptp == NULL)
{
EMSG2(_(e_intern2), "win_close_othertab()");
return;
}
ptp->tp_next = tp->tp_next;
}
free_tp = TRUE;
}
/* Free the memory used for the window. */
win_free_mem(win, &dir, tp);
if (free_tp)
free_tabpage(tp);
}
/*
* Free the memory used for a window.
* Returns a pointer to the window that got the freed up space.
*/
static win_T *
win_free_mem(win, dirp, tp)
win_T *win;
int *dirp; /* set to 'v' or 'h' for direction if 'ea' */
tabpage_T *tp; /* tab page "win" is in, NULL for current */
{
frame_T *frp;
win_T *wp;
/* Remove the window and its frame from the tree of frames. */
frp = win->w_frame;
wp = winframe_remove(win, dirp, tp);
vim_free(frp);
win_free(win, tp);
/* When deleting the current window of another tab page select a new
* current window. */
if (tp != NULL && win == tp->tp_curwin)
tp->tp_curwin = wp;
return wp;
}
#if defined(EXITFREE) || defined(PROTO)
void
win_free_all()
{
int dummy;
# ifdef FEAT_WINDOWS
while (first_tabpage->tp_next != NULL)
tabpage_close(TRUE);
# endif
# ifdef FEAT_AUTOCMD
if (aucmd_win != NULL)
{
(void)win_free_mem(aucmd_win, &dummy, NULL);
aucmd_win = NULL;
}
# endif
while (firstwin != NULL)
(void)win_free_mem(firstwin, &dummy, NULL);
}
#endif
/*
* Remove a window and its frame from the tree of frames.
* Returns a pointer to the window that got the freed up space.
*/
win_T *
winframe_remove(win, dirp, tp)
win_T *win;
int *dirp UNUSED; /* set to 'v' or 'h' for direction if 'ea' */
tabpage_T *tp; /* tab page "win" is in, NULL for current */
{
frame_T *frp, *frp2, *frp3;
frame_T *frp_close = win->w_frame;
win_T *wp;
/*
* If there is only one window there is nothing to remove.
*/
if (tp == NULL ? firstwin == lastwin : tp->tp_firstwin == tp->tp_lastwin)
return NULL;
/*
* Remove the window from its frame.
*/
frp2 = win_altframe(win, tp);
wp = frame2win(frp2);
/* Remove this frame from the list of frames. */
frame_remove(frp_close);
#ifdef FEAT_VERTSPLIT
if (frp_close->fr_parent->fr_layout == FR_COL)
{
#endif
/* When 'winfixheight' is set, try to find another frame in the column
* (as close to the closed frame as possible) to distribute the height
* to. */
if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfh)
{
frp = frp_close->fr_prev;
frp3 = frp_close->fr_next;
while (frp != NULL || frp3 != NULL)
{
if (frp != NULL)
{
if (frp->fr_win != NULL && !frp->fr_win->w_p_wfh)
{
frp2 = frp;
wp = frp->fr_win;
break;
}
frp = frp->fr_prev;
}
if (frp3 != NULL)
{
if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfh)
{
frp2 = frp3;
wp = frp3->fr_win;
break;
}
frp3 = frp3->fr_next;
}
}
}
frame_new_height(frp2, frp2->fr_height + frp_close->fr_height,
frp2 == frp_close->fr_next ? TRUE : FALSE, FALSE);
#ifdef FEAT_VERTSPLIT
*dirp = 'v';
}
else
{
/* When 'winfixwidth' is set, try to find another frame in the column
* (as close to the closed frame as possible) to distribute the width
* to. */
if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfw)
{
frp = frp_close->fr_prev;
frp3 = frp_close->fr_next;
while (frp != NULL || frp3 != NULL)
{
if (frp != NULL)
{
if (frp->fr_win != NULL && !frp->fr_win->w_p_wfw)
{
frp2 = frp;
wp = frp->fr_win;
break;
}
frp = frp->fr_prev;
}
if (frp3 != NULL)
{
if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfw)
{
frp2 = frp3;
wp = frp3->fr_win;
break;
}
frp3 = frp3->fr_next;
}
}
}
frame_new_width(frp2, frp2->fr_width + frp_close->fr_width,
frp2 == frp_close->fr_next ? TRUE : FALSE, FALSE);
*dirp = 'h';
}
#endif
/* If rows/columns go to a window below/right its positions need to be
* updated. Can only be done after the sizes have been updated. */
if (frp2 == frp_close->fr_next)
{
int row = win->w_winrow;
int col = W_WINCOL(win);
frame_comp_pos(frp2, &row, &col);
}
if (frp2->fr_next == NULL && frp2->fr_prev == NULL)
{
/* There is no other frame in this list, move its info to the parent
* and remove it. */
frp2->fr_parent->fr_layout = frp2->fr_layout;
frp2->fr_parent->fr_child = frp2->fr_child;
for (frp = frp2->fr_child; frp != NULL; frp = frp->fr_next)
frp->fr_parent = frp2->fr_parent;
frp2->fr_parent->fr_win = frp2->fr_win;
if (frp2->fr_win != NULL)
frp2->fr_win->w_frame = frp2->fr_parent;
frp = frp2->fr_parent;
vim_free(frp2);
frp2 = frp->fr_parent;
if (frp2 != NULL && frp2->fr_layout == frp->fr_layout)
{
/* The frame above the parent has the same layout, have to merge
* the frames into this list. */
if (frp2->fr_child == frp)
frp2->fr_child = frp->fr_child;
frp->fr_child->fr_prev = frp->fr_prev;
if (frp->fr_prev != NULL)
frp->fr_prev->fr_next = frp->fr_child;
for (frp3 = frp->fr_child; ; frp3 = frp3->fr_next)
{
frp3->fr_parent = frp2;
if (frp3->fr_next == NULL)
{
frp3->fr_next = frp->fr_next;
if (frp->fr_next != NULL)
frp->fr_next->fr_prev = frp3;
break;
}
}
vim_free(frp);
}
}
return wp;
}
/*
* Find out which frame is going to get the freed up space when "win" is
* closed.
* if 'splitbelow'/'splitleft' the space goes to the window above/left.
* if 'nosplitbelow'/'nosplitleft' the space goes to the window below/right.
* This makes opening a window and closing it immediately keep the same window
* layout.
*/
static frame_T *
win_altframe(win, tp)
win_T *win;
tabpage_T *tp; /* tab page "win" is in, NULL for current */
{
frame_T *frp;
int b;
if (tp == NULL ? firstwin == lastwin : tp->tp_firstwin == tp->tp_lastwin)
/* Last window in this tab page, will go to next tab page. */
return alt_tabpage()->tp_curwin->w_frame;
frp = win->w_frame;
#ifdef FEAT_VERTSPLIT
if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_ROW)
b = p_spr;
else
#endif
b = p_sb;
if ((!b && frp->fr_next != NULL) || frp->fr_prev == NULL)
return frp->fr_next;
return frp->fr_prev;
}
/*
* Return the tabpage that will be used if the current one is closed.
*/
static tabpage_T *
alt_tabpage()
{
tabpage_T *tp;
/* Use the next tab page if possible. */
if (curtab->tp_next != NULL)
return curtab->tp_next;
/* Find the last but one tab page. */
for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next)
;
return tp;
}
/*
* Find the left-upper window in frame "frp".
*/
static win_T *
frame2win(frp)
frame_T *frp;
{
while (frp->fr_win == NULL)
frp = frp->fr_child;
return frp->fr_win;
}
/*
* Return TRUE if frame "frp" contains window "wp".
*/
static int
frame_has_win(frp, wp)
frame_T *frp;
win_T *wp;
{
frame_T *p;
if (frp->fr_layout == FR_LEAF)
return frp->fr_win == wp;
for (p = frp->fr_child; p != NULL; p = p->fr_next)
if (frame_has_win(p, wp))
return TRUE;
return FALSE;
}
/*
* Set a new height for a frame. Recursively sets the height for contained
* frames and windows. Caller must take care of positions.
*/
static void
frame_new_height(topfrp, height, topfirst, wfh)
frame_T *topfrp;
int height;
int topfirst; /* resize topmost contained frame first */
int wfh; /* obey 'winfixheight' when there is a choice;
may cause the height not to be set */
{
frame_T *frp;
int extra_lines;
int h;
if (topfrp->fr_win != NULL)
{
/* Simple case: just one window. */
win_new_height(topfrp->fr_win,
height - topfrp->fr_win->w_status_height);
}
#ifdef FEAT_VERTSPLIT
else if (topfrp->fr_layout == FR_ROW)
{
do
{
/* All frames in this row get the same new height. */
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
{
frame_new_height(frp, height, topfirst, wfh);
if (frp->fr_height > height)
{
/* Could not fit the windows, make the whole row higher. */
height = frp->fr_height;
break;
}
}
}
while (frp != NULL);
}
#endif
else /* fr_layout == FR_COL */
{
/* Complicated case: Resize a column of frames. Resize the bottom
* frame first, frames above that when needed. */
frp = topfrp->fr_child;
if (wfh)
/* Advance past frames with one window with 'wfh' set. */
while (frame_fixed_height(frp))
{
frp = frp->fr_next;
if (frp == NULL)
return; /* no frame without 'wfh', give up */
}
if (!topfirst)
{
/* Find the bottom frame of this column */
while (frp->fr_next != NULL)
frp = frp->fr_next;
if (wfh)
/* Advance back for frames with one window with 'wfh' set. */
while (frame_fixed_height(frp))
frp = frp->fr_prev;
}
extra_lines = height - topfrp->fr_height;
if (extra_lines < 0)
{
/* reduce height of contained frames, bottom or top frame first */
while (frp != NULL)
{
h = frame_minheight(frp, NULL);
if (frp->fr_height + extra_lines < h)
{
extra_lines += frp->fr_height - h;
frame_new_height(frp, h, topfirst, wfh);
}
else
{
frame_new_height(frp, frp->fr_height + extra_lines,
topfirst, wfh);
break;
}
if (topfirst)
{
do
frp = frp->fr_next;
while (wfh && frp != NULL && frame_fixed_height(frp));
}
else
{
do
frp = frp->fr_prev;
while (wfh && frp != NULL && frame_fixed_height(frp));
}
/* Increase "height" if we could not reduce enough frames. */
if (frp == NULL)
height -= extra_lines;
}
}
else if (extra_lines > 0)
{
/* increase height of bottom or top frame */
frame_new_height(frp, frp->fr_height + extra_lines, topfirst, wfh);
}
}
topfrp->fr_height = height;
}
/*
* Return TRUE if height of frame "frp" should not be changed because of
* the 'winfixheight' option.
*/
static int
frame_fixed_height(frp)
frame_T *frp;
{
/* frame with one window: fixed height if 'winfixheight' set. */
if (frp->fr_win != NULL)
return frp->fr_win->w_p_wfh;
if (frp->fr_layout == FR_ROW)
{
/* The frame is fixed height if one of the frames in the row is fixed
* height. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
if (frame_fixed_height(frp))
return TRUE;
return FALSE;
}
/* frp->fr_layout == FR_COL: The frame is fixed height if all of the
* frames in the row are fixed height. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
if (!frame_fixed_height(frp))
return FALSE;
return TRUE;
}
#ifdef FEAT_VERTSPLIT
/*
* Return TRUE if width of frame "frp" should not be changed because of
* the 'winfixwidth' option.
*/
static int
frame_fixed_width(frp)
frame_T *frp;
{
/* frame with one window: fixed width if 'winfixwidth' set. */
if (frp->fr_win != NULL)
return frp->fr_win->w_p_wfw;
if (frp->fr_layout == FR_COL)
{
/* The frame is fixed width if one of the frames in the row is fixed
* width. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
if (frame_fixed_width(frp))
return TRUE;
return FALSE;
}
/* frp->fr_layout == FR_ROW: The frame is fixed width if all of the
* frames in the row are fixed width. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
if (!frame_fixed_width(frp))
return FALSE;
return TRUE;
}
/*
* Add a status line to windows at the bottom of "frp".
* Note: Does not check if there is room!
*/
static void
frame_add_statusline(frp)
frame_T *frp;
{
win_T *wp;
if (frp->fr_layout == FR_LEAF)
{
wp = frp->fr_win;
if (wp->w_status_height == 0)
{
if (wp->w_height > 0) /* don't make it negative */
--wp->w_height;
wp->w_status_height = STATUS_HEIGHT;
}
}
else if (frp->fr_layout == FR_ROW)
{
/* Handle all the frames in the row. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
frame_add_statusline(frp);
}
else /* frp->fr_layout == FR_COL */
{
/* Only need to handle the last frame in the column. */
for (frp = frp->fr_child; frp->fr_next != NULL; frp = frp->fr_next)
;
frame_add_statusline(frp);
}
}
/*
* Set width of a frame. Handles recursively going through contained frames.
* May remove separator line for windows at the right side (for win_close()).
*/
static void
frame_new_width(topfrp, width, leftfirst, wfw)
frame_T *topfrp;
int width;
int leftfirst; /* resize leftmost contained frame first */
int wfw; /* obey 'winfixwidth' when there is a choice;
may cause the width not to be set */
{
frame_T *frp;
int extra_cols;
int w;
win_T *wp;
if (topfrp->fr_layout == FR_LEAF)
{
/* Simple case: just one window. */
wp = topfrp->fr_win;
/* Find out if there are any windows right of this one. */
for (frp = topfrp; frp->fr_parent != NULL; frp = frp->fr_parent)
if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_next != NULL)
break;
if (frp->fr_parent == NULL)
wp->w_vsep_width = 0;
win_new_width(wp, width - wp->w_vsep_width);
}
else if (topfrp->fr_layout == FR_COL)
{
do
{
/* All frames in this column get the same new width. */
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
{
frame_new_width(frp, width, leftfirst, wfw);
if (frp->fr_width > width)
{
/* Could not fit the windows, make whole column wider. */
width = frp->fr_width;
break;
}
}
} while (frp != NULL);
}
else /* fr_layout == FR_ROW */
{
/* Complicated case: Resize a row of frames. Resize the rightmost
* frame first, frames left of it when needed. */
frp = topfrp->fr_child;
if (wfw)
/* Advance past frames with one window with 'wfw' set. */
while (frame_fixed_width(frp))
{
frp = frp->fr_next;
if (frp == NULL)
return; /* no frame without 'wfw', give up */
}
if (!leftfirst)
{
/* Find the rightmost frame of this row */
while (frp->fr_next != NULL)
frp = frp->fr_next;
if (wfw)
/* Advance back for frames with one window with 'wfw' set. */
while (frame_fixed_width(frp))
frp = frp->fr_prev;
}
extra_cols = width - topfrp->fr_width;
if (extra_cols < 0)
{
/* reduce frame width, rightmost frame first */
while (frp != NULL)
{
w = frame_minwidth(frp, NULL);
if (frp->fr_width + extra_cols < w)
{
extra_cols += frp->fr_width - w;
frame_new_width(frp, w, leftfirst, wfw);
}
else
{
frame_new_width(frp, frp->fr_width + extra_cols,
leftfirst, wfw);
break;
}
if (leftfirst)
{
do
frp = frp->fr_next;
while (wfw && frp != NULL && frame_fixed_width(frp));
}
else
{
do
frp = frp->fr_prev;
while (wfw && frp != NULL && frame_fixed_width(frp));
}
/* Increase "width" if we could not reduce enough frames. */
if (frp == NULL)
width -= extra_cols;
}
}
else if (extra_cols > 0)
{
/* increase width of rightmost frame */
frame_new_width(frp, frp->fr_width + extra_cols, leftfirst, wfw);
}
}
topfrp->fr_width = width;
}
/*
* Add the vertical separator to windows at the right side of "frp".
* Note: Does not check if there is room!
*/
static void
frame_add_vsep(frp)
frame_T *frp;
{
win_T *wp;
if (frp->fr_layout == FR_LEAF)
{
wp = frp->fr_win;
if (wp->w_vsep_width == 0)
{
if (wp->w_width > 0) /* don't make it negative */
--wp->w_width;
wp->w_vsep_width = 1;
}
}
else if (frp->fr_layout == FR_COL)
{
/* Handle all the frames in the column. */
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
frame_add_vsep(frp);
}
else /* frp->fr_layout == FR_ROW */
{
/* Only need to handle the last frame in the row. */
frp = frp->fr_child;
while (frp->fr_next != NULL)
frp = frp->fr_next;
frame_add_vsep(frp);
}
}
/*
* Set frame width from the window it contains.
*/
static void
frame_fix_width(wp)
win_T *wp;
{
wp->w_frame->fr_width = wp->w_width + wp->w_vsep_width;
}
#endif
/*
* Set frame height from the window it contains.
*/
static void
frame_fix_height(wp)
win_T *wp;
{
wp->w_frame->fr_height = wp->w_height + wp->w_status_height;
}
/*
* Compute the minimal height for frame "topfrp".
* Uses the 'winminheight' option.
* When "next_curwin" isn't NULL, use p_wh for this window.
* When "next_curwin" is NOWIN, don't use at least one line for the current
* window.
*/
static int
frame_minheight(topfrp, next_curwin)
frame_T *topfrp;
win_T *next_curwin;
{
frame_T *frp;
int m;
#ifdef FEAT_VERTSPLIT
int n;
#endif
if (topfrp->fr_win != NULL)
{
if (topfrp->fr_win == next_curwin)
m = p_wh + topfrp->fr_win->w_status_height;
else
{
/* window: minimal height of the window plus status line */
m = p_wmh + topfrp->fr_win->w_status_height;
/* Current window is minimal one line high */
if (p_wmh == 0 && topfrp->fr_win == curwin && next_curwin == NULL)
++m;
}
}
#ifdef FEAT_VERTSPLIT
else if (topfrp->fr_layout == FR_ROW)
{
/* get the minimal height from each frame in this row */
m = 0;
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
{
n = frame_minheight(frp, next_curwin);
if (n > m)
m = n;
}
}
#endif
else
{
/* Add up the minimal heights for all frames in this column. */
m = 0;
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
m += frame_minheight(frp, next_curwin);
}
return m;
}
#ifdef FEAT_VERTSPLIT
/*
* Compute the minimal width for frame "topfrp".
* When "next_curwin" isn't NULL, use p_wiw for this window.
* When "next_curwin" is NOWIN, don't use at least one column for the current
* window.
*/
static int
frame_minwidth(topfrp, next_curwin)
frame_T *topfrp;
win_T *next_curwin; /* use p_wh and p_wiw for next_curwin */
{
frame_T *frp;
int m, n;
if (topfrp->fr_win != NULL)
{
if (topfrp->fr_win == next_curwin)
m = p_wiw + topfrp->fr_win->w_vsep_width;
else
{
/* window: minimal width of the window plus separator column */
m = p_wmw + topfrp->fr_win->w_vsep_width;
/* Current window is minimal one column wide */
if (p_wmw == 0 && topfrp->fr_win == curwin && next_curwin == NULL)
++m;
}
}
else if (topfrp->fr_layout == FR_COL)
{
/* get the minimal width from each frame in this column */
m = 0;
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
{
n = frame_minwidth(frp, next_curwin);
if (n > m)
m = n;
}
}
else
{
/* Add up the minimal widths for all frames in this row. */
m = 0;
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
m += frame_minwidth(frp, next_curwin);
}
return m;
}
#endif
/*
* Try to close all windows except current one.
* Buffers in the other windows become hidden if 'hidden' is set, or '!' is
* used and the buffer was modified.
*
* Used by ":bdel" and ":only".
*/
void
close_others(message, forceit)
int message;
int forceit; /* always hide all other windows */
{
win_T *wp;
win_T *nextwp;
int r;
if (one_window())
{
if (message
#ifdef FEAT_AUTOCMD
&& !autocmd_busy
#endif
)
MSG(_(m_onlyone));
return;
}
/* Be very careful here: autocommands may change the window layout. */
for (wp = firstwin; win_valid(wp); wp = nextwp)
{
nextwp = wp->w_next;
if (wp != curwin) /* don't close current window */
{
/* Check if it's allowed to abandon this window */
r = can_abandon(wp->w_buffer, forceit);
#ifdef FEAT_AUTOCMD
if (!win_valid(wp)) /* autocommands messed wp up */
{
nextwp = firstwin;
continue;
}
#endif
if (!r)
{
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if (message && (p_confirm || cmdmod.confirm) && p_write)
{
dialog_changed(wp->w_buffer, FALSE);
# ifdef FEAT_AUTOCMD
if (!win_valid(wp)) /* autocommands messed wp up */
{
nextwp = firstwin;
continue;
}
# endif
}
if (bufIsChanged(wp->w_buffer))
#endif
continue;
}
win_close(wp, !P_HID(wp->w_buffer) && !bufIsChanged(wp->w_buffer));
}
}
if (message && lastwin != firstwin)
EMSG(_("E445: Other window contains changes"));
}
#endif /* FEAT_WINDOWS */
/*
* Init the current window "curwin".
* Called when a new file is being edited.
*/
void
curwin_init()
{
win_init_empty(curwin);
}
void
win_init_empty(wp)
win_T *wp;
{
redraw_win_later(wp, NOT_VALID);
wp->w_lines_valid = 0;
wp->w_cursor.lnum = 1;
wp->w_curswant = wp->w_cursor.col = 0;
#ifdef FEAT_VIRTUALEDIT
wp->w_cursor.coladd = 0;
#endif
wp->w_pcmark.lnum = 1; /* pcmark not cleared but set to line 1 */
wp->w_pcmark.col = 0;
wp->w_prev_pcmark.lnum = 0;
wp->w_prev_pcmark.col = 0;
wp->w_topline = 1;
#ifdef FEAT_DIFF
wp->w_topfill = 0;
#endif
wp->w_botline = 2;
#ifdef FEAT_FKMAP
if (wp->w_p_rl)
wp->w_farsi = W_CONV + W_R_L;
else
wp->w_farsi = W_CONV;
#endif
#ifdef FEAT_SYN_HL
wp->w_s = &wp->w_buffer->b_s;
#endif
}
/*
* Allocate the first window and put an empty buffer in it.
* Called from main().
* Return FAIL when something goes wrong (out of memory).
*/
int
win_alloc_first()
{
if (win_alloc_firstwin(NULL) == FAIL)
return FAIL;
#ifdef FEAT_WINDOWS
first_tabpage = alloc_tabpage();
if (first_tabpage == NULL)
return FAIL;
first_tabpage->tp_topframe = topframe;
curtab = first_tabpage;
#endif
return OK;
}
#if defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* Init "aucmd_win". This can only be done after the first
* window is fully initialized, thus it can't be in win_alloc_first().
*/
void
win_alloc_aucmd_win()
{
aucmd_win = win_alloc(NULL, TRUE);
if (aucmd_win != NULL)
{
win_init_some(aucmd_win, curwin);
RESET_BINDING(aucmd_win);
new_frame(aucmd_win);
}
}
#endif
/*
* Allocate the first window or the first window in a new tab page.
* When "oldwin" is NULL create an empty buffer for it.
* When "oldwin" is not NULL copy info from it to the new window (only with
* FEAT_WINDOWS).
* Return FAIL when something goes wrong (out of memory).
*/
static int
win_alloc_firstwin(oldwin)
win_T *oldwin;
{
curwin = win_alloc(NULL, FALSE);
if (oldwin == NULL)
{
/* Very first window, need to create an empty buffer for it and
* initialize from scratch. */
curbuf = buflist_new(NULL, NULL, 1L, BLN_LISTED);
if (curwin == NULL || curbuf == NULL)
return FAIL;
curwin->w_buffer = curbuf;
#ifdef FEAT_SYN_HL
curwin->w_s = &(curbuf->b_s);
#endif
curbuf->b_nwindows = 1; /* there is one window */
#ifdef FEAT_WINDOWS
curwin->w_alist = &global_alist;
#endif
curwin_init(); /* init current window */
}
#ifdef FEAT_WINDOWS
else
{
/* First window in new tab page, initialize it from "oldwin". */
win_init(curwin, oldwin, 0);
/* We don't want cursor- and scroll-binding in the first window. */
RESET_BINDING(curwin);
}
#endif
new_frame(curwin);
if (curwin->w_frame == NULL)
return FAIL;
topframe = curwin->w_frame;
#ifdef FEAT_VERTSPLIT
topframe->fr_width = Columns;
#endif
topframe->fr_height = Rows - p_ch;
topframe->fr_win = curwin;
return OK;
}
/*
* Create a frame for window "wp".
*/
static void
new_frame(win_T *wp)
{
frame_T *frp = (frame_T *)alloc_clear((unsigned)sizeof(frame_T));
wp->w_frame = frp;
if (frp != NULL)
{
frp->fr_layout = FR_LEAF;
frp->fr_win = wp;
}
}
/*
* Initialize the window and frame size to the maximum.
*/
void
win_init_size()
{
firstwin->w_height = ROWS_AVAIL;
topframe->fr_height = ROWS_AVAIL;
#ifdef FEAT_VERTSPLIT
firstwin->w_width = Columns;
topframe->fr_width = Columns;
#endif
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Allocate a new tabpage_T and init the values.
* Returns NULL when out of memory.
*/
static tabpage_T *
alloc_tabpage()
{
tabpage_T *tp;
tp = (tabpage_T *)alloc_clear((unsigned)sizeof(tabpage_T));
if (tp != NULL)
{
# ifdef FEAT_GUI
int i;
for (i = 0; i < 3; i++)
tp->tp_prev_which_scrollbars[i] = -1;
# endif
# ifdef FEAT_DIFF
tp->tp_diff_invalid = TRUE;
# endif
#ifdef FEAT_EVAL
/* init t: variables */
init_var_dict(&tp->tp_vars, &tp->tp_winvar);
#endif
tp->tp_ch_used = p_ch;
}
return tp;
}
void
free_tabpage(tp)
tabpage_T *tp;
{
int idx;
# ifdef FEAT_DIFF
diff_clear(tp);
# endif
for (idx = 0; idx < SNAP_COUNT; ++idx)
clear_snapshot(tp, idx);
#ifdef FEAT_EVAL
vars_clear(&tp->tp_vars.dv_hashtab); /* free all t: variables */
#endif
vim_free(tp);
}
/*
* Create a new Tab page with one window.
* It will edit the current buffer, like after ":split".
* When "after" is 0 put it just after the current Tab page.
* Otherwise put it just before tab page "after".
* Return FAIL or OK.
*/
int
win_new_tabpage(after)
int after;
{
tabpage_T *tp = curtab;
tabpage_T *newtp;
int n;
newtp = alloc_tabpage();
if (newtp == NULL)
return FAIL;
/* Remember the current windows in this Tab page. */
if (leave_tabpage(curbuf) == FAIL)
{
vim_free(newtp);
return FAIL;
}
curtab = newtp;
/* Create a new empty window. */
if (win_alloc_firstwin(tp->tp_curwin) == OK)
{
/* Make the new Tab page the new topframe. */
if (after == 1)
{
/* New tab page becomes the first one. */
newtp->tp_next = first_tabpage;
first_tabpage = newtp;
}
else
{
if (after > 0)
{
/* Put new tab page before tab page "after". */
n = 2;
for (tp = first_tabpage; tp->tp_next != NULL
&& n < after; tp = tp->tp_next)
++n;
}
newtp->tp_next = tp->tp_next;
tp->tp_next = newtp;
}
win_init_size();
firstwin->w_winrow = tabline_height();
win_comp_scroll(curwin);
newtp->tp_topframe = topframe;
last_status(FALSE);
#if defined(FEAT_GUI)
/* When 'guioptions' includes 'L' or 'R' may have to remove or add
* scrollbars. Have to update them anyway. */
gui_may_update_scrollbars();
#endif
redraw_all_later(CLEAR);
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
#endif
return OK;
}
/* Failed, get back the previous Tab page */
enter_tabpage(curtab, curbuf, TRUE);
return FAIL;
}
/*
* Open a new tab page if ":tab cmd" was used. It will edit the same buffer,
* like with ":split".
* Returns OK if a new tab page was created, FAIL otherwise.
*/
int
may_open_tabpage()
{
int n = (cmdmod.tab == 0) ? postponed_split_tab : cmdmod.tab;
if (n != 0)
{
cmdmod.tab = 0; /* reset it to avoid doing it twice */
postponed_split_tab = 0;
return win_new_tabpage(n);
}
return FAIL;
}
/*
* Create up to "maxcount" tabpages with empty windows.
* Returns the number of resulting tab pages.
*/
int
make_tabpages(maxcount)
int maxcount;
{
int count = maxcount;
int todo;
/* Limit to 'tabpagemax' tabs. */
if (count > p_tpm)
count = p_tpm;
#ifdef FEAT_AUTOCMD
/*
* Don't execute autocommands while creating the tab pages. Must do that
* when putting the buffers in the windows.
*/
block_autocmds();
#endif
for (todo = count - 1; todo > 0; --todo)
if (win_new_tabpage(0) == FAIL)
break;
#ifdef FEAT_AUTOCMD
unblock_autocmds();
#endif
/* return actual number of tab pages */
return (count - todo);
}
/*
* Return TRUE when "tpc" points to a valid tab page.
*/
int
valid_tabpage(tpc)
tabpage_T *tpc;
{
tabpage_T *tp;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
if (tp == tpc)
return TRUE;
return FALSE;
}
/*
* Find tab page "n" (first one is 1). Returns NULL when not found.
*/
tabpage_T *
find_tabpage(n)
int n;
{
tabpage_T *tp;
int i = 1;
for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next)
++i;
return tp;
}
/*
* Get index of tab page "tp". First one has index 1.
* When not found returns number of tab pages plus one.
*/
int
tabpage_index(ftp)
tabpage_T *ftp;
{
int i = 1;
tabpage_T *tp;
for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next)
++i;
return i;
}
/*
* Prepare for leaving the current tab page.
* When autocomands change "curtab" we don't leave the tab page and return
* FAIL.
* Careful: When OK is returned need to get a new tab page very very soon!
*/
static int
leave_tabpage(new_curbuf)
buf_T *new_curbuf UNUSED; /* what is going to be the new curbuf,
NULL if unknown */
{
tabpage_T *tp = curtab;
#ifdef FEAT_VISUAL
reset_VIsual_and_resel(); /* stop Visual mode */
#endif
#ifdef FEAT_AUTOCMD
if (new_curbuf != curbuf)
{
apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
if (curtab != tp)
return FAIL;
}
apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
if (curtab != tp)
return FAIL;
apply_autocmds(EVENT_TABLEAVE, NULL, NULL, FALSE, curbuf);
if (curtab != tp)
return FAIL;
#endif
#if defined(FEAT_GUI)
/* Remove the scrollbars. They may be added back later. */
if (gui.in_use)
gui_remove_scrollbars();
#endif
tp->tp_curwin = curwin;
tp->tp_prevwin = prevwin;
tp->tp_firstwin = firstwin;
tp->tp_lastwin = lastwin;
tp->tp_old_Rows = Rows;
tp->tp_old_Columns = Columns;
firstwin = NULL;
lastwin = NULL;
return OK;
}
/*
* Start using tab page "tp".
* Only to be used after leave_tabpage() or freeing the current tab page.
* Only trigger *Enter autocommands when trigger_autocmds is TRUE.
*/
static void
enter_tabpage(tp, old_curbuf, trigger_autocmds)
tabpage_T *tp;
buf_T *old_curbuf UNUSED;
int trigger_autocmds UNUSED;
{
int old_off = tp->tp_firstwin->w_winrow;
win_T *next_prevwin = tp->tp_prevwin;
curtab = tp;
firstwin = tp->tp_firstwin;
lastwin = tp->tp_lastwin;
topframe = tp->tp_topframe;
/* We would like doing the TabEnter event first, but we don't have a
* valid current window yet, which may break some commands.
* This triggers autocommands, thus may make "tp" invalid. */
win_enter_ext(tp->tp_curwin, FALSE, TRUE);
prevwin = next_prevwin;
last_status(FALSE); /* status line may appear or disappear */
(void)win_comp_pos(); /* recompute w_winrow for all windows */
must_redraw = CLEAR; /* need to redraw everything */
#ifdef FEAT_DIFF
diff_need_scrollbind = TRUE;
#endif
/* The tabpage line may have appeared or disappeared, may need to resize
* the frames for that. When the Vim window was resized need to update
* frame sizes too. Use the stored value of p_ch, so that it can be
* different for each tab page. */
p_ch = curtab->tp_ch_used;
if (curtab->tp_old_Rows != Rows || (old_off != firstwin->w_winrow
#ifdef FEAT_GUI_TABLINE
&& !gui_use_tabline()
#endif
))
shell_new_rows();
#ifdef FEAT_VERTSPLIT
if (curtab->tp_old_Columns != Columns && starting == 0)
shell_new_columns(); /* update window widths */
#endif
#if defined(FEAT_GUI)
/* When 'guioptions' includes 'L' or 'R' may have to remove or add
* scrollbars. Have to update them anyway. */
gui_may_update_scrollbars();
#endif
#ifdef FEAT_AUTOCMD
/* Apply autocommands after updating the display, when 'rows' and
* 'columns' have been set correctly. */
if (trigger_autocmds)
{
apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
if (old_curbuf != curbuf)
apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
}
#endif
redraw_all_later(CLEAR);
}
/*
* Go to tab page "n". For ":tab N" and "Ngt".
* When "n" is 9999 go to the last tab page.
*/
void
goto_tabpage(n)
int n;
{
tabpage_T *tp;
tabpage_T *ttp;
int i;
if (text_locked())
{
/* Not allowed when editing the command line. */
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
EMSG(_(e_cmdwin));
else
#endif
EMSG(_(e_secure));
return;
}
/* If there is only one it can't work. */
if (first_tabpage->tp_next == NULL)
{
if (n > 1)
beep_flush();
return;
}
if (n == 0)
{
/* No count, go to next tab page, wrap around end. */
if (curtab->tp_next == NULL)
tp = first_tabpage;
else
tp = curtab->tp_next;
}
else if (n < 0)
{
/* "gT": go to previous tab page, wrap around end. "N gT" repeats
* this N times. */
ttp = curtab;
for (i = n; i < 0; ++i)
{
for (tp = first_tabpage; tp->tp_next != ttp && tp->tp_next != NULL;
tp = tp->tp_next)
;
ttp = tp;
}
}
else if (n == 9999)
{
/* Go to last tab page. */
for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next)
;
}
else
{
/* Go to tab page "n". */
tp = find_tabpage(n);
if (tp == NULL)
{
beep_flush();
return;
}
}
goto_tabpage_tp(tp, TRUE);
#ifdef FEAT_GUI_TABLINE
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
#endif
}
/*
* Go to tabpage "tp".
* Only trigger *Enter autocommands when trigger_autocmds is TRUE.
* Note: doesn't update the GUI tab.
*/
void
goto_tabpage_tp(tp, trigger_autocmds)
tabpage_T *tp;
int trigger_autocmds;
{
/* Don't repeat a message in another tab page. */
set_keep_msg(NULL, 0);
if (tp != curtab && leave_tabpage(tp->tp_curwin->w_buffer) == OK)
{
if (valid_tabpage(tp))
enter_tabpage(tp, curbuf, trigger_autocmds);
else
enter_tabpage(curtab, curbuf, trigger_autocmds);
}
}
/*
* Enter window "wp" in tab page "tp".
* Also updates the GUI tab.
*/
void
goto_tabpage_win(tp, wp)
tabpage_T *tp;
win_T *wp;
{
goto_tabpage_tp(tp, TRUE);
if (curtab == tp && win_valid(wp))
{
win_enter(wp, TRUE);
# ifdef FEAT_GUI_TABLINE
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
# endif
}
}
/*
* Move the current tab page to before tab page "nr".
*/
void
tabpage_move(nr)
int nr;
{
int n = nr;
tabpage_T *tp;
if (first_tabpage->tp_next == NULL)
return;
/* Remove the current tab page from the list of tab pages. */
if (curtab == first_tabpage)
first_tabpage = curtab->tp_next;
else
{
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
if (tp->tp_next == curtab)
break;
if (tp == NULL) /* "cannot happen" */
return;
tp->tp_next = curtab->tp_next;
}
/* Re-insert it at the specified position. */
if (n == 0)
{
curtab->tp_next = first_tabpage;
first_tabpage = curtab;
}
else
{
for (tp = first_tabpage; tp->tp_next != NULL && n > 1; tp = tp->tp_next)
--n;
curtab->tp_next = tp->tp_next;
tp->tp_next = curtab;
}
/* Need to redraw the tabline. Tab page contents doesn't change. */
redraw_tabline = TRUE;
}
/*
* Go to another window.
* When jumping to another buffer, stop Visual mode. Do this before
* changing windows so we can yank the selection into the '*' register.
* When jumping to another window on the same buffer, adjust its cursor
* position to keep the same Visual area.
*/
void
win_goto(wp)
win_T *wp;
{
#ifdef FEAT_CONCEAL
win_T *owp = curwin;
#endif
if (text_locked())
{
beep_flush();
text_locked_msg();
return;
}
#ifdef FEAT_AUTOCMD
if (curbuf_locked())
return;
#endif
#ifdef FEAT_VISUAL
if (wp->w_buffer != curbuf)
reset_VIsual_and_resel();
else if (VIsual_active)
wp->w_cursor = curwin->w_cursor;
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_enter(wp, TRUE);
#ifdef FEAT_CONCEAL
/* Conceal cursor line in previous window, unconceal in current window. */
if (win_valid(owp))
update_single_line(owp, owp->w_cursor.lnum);
update_single_line(curwin, curwin->w_cursor.lnum);
#endif
}
#if defined(FEAT_PERL) || defined(PROTO)
/*
* Find window number "winnr" (counting top to bottom).
*/
win_T *
win_find_nr(winnr)
int winnr;
{
win_T *wp;
# ifdef FEAT_WINDOWS
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (--winnr == 0)
break;
return wp;
# else
return curwin;
# endif
}
#endif
#ifdef FEAT_VERTSPLIT
/*
* Move to window above or below "count" times.
*/
static void
win_goto_ver(up, count)
int up; /* TRUE to go to win above */
long count;
{
frame_T *fr;
frame_T *nfr;
frame_T *foundfr;
foundfr = curwin->w_frame;
while (count--)
{
/*
* First go upwards in the tree of frames until we find a upwards or
* downwards neighbor.
*/
fr = foundfr;
for (;;)
{
if (fr == topframe)
goto end;
if (up)
nfr = fr->fr_prev;
else
nfr = fr->fr_next;
if (fr->fr_parent->fr_layout == FR_COL && nfr != NULL)
break;
fr = fr->fr_parent;
}
/*
* Now go downwards to find the bottom or top frame in it.
*/
for (;;)
{
if (nfr->fr_layout == FR_LEAF)
{
foundfr = nfr;
break;
}
fr = nfr->fr_child;
if (nfr->fr_layout == FR_ROW)
{
/* Find the frame at the cursor row. */
while (fr->fr_next != NULL
&& frame2win(fr)->w_wincol + fr->fr_width
<= curwin->w_wincol + curwin->w_wcol)
fr = fr->fr_next;
}
if (nfr->fr_layout == FR_COL && up)
while (fr->fr_next != NULL)
fr = fr->fr_next;
nfr = fr;
}
}
end:
if (foundfr != NULL)
win_goto(foundfr->fr_win);
}
/*
* Move to left or right window.
*/
static void
win_goto_hor(left, count)
int left; /* TRUE to go to left win */
long count;
{
frame_T *fr;
frame_T *nfr;
frame_T *foundfr;
foundfr = curwin->w_frame;
while (count--)
{
/*
* First go upwards in the tree of frames until we find a left or
* right neighbor.
*/
fr = foundfr;
for (;;)
{
if (fr == topframe)
goto end;
if (left)
nfr = fr->fr_prev;
else
nfr = fr->fr_next;
if (fr->fr_parent->fr_layout == FR_ROW && nfr != NULL)
break;
fr = fr->fr_parent;
}
/*
* Now go downwards to find the leftmost or rightmost frame in it.
*/
for (;;)
{
if (nfr->fr_layout == FR_LEAF)
{
foundfr = nfr;
break;
}
fr = nfr->fr_child;
if (nfr->fr_layout == FR_COL)
{
/* Find the frame at the cursor row. */
while (fr->fr_next != NULL
&& frame2win(fr)->w_winrow + fr->fr_height
<= curwin->w_winrow + curwin->w_wrow)
fr = fr->fr_next;
}
if (nfr->fr_layout == FR_ROW && left)
while (fr->fr_next != NULL)
fr = fr->fr_next;
nfr = fr;
}
}
end:
if (foundfr != NULL)
win_goto(foundfr->fr_win);
}
#endif
/*
* Make window "wp" the current window.
*/
void
win_enter(wp, undo_sync)
win_T *wp;
int undo_sync;
{
win_enter_ext(wp, undo_sync, FALSE);
}
/*
* Make window wp the current window.
* Can be called with "curwin_invalid" TRUE, which means that curwin has just
* been closed and isn't valid.
*/
static void
win_enter_ext(wp, undo_sync, curwin_invalid)
win_T *wp;
int undo_sync;
int curwin_invalid;
{
#ifdef FEAT_AUTOCMD
int other_buffer = FALSE;
#endif
if (wp == curwin && !curwin_invalid) /* nothing to do */
return;
#ifdef FEAT_AUTOCMD
if (!curwin_invalid)
{
/*
* Be careful: If autocommands delete the window, return now.
*/
if (wp->w_buffer != curbuf)
{
apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
other_buffer = TRUE;
if (!win_valid(wp))
return;
}
apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
if (!win_valid(wp))
return;
# ifdef FEAT_EVAL
/* autocmds may abort script processing */
if (aborting())
return;
# endif
}
#endif
/* sync undo before leaving the current buffer */
if (undo_sync && curbuf != wp->w_buffer)
u_sync(FALSE);
/* may have to copy the buffer options when 'cpo' contains 'S' */
if (wp->w_buffer != curbuf)
buf_copy_options(wp->w_buffer, BCO_ENTER | BCO_NOHELP);
if (!curwin_invalid)
{
prevwin = curwin; /* remember for CTRL-W p */
curwin->w_redr_status = TRUE;
}
curwin = wp;
curbuf = wp->w_buffer;
check_cursor();
#ifdef FEAT_VIRTUALEDIT
if (!virtual_active())
curwin->w_cursor.coladd = 0;
#endif
changed_line_abv_curs(); /* assume cursor position needs updating */
if (curwin->w_localdir != NULL)
{
/* Window has a local directory: Save current directory as global
* directory (unless that was done already) and change to the local
* directory. */
if (globaldir == NULL)
{
char_u cwd[MAXPATHL];
if (mch_dirname(cwd, MAXPATHL) == OK)
globaldir = vim_strsave(cwd);
}
if (mch_chdir((char *)curwin->w_localdir) == 0)
shorten_fnames(TRUE);
}
else if (globaldir != NULL)
{
/* Window doesn't have a local directory and we are not in the global
* directory: Change to the global directory. */
ignored = mch_chdir((char *)globaldir);
vim_free(globaldir);
globaldir = NULL;
shorten_fnames(TRUE);
}
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
if (other_buffer)
apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
#endif
#ifdef FEAT_TITLE
maketitle();
#endif
curwin->w_redr_status = TRUE;
redraw_tabline = TRUE;
if (restart_edit)
redraw_later(VALID); /* causes status line redraw */
/* set window height to desired minimal value */
if (curwin->w_height < p_wh && !curwin->w_p_wfh)
win_setheight((int)p_wh);
else if (curwin->w_height == 0)
win_setheight(1);
#ifdef FEAT_VERTSPLIT
/* set window width to desired minimal value */
if (curwin->w_width < p_wiw && !curwin->w_p_wfw)
win_setwidth((int)p_wiw);
#endif
#ifdef FEAT_MOUSE
setmouse(); /* in case jumped to/from help buffer */
#endif
/* Change directories when the 'acd' option is set. */
DO_AUTOCHDIR
}
#endif /* FEAT_WINDOWS */
#if defined(FEAT_WINDOWS) || defined(FEAT_SIGNS) || defined(PROTO)
/*
* Jump to the first open window that contains buffer "buf", if one exists.
* Returns a pointer to the window found, otherwise NULL.
*/
win_T *
buf_jump_open_win(buf)
buf_T *buf;
{
# ifdef FEAT_WINDOWS
win_T *wp;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_buffer == buf)
break;
if (wp != NULL)
win_enter(wp, FALSE);
return wp;
# else
if (curwin->w_buffer == buf)
return curwin;
return NULL;
# endif
}
/*
* Jump to the first open window in any tab page that contains buffer "buf",
* if one exists.
* Returns a pointer to the window found, otherwise NULL.
*/
win_T *
buf_jump_open_tab(buf)
buf_T *buf;
{
# ifdef FEAT_WINDOWS
win_T *wp;
tabpage_T *tp;
/* First try the current tab page. */
wp = buf_jump_open_win(buf);
if (wp != NULL)
return wp;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
if (tp != curtab)
{
for (wp = tp->tp_firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_buffer == buf)
break;
if (wp != NULL)
{
goto_tabpage_win(tp, wp);
if (curwin != wp)
wp = NULL; /* something went wrong */
break;
}
}
return wp;
# else
if (curwin->w_buffer == buf)
return curwin;
return NULL;
# endif
}
#endif
/*
* Allocate a window structure and link it in the window list when "hidden" is
* FALSE.
*/
static win_T *
win_alloc(after, hidden)
win_T *after UNUSED;
int hidden UNUSED;
{
win_T *new_wp;
/*
* allocate window structure and linesizes arrays
*/
new_wp = (win_T *)alloc_clear((unsigned)sizeof(win_T));
if (new_wp != NULL && win_alloc_lines(new_wp) == FAIL)
{
vim_free(new_wp);
new_wp = NULL;
}
if (new_wp != NULL)
{
#ifdef FEAT_AUTOCMD
/* Don't execute autocommands while the window is not properly
* initialized yet. gui_create_scrollbar() may trigger a FocusGained
* event. */
block_autocmds();
#endif
/*
* link the window in the window list
*/
#ifdef FEAT_WINDOWS
if (!hidden)
win_append(after, new_wp);
#endif
#ifdef FEAT_VERTSPLIT
new_wp->w_wincol = 0;
new_wp->w_width = Columns;
#endif
/* position the display and the cursor at the top of the file. */
new_wp->w_topline = 1;
#ifdef FEAT_DIFF
new_wp->w_topfill = 0;
#endif
new_wp->w_botline = 2;
new_wp->w_cursor.lnum = 1;
#ifdef FEAT_SCROLLBIND
new_wp->w_scbind_pos = 1;
#endif
/* We won't calculate w_fraction until resizing the window */
new_wp->w_fraction = 0;
new_wp->w_prev_fraction_row = -1;
#ifdef FEAT_GUI
if (gui.in_use)
{
gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_LEFT],
SBAR_LEFT, new_wp);
gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_RIGHT],
SBAR_RIGHT, new_wp);
}
#endif
#ifdef FEAT_EVAL
/* init w: variables */
init_var_dict(&new_wp->w_vars, &new_wp->w_winvar);
#endif
#ifdef FEAT_FOLDING
foldInitWin(new_wp);
#endif
#ifdef FEAT_AUTOCMD
unblock_autocmds();
#endif
#ifdef FEAT_SEARCH_EXTRA
new_wp->w_match_head = NULL;
new_wp->w_next_match_id = 4;
#endif
}
return new_wp;
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* remove window 'wp' from the window list and free the structure
*/
static void
win_free(wp, tp)
win_T *wp;
tabpage_T *tp; /* tab page "win" is in, NULL for current */
{
int i;
#ifdef FEAT_FOLDING
clearFolding(wp);
#endif
/* reduce the reference count to the argument list. */
alist_unlink(wp->w_alist);
#ifdef FEAT_AUTOCMD
/* Don't execute autocommands while the window is halfway being deleted.
* gui_mch_destroy_scrollbar() may trigger a FocusGained event. */
block_autocmds();
#endif
#ifdef FEAT_LUA
lua_window_free(wp);
#endif
#ifdef FEAT_MZSCHEME
mzscheme_window_free(wp);
#endif
#ifdef FEAT_PERL
perl_win_free(wp);
#endif
#ifdef FEAT_PYTHON
python_window_free(wp);
#endif
#ifdef FEAT_PYTHON3
python3_window_free(wp);
#endif
#ifdef FEAT_TCL
tcl_window_free(wp);
#endif
#ifdef FEAT_RUBY
ruby_window_free(wp);
#endif
clear_winopt(&wp->w_onebuf_opt);
clear_winopt(&wp->w_allbuf_opt);
#ifdef FEAT_EVAL
vars_clear(&wp->w_vars.dv_hashtab); /* free all w: variables */
#endif
if (prevwin == wp)
prevwin = NULL;
win_free_lsize(wp);
for (i = 0; i < wp->w_tagstacklen; ++i)
vim_free(wp->w_tagstack[i].tagname);
vim_free(wp->w_localdir);
#ifdef FEAT_SEARCH_EXTRA
clear_matches(wp);
#endif
#ifdef FEAT_JUMPLIST
free_jumplist(wp);
#endif
#ifdef FEAT_QUICKFIX
qf_free_all(wp);
#endif
#ifdef FEAT_GUI
if (gui.in_use)
{
gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_LEFT]);
gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_RIGHT]);
}
#endif /* FEAT_GUI */
#ifdef FEAT_SYN_HL
vim_free(wp->w_p_cc_cols);
#endif
#ifdef FEAT_AUTOCMD
if (wp != aucmd_win)
#endif
win_remove(wp, tp);
vim_free(wp);
#ifdef FEAT_AUTOCMD
unblock_autocmds();
#endif
}
/*
* Append window "wp" in the window list after window "after".
*/
void
win_append(after, wp)
win_T *after, *wp;
{
win_T *before;
if (after == NULL) /* after NULL is in front of the first */
before = firstwin;
else
before = after->w_next;
wp->w_next = before;
wp->w_prev = after;
if (after == NULL)
firstwin = wp;
else
after->w_next = wp;
if (before == NULL)
lastwin = wp;
else
before->w_prev = wp;
}
/*
* Remove a window from the window list.
*/
void
win_remove(wp, tp)
win_T *wp;
tabpage_T *tp; /* tab page "win" is in, NULL for current */
{
if (wp->w_prev != NULL)
wp->w_prev->w_next = wp->w_next;
else if (tp == NULL)
firstwin = wp->w_next;
else
tp->tp_firstwin = wp->w_next;
if (wp->w_next != NULL)
wp->w_next->w_prev = wp->w_prev;
else if (tp == NULL)
lastwin = wp->w_prev;
else
tp->tp_lastwin = wp->w_prev;
}
/*
* Append frame "frp" in a frame list after frame "after".
*/
static void
frame_append(after, frp)
frame_T *after, *frp;
{
frp->fr_next = after->fr_next;
after->fr_next = frp;
if (frp->fr_next != NULL)
frp->fr_next->fr_prev = frp;
frp->fr_prev = after;
}
/*
* Insert frame "frp" in a frame list before frame "before".
*/
static void
frame_insert(before, frp)
frame_T *before, *frp;
{
frp->fr_next = before;
frp->fr_prev = before->fr_prev;
before->fr_prev = frp;
if (frp->fr_prev != NULL)
frp->fr_prev->fr_next = frp;
else
frp->fr_parent->fr_child = frp;
}
/*
* Remove a frame from a frame list.
*/
static void
frame_remove(frp)
frame_T *frp;
{
if (frp->fr_prev != NULL)
frp->fr_prev->fr_next = frp->fr_next;
else
frp->fr_parent->fr_child = frp->fr_next;
if (frp->fr_next != NULL)
frp->fr_next->fr_prev = frp->fr_prev;
}
#endif /* FEAT_WINDOWS */
/*
* Allocate w_lines[] for window "wp".
* Return FAIL for failure, OK for success.
*/
int
win_alloc_lines(wp)
win_T *wp;
{
wp->w_lines_valid = 0;
wp->w_lines = (wline_T *)alloc_clear((unsigned)(Rows * sizeof(wline_T)));
if (wp->w_lines == NULL)
return FAIL;
return OK;
}
/*
* free lsize arrays for a window
*/
void
win_free_lsize(wp)
win_T *wp;
{
vim_free(wp->w_lines);
wp->w_lines = NULL;
}
/*
* Called from win_new_shellsize() after Rows changed.
* This only does the current tab page, others must be done when made active.
*/
void
shell_new_rows()
{
int h = (int)ROWS_AVAIL;
if (firstwin == NULL) /* not initialized yet */
return;
#ifdef FEAT_WINDOWS
if (h < frame_minheight(topframe, NULL))
h = frame_minheight(topframe, NULL);
/* First try setting the heights of windows with 'winfixheight'. If
* that doesn't result in the right height, forget about that option. */
frame_new_height(topframe, h, FALSE, TRUE);
if (topframe->fr_height != h)
frame_new_height(topframe, h, FALSE, FALSE);
(void)win_comp_pos(); /* recompute w_winrow and w_wincol */
#else
if (h < 1)
h = 1;
win_new_height(firstwin, h);
#endif
compute_cmdrow();
#ifdef FEAT_WINDOWS
curtab->tp_ch_used = p_ch;
#endif
#if 0
/* Disabled: don't want making the screen smaller make a window larger. */
if (p_ea)
win_equal(curwin, FALSE, 'v');
#endif
}
#if defined(FEAT_VERTSPLIT) || defined(PROTO)
/*
* Called from win_new_shellsize() after Columns changed.
*/
void
shell_new_columns()
{
if (firstwin == NULL) /* not initialized yet */
return;
/* First try setting the widths of windows with 'winfixwidth'. If that
* doesn't result in the right width, forget about that option. */
frame_new_width(topframe, (int)Columns, FALSE, TRUE);
if (topframe->fr_width != Columns)
frame_new_width(topframe, (int)Columns, FALSE, FALSE);
(void)win_comp_pos(); /* recompute w_winrow and w_wincol */
#if 0
/* Disabled: don't want making the screen smaller make a window larger. */
if (p_ea)
win_equal(curwin, FALSE, 'h');
#endif
}
#endif
#if defined(FEAT_CMDWIN) || defined(PROTO)
/*
* Save the size of all windows in "gap".
*/
void
win_size_save(gap)
garray_T *gap;
{
win_T *wp;
ga_init2(gap, (int)sizeof(int), 1);
if (ga_grow(gap, win_count() * 2) == OK)
for (wp = firstwin; wp != NULL; wp = wp->w_next)
{
((int *)gap->ga_data)[gap->ga_len++] =
wp->w_width + wp->w_vsep_width;
((int *)gap->ga_data)[gap->ga_len++] = wp->w_height;
}
}
/*
* Restore window sizes, but only if the number of windows is still the same.
* Does not free the growarray.
*/
void
win_size_restore(gap)
garray_T *gap;
{
win_T *wp;
int i;
if (win_count() * 2 == gap->ga_len)
{
i = 0;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
{
frame_setwidth(wp->w_frame, ((int *)gap->ga_data)[i++]);
win_setheight_win(((int *)gap->ga_data)[i++], wp);
}
/* recompute the window positions */
(void)win_comp_pos();
}
}
#endif /* FEAT_CMDWIN */
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Update the position for all windows, using the width and height of the
* frames.
* Returns the row just after the last window.
*/
int
win_comp_pos()
{
int row = tabline_height();
int col = 0;
frame_comp_pos(topframe, &row, &col);
return row;
}
/*
* Update the position of the windows in frame "topfrp", using the width and
* height of the frames.
* "*row" and "*col" are the top-left position of the frame. They are updated
* to the bottom-right position plus one.
*/
static void
frame_comp_pos(topfrp, row, col)
frame_T *topfrp;
int *row;
int *col;
{
win_T *wp;
frame_T *frp;
#ifdef FEAT_VERTSPLIT
int startcol;
int startrow;
#endif
wp = topfrp->fr_win;
if (wp != NULL)
{
if (wp->w_winrow != *row
#ifdef FEAT_VERTSPLIT
|| wp->w_wincol != *col
#endif
)
{
/* position changed, redraw */
wp->w_winrow = *row;
#ifdef FEAT_VERTSPLIT
wp->w_wincol = *col;
#endif
redraw_win_later(wp, NOT_VALID);
wp->w_redr_status = TRUE;
}
*row += wp->w_height + wp->w_status_height;
#ifdef FEAT_VERTSPLIT
*col += wp->w_width + wp->w_vsep_width;
#endif
}
else
{
#ifdef FEAT_VERTSPLIT
startrow = *row;
startcol = *col;
#endif
for (frp = topfrp->fr_child; frp != NULL; frp = frp->fr_next)
{
#ifdef FEAT_VERTSPLIT
if (topfrp->fr_layout == FR_ROW)
*row = startrow; /* all frames are at the same row */
else
*col = startcol; /* all frames are at the same col */
#endif
frame_comp_pos(frp, row, col);
}
}
}
#endif /* FEAT_WINDOWS */
/*
* Set current window height and take care of repositioning other windows to
* fit around it.
*/
void
win_setheight(height)
int height;
{
win_setheight_win(height, curwin);
}
/*
* Set the window height of window "win" and take care of repositioning other
* windows to fit around it.
*/
void
win_setheight_win(height, win)
int height;
win_T *win;
{
int row;
if (win == curwin)
{
/* Always keep current window at least one line high, even when
* 'winminheight' is zero. */
#ifdef FEAT_WINDOWS
if (height < p_wmh)
height = p_wmh;
#endif
if (height == 0)
height = 1;
}
#ifdef FEAT_WINDOWS
frame_setheight(win->w_frame, height + win->w_status_height);
/* recompute the window positions */
row = win_comp_pos();
#else
if (height > topframe->fr_height)
height = topframe->fr_height;
win->w_height = height;
row = height;
#endif
/*
* If there is extra space created between the last window and the command
* line, clear it.
*/
if (full_screen && msg_scrolled == 0 && row < cmdline_row)
screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
cmdline_row = row;
msg_row = row;
msg_col = 0;
redraw_all_later(NOT_VALID);
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Set the height of a frame to "height" and take care that all frames and
* windows inside it are resized. Also resize frames on the left and right if
* the are in the same FR_ROW frame.
*
* Strategy:
* If the frame is part of a FR_COL frame, try fitting the frame in that
* frame. If that doesn't work (the FR_COL frame is too small), recursively
* go to containing frames to resize them and make room.
* If the frame is part of a FR_ROW frame, all frames must be resized as well.
* Check for the minimal height of the FR_ROW frame.
* At the top level we can also use change the command line height.
*/
static void
frame_setheight(curfrp, height)
frame_T *curfrp;
int height;
{
int room; /* total number of lines available */
int take; /* number of lines taken from other windows */
int room_cmdline; /* lines available from cmdline */
int run;
frame_T *frp;
int h;
int room_reserved;
/* If the height already is the desired value, nothing to do. */
if (curfrp->fr_height == height)
return;
if (curfrp->fr_parent == NULL)
{
/* topframe: can only change the command line */
if (height > ROWS_AVAIL)
height = ROWS_AVAIL;
if (height > 0)
frame_new_height(curfrp, height, FALSE, FALSE);
}
else if (curfrp->fr_parent->fr_layout == FR_ROW)
{
/* Row of frames: Also need to resize frames left and right of this
* one. First check for the minimal height of these. */
h = frame_minheight(curfrp->fr_parent, NULL);
if (height < h)
height = h;
frame_setheight(curfrp->fr_parent, height);
}
else
{
/*
* Column of frames: try to change only frames in this column.
*/
#ifdef FEAT_VERTSPLIT
/*
* Do this twice:
* 1: compute room available, if it's not enough try resizing the
* containing frame.
* 2: compute the room available and adjust the height to it.
* Try not to reduce the height of a window with 'winfixheight' set.
*/
for (run = 1; run <= 2; ++run)
#else
for (;;)
#endif
{
room = 0;
room_reserved = 0;
for (frp = curfrp->fr_parent->fr_child; frp != NULL;
frp = frp->fr_next)
{
if (frp != curfrp
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfh)
room_reserved += frp->fr_height;
room += frp->fr_height;
if (frp != curfrp)
room -= frame_minheight(frp, NULL);
}
#ifdef FEAT_VERTSPLIT
if (curfrp->fr_width != Columns)
room_cmdline = 0;
else
#endif
{
room_cmdline = Rows - p_ch - (lastwin->w_winrow
+ lastwin->w_height + lastwin->w_status_height);
if (room_cmdline < 0)
room_cmdline = 0;
}
if (height <= room + room_cmdline)
break;
#ifdef FEAT_VERTSPLIT
if (run == 2 || curfrp->fr_width == Columns)
#endif
{
if (height > room + room_cmdline)
height = room + room_cmdline;
break;
}
#ifdef FEAT_VERTSPLIT
frame_setheight(curfrp->fr_parent, height
+ frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1);
#endif
/*NOTREACHED*/
}
/*
* Compute the number of lines we will take from others frames (can be
* negative!).
*/
take = height - curfrp->fr_height;
/* If there is not enough room, also reduce the height of a window
* with 'winfixheight' set. */
if (height > room + room_cmdline - room_reserved)
room_reserved = room + room_cmdline - height;
/* If there is only a 'winfixheight' window and making the
* window smaller, need to make the other window taller. */
if (take < 0 && room - curfrp->fr_height < room_reserved)
room_reserved = 0;
if (take > 0 && room_cmdline > 0)
{
/* use lines from cmdline first */
if (take < room_cmdline)
room_cmdline = take;
take -= room_cmdline;
topframe->fr_height += room_cmdline;
}
/*
* set the current frame to the new height
*/
frame_new_height(curfrp, height, FALSE, FALSE);
/*
* First take lines from the frames after the current frame. If
* that is not enough, takes lines from frames above the current
* frame.
*/
for (run = 0; run < 2; ++run)
{
if (run == 0)
frp = curfrp->fr_next; /* 1st run: start with next window */
else
frp = curfrp->fr_prev; /* 2nd run: start with prev window */
while (frp != NULL && take != 0)
{
h = frame_minheight(frp, NULL);
if (room_reserved > 0
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfh)
{
if (room_reserved >= frp->fr_height)
room_reserved -= frp->fr_height;
else
{
if (frp->fr_height - room_reserved > take)
room_reserved = frp->fr_height - take;
take -= frp->fr_height - room_reserved;
frame_new_height(frp, room_reserved, FALSE, FALSE);
room_reserved = 0;
}
}
else
{
if (frp->fr_height - take < h)
{
take -= frp->fr_height - h;
frame_new_height(frp, h, FALSE, FALSE);
}
else
{
frame_new_height(frp, frp->fr_height - take,
FALSE, FALSE);
take = 0;
}
}
if (run == 0)
frp = frp->fr_next;
else
frp = frp->fr_prev;
}
}
}
}
#if defined(FEAT_VERTSPLIT) || defined(PROTO)
/*
* Set current window width and take care of repositioning other windows to
* fit around it.
*/
void
win_setwidth(width)
int width;
{
win_setwidth_win(width, curwin);
}
void
win_setwidth_win(width, wp)
int width;
win_T *wp;
{
/* Always keep current window at least one column wide, even when
* 'winminwidth' is zero. */
if (wp == curwin)
{
if (width < p_wmw)
width = p_wmw;
if (width == 0)
width = 1;
}
frame_setwidth(wp->w_frame, width + wp->w_vsep_width);
/* recompute the window positions */
(void)win_comp_pos();
redraw_all_later(NOT_VALID);
}
/*
* Set the width of a frame to "width" and take care that all frames and
* windows inside it are resized. Also resize frames above and below if the
* are in the same FR_ROW frame.
*
* Strategy is similar to frame_setheight().
*/
static void
frame_setwidth(curfrp, width)
frame_T *curfrp;
int width;
{
int room; /* total number of lines available */
int take; /* number of lines taken from other windows */
int run;
frame_T *frp;
int w;
int room_reserved;
/* If the width already is the desired value, nothing to do. */
if (curfrp->fr_width == width)
return;
if (curfrp->fr_parent == NULL)
/* topframe: can't change width */
return;
if (curfrp->fr_parent->fr_layout == FR_COL)
{
/* Column of frames: Also need to resize frames above and below of
* this one. First check for the minimal width of these. */
w = frame_minwidth(curfrp->fr_parent, NULL);
if (width < w)
width = w;
frame_setwidth(curfrp->fr_parent, width);
}
else
{
/*
* Row of frames: try to change only frames in this row.
*
* Do this twice:
* 1: compute room available, if it's not enough try resizing the
* containing frame.
* 2: compute the room available and adjust the width to it.
*/
for (run = 1; run <= 2; ++run)
{
room = 0;
room_reserved = 0;
for (frp = curfrp->fr_parent->fr_child; frp != NULL;
frp = frp->fr_next)
{
if (frp != curfrp
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfw)
room_reserved += frp->fr_width;
room += frp->fr_width;
if (frp != curfrp)
room -= frame_minwidth(frp, NULL);
}
if (width <= room)
break;
if (run == 2 || curfrp->fr_height >= ROWS_AVAIL)
{
if (width > room)
width = room;
break;
}
frame_setwidth(curfrp->fr_parent, width
+ frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1);
}
/*
* Compute the number of lines we will take from others frames (can be
* negative!).
*/
take = width - curfrp->fr_width;
/* If there is not enough room, also reduce the width of a window
* with 'winfixwidth' set. */
if (width > room - room_reserved)
room_reserved = room - width;
/* If there is only a 'winfixwidth' window and making the
* window smaller, need to make the other window narrower. */
if (take < 0 && room - curfrp->fr_width < room_reserved)
room_reserved = 0;
/*
* set the current frame to the new width
*/
frame_new_width(curfrp, width, FALSE, FALSE);
/*
* First take lines from the frames right of the current frame. If
* that is not enough, takes lines from frames left of the current
* frame.
*/
for (run = 0; run < 2; ++run)
{
if (run == 0)
frp = curfrp->fr_next; /* 1st run: start with next window */
else
frp = curfrp->fr_prev; /* 2nd run: start with prev window */
while (frp != NULL && take != 0)
{
w = frame_minwidth(frp, NULL);
if (room_reserved > 0
&& frp->fr_win != NULL
&& frp->fr_win->w_p_wfw)
{
if (room_reserved >= frp->fr_width)
room_reserved -= frp->fr_width;
else
{
if (frp->fr_width - room_reserved > take)
room_reserved = frp->fr_width - take;
take -= frp->fr_width - room_reserved;
frame_new_width(frp, room_reserved, FALSE, FALSE);
room_reserved = 0;
}
}
else
{
if (frp->fr_width - take < w)
{
take -= frp->fr_width - w;
frame_new_width(frp, w, FALSE, FALSE);
}
else
{
frame_new_width(frp, frp->fr_width - take,
FALSE, FALSE);
take = 0;
}
}
if (run == 0)
frp = frp->fr_next;
else
frp = frp->fr_prev;
}
}
}
}
#endif /* FEAT_VERTSPLIT */
/*
* Check 'winminheight' for a valid value.
*/
void
win_setminheight()
{
int room;
int first = TRUE;
win_T *wp;
/* loop until there is a 'winminheight' that is possible */
while (p_wmh > 0)
{
/* TODO: handle vertical splits */
room = -p_wh;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
room += wp->w_height - p_wmh;
if (room >= 0)
break;
--p_wmh;
if (first)
{
EMSG(_(e_noroom));
first = FALSE;
}
}
}
#ifdef FEAT_MOUSE
/*
* Status line of dragwin is dragged "offset" lines down (negative is up).
*/
void
win_drag_status_line(dragwin, offset)
win_T *dragwin;
int offset;
{
frame_T *curfr;
frame_T *fr;
int room;
int row;
int up; /* if TRUE, drag status line up, otherwise down */
int n;
fr = dragwin->w_frame;
curfr = fr;
if (fr != topframe) /* more than one window */
{
fr = fr->fr_parent;
/* When the parent frame is not a column of frames, its parent should
* be. */
if (fr->fr_layout != FR_COL)
{
curfr = fr;
if (fr != topframe) /* only a row of windows, may drag statusline */
fr = fr->fr_parent;
}
}
/* If this is the last frame in a column, may want to resize the parent
* frame instead (go two up to skip a row of frames). */
while (curfr != topframe && curfr->fr_next == NULL)
{
if (fr != topframe)
fr = fr->fr_parent;
curfr = fr;
if (fr != topframe)
fr = fr->fr_parent;
}
if (offset < 0) /* drag up */
{
up = TRUE;
offset = -offset;
/* sum up the room of the current frame and above it */
if (fr == curfr)
{
/* only one window */
room = fr->fr_height - frame_minheight(fr, NULL);
}
else
{
room = 0;
for (fr = fr->fr_child; ; fr = fr->fr_next)
{
room += fr->fr_height - frame_minheight(fr, NULL);
if (fr == curfr)
break;
}
}
fr = curfr->fr_next; /* put fr at frame that grows */
}
else /* drag down */
{
up = FALSE;
/*
* Only dragging the last status line can reduce p_ch.
*/
room = Rows - cmdline_row;
if (curfr->fr_next == NULL)
room -= 1;
else
room -= p_ch;
if (room < 0)
room = 0;
/* sum up the room of frames below of the current one */
for (fr = curfr->fr_next; fr != NULL; fr = fr->fr_next)
room += fr->fr_height - frame_minheight(fr, NULL);
fr = curfr; /* put fr at window that grows */
}
if (room < offset) /* Not enough room */
offset = room; /* Move as far as we can */
if (offset <= 0)
return;
/*
* Grow frame fr by "offset" lines.
* Doesn't happen when dragging the last status line up.
*/
if (fr != NULL)
frame_new_height(fr, fr->fr_height + offset, up, FALSE);
if (up)
fr = curfr; /* current frame gets smaller */
else
fr = curfr->fr_next; /* next frame gets smaller */
/*
* Now make the other frames smaller.
*/
while (fr != NULL && offset > 0)
{
n = frame_minheight(fr, NULL);
if (fr->fr_height - offset <= n)
{
offset -= fr->fr_height - n;
frame_new_height(fr, n, !up, FALSE);
}
else
{
frame_new_height(fr, fr->fr_height - offset, !up, FALSE);
break;
}
if (up)
fr = fr->fr_prev;
else
fr = fr->fr_next;
}
row = win_comp_pos();
screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
cmdline_row = row;
p_ch = Rows - cmdline_row;
if (p_ch < 1)
p_ch = 1;
curtab->tp_ch_used = p_ch;
redraw_all_later(SOME_VALID);
showmode();
}
#ifdef FEAT_VERTSPLIT
/*
* Separator line of dragwin is dragged "offset" lines right (negative is left).
*/
void
win_drag_vsep_line(dragwin, offset)
win_T *dragwin;
int offset;
{
frame_T *curfr;
frame_T *fr;
int room;
int left; /* if TRUE, drag separator line left, otherwise right */
int n;
fr = dragwin->w_frame;
if (fr == topframe) /* only one window (cannot happen?) */
return;
curfr = fr;
fr = fr->fr_parent;
/* When the parent frame is not a row of frames, its parent should be. */
if (fr->fr_layout != FR_ROW)
{
if (fr == topframe) /* only a column of windows (cannot happen?) */
return;
curfr = fr;
fr = fr->fr_parent;
}
/* If this is the last frame in a row, may want to resize a parent
* frame instead. */
while (curfr->fr_next == NULL)
{
if (fr == topframe)
break;
curfr = fr;
fr = fr->fr_parent;
if (fr != topframe)
{
curfr = fr;
fr = fr->fr_parent;
}
}
if (offset < 0) /* drag left */
{
left = TRUE;
offset = -offset;
/* sum up the room of the current frame and left of it */
room = 0;
for (fr = fr->fr_child; ; fr = fr->fr_next)
{
room += fr->fr_width - frame_minwidth(fr, NULL);
if (fr == curfr)
break;
}
fr = curfr->fr_next; /* put fr at frame that grows */
}
else /* drag right */
{
left = FALSE;
/* sum up the room of frames right of the current one */
room = 0;
for (fr = curfr->fr_next; fr != NULL; fr = fr->fr_next)
room += fr->fr_width - frame_minwidth(fr, NULL);
fr = curfr; /* put fr at window that grows */
}
if (room < offset) /* Not enough room */
offset = room; /* Move as far as we can */
if (offset <= 0) /* No room at all, quit. */
return;
/* grow frame fr by offset lines */
frame_new_width(fr, fr->fr_width + offset, left, FALSE);
/* shrink other frames: current and at the left or at the right */
if (left)
fr = curfr; /* current frame gets smaller */
else
fr = curfr->fr_next; /* next frame gets smaller */
while (fr != NULL && offset > 0)
{
n = frame_minwidth(fr, NULL);
if (fr->fr_width - offset <= n)
{
offset -= fr->fr_width - n;
frame_new_width(fr, n, !left, FALSE);
}
else
{
frame_new_width(fr, fr->fr_width - offset, !left, FALSE);
break;
}
if (left)
fr = fr->fr_prev;
else
fr = fr->fr_next;
}
(void)win_comp_pos();
redraw_all_later(NOT_VALID);
}
#endif /* FEAT_VERTSPLIT */
#endif /* FEAT_MOUSE */
#endif /* FEAT_WINDOWS */
#define FRACTION_MULT 16384L
/*
* Set wp->w_fraction for the current w_wrow and w_height.
*/
static void
set_fraction(wp)
win_T *wp;
{
wp->w_fraction = ((long)wp->w_wrow * FRACTION_MULT
+ FRACTION_MULT / 2) / (long)wp->w_height;
}
/*
* Set the height of a window.
* This takes care of the things inside the window, not what happens to the
* window position, the frame or to other windows.
*/
static void
win_new_height(wp, height)
win_T *wp;
int height;
{
linenr_T lnum;
int sline, line_size;
/* Don't want a negative height. Happens when splitting a tiny window.
* Will equalize heights soon to fix it. */
if (height < 0)
height = 0;
if (wp->w_height == height)
return; /* nothing to do */
if (wp->w_wrow != wp->w_prev_fraction_row && wp->w_height > 0)
set_fraction(wp);
wp->w_height = height;
wp->w_skipcol = 0;
/* Don't change w_topline when height is zero. Don't set w_topline when
* 'scrollbind' is set and this isn't the current window. */
if (height > 0
#ifdef FEAT_SCROLLBIND
&& (!wp->w_p_scb || wp == curwin)
#endif
)
{
/*
* Find a value for w_topline that shows the cursor at the same
* relative position in the window as before (more or less).
*/
lnum = wp->w_cursor.lnum;
if (lnum < 1) /* can happen when starting up */
lnum = 1;
wp->w_wrow = ((long)wp->w_fraction * (long)height - 1L) / FRACTION_MULT;
line_size = plines_win_col(wp, lnum, (long)(wp->w_cursor.col)) - 1;
sline = wp->w_wrow - line_size;
if (sline >= 0)
{
/* Make sure the whole cursor line is visible, if possible. */
int rows = plines_win(wp, lnum, FALSE);
if (sline > wp->w_height - rows)
{
sline = wp->w_height - rows;
wp->w_wrow -= rows - line_size;
}
}
if (sline < 0)
{
/*
* Cursor line would go off top of screen if w_wrow was this high.
* Make cursor line the first line in the window. If not enough
* room use w_skipcol;
*/
wp->w_wrow = line_size;
if (wp->w_wrow >= wp->w_height
&& (W_WIDTH(wp) - win_col_off(wp)) > 0)
{
wp->w_skipcol += W_WIDTH(wp) - win_col_off(wp);
--wp->w_wrow;
while (wp->w_wrow >= wp->w_height)
{
wp->w_skipcol += W_WIDTH(wp) - win_col_off(wp)
+ win_col_off2(wp);
--wp->w_wrow;
}
}
}
else
{
while (sline > 0 && lnum > 1)
{
#ifdef FEAT_FOLDING
hasFoldingWin(wp, lnum, &lnum, NULL, TRUE, NULL);
if (lnum == 1)
{
/* first line in buffer is folded */
line_size = 1;
--sline;
break;
}
#endif
--lnum;
#ifdef FEAT_DIFF
if (lnum == wp->w_topline)
line_size = plines_win_nofill(wp, lnum, TRUE)
+ wp->w_topfill;
else
#endif
line_size = plines_win(wp, lnum, TRUE);
sline -= line_size;
}
if (sline < 0)
{
/*
* Line we want at top would go off top of screen. Use next
* line instead.
*/
#ifdef FEAT_FOLDING
hasFoldingWin(wp, lnum, NULL, &lnum, TRUE, NULL);
#endif
lnum++;
wp->w_wrow -= line_size + sline;
}
else if (sline > 0)
{
/* First line of file reached, use that as topline. */
lnum = 1;
wp->w_wrow -= sline;
}
}
set_topline(wp, lnum);
}
if (wp == curwin)
{
if (p_so)
update_topline();
curs_columns(FALSE); /* validate w_wrow */
}
wp->w_prev_fraction_row = wp->w_wrow;
win_comp_scroll(wp);
redraw_win_later(wp, SOME_VALID);
#ifdef FEAT_WINDOWS
wp->w_redr_status = TRUE;
#endif
invalidate_botline_win(wp);
}
#ifdef FEAT_VERTSPLIT
/*
* Set the width of a window.
*/
static void
win_new_width(wp, width)
win_T *wp;
int width;
{
wp->w_width = width;
wp->w_lines_valid = 0;
changed_line_abv_curs_win(wp);
invalidate_botline_win(wp);
if (wp == curwin)
{
update_topline();
curs_columns(TRUE); /* validate w_wrow */
}
redraw_win_later(wp, NOT_VALID);
wp->w_redr_status = TRUE;
}
#endif
void
win_comp_scroll(wp)
win_T *wp;
{
wp->w_p_scr = ((unsigned)wp->w_height >> 1);
if (wp->w_p_scr == 0)
wp->w_p_scr = 1;
}
/*
* command_height: called whenever p_ch has been changed
*/
void
command_height()
{
#ifdef FEAT_WINDOWS
int h;
frame_T *frp;
int old_p_ch = curtab->tp_ch_used;
/* Use the value of p_ch that we remembered. This is needed for when the
* GUI starts up, we can't be sure in what order things happen. And when
* p_ch was changed in another tab page. */
curtab->tp_ch_used = p_ch;
/* Find bottom frame with width of screen. */
frp = lastwin->w_frame;
# ifdef FEAT_VERTSPLIT
while (frp->fr_width != Columns && frp->fr_parent != NULL)
frp = frp->fr_parent;
# endif
/* Avoid changing the height of a window with 'winfixheight' set. */
while (frp->fr_prev != NULL && frp->fr_layout == FR_LEAF
&& frp->fr_win->w_p_wfh)
frp = frp->fr_prev;
if (starting != NO_SCREEN)
{
cmdline_row = Rows - p_ch;
if (p_ch > old_p_ch) /* p_ch got bigger */
{
while (p_ch > old_p_ch)
{
if (frp == NULL)
{
EMSG(_(e_noroom));
p_ch = old_p_ch;
curtab->tp_ch_used = p_ch;
cmdline_row = Rows - p_ch;
break;
}
h = frp->fr_height - frame_minheight(frp, NULL);
if (h > p_ch - old_p_ch)
h = p_ch - old_p_ch;
old_p_ch += h;
frame_add_height(frp, -h);
frp = frp->fr_prev;
}
/* Recompute window positions. */
(void)win_comp_pos();
/* clear the lines added to cmdline */
if (full_screen)
screen_fill((int)(cmdline_row), (int)Rows, 0,
(int)Columns, ' ', ' ', 0);
msg_row = cmdline_row;
redraw_cmdline = TRUE;
return;
}
if (msg_row < cmdline_row)
msg_row = cmdline_row;
redraw_cmdline = TRUE;
}
frame_add_height(frp, (int)(old_p_ch - p_ch));
/* Recompute window positions. */
if (frp != lastwin->w_frame)
(void)win_comp_pos();
#else
cmdline_row = Rows - p_ch;
win_setheight(cmdline_row);
#endif
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Resize frame "frp" to be "n" lines higher (negative for less high).
* Also resize the frames it is contained in.
*/
static void
frame_add_height(frp, n)
frame_T *frp;
int n;
{
frame_new_height(frp, frp->fr_height + n, FALSE, FALSE);
for (;;)
{
frp = frp->fr_parent;
if (frp == NULL)
break;
frp->fr_height += n;
}
}
/*
* Add or remove a status line for the bottom window(s), according to the
* value of 'laststatus'.
*/
void
last_status(morewin)
int morewin; /* pretend there are two or more windows */
{
/* Don't make a difference between horizontal or vertical split. */
last_status_rec(topframe, (p_ls == 2
|| (p_ls == 1 && (morewin || lastwin != firstwin))));
}
static void
last_status_rec(fr, statusline)
frame_T *fr;
int statusline;
{
frame_T *fp;
win_T *wp;
if (fr->fr_layout == FR_LEAF)
{
wp = fr->fr_win;
if (wp->w_status_height != 0 && !statusline)
{
/* remove status line */
win_new_height(wp, wp->w_height + 1);
wp->w_status_height = 0;
comp_col();
}
else if (wp->w_status_height == 0 && statusline)
{
/* Find a frame to take a line from. */
fp = fr;
while (fp->fr_height <= frame_minheight(fp, NULL))
{
if (fp == topframe)
{
EMSG(_(e_noroom));
return;
}
/* In a column of frames: go to frame above. If already at
* the top or in a row of frames: go to parent. */
if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL)
fp = fp->fr_prev;
else
fp = fp->fr_parent;
}
wp->w_status_height = 1;
if (fp != fr)
{
frame_new_height(fp, fp->fr_height - 1, FALSE, FALSE);
frame_fix_height(wp);
(void)win_comp_pos();
}
else
win_new_height(wp, wp->w_height - 1);
comp_col();
redraw_all_later(SOME_VALID);
}
}
#ifdef FEAT_VERTSPLIT
else if (fr->fr_layout == FR_ROW)
{
/* vertically split windows, set status line for each one */
for (fp = fr->fr_child; fp != NULL; fp = fp->fr_next)
last_status_rec(fp, statusline);
}
#endif
else
{
/* horizontally split window, set status line for last one */
for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next)
;
last_status_rec(fp, statusline);
}
}
/*
* Return the number of lines used by the tab page line.
*/
int
tabline_height()
{
#ifdef FEAT_GUI_TABLINE
/* When the GUI has the tabline then this always returns zero. */
if (gui_use_tabline())
return 0;
#endif
switch (p_stal)
{
case 0: return 0;
case 1: return (first_tabpage->tp_next == NULL) ? 0 : 1;
}
return 1;
}
#endif /* FEAT_WINDOWS */
#if defined(FEAT_SEARCHPATH) || defined(PROTO)
/*
* Get the file name at the cursor.
* If Visual mode is active, use the selected text if it's in one line.
* Returns the name in allocated memory, NULL for failure.
*/
char_u *
grab_file_name(count, file_lnum)
long count;
linenr_T *file_lnum;
{
# ifdef FEAT_VISUAL
if (VIsual_active)
{
int len;
char_u *ptr;
if (get_visual_text(NULL, &ptr, &len) == FAIL)
return NULL;
return find_file_name_in_path(ptr, len,
FNAME_MESS|FNAME_EXP|FNAME_REL, count, curbuf->b_ffname);
}
# endif
return file_name_at_cursor(FNAME_MESS|FNAME_HYP|FNAME_EXP|FNAME_REL, count,
file_lnum);
}
/*
* Return the file name under or after the cursor.
*
* The 'path' option is searched if the file name is not absolute.
* The string returned has been alloc'ed and should be freed by the caller.
* NULL is returned if the file name or file is not found.
*
* options:
* FNAME_MESS give error messages
* FNAME_EXP expand to path
* FNAME_HYP check for hypertext link
* FNAME_INCL apply "includeexpr"
*/
char_u *
file_name_at_cursor(options, count, file_lnum)
int options;
long count;
linenr_T *file_lnum;
{
return file_name_in_line(ml_get_curline(),
curwin->w_cursor.col, options, count, curbuf->b_ffname,
file_lnum);
}
/*
* Return the name of the file under or after ptr[col].
* Otherwise like file_name_at_cursor().
*/
char_u *
file_name_in_line(line, col, options, count, rel_fname, file_lnum)
char_u *line;
int col;
int options;
long count;
char_u *rel_fname; /* file we are searching relative to */
linenr_T *file_lnum; /* line number after the file name */
{
char_u *ptr;
int len;
/*
* search forward for what could be the start of a file name
*/
ptr = line + col;
while (*ptr != NUL && !vim_isfilec(*ptr))
mb_ptr_adv(ptr);
if (*ptr == NUL) /* nothing found */
{
if (options & FNAME_MESS)
EMSG(_("E446: No file name under cursor"));
return NULL;
}
/*
* Search backward for first char of the file name.
* Go one char back to ":" before "//" even when ':' is not in 'isfname'.
*/
while (ptr > line)
{
#ifdef FEAT_MBYTE
if (has_mbyte && (len = (*mb_head_off)(line, ptr - 1)) > 0)
ptr -= len + 1;
else
#endif
if (vim_isfilec(ptr[-1])
|| ((options & FNAME_HYP) && path_is_url(ptr - 1)))
--ptr;
else
break;
}
/*
* Search forward for the last char of the file name.
* Also allow "://" when ':' is not in 'isfname'.
*/
len = 0;
while (vim_isfilec(ptr[len])
|| ((options & FNAME_HYP) && path_is_url(ptr + len)))
#ifdef FEAT_MBYTE
if (has_mbyte)
len += (*mb_ptr2len)(ptr + len);
else
#endif
++len;
/*
* If there is trailing punctuation, remove it.
* But don't remove "..", could be a directory name.
*/
if (len > 2 && vim_strchr((char_u *)".,:;!", ptr[len - 1]) != NULL
&& ptr[len - 2] != '.')
--len;
if (file_lnum != NULL)
{
char_u *p;
/* Get the number after the file name and a separator character */
p = ptr + len;
p = skipwhite(p);
if (*p != NUL)
{
if (!isdigit(*p))
++p; /* skip the separator */
p = skipwhite(p);
if (isdigit(*p))
*file_lnum = (int)getdigits(&p);
}
}
return find_file_name_in_path(ptr, len, options, count, rel_fname);
}
# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
static char_u *eval_includeexpr __ARGS((char_u *ptr, int len));
static char_u *
eval_includeexpr(ptr, len)
char_u *ptr;
int len;
{
char_u *res;
set_vim_var_string(VV_FNAME, ptr, len);
res = eval_to_string_safe(curbuf->b_p_inex, NULL,
was_set_insecurely((char_u *)"includeexpr", OPT_LOCAL));
set_vim_var_string(VV_FNAME, NULL, 0);
return res;
}
#endif
/*
* Return the name of the file ptr[len] in 'path'.
* Otherwise like file_name_at_cursor().
*/
char_u *
find_file_name_in_path(ptr, len, options, count, rel_fname)
char_u *ptr;
int len;
int options;
long count;
char_u *rel_fname; /* file we are searching relative to */
{
char_u *file_name;
int c;
# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
char_u *tofree = NULL;
if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
{
tofree = eval_includeexpr(ptr, len);
if (tofree != NULL)
{
ptr = tofree;
len = (int)STRLEN(ptr);
}
}
# endif
if (options & FNAME_EXP)
{
file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
TRUE, rel_fname);
# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
/*
* If the file could not be found in a normal way, try applying
* 'includeexpr' (unless done already).
*/
if (file_name == NULL
&& !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
{
tofree = eval_includeexpr(ptr, len);
if (tofree != NULL)
{
ptr = tofree;
len = (int)STRLEN(ptr);
file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
TRUE, rel_fname);
}
}
# endif
if (file_name == NULL && (options & FNAME_MESS))
{
c = ptr[len];
ptr[len] = NUL;
EMSG2(_("E447: Can't find file \"%s\" in path"), ptr);
ptr[len] = c;
}
/* Repeat finding the file "count" times. This matters when it
* appears several times in the path. */
while (file_name != NULL && --count > 0)
{
vim_free(file_name);
file_name = find_file_in_path(ptr, len, options, FALSE, rel_fname);
}
}
else
file_name = vim_strnsave(ptr, len);
# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
vim_free(tofree);
# endif
return file_name;
}
#endif /* FEAT_SEARCHPATH */
/*
* Check if the "://" of a URL is at the pointer, return URL_SLASH.
* Also check for ":\\", which MS Internet Explorer accepts, return
* URL_BACKSLASH.
*/
static int
path_is_url(p)
char_u *p;
{
if (STRNCMP(p, "://", (size_t)3) == 0)
return URL_SLASH;
else if (STRNCMP(p, ":\\\\", (size_t)3) == 0)
return URL_BACKSLASH;
return 0;
}
/*
* Check if "fname" starts with "name://". Return URL_SLASH if it does.
* Return URL_BACKSLASH for "name:\\".
* Return zero otherwise.
*/
int
path_with_url(fname)
char_u *fname;
{
char_u *p;
for (p = fname; isalpha(*p); ++p)
;
return path_is_url(p);
}
/*
* Return TRUE if "name" is a full (absolute) path name or URL.
*/
int
vim_isAbsName(name)
char_u *name;
{
return (path_with_url(name) != 0 || mch_isFullName(name));
}
/*
* Get absolute file name into buffer "buf[len]".
*
* return FAIL for failure, OK otherwise
*/
int
vim_FullName(fname, buf, len, force)
char_u *fname, *buf;
int len;
int force; /* force expansion even when already absolute */
{
int retval = OK;
int url;
*buf = NUL;
if (fname == NULL)
return FAIL;
url = path_with_url(fname);
if (!url)
retval = mch_FullName(fname, buf, len, force);
if (url || retval == FAIL)
{
/* something failed; use the file name (truncate when too long) */
vim_strncpy(buf, fname, len - 1);
}
#if defined(MACOS_CLASSIC) || defined(OS2) || defined(MSDOS) || defined(MSWIN)
slash_adjust(buf);
#endif
return retval;
}
/*
* Return the minimal number of rows that is needed on the screen to display
* the current number of windows.
*/
int
min_rows()
{
int total;
#ifdef FEAT_WINDOWS
tabpage_T *tp;
int n;
#endif
if (firstwin == NULL) /* not initialized yet */
return MIN_LINES;
#ifdef FEAT_WINDOWS
total = 0;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
{
n = frame_minheight(tp->tp_topframe, NULL);
if (total < n)
total = n;
}
total += tabline_height();
#else
total = 1; /* at least one window should have a line! */
#endif
total += 1; /* count the room for the command line */
return total;
}
/*
* Return TRUE if there is only one window (in the current tab page), not
* counting a help or preview window, unless it is the current window.
* Does not count "aucmd_win".
*/
int
only_one_window()
{
#ifdef FEAT_WINDOWS
int count = 0;
win_T *wp;
/* If there is another tab page there always is another window. */
if (first_tabpage->tp_next != NULL)
return FALSE;
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if ((!((wp->w_buffer->b_help && !curbuf->b_help)
# ifdef FEAT_QUICKFIX
|| wp->w_p_pvw
# endif
) || wp == curwin)
# ifdef FEAT_AUTOCMD
&& wp != aucmd_win
# endif
)
++count;
return (count <= 1);
#else
return TRUE;
#endif
}
#if defined(FEAT_WINDOWS) || defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* Correct the cursor line number in other windows. Used after changing the
* current buffer, and before applying autocommands.
* When "do_curwin" is TRUE, also check current window.
*/
void
check_lnums(do_curwin)
int do_curwin;
{
win_T *wp;
#ifdef FEAT_WINDOWS
tabpage_T *tp;
FOR_ALL_TAB_WINDOWS(tp, wp)
if ((do_curwin || wp != curwin) && wp->w_buffer == curbuf)
#else
wp = curwin;
if (do_curwin)
#endif
{
if (wp->w_cursor.lnum > curbuf->b_ml.ml_line_count)
wp->w_cursor.lnum = curbuf->b_ml.ml_line_count;
if (wp->w_topline > curbuf->b_ml.ml_line_count)
wp->w_topline = curbuf->b_ml.ml_line_count;
}
}
#endif
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* A snapshot of the window sizes, to restore them after closing the help
* window.
* Only these fields are used:
* fr_layout
* fr_width
* fr_height
* fr_next
* fr_child
* fr_win (only valid for the old curwin, NULL otherwise)
*/
/*
* Create a snapshot of the current frame sizes.
*/
void
make_snapshot(idx)
int idx;
{
clear_snapshot(curtab, idx);
make_snapshot_rec(topframe, &curtab->tp_snapshot[idx]);
}
static void
make_snapshot_rec(fr, frp)
frame_T *fr;
frame_T **frp;
{
*frp = (frame_T *)alloc_clear((unsigned)sizeof(frame_T));
if (*frp == NULL)
return;
(*frp)->fr_layout = fr->fr_layout;
# ifdef FEAT_VERTSPLIT
(*frp)->fr_width = fr->fr_width;
# endif
(*frp)->fr_height = fr->fr_height;
if (fr->fr_next != NULL)
make_snapshot_rec(fr->fr_next, &((*frp)->fr_next));
if (fr->fr_child != NULL)
make_snapshot_rec(fr->fr_child, &((*frp)->fr_child));
if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin)
(*frp)->fr_win = curwin;
}
/*
* Remove any existing snapshot.
*/
static void
clear_snapshot(tp, idx)
tabpage_T *tp;
int idx;
{
clear_snapshot_rec(tp->tp_snapshot[idx]);
tp->tp_snapshot[idx] = NULL;
}
static void
clear_snapshot_rec(fr)
frame_T *fr;
{
if (fr != NULL)
{
clear_snapshot_rec(fr->fr_next);
clear_snapshot_rec(fr->fr_child);
vim_free(fr);
}
}
/*
* Restore a previously created snapshot, if there is any.
* This is only done if the screen size didn't change and the window layout is
* still the same.
*/
void
restore_snapshot(idx, close_curwin)
int idx;
int close_curwin; /* closing current window */
{
win_T *wp;
if (curtab->tp_snapshot[idx] != NULL
# ifdef FEAT_VERTSPLIT
&& curtab->tp_snapshot[idx]->fr_width == topframe->fr_width
# endif
&& curtab->tp_snapshot[idx]->fr_height == topframe->fr_height
&& check_snapshot_rec(curtab->tp_snapshot[idx], topframe) == OK)
{
wp = restore_snapshot_rec(curtab->tp_snapshot[idx], topframe);
win_comp_pos();
if (wp != NULL && close_curwin)
win_goto(wp);
redraw_all_later(CLEAR);
}
clear_snapshot(curtab, idx);
}
/*
* Check if frames "sn" and "fr" have the same layout, same following frames
* and same children.
*/
static int
check_snapshot_rec(sn, fr)
frame_T *sn;
frame_T *fr;
{
if (sn->fr_layout != fr->fr_layout
|| (sn->fr_next == NULL) != (fr->fr_next == NULL)
|| (sn->fr_child == NULL) != (fr->fr_child == NULL)
|| (sn->fr_next != NULL
&& check_snapshot_rec(sn->fr_next, fr->fr_next) == FAIL)
|| (sn->fr_child != NULL
&& check_snapshot_rec(sn->fr_child, fr->fr_child) == FAIL))
return FAIL;
return OK;
}
/*
* Copy the size of snapshot frame "sn" to frame "fr". Do the same for all
* following frames and children.
* Returns a pointer to the old current window, or NULL.
*/
static win_T *
restore_snapshot_rec(sn, fr)
frame_T *sn;
frame_T *fr;
{
win_T *wp = NULL;
win_T *wp2;
fr->fr_height = sn->fr_height;
# ifdef FEAT_VERTSPLIT
fr->fr_width = sn->fr_width;
# endif
if (fr->fr_layout == FR_LEAF)
{
frame_new_height(fr, fr->fr_height, FALSE, FALSE);
# ifdef FEAT_VERTSPLIT
frame_new_width(fr, fr->fr_width, FALSE, FALSE);
# endif
wp = sn->fr_win;
}
if (sn->fr_next != NULL)
{
wp2 = restore_snapshot_rec(sn->fr_next, fr->fr_next);
if (wp2 != NULL)
wp = wp2;
}
if (sn->fr_child != NULL)
{
wp2 = restore_snapshot_rec(sn->fr_child, fr->fr_child);
if (wp2 != NULL)
wp = wp2;
}
return wp;
}
#endif
#if (defined(FEAT_GUI) && defined(FEAT_VERTSPLIT)) || defined(PROTO)
/*
* Return TRUE if there is any vertically split window.
*/
int
win_hasvertsplit()
{
frame_T *fr;
if (topframe->fr_layout == FR_ROW)
return TRUE;
if (topframe->fr_layout == FR_COL)
for (fr = topframe->fr_child; fr != NULL; fr = fr->fr_next)
if (fr->fr_layout == FR_ROW)
return TRUE;
return FALSE;
}
#endif
#if defined(FEAT_SEARCH_EXTRA) || defined(PROTO)
/*
* Add match to the match list of window 'wp'. The pattern 'pat' will be
* highlighted with the group 'grp' with priority 'prio'.
* Optionally, a desired ID 'id' can be specified (greater than or equal to 1).
* If no particular ID is desired, -1 must be specified for 'id'.
* Return ID of added match, -1 on failure.
*/
int
match_add(wp, grp, pat, prio, id)
win_T *wp;
char_u *grp;
char_u *pat;
int prio;
int id;
{
matchitem_T *cur;
matchitem_T *prev;
matchitem_T *m;
int hlg_id;
regprog_T *regprog;
if (*grp == NUL || *pat == NUL)
return -1;
if (id < -1 || id == 0)
{
EMSGN("E799: Invalid ID: %ld (must be greater than or equal to 1)", id);
return -1;
}
if (id != -1)
{
cur = wp->w_match_head;
while (cur != NULL)
{
if (cur->id == id)
{
EMSGN("E801: ID already taken: %ld", id);
return -1;
}
cur = cur->next;
}
}
if ((hlg_id = syn_namen2id(grp, (int)STRLEN(grp))) == 0)
{
EMSG2(_(e_nogroup), grp);
return -1;
}
if ((regprog = vim_regcomp(pat, RE_MAGIC)) == NULL)
{
EMSG2(_(e_invarg2), pat);
return -1;
}
/* Find available match ID. */
while (id == -1)
{
cur = wp->w_match_head;
while (cur != NULL && cur->id != wp->w_next_match_id)
cur = cur->next;
if (cur == NULL)
id = wp->w_next_match_id;
wp->w_next_match_id++;
}
/* Build new match. */
m = (matchitem_T *)alloc(sizeof(matchitem_T));
m->id = id;
m->priority = prio;
m->pattern = vim_strsave(pat);
m->hlg_id = hlg_id;
m->match.regprog = regprog;
m->match.rmm_ic = FALSE;
m->match.rmm_maxcol = 0;
/* Insert new match. The match list is in ascending order with regard to
* the match priorities. */
cur = wp->w_match_head;
prev = cur;
while (cur != NULL && prio >= cur->priority)
{
prev = cur;
cur = cur->next;
}
if (cur == prev)
wp->w_match_head = m;
else
prev->next = m;
m->next = cur;
redraw_later(SOME_VALID);
return id;
}
/*
* Delete match with ID 'id' in the match list of window 'wp'.
* Print error messages if 'perr' is TRUE.
*/
int
match_delete(wp, id, perr)
win_T *wp;
int id;
int perr;
{
matchitem_T *cur = wp->w_match_head;
matchitem_T *prev = cur;
if (id < 1)
{
if (perr == TRUE)
EMSGN("E802: Invalid ID: %ld (must be greater than or equal to 1)",
id);
return -1;
}
while (cur != NULL && cur->id != id)
{
prev = cur;
cur = cur->next;
}
if (cur == NULL)
{
if (perr == TRUE)
EMSGN("E803: ID not found: %ld", id);
return -1;
}
if (cur == prev)
wp->w_match_head = cur->next;
else
prev->next = cur->next;
vim_free(cur->match.regprog);
vim_free(cur->pattern);
vim_free(cur);
redraw_later(SOME_VALID);
return 0;
}
/*
* Delete all matches in the match list of window 'wp'.
*/
void
clear_matches(wp)
win_T *wp;
{
matchitem_T *m;
while (wp->w_match_head != NULL)
{
m = wp->w_match_head->next;
vim_free(wp->w_match_head->match.regprog);
vim_free(wp->w_match_head->pattern);
vim_free(wp->w_match_head);
wp->w_match_head = m;
}
redraw_later(SOME_VALID);
}
/*
* Get match from ID 'id' in window 'wp'.
* Return NULL if match not found.
*/
matchitem_T *
get_match(wp, id)
win_T *wp;
int id;
{
matchitem_T *cur = wp->w_match_head;
while (cur != NULL && cur->id != id)
cur = cur->next;
return cur;
}
#endif
| zyz2011-vim | src/window.c | C | gpl2 | 156,216 |
/* 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.
*/
#if defined(FEAT_OLE) && defined(FEAT_GUI_W32)
/*
* OLE server implementation.
*
* See os_mswin.c for the client side.
*/
/*
* We have some trouble with order of includes here. For Borland it needs to
* be different from MSVC...
*/
#ifndef __BORLANDC__
extern "C" {
# include "vim.h"
}
#endif
#include <windows.h>
#include <oleauto.h>
extern "C" {
#ifdef __BORLANDC__
# include "vim.h"
#endif
extern HWND s_hwnd;
extern HWND vim_parent_hwnd;
}
#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
#include "if_ole.h" // Interface definitions
#include "iid_ole.c" // UUID definitions (compile here)
/* Supply function prototype to work around bug in Mingw oleauto.h header */
#ifdef __MINGW32__
WINOLEAUTAPI UnRegisterTypeLib(REFGUID libID, WORD wVerMajor,
WORD wVerMinor, LCID lcid, SYSKIND syskind);
#endif
/*****************************************************************************
1. Internal definitions for this file
*****************************************************************************/
class CVim;
class CVimCF;
/* Internal data */
// The identifier of the registered class factory
static unsigned long cf_id = 0;
// The identifier of the running application object
static unsigned long app_id = 0;
// The single global instance of the class factory
static CVimCF *cf = 0;
// The single global instance of the application object
static CVim *app = 0;
/* GUIDs, versions and type library information */
#define MYCLSID CLSID_Vim
#define MYLIBID LIBID_Vim
#define MYIID IID_IVim
#define MAJORVER 1
#define MINORVER 0
#define LOCALE 0x0409
#define MYNAME "Vim"
#define MYPROGID "Vim.Application.1"
#define MYVIPROGID "Vim.Application"
#define MAX_CLSID_LEN 100
/*****************************************************************************
2. The application object
*****************************************************************************/
/* Definition
* ----------
*/
class CVim : public IVim
{
public:
~CVim();
static CVim *Create(int *pbDoRestart);
// IUnknown members
STDMETHOD(QueryInterface)(REFIID riid, void ** ppv);
STDMETHOD_(unsigned long, AddRef)(void);
STDMETHOD_(unsigned long, Release)(void);
// IDispatch members
STDMETHOD(GetTypeInfoCount)(UINT *pCount);
STDMETHOD(GetTypeInfo)(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo);
STDMETHOD(GetIDsOfNames)(const IID &iid, OLECHAR **names, UINT n, LCID, DISPID *dispids);
STDMETHOD(Invoke)(DISPID member, const IID &iid, LCID, WORD flags, DISPPARAMS *dispparams, VARIANT *result, EXCEPINFO *excepinfo, UINT *argerr);
// IVim members
STDMETHOD(SendKeys)(BSTR keys);
STDMETHOD(Eval)(BSTR expr, BSTR *result);
STDMETHOD(SetForeground)(void);
STDMETHOD(GetHwnd)(UINT_PTR *result);
private:
// Constructor is private - create using CVim::Create()
CVim() : ref(0), typeinfo(0) {};
// Reference count
unsigned long ref;
// The object's TypeInfo
ITypeInfo *typeinfo;
};
/* Implementation
* --------------
*/
CVim *CVim::Create(int *pbDoRestart)
{
HRESULT hr;
CVim *me = 0;
ITypeLib *typelib = 0;
ITypeInfo *typeinfo = 0;
*pbDoRestart = FALSE;
// Create the object
me = new CVim();
if (me == NULL)
{
MessageBox(0, "Cannot create application object", "Vim Initialisation", 0);
return NULL;
}
// Load the type library from the registry
hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib);
if (FAILED(hr))
{
HKEY hKey;
// Check we can write to the registry.
// RegCreateKeyEx succeeds even if key exists. W.Briscoe W2K 20021011
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, MYVIPROGID, 0, NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hKey, NULL))
{
delete me;
return NULL; // Unable to write to registry. Quietly fail.
}
RegCloseKey(hKey);
if (MessageBox(0, "Cannot load registered type library.\nDo you want to register Vim now?",
"Vim Initialisation", MB_YESNO | MB_ICONQUESTION) != IDYES)
{
delete me;
return NULL;
}
RegisterMe(FALSE);
// Load the type library from the registry
hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib);
if (FAILED(hr))
{
MessageBox(0, "You must restart Vim in order for the registration to take effect.",
"Vim Initialisation", 0);
*pbDoRestart = TRUE;
delete me;
return NULL;
}
}
// Get the type info of the vtable interface
hr = typelib->GetTypeInfoOfGuid(MYIID, &typeinfo);
typelib->Release();
if (FAILED(hr))
{
MessageBox(0, "Cannot get interface type information",
"Vim Initialisation", 0);
delete me;
return NULL;
}
// Save the type information
me->typeinfo = typeinfo;
return me;
}
CVim::~CVim()
{
if (typeinfo && vim_parent_hwnd == NULL)
typeinfo->Release();
typeinfo = 0;
}
STDMETHODIMP
CVim::QueryInterface(REFIID riid, void **ppv)
{
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDispatch) || IsEqualIID(riid, MYIID))
{
AddRef();
*ppv = this;
return S_OK;
}
*ppv = 0;
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG)
CVim::AddRef()
{
return ++ref;
}
STDMETHODIMP_(ULONG)
CVim::Release()
{
// Don't delete the object when the reference count reaches zero, as there
// is only a single application object, and its lifetime is controlled by
// the running instance, not by its reference count.
if (ref > 0)
--ref;
return ref;
}
STDMETHODIMP
CVim::GetTypeInfoCount(UINT *pCount)
{
*pCount = 1;
return S_OK;
}
STDMETHODIMP
CVim::GetTypeInfo(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo)
{
*ppITypeInfo = 0;
if (iTypeInfo != 0)
return DISP_E_BADINDEX;
typeinfo->AddRef();
*ppITypeInfo = typeinfo;
return S_OK;
}
STDMETHODIMP
CVim::GetIDsOfNames(
const IID &iid,
OLECHAR **names,
UINT n,
LCID,
DISPID *dispids)
{
if (iid != IID_NULL)
return DISP_E_UNKNOWNINTERFACE;
return typeinfo->GetIDsOfNames(names, n, dispids);
}
STDMETHODIMP
CVim::Invoke(
DISPID member,
const IID &iid,
LCID,
WORD flags,
DISPPARAMS *dispparams,
VARIANT *result,
EXCEPINFO *excepinfo,
UINT *argerr)
{
if (iid != IID_NULL)
return DISP_E_UNKNOWNINTERFACE;
::SetErrorInfo(0, NULL);
return typeinfo->Invoke(static_cast<IDispatch*>(this),
member, flags, dispparams,
result, excepinfo, argerr);
}
STDMETHODIMP
CVim::GetHwnd(UINT_PTR *result)
{
*result = (UINT_PTR)s_hwnd;
return S_OK;
}
STDMETHODIMP
CVim::SetForeground(void)
{
/* Make the Vim window come to the foreground */
gui_mch_set_foreground();
return S_OK;
}
STDMETHODIMP
CVim::SendKeys(BSTR keys)
{
int len;
char *buffer;
char_u *str;
char_u *ptr;
/* Get a suitable buffer */
len = WideCharToMultiByte(CP_ACP, 0, keys, -1, 0, 0, 0, 0);
buffer = (char *)alloc(len+1);
if (buffer == NULL)
return E_OUTOFMEMORY;
len = WideCharToMultiByte(CP_ACP, 0, keys, -1, buffer, len, 0, 0);
if (len == 0)
{
vim_free(buffer);
return E_INVALIDARG;
}
/* Translate key codes like <Esc> */
str = replace_termcodes((char_u *)buffer, &ptr, FALSE, TRUE, FALSE);
/* If ptr was set, then a new buffer was allocated,
* so we can free the old one.
*/
if (ptr)
vim_free((char_u *)(buffer));
/* Reject strings too long to fit in the input buffer. Allow 10 bytes
* space to cover for the (remote) possibility that characters may enter
* the input buffer between now and when the WM_OLE message is actually
* processed. If more that 10 characters enter the input buffer in that
* time, the WM_OLE processing will simply fail to insert the characters.
*/
if ((int)(STRLEN(str)) > (vim_free_in_input_buf() - 10))
{
vim_free(str);
return E_INVALIDARG;
}
/* Pass the string to the main input loop. The memory will be freed when
* the message is processed. Except for an empty message, we don't need
* to post it then.
*/
if (*str == NUL)
vim_free(str);
else
PostMessage(NULL, WM_OLE, 0, (LPARAM)str);
return S_OK;
}
STDMETHODIMP
CVim::Eval(BSTR expr, BSTR *result)
{
#ifdef FEAT_EVAL
int len;
char *buffer;
char *str;
wchar_t *w_buffer;
/* Get a suitable buffer */
len = WideCharToMultiByte(CP_ACP, 0, expr, -1, 0, 0, 0, 0);
if (len == 0)
return E_INVALIDARG;
buffer = (char *)alloc((unsigned)len);
if (buffer == NULL)
return E_OUTOFMEMORY;
/* Convert the (wide character) expression to an ASCII string */
len = WideCharToMultiByte(CP_ACP, 0, expr, -1, buffer, len, 0, 0);
if (len == 0)
return E_INVALIDARG;
/* Evaluate the expression */
++emsg_skip;
str = (char *)eval_to_string((char_u *)buffer, NULL, TRUE);
--emsg_skip;
vim_free(buffer);
if (str == NULL)
return E_FAIL;
/* Convert the result to wide characters */
MultiByteToWideChar_alloc(CP_ACP, 0, str, -1, &w_buffer, &len);
vim_free(str);
if (w_buffer == NULL)
return E_OUTOFMEMORY;
if (len == 0)
{
vim_free(w_buffer);
return E_FAIL;
}
/* Store the result */
*result = SysAllocString(w_buffer);
vim_free(w_buffer);
return S_OK;
#else
return E_NOTIMPL;
#endif
}
/*****************************************************************************
3. The class factory
*****************************************************************************/
/* Definition
* ----------
*/
class CVimCF : public IClassFactory
{
public:
static CVimCF *Create();
STDMETHOD(QueryInterface)(REFIID riid, void ** ppv);
STDMETHOD_(unsigned long, AddRef)(void);
STDMETHOD_(unsigned long, Release)(void);
STDMETHOD(CreateInstance)(IUnknown *punkOuter, REFIID riid, void ** ppv);
STDMETHOD(LockServer)(BOOL lock);
private:
// Constructor is private - create via Create()
CVimCF() : ref(0) {};
// Reference count
unsigned long ref;
};
/* Implementation
* --------------
*/
CVimCF *CVimCF::Create()
{
CVimCF *me = new CVimCF();
if (me == NULL)
MessageBox(0, "Cannot create class factory", "Vim Initialisation", 0);
return me;
}
STDMETHODIMP
CVimCF::QueryInterface(REFIID riid, void **ppv)
{
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
{
AddRef();
*ppv = this;
return S_OK;
}
*ppv = 0;
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG)
CVimCF::AddRef()
{
return ++ref;
}
STDMETHODIMP_(ULONG)
CVimCF::Release()
{
// Don't delete the object when the reference count reaches zero, as there
// is only a single application object, and its lifetime is controlled by
// the running instance, not by its reference count.
if (ref > 0)
--ref;
return ref;
}
/*ARGSUSED*/
STDMETHODIMP
CVimCF::CreateInstance(IUnknown *punkOuter, REFIID riid, void **ppv)
{
return app->QueryInterface(riid, ppv);
}
/*ARGSUSED*/
STDMETHODIMP
CVimCF::LockServer(BOOL lock)
{
return S_OK;
}
/*****************************************************************************
4. Registry manipulation code
*****************************************************************************/
// Internal use only
static void SetKeyAndValue(const char *path, const char *subkey, const char *value);
static void GUIDtochar(const GUID &guid, char *GUID, int length);
static void RecursiveDeleteKey(HKEY hKeyParent, const char *child);
static const int GUID_STRING_SIZE = 39;
// Register the component in the registry
// When "silent" is TRUE don't give any messages.
extern "C" void RegisterMe(int silent)
{
BOOL ok = TRUE;
// Get the application startup command
char module[MAX_PATH];
::GetModuleFileName(NULL, module, MAX_PATH);
// Unregister first (quietly)
UnregisterMe(FALSE);
// Convert the CLSID into a char
char clsid[GUID_STRING_SIZE];
GUIDtochar(MYCLSID, clsid, sizeof(clsid));
// Convert the LIBID into a char
char libid[GUID_STRING_SIZE];
GUIDtochar(MYLIBID, libid, sizeof(libid));
// Build the key CLSID\\{...}
char Key[MAX_CLSID_LEN];
strcpy(Key, "CLSID\\");
strcat(Key, clsid);
// Add the CLSID to the registry
SetKeyAndValue(Key, NULL, MYNAME);
SetKeyAndValue(Key, "LocalServer32", module);
SetKeyAndValue(Key, "ProgID", MYPROGID);
SetKeyAndValue(Key, "VersionIndependentProgID", MYVIPROGID);
SetKeyAndValue(Key, "TypeLib", libid);
// Add the version-independent ProgID subkey under HKEY_CLASSES_ROOT
SetKeyAndValue(MYVIPROGID, NULL, MYNAME);
SetKeyAndValue(MYVIPROGID, "CLSID", clsid);
SetKeyAndValue(MYVIPROGID, "CurVer", MYPROGID);
// Add the versioned ProgID subkey under HKEY_CLASSES_ROOT
SetKeyAndValue(MYPROGID, NULL, MYNAME);
SetKeyAndValue(MYPROGID, "CLSID", clsid);
wchar_t w_module[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, module, -1, w_module, MAX_PATH);
ITypeLib *typelib = NULL;
if (LoadTypeLib(w_module, &typelib) != S_OK)
{
if (!silent)
MessageBox(0, "Cannot load type library to register",
"Vim Registration", 0);
ok = FALSE;
}
else
{
if (RegisterTypeLib(typelib, w_module, NULL) != S_OK)
{
if (!silent)
MessageBox(0, "Cannot register type library",
"Vim Registration", 0);
ok = FALSE;
}
typelib->Release();
}
if (ok && !silent)
MessageBox(0, "Registered successfully", "Vim", 0);
}
// Remove the component from the registry
//
// Note: There is little error checking in this code, to allow incomplete
// or failed registrations to be undone.
extern "C" void UnregisterMe(int bNotifyUser)
{
// Unregister the type library
ITypeLib *typelib;
if (SUCCEEDED(LoadRegTypeLib(MYLIBID, MAJORVER, MINORVER, LOCALE, &typelib)))
{
TLIBATTR *tla;
if (SUCCEEDED(typelib->GetLibAttr(&tla)))
{
UnRegisterTypeLib(tla->guid, tla->wMajorVerNum, tla->wMinorVerNum,
tla->lcid, tla->syskind);
typelib->ReleaseTLibAttr(tla);
}
typelib->Release();
}
// Convert the CLSID into a char
char clsid[GUID_STRING_SIZE];
GUIDtochar(MYCLSID, clsid, sizeof(clsid));
// Build the key CLSID\\{...}
char Key[MAX_CLSID_LEN];
strcpy(Key, "CLSID\\");
strcat(Key, clsid);
// Delete the CLSID Key - CLSID\{...}
RecursiveDeleteKey(HKEY_CLASSES_ROOT, Key);
// Delete the version-independent ProgID Key
RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYVIPROGID);
// Delete the ProgID key
RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYPROGID);
if (bNotifyUser)
MessageBox(0, "Unregistered successfully", "Vim", 0);
}
/****************************************************************************/
// Convert a GUID to a char string
static void GUIDtochar(const GUID &guid, char *GUID, int length)
{
// Get wide string version
LPOLESTR wGUID = NULL;
StringFromCLSID(guid, &wGUID);
// Covert from wide characters to non-wide
wcstombs(GUID, wGUID, length);
// Free memory
CoTaskMemFree(wGUID);
}
// Delete a key and all of its descendents
static void RecursiveDeleteKey(HKEY hKeyParent, const char *child)
{
// Open the child
HKEY hKeyChild;
LONG result = RegOpenKeyEx(hKeyParent, child, 0,
KEY_ALL_ACCESS, &hKeyChild);
if (result != ERROR_SUCCESS)
return;
// Enumerate all of the decendents of this child
FILETIME time;
char buffer[1024];
DWORD size = 1024;
while (RegEnumKeyEx(hKeyChild, 0, buffer, &size, NULL,
NULL, NULL, &time) == S_OK)
{
// Delete the decendents of this child
RecursiveDeleteKey(hKeyChild, buffer);
size = 256;
}
// Close the child
RegCloseKey(hKeyChild);
// Delete this child
RegDeleteKey(hKeyParent, child);
}
// Create a key and set its value
static void SetKeyAndValue(const char *key, const char *subkey, const char *value)
{
HKEY hKey;
char buffer[1024];
strcpy(buffer, key);
// Add subkey name to buffer.
if (subkey)
{
strcat(buffer, "\\");
strcat(buffer, subkey);
}
// Create and open key and subkey.
long result = RegCreateKeyEx(HKEY_CLASSES_ROOT,
buffer,
0, NULL, REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL,
&hKey, NULL);
if (result != ERROR_SUCCESS)
return;
// Set the value
if (value)
RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *)value,
(DWORD)STRLEN(value)+1);
RegCloseKey(hKey);
}
/*****************************************************************************
5. OLE Initialisation and shutdown processing
*****************************************************************************/
extern "C" void InitOLE(int *pbDoRestart)
{
HRESULT hr;
*pbDoRestart = FALSE;
// Initialize the OLE libraries
hr = OleInitialize(NULL);
if (FAILED(hr))
{
MessageBox(0, "Cannot initialise OLE", "Vim Initialisation", 0);
goto error0;
}
// Create the application object
app = CVim::Create(pbDoRestart);
if (app == NULL)
goto error1;
// Create the class factory
cf = CVimCF::Create();
if (cf == NULL)
goto error1;
// Register the class factory
hr = CoRegisterClassObject(
MYCLSID,
cf,
CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE,
&cf_id);
if (FAILED(hr))
{
MessageBox(0, "Cannot register class factory", "Vim Initialisation", 0);
goto error1;
}
// Register the application object as active
hr = RegisterActiveObject(
app,
MYCLSID,
NULL,
&app_id);
if (FAILED(hr))
{
MessageBox(0, "Cannot register application object", "Vim Initialisation", 0);
goto error1;
}
return;
// Errors: tidy up as much as needed and return
error1:
UninitOLE();
error0:
return;
}
extern "C" void UninitOLE()
{
// Unregister the application object
if (app_id)
{
RevokeActiveObject(app_id, NULL);
app_id = 0;
}
// Unregister the class factory
if (cf_id)
{
CoRevokeClassObject(cf_id);
cf_id = 0;
}
// Shut down the OLE libraries
OleUninitialize();
// Delete the application object
if (app)
{
delete app;
app = NULL;
}
// Delete the class factory
if (cf)
{
delete cf;
cf = NULL;
}
}
#endif /* FEAT_OLE */
| zyz2011-vim | src/if_ole.cpp | C++ | gpl2 | 18,542 |
/* 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.
*/
#include "vim.h"
/* Structure containing all the GUI information */
gui_T gui;
#if defined(FEAT_MBYTE) && !defined(FEAT_GUI_GTK)
static void set_guifontwide __ARGS((char_u *font_name));
#endif
static void gui_check_pos __ARGS((void));
static void gui_position_components __ARGS((int));
static void gui_outstr __ARGS((char_u *, int));
static int gui_screenchar __ARGS((int off, int flags, guicolor_T fg, guicolor_T bg, int back));
#ifdef FEAT_GUI_GTK
static int gui_screenstr __ARGS((int off, int len, int flags, guicolor_T fg, guicolor_T bg, int back));
#endif
static void gui_delete_lines __ARGS((int row, int count));
static void gui_insert_lines __ARGS((int row, int count));
static void fill_mouse_coord __ARGS((char_u *p, int col, int row));
#if defined(FEAT_GUI_TABLINE) || defined(PROTO)
static int gui_has_tabline __ARGS((void));
#endif
static void gui_do_scrollbar __ARGS((win_T *wp, int which, int enable));
static colnr_T scroll_line_len __ARGS((linenr_T lnum));
static linenr_T gui_find_longest_lnum __ARGS((void));
static void gui_update_horiz_scrollbar __ARGS((int));
static void gui_set_fg_color __ARGS((char_u *name));
static void gui_set_bg_color __ARGS((char_u *name));
static win_T *xy2win __ARGS((int x, int y));
#if defined(UNIX) && !defined(__BEOS__) && !defined(MACOS_X) \
&& !defined(__APPLE__)
# define MAY_FORK
static void gui_do_fork __ARGS((void));
static int gui_read_child_pipe __ARGS((int fd));
/* Return values for gui_read_child_pipe */
enum {
GUI_CHILD_IO_ERROR,
GUI_CHILD_OK,
GUI_CHILD_FAILED
};
#endif /* MAY_FORK */
static void gui_attempt_start __ARGS((void));
static int can_update_cursor = TRUE; /* can display the cursor */
/*
* The Athena scrollbars can move the thumb to after the end of the scrollbar,
* this makes the thumb indicate the part of the text that is shown. Motif
* can't do this.
*/
#if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MAC)
# define SCROLL_PAST_END
#endif
/*
* gui_start -- Called when user wants to start the GUI.
*
* Careful: This function can be called recursively when there is a ":gui"
* command in the .gvimrc file. Only the first call should fork, not the
* recursive call.
*/
void
gui_start()
{
char_u *old_term;
static int recursive = 0;
old_term = vim_strsave(T_NAME);
settmode(TMODE_COOK); /* stop RAW mode */
if (full_screen)
cursor_on(); /* needed for ":gui" in .vimrc */
full_screen = FALSE;
++recursive;
#ifdef MAY_FORK
/*
* Quit the current process and continue in the child.
* Makes "gvim file" disconnect from the shell it was started in.
* Don't do this when Vim was started with "-f" or the 'f' flag is present
* in 'guioptions'.
*/
if (gui.dofork && !vim_strchr(p_go, GO_FORG) && recursive <= 1)
{
gui_do_fork();
}
else
#endif
{
#ifdef FEAT_GUI_GTK
/* If there is 'f' in 'guioptions' and specify -g argument,
* gui_mch_init_check() was not called yet. */
if (gui_mch_init_check() != OK)
exit(1);
#endif
gui_attempt_start();
}
if (!gui.in_use) /* failed to start GUI */
{
/* Back to old term settings
*
* FIXME: If we got here because a child process failed and flagged to
* the parent to resume, and X11 is enabled with FEAT_TITLE, this will
* hit an X11 I/O error and do a longjmp(), leaving recursive
* permanently set to 1. This is probably not as big a problem as it
* sounds, because gui_mch_init() in both gui_x11.c and gui_gtk_x11.c
* return "OK" unconditionally, so it would be very difficult to
* actually hit this case.
*/
termcapinit(old_term);
settmode(TMODE_RAW); /* restart RAW mode */
#ifdef FEAT_TITLE
set_title_defaults(); /* set 'title' and 'icon' again */
#endif
}
vim_free(old_term);
#ifdef FEAT_AUTOCMD
/* If the GUI started successfully, trigger the GUIEnter event, otherwise
* the GUIFailed event. */
gui_mch_update();
apply_autocmds(gui.in_use ? EVENT_GUIENTER : EVENT_GUIFAILED,
NULL, NULL, FALSE, curbuf);
#endif
--recursive;
}
/*
* Set_termname() will call gui_init() to start the GUI.
* Set the "starting" flag, to indicate that the GUI will start.
*
* We don't want to open the GUI shell until after we've read .gvimrc,
* otherwise we don't know what font we will use, and hence we don't know
* what size the shell should be. So if there are errors in the .gvimrc
* file, they will have to go to the terminal: Set full_screen to FALSE.
* full_screen will be set to TRUE again by a successful termcapinit().
*/
static void
gui_attempt_start()
{
static int recursive = 0;
++recursive;
gui.starting = TRUE;
#ifdef FEAT_GUI_GTK
gui.event_time = GDK_CURRENT_TIME;
#endif
termcapinit((char_u *)"builtin_gui");
gui.starting = recursive - 1;
#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)
if (gui.in_use)
{
# ifdef FEAT_EVAL
Window x11_window;
Display *x11_display;
if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
set_vim_var_nr(VV_WINDOWID, (long)x11_window);
# endif
/* Display error messages in a dialog now. */
display_errors();
}
#endif
--recursive;
}
#ifdef MAY_FORK
/* for waitpid() */
# if defined(HAVE_SYS_WAIT_H) || defined(HAVE_UNION_WAIT)
# include <sys/wait.h>
# endif
/*
* Create a new process, by forking. In the child, start the GUI, and in
* the parent, exit.
*
* If something goes wrong, this will return with gui.in_use still set
* to FALSE, in which case the caller should continue execution without
* the GUI.
*
* If the child fails to start the GUI, then the child will exit and the
* parent will return. If the child succeeds, then the parent will exit
* and the child will return.
*/
static void
gui_do_fork()
{
#ifdef __QNXNTO__
procmgr_daemon(0, PROCMGR_DAEMON_KEEPUMASK | PROCMGR_DAEMON_NOCHDIR |
PROCMGR_DAEMON_NOCLOSE | PROCMGR_DAEMON_NODEVNULL);
gui_attempt_start();
return;
#else
int pipefd[2]; /* pipe between parent and child */
int pipe_error;
int status;
int exit_status;
pid_t pid = -1;
/* Setup a pipe between the child and the parent, so that the parent
* knows when the child has done the setsid() call and is allowed to
* exit. */
pipe_error = (pipe(pipefd) < 0);
pid = fork();
if (pid < 0) /* Fork error */
{
EMSG(_("E851: Failed to create a new process for the GUI"));
return;
}
else if (pid > 0) /* Parent */
{
/* Give the child some time to do the setsid(), otherwise the
* exit() may kill the child too (when starting gvim from inside a
* gvim). */
if (!pipe_error)
{
/* The read returns when the child closes the pipe (or when
* the child dies for some reason). */
close(pipefd[1]);
status = gui_read_child_pipe(pipefd[0]);
if (status == GUI_CHILD_FAILED)
{
/* The child failed to start the GUI, so the caller must
* continue. There may be more error information written
* to stderr by the child. */
# ifdef __NeXT__
wait4(pid, &exit_status, 0, (struct rusage *)0);
# else
waitpid(pid, &exit_status, 0);
# endif
EMSG(_("E852: The child process failed to start the GUI"));
return;
}
else if (status == GUI_CHILD_IO_ERROR)
{
pipe_error = TRUE;
}
/* else GUI_CHILD_OK: parent exit */
}
if (pipe_error)
ui_delay(300L, TRUE);
/* When swapping screens we may need to go to the next line, e.g.,
* after a hit-enter prompt and using ":gui". */
if (newline_on_exit)
mch_errmsg("\r\n");
/*
* The parent must skip the normal exit() processing, the child
* will do it. For example, GTK messes up signals when exiting.
*/
_exit(0);
}
/* Child */
#ifdef FEAT_GUI_GTK
/* Call gtk_init_check() here after fork(). See gui_init_check(). */
if (gui_mch_init_check() != OK)
exit(1);
#endif
# if defined(HAVE_SETSID) || defined(HAVE_SETPGID)
/*
* Change our process group. On some systems/shells a CTRL-C in the
* shell where Vim was started would otherwise kill gvim!
*/
# if defined(HAVE_SETSID)
(void)setsid();
# else
(void)setpgid(0, 0);
# endif
# endif
if (!pipe_error)
close(pipefd[0]);
# if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
/* Tell the session manager our new PID */
gui_mch_forked();
# endif
/* Try to start the GUI */
gui_attempt_start();
/* Notify the parent */
if (!pipe_error)
{
if (gui.in_use)
write_eintr(pipefd[1], "ok", 3);
else
write_eintr(pipefd[1], "fail", 5);
close(pipefd[1]);
}
/* If we failed to start the GUI, exit now. */
if (!gui.in_use)
exit(1);
#endif
}
/*
* Read from a pipe assumed to be connected to the child process (this
* function is called from the parent).
* Return GUI_CHILD_OK if the child successfully started the GUI,
* GUY_CHILD_FAILED if the child failed, or GUI_CHILD_IO_ERROR if there was
* some other error.
*
* The file descriptor will be closed before the function returns.
*/
static int
gui_read_child_pipe(int fd)
{
long bytes_read;
#define READ_BUFFER_SIZE 10
char buffer[READ_BUFFER_SIZE];
bytes_read = read_eintr(fd, buffer, READ_BUFFER_SIZE - 1);
#undef READ_BUFFER_SIZE
close(fd);
if (bytes_read < 0)
return GUI_CHILD_IO_ERROR;
buffer[bytes_read] = NUL;
if (strcmp(buffer, "ok") == 0)
return GUI_CHILD_OK;
return GUI_CHILD_FAILED;
}
#endif /* MAY_FORK */
/*
* Call this when vim starts up, whether or not the GUI is started
*/
void
gui_prepare(argc, argv)
int *argc;
char **argv;
{
gui.in_use = FALSE; /* No GUI yet (maybe later) */
gui.starting = FALSE; /* No GUI yet (maybe later) */
gui_mch_prepare(argc, argv);
}
/*
* Try initializing the GUI and check if it can be started.
* Used from main() to check early if "vim -g" can start the GUI.
* Used from gui_init() to prepare for starting the GUI.
* Returns FAIL or OK.
*/
int
gui_init_check()
{
static int result = MAYBE;
if (result != MAYBE)
{
if (result == FAIL)
EMSG(_("E229: Cannot start the GUI"));
return result;
}
gui.shell_created = FALSE;
gui.dying = FALSE;
gui.in_focus = TRUE; /* so the guicursor setting works */
gui.dragged_sb = SBAR_NONE;
gui.dragged_wp = NULL;
gui.pointer_hidden = FALSE;
gui.col = 0;
gui.row = 0;
gui.num_cols = Columns;
gui.num_rows = Rows;
gui.cursor_is_valid = FALSE;
gui.scroll_region_top = 0;
gui.scroll_region_bot = Rows - 1;
gui.scroll_region_left = 0;
gui.scroll_region_right = Columns - 1;
gui.highlight_mask = HL_NORMAL;
gui.char_width = 1;
gui.char_height = 1;
gui.char_ascent = 0;
gui.border_width = 0;
gui.norm_font = NOFONT;
#ifndef FEAT_GUI_GTK
gui.bold_font = NOFONT;
gui.ital_font = NOFONT;
gui.boldital_font = NOFONT;
# ifdef FEAT_XFONTSET
gui.fontset = NOFONTSET;
# endif
#endif
#ifdef FEAT_MENU
# ifndef FEAT_GUI_GTK
# ifdef FONTSET_ALWAYS
gui.menu_fontset = NOFONTSET;
# else
gui.menu_font = NOFONT;
# endif
# endif
gui.menu_is_active = TRUE; /* default: include menu */
# ifndef FEAT_GUI_GTK
gui.menu_height = MENU_DEFAULT_HEIGHT;
gui.menu_width = 0;
# endif
#endif
#if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA))
gui.toolbar_height = 0;
#endif
#if defined(FEAT_FOOTER) && defined(FEAT_GUI_MOTIF)
gui.footer_height = 0;
#endif
#ifdef FEAT_BEVAL_TIP
gui.tooltip_fontset = NOFONTSET;
#endif
gui.scrollbar_width = gui.scrollbar_height = SB_DEFAULT_WIDTH;
gui.prev_wrap = -1;
#ifdef ALWAYS_USE_GUI
result = OK;
#else
# ifdef FEAT_GUI_GTK
/*
* Note: Don't call gtk_init_check() before fork, it will be called after
* the fork. When calling it before fork, it make vim hang for a while.
* See gui_do_fork().
* Use a simpler check if the GUI window can probably be opened.
*/
result = gui.dofork ? gui_mch_early_init_check() : gui_mch_init_check();
# else
result = gui_mch_init_check();
# endif
#endif
return result;
}
/*
* This is the call which starts the GUI.
*/
void
gui_init()
{
win_T *wp;
static int recursive = 0;
/*
* It's possible to use ":gui" in a .gvimrc file. The first halve of this
* function will then be executed at the first call, the rest by the
* recursive call. This allow the shell to be opened halfway reading a
* gvimrc file.
*/
if (!recursive)
{
++recursive;
clip_init(TRUE);
/* If can't initialize, don't try doing the rest */
if (gui_init_check() == FAIL)
{
--recursive;
clip_init(FALSE);
return;
}
/*
* Reset 'paste'. It's useful in the terminal, but not in the GUI. It
* breaks the Paste toolbar button.
*/
set_option_value((char_u *)"paste", 0L, NULL, 0);
/*
* Set up system-wide default menus.
*/
#if defined(SYS_MENU_FILE) && defined(FEAT_MENU)
if (vim_strchr(p_go, GO_NOSYSMENU) == NULL)
{
sys_menu = TRUE;
do_source((char_u *)SYS_MENU_FILE, FALSE, DOSO_NONE);
sys_menu = FALSE;
}
#endif
/*
* Switch on the mouse by default, unless the user changed it already.
* This can then be changed in the .gvimrc.
*/
if (!option_was_set((char_u *)"mouse"))
set_string_option_direct((char_u *)"mouse", -1,
(char_u *)"a", OPT_FREE, SID_NONE);
/*
* If -U option given, use only the initializations from that file and
* nothing else. Skip all initializations for "-U NONE" or "-u NORC".
*/
if (use_gvimrc != NULL)
{
if (STRCMP(use_gvimrc, "NONE") != 0
&& STRCMP(use_gvimrc, "NORC") != 0
&& do_source(use_gvimrc, FALSE, DOSO_NONE) != OK)
EMSG2(_("E230: Cannot read from \"%s\""), use_gvimrc);
}
else
{
/*
* Get system wide defaults for gvim, only when file name defined.
*/
#ifdef SYS_GVIMRC_FILE
do_source((char_u *)SYS_GVIMRC_FILE, FALSE, DOSO_NONE);
#endif
/*
* Try to read GUI initialization commands from the following
* places:
* - environment variable GVIMINIT
* - the user gvimrc file (~/.gvimrc)
* - the second user gvimrc file ($VIM/.gvimrc for Dos)
* - the third user gvimrc file ($VIM/.gvimrc for Amiga)
* The first that exists is used, the rest is ignored.
*/
if (process_env((char_u *)"GVIMINIT", FALSE) == FAIL
&& do_source((char_u *)USR_GVIMRC_FILE, TRUE,
DOSO_GVIMRC) == FAIL
#ifdef USR_GVIMRC_FILE2
&& do_source((char_u *)USR_GVIMRC_FILE2, TRUE,
DOSO_GVIMRC) == FAIL
#endif
)
{
#ifdef USR_GVIMRC_FILE3
(void)do_source((char_u *)USR_GVIMRC_FILE3, TRUE, DOSO_GVIMRC);
#endif
}
/*
* Read initialization commands from ".gvimrc" in current
* directory. This is only done if the 'exrc' option is set.
* Because of security reasons we disallow shell and write
* commands now, except for unix if the file is owned by the user
* or 'secure' option has been reset in environment of global
* ".gvimrc".
* Only do this if GVIMRC_FILE is not the same as USR_GVIMRC_FILE,
* USR_GVIMRC_FILE2, USR_GVIMRC_FILE3 or SYS_GVIMRC_FILE.
*/
if (p_exrc)
{
#ifdef UNIX
{
struct stat s;
/* if ".gvimrc" file is not owned by user, set 'secure'
* mode */
if (mch_stat(GVIMRC_FILE, &s) || s.st_uid != getuid())
secure = p_secure;
}
#else
secure = p_secure;
#endif
if ( fullpathcmp((char_u *)USR_GVIMRC_FILE,
(char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
#ifdef SYS_GVIMRC_FILE
&& fullpathcmp((char_u *)SYS_GVIMRC_FILE,
(char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
#endif
#ifdef USR_GVIMRC_FILE2
&& fullpathcmp((char_u *)USR_GVIMRC_FILE2,
(char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
#endif
#ifdef USR_GVIMRC_FILE3
&& fullpathcmp((char_u *)USR_GVIMRC_FILE3,
(char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
#endif
)
do_source((char_u *)GVIMRC_FILE, TRUE, DOSO_GVIMRC);
if (secure == 2)
need_wait_return = TRUE;
secure = 0;
}
}
if (need_wait_return || msg_didany)
wait_return(TRUE);
--recursive;
}
/* If recursive call opened the shell, return here from the first call */
if (gui.in_use)
return;
/*
* Create the GUI shell.
*/
gui.in_use = TRUE; /* Must be set after menus have been set up */
if (gui_mch_init() == FAIL)
goto error;
/* Avoid a delay for an error message that was printed in the terminal
* where Vim was started. */
emsg_on_display = FALSE;
msg_scrolled = 0;
clear_sb_text();
need_wait_return = FALSE;
msg_didany = FALSE;
/*
* Check validity of any generic resources that may have been loaded.
*/
if (gui.border_width < 0)
gui.border_width = 0;
/*
* Set up the fonts. First use a font specified with "-fn" or "-font".
*/
if (font_argument != NULL)
set_option_value((char_u *)"gfn", 0L, (char_u *)font_argument, 0);
if (
#ifdef FEAT_XFONTSET
(*p_guifontset == NUL
|| gui_init_font(p_guifontset, TRUE) == FAIL) &&
#endif
gui_init_font(*p_guifont == NUL ? hl_get_font_name()
: p_guifont, FALSE) == FAIL)
{
EMSG(_("E665: Cannot start GUI, no valid font found"));
goto error2;
}
#ifdef FEAT_MBYTE
if (gui_get_wide_font() == FAIL)
EMSG(_("E231: 'guifontwide' invalid"));
#endif
gui.num_cols = Columns;
gui.num_rows = Rows;
gui_reset_scroll_region();
/* Create initial scrollbars */
FOR_ALL_WINDOWS(wp)
{
gui_create_scrollbar(&wp->w_scrollbars[SBAR_LEFT], SBAR_LEFT, wp);
gui_create_scrollbar(&wp->w_scrollbars[SBAR_RIGHT], SBAR_RIGHT, wp);
}
gui_create_scrollbar(&gui.bottom_sbar, SBAR_BOTTOM, NULL);
#ifdef FEAT_MENU
gui_create_initial_menus(root_menu);
#endif
#ifdef FEAT_SUN_WORKSHOP
if (usingSunWorkShop)
workshop_init();
#endif
#ifdef FEAT_SIGN_ICONS
sign_gui_started();
#endif
/* Configure the desired menu and scrollbars */
gui_init_which_components(NULL);
/* All components of the GUI have been created now */
gui.shell_created = TRUE;
#ifndef FEAT_GUI_GTK
/* Set the shell size, adjusted for the screen size. For GTK this only
* works after the shell has been opened, thus it is further down. */
gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
#endif
#if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
/* Need to set the size of the menubar after all the menus have been
* created. */
gui_mch_compute_menu_height((Widget)0);
#endif
/*
* Actually open the GUI shell.
*/
if (gui_mch_open() != FAIL)
{
#ifdef FEAT_TITLE
maketitle();
resettitle();
#endif
init_gui_options();
#ifdef FEAT_ARABIC
/* Our GUI can't do bidi. */
p_tbidi = FALSE;
#endif
#if defined(FEAT_GUI_GTK)
/* Give GTK+ a chance to put all widget's into place. */
gui_mch_update();
# ifdef FEAT_MENU
/* If there is no 'm' in 'guioptions' we need to remove the menu now.
* It was still there to make F10 work. */
if (vim_strchr(p_go, GO_MENUS) == NULL)
{
--gui.starting;
gui_mch_enable_menu(FALSE);
++gui.starting;
gui_mch_update();
}
# endif
/* Now make sure the shell fits on the screen. */
gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
#endif
/* When 'lines' was set while starting up the topframe may have to be
* resized. */
win_new_shellsize();
#ifdef FEAT_BEVAL
/* Always create the Balloon Evaluation area, but disable it when
* 'ballooneval' is off */
# ifdef FEAT_GUI_GTK
balloonEval = gui_mch_create_beval_area(gui.drawarea, NULL,
&general_beval_cb, NULL);
# else
# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
{
extern Widget textArea;
balloonEval = gui_mch_create_beval_area(textArea, NULL,
&general_beval_cb, NULL);
}
# else
# ifdef FEAT_GUI_W32
balloonEval = gui_mch_create_beval_area(NULL, NULL,
&general_beval_cb, NULL);
# endif
# endif
# endif
if (!p_beval)
gui_mch_disable_beval_area(balloonEval);
#endif
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
if (!im_xim_isvalid_imactivate())
EMSG(_("E599: Value of 'imactivatekey' is invalid"));
#endif
/* When 'cmdheight' was set during startup it may not have taken
* effect yet. */
if (p_ch != 1L)
command_height();
return;
}
error2:
#ifdef FEAT_GUI_X11
/* undo gui_mch_init() */
gui_mch_uninit();
#endif
error:
gui.in_use = FALSE;
clip_init(FALSE);
}
void
gui_exit(rc)
int rc;
{
#ifndef __BEOS__
/* don't free the fonts, it leads to a BUS error
* richard@whitequeen.com Jul 99 */
free_highlight_fonts();
#endif
gui.in_use = FALSE;
gui_mch_exit(rc);
}
#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(PROTO)
# define NEED_GUI_UPDATE_SCREEN 1
/*
* Called when the GUI shell is closed by the user. If there are no changed
* files Vim exits, otherwise there will be a dialog to ask the user what to
* do.
* When this function returns, Vim should NOT exit!
*/
void
gui_shell_closed()
{
cmdmod_T save_cmdmod;
save_cmdmod = cmdmod;
/* Only exit when there are no changed files */
exiting = TRUE;
# ifdef FEAT_BROWSE
cmdmod.browse = TRUE;
# endif
# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmdmod.confirm = TRUE;
# endif
/* If there are changed buffers, present the user with a dialog if
* possible, otherwise give an error message. */
if (!check_changed_any(FALSE))
getout(0);
exiting = FALSE;
cmdmod = save_cmdmod;
gui_update_screen(); /* redraw, window may show changed buffer */
}
#endif
/*
* Set the font. "font_list" is a a comma separated list of font names. The
* first font name that works is used. If none is found, use the default
* font.
* If "fontset" is TRUE, the "font_list" is used as one name for the fontset.
* Return OK when able to set the font. When it failed FAIL is returned and
* the fonts are unchanged.
*/
int
gui_init_font(font_list, fontset)
char_u *font_list;
int fontset UNUSED;
{
#define FONTLEN 320
char_u font_name[FONTLEN];
int font_list_empty = FALSE;
int ret = FAIL;
if (!gui.in_use)
return FAIL;
font_name[0] = NUL;
if (*font_list == NUL)
font_list_empty = TRUE;
else
{
#ifdef FEAT_XFONTSET
/* When using a fontset, the whole list of fonts is one name. */
if (fontset)
ret = gui_mch_init_font(font_list, TRUE);
else
#endif
while (*font_list != NUL)
{
/* Isolate one comma separated font name. */
(void)copy_option_part(&font_list, font_name, FONTLEN, ",");
/* Careful!!! The Win32 version of gui_mch_init_font(), when
* called with "*" will change p_guifont to the selected font
* name, which frees the old value. This makes font_list
* invalid. Thus when OK is returned here, font_list must no
* longer be used! */
if (gui_mch_init_font(font_name, FALSE) == OK)
{
#if defined(FEAT_MBYTE) && !defined(FEAT_GUI_GTK)
/* If it's a Unicode font, try setting 'guifontwide' to a
* similar double-width font. */
if ((p_guifontwide == NULL || *p_guifontwide == NUL)
&& strstr((char *)font_name, "10646") != NULL)
set_guifontwide(font_name);
#endif
ret = OK;
break;
}
}
}
if (ret != OK
&& STRCMP(font_list, "*") != 0
&& (font_list_empty || gui.norm_font == NOFONT))
{
/*
* Couldn't load any font in 'font_list', keep the current font if
* there is one. If 'font_list' is empty, or if there is no current
* font, tell gui_mch_init_font() to try to find a font we can load.
*/
ret = gui_mch_init_font(NULL, FALSE);
}
if (ret == OK)
{
#ifndef FEAT_GUI_GTK
/* Set normal font as current font */
# ifdef FEAT_XFONTSET
if (gui.fontset != NOFONTSET)
gui_mch_set_fontset(gui.fontset);
else
# endif
gui_mch_set_font(gui.norm_font);
#endif
gui_set_shellsize(FALSE,
#ifdef MSWIN
TRUE
#else
FALSE
#endif
, RESIZE_BOTH);
}
return ret;
}
#if defined(FEAT_MBYTE) || defined(PROTO)
# ifndef FEAT_GUI_GTK
/*
* Try setting 'guifontwide' to a font twice as wide as "name".
*/
static void
set_guifontwide(name)
char_u *name;
{
int i = 0;
char_u wide_name[FONTLEN + 10]; /* room for 2 * width and '*' */
char_u *wp = NULL;
char_u *p;
GuiFont font;
wp = wide_name;
for (p = name; *p != NUL; ++p)
{
*wp++ = *p;
if (*p == '-')
{
++i;
if (i == 6) /* font type: change "--" to "-*-" */
{
if (p[1] == '-')
*wp++ = '*';
}
else if (i == 12) /* found the width */
{
++p;
i = getdigits(&p);
if (i != 0)
{
/* Double the width specification. */
sprintf((char *)wp, "%d%s", i * 2, p);
font = gui_mch_get_font(wide_name, FALSE);
if (font != NOFONT)
{
gui_mch_free_font(gui.wide_font);
gui.wide_font = font;
set_string_option_direct((char_u *)"gfw", -1,
wide_name, OPT_FREE, 0);
}
}
break;
}
}
}
}
# endif /* !FEAT_GUI_GTK */
/*
* Get the font for 'guifontwide'.
* Return FAIL for an invalid font name.
*/
int
gui_get_wide_font()
{
GuiFont font = NOFONT;
char_u font_name[FONTLEN];
char_u *p;
if (!gui.in_use) /* Can't allocate font yet, assume it's OK. */
return OK; /* Will give an error message later. */
if (p_guifontwide != NULL && *p_guifontwide != NUL)
{
for (p = p_guifontwide; *p != NUL; )
{
/* Isolate one comma separated font name. */
(void)copy_option_part(&p, font_name, FONTLEN, ",");
font = gui_mch_get_font(font_name, FALSE);
if (font != NOFONT)
break;
}
if (font == NOFONT)
return FAIL;
}
gui_mch_free_font(gui.wide_font);
#ifdef FEAT_GUI_GTK
/* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
if (font != NOFONT && gui.norm_font != NOFONT
&& pango_font_description_equal(font, gui.norm_font))
{
gui.wide_font = NOFONT;
gui_mch_free_font(font);
}
else
#endif
gui.wide_font = font;
return OK;
}
#endif
void
gui_set_cursor(row, col)
int row;
int col;
{
gui.row = row;
gui.col = col;
}
/*
* gui_check_pos - check if the cursor is on the screen.
*/
static void
gui_check_pos()
{
if (gui.row >= screen_Rows)
gui.row = screen_Rows - 1;
if (gui.col >= screen_Columns)
gui.col = screen_Columns - 1;
if (gui.cursor_row >= screen_Rows || gui.cursor_col >= screen_Columns)
gui.cursor_is_valid = FALSE;
}
/*
* Redraw the cursor if necessary or when forced.
* Careful: The contents of ScreenLines[] must match what is on the screen,
* otherwise this goes wrong. May need to call out_flush() first.
*/
void
gui_update_cursor(force, clear_selection)
int force; /* when TRUE, update even when not moved */
int clear_selection;/* clear selection under cursor */
{
int cur_width = 0;
int cur_height = 0;
int old_hl_mask;
int idx;
int id;
guicolor_T cfg, cbg, cc; /* cursor fore-/background color */
int cattr; /* cursor attributes */
int attr;
attrentry_T *aep = NULL;
/* Don't update the cursor when halfway busy scrolling or the screen size
* doesn't match 'columns' and 'lines. ScreenLines[] isn't valid then. */
if (!can_update_cursor || screen_Columns != gui.num_cols
|| screen_Rows != gui.num_rows)
return;
gui_check_pos();
if (!gui.cursor_is_valid || force
|| gui.row != gui.cursor_row || gui.col != gui.cursor_col)
{
gui_undraw_cursor();
if (gui.row < 0)
return;
#ifdef USE_IM_CONTROL
if (gui.row != gui.cursor_row || gui.col != gui.cursor_col)
im_set_position(gui.row, gui.col);
#endif
gui.cursor_row = gui.row;
gui.cursor_col = gui.col;
/* Only write to the screen after ScreenLines[] has been initialized */
if (!screen_cleared || ScreenLines == NULL)
return;
/* Clear the selection if we are about to write over it */
if (clear_selection)
clip_may_clear_selection(gui.row, gui.row);
/* Check that the cursor is inside the shell (resizing may have made
* it invalid) */
if (gui.row >= screen_Rows || gui.col >= screen_Columns)
return;
gui.cursor_is_valid = TRUE;
/*
* How the cursor is drawn depends on the current mode.
*/
idx = get_shape_idx(FALSE);
if (State & LANGMAP)
id = shape_table[idx].id_lm;
else
id = shape_table[idx].id;
/* get the colors and attributes for the cursor. Default is inverted */
cfg = INVALCOLOR;
cbg = INVALCOLOR;
cattr = HL_INVERSE;
gui_mch_set_blinking(shape_table[idx].blinkwait,
shape_table[idx].blinkon,
shape_table[idx].blinkoff);
if (id > 0)
{
cattr = syn_id2colors(id, &cfg, &cbg);
#if defined(USE_IM_CONTROL) || defined(FEAT_HANGULIN)
{
static int iid;
guicolor_T fg, bg;
if (
# if defined(FEAT_GUI_GTK) && !defined(FEAT_HANGULIN)
preedit_get_status()
# else
im_get_status()
# endif
)
{
iid = syn_name2id((char_u *)"CursorIM");
if (iid > 0)
{
syn_id2colors(iid, &fg, &bg);
if (bg != INVALCOLOR)
cbg = bg;
if (fg != INVALCOLOR)
cfg = fg;
}
}
}
#endif
}
/*
* Get the attributes for the character under the cursor.
* When no cursor color was given, use the character color.
*/
attr = ScreenAttrs[LineOffset[gui.row] + gui.col];
if (attr > HL_ALL)
aep = syn_gui_attr2entry(attr);
if (aep != NULL)
{
attr = aep->ae_attr;
if (cfg == INVALCOLOR)
cfg = ((attr & HL_INVERSE) ? aep->ae_u.gui.bg_color
: aep->ae_u.gui.fg_color);
if (cbg == INVALCOLOR)
cbg = ((attr & HL_INVERSE) ? aep->ae_u.gui.fg_color
: aep->ae_u.gui.bg_color);
}
if (cfg == INVALCOLOR)
cfg = (attr & HL_INVERSE) ? gui.back_pixel : gui.norm_pixel;
if (cbg == INVALCOLOR)
cbg = (attr & HL_INVERSE) ? gui.norm_pixel : gui.back_pixel;
#ifdef FEAT_XIM
if (aep != NULL)
{
xim_bg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.fg_color
: aep->ae_u.gui.bg_color);
xim_fg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.bg_color
: aep->ae_u.gui.fg_color);
if (xim_bg_color == INVALCOLOR)
xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
: gui.back_pixel;
if (xim_fg_color == INVALCOLOR)
xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
: gui.norm_pixel;
}
else
{
xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
: gui.back_pixel;
xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
: gui.norm_pixel;
}
#endif
attr &= ~HL_INVERSE;
if (cattr & HL_INVERSE)
{
cc = cbg;
cbg = cfg;
cfg = cc;
}
cattr &= ~HL_INVERSE;
/*
* When we don't have window focus, draw a hollow cursor.
*/
if (!gui.in_focus)
{
gui_mch_draw_hollow_cursor(cbg);
return;
}
old_hl_mask = gui.highlight_mask;
if (shape_table[idx].shape == SHAPE_BLOCK
#ifdef FEAT_HANGULIN
|| composing_hangul
#endif
)
{
/*
* Draw the text character with the cursor colors. Use the
* character attributes plus the cursor attributes.
*/
gui.highlight_mask = (cattr | attr);
#ifdef FEAT_HANGULIN
if (composing_hangul)
(void)gui_outstr_nowrap(composing_hangul_buffer, 2,
GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR, cfg, cbg, 0);
else
#endif
(void)gui_screenchar(LineOffset[gui.row] + gui.col,
GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR, cfg, cbg, 0);
}
else
{
#if defined(FEAT_MBYTE) && defined(FEAT_RIGHTLEFT)
int col_off = FALSE;
#endif
/*
* First draw the partial cursor, then overwrite with the text
* character, using a transparent background.
*/
if (shape_table[idx].shape == SHAPE_VER)
{
cur_height = gui.char_height;
cur_width = (gui.char_width * shape_table[idx].percentage
+ 99) / 100;
}
else
{
cur_height = (gui.char_height * shape_table[idx].percentage
+ 99) / 100;
cur_width = gui.char_width;
}
#ifdef FEAT_MBYTE
if (has_mbyte && (*mb_off2cells)(LineOffset[gui.row] + gui.col,
LineOffset[gui.row] + screen_Columns) > 1)
{
/* Double wide character. */
if (shape_table[idx].shape != SHAPE_VER)
cur_width += gui.char_width;
# ifdef FEAT_RIGHTLEFT
if (CURSOR_BAR_RIGHT)
{
/* gui.col points to the left halve of the character but
* the vertical line needs to be on the right halve.
* A double-wide horizontal line is also drawn from the
* right halve in gui_mch_draw_part_cursor(). */
col_off = TRUE;
++gui.col;
}
# endif
}
#endif
gui_mch_draw_part_cursor(cur_width, cur_height, cbg);
#if defined(FEAT_MBYTE) && defined(FEAT_RIGHTLEFT)
if (col_off)
--gui.col;
#endif
#ifndef FEAT_GUI_MSWIN /* doesn't seem to work for MSWindows */
gui.highlight_mask = ScreenAttrs[LineOffset[gui.row] + gui.col];
(void)gui_screenchar(LineOffset[gui.row] + gui.col,
GUI_MON_TRS_CURSOR | GUI_MON_NOCLEAR,
(guicolor_T)0, (guicolor_T)0, 0);
#endif
}
gui.highlight_mask = old_hl_mask;
}
}
#if defined(FEAT_MENU) || defined(PROTO)
void
gui_position_menu()
{
# if !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
if (gui.menu_is_active && gui.in_use)
gui_mch_set_menu_pos(0, 0, gui.menu_width, gui.menu_height);
# endif
}
#endif
/*
* Position the various GUI components (text area, menu). The vertical
* scrollbars are NOT handled here. See gui_update_scrollbars().
*/
static void
gui_position_components(total_width)
int total_width UNUSED;
{
int text_area_x;
int text_area_y;
int text_area_width;
int text_area_height;
/* avoid that moving components around generates events */
++hold_gui_events;
text_area_x = 0;
if (gui.which_scrollbars[SBAR_LEFT])
text_area_x += gui.scrollbar_width;
text_area_y = 0;
#if defined(FEAT_MENU) && !(defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON))
gui.menu_width = total_width;
if (gui.menu_is_active)
text_area_y += gui.menu_height;
#endif
#if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_MSWIN)
if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
text_area_y = TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
#endif
# if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_MAC))
if (gui_has_tabline())
text_area_y += gui.tabline_height;
#endif
#if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA))
if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
{
# ifdef FEAT_GUI_ATHENA
gui_mch_set_toolbar_pos(0, text_area_y,
gui.menu_width, gui.toolbar_height);
# endif
text_area_y += gui.toolbar_height;
}
#endif
text_area_width = gui.num_cols * gui.char_width + gui.border_offset * 2;
text_area_height = gui.num_rows * gui.char_height + gui.border_offset * 2;
gui_mch_set_text_area_pos(text_area_x,
text_area_y,
text_area_width,
text_area_height
#if defined(FEAT_XIM) && !defined(FEAT_GUI_GTK)
+ xim_get_status_area_height()
#endif
);
#ifdef FEAT_MENU
gui_position_menu();
#endif
if (gui.which_scrollbars[SBAR_BOTTOM])
gui_mch_set_scrollbar_pos(&gui.bottom_sbar,
text_area_x,
text_area_y + text_area_height,
text_area_width,
gui.scrollbar_height);
gui.left_sbar_x = 0;
gui.right_sbar_x = text_area_x + text_area_width;
--hold_gui_events;
}
/*
* Get the width of the widgets and decorations to the side of the text area.
*/
int
gui_get_base_width()
{
int base_width;
base_width = 2 * gui.border_offset;
if (gui.which_scrollbars[SBAR_LEFT])
base_width += gui.scrollbar_width;
if (gui.which_scrollbars[SBAR_RIGHT])
base_width += gui.scrollbar_width;
return base_width;
}
/*
* Get the height of the widgets and decorations above and below the text area.
*/
int
gui_get_base_height()
{
int base_height;
base_height = 2 * gui.border_offset;
if (gui.which_scrollbars[SBAR_BOTTOM])
base_height += gui.scrollbar_height;
#ifdef FEAT_GUI_GTK
/* We can't take the sizes properly into account until anything is
* realized. Therefore we recalculate all the values here just before
* setting the size. (--mdcki) */
#else
# ifdef FEAT_MENU
if (gui.menu_is_active)
base_height += gui.menu_height;
# endif
# ifdef FEAT_TOOLBAR
if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
# if defined(FEAT_GUI_MSWIN) && defined(FEAT_TOOLBAR)
base_height += (TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT);
# else
base_height += gui.toolbar_height;
# endif
# endif
# if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MOTIF))
if (gui_has_tabline())
base_height += gui.tabline_height;
# endif
# ifdef FEAT_FOOTER
if (vim_strchr(p_go, GO_FOOTER) != NULL)
base_height += gui.footer_height;
# endif
# if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
base_height += gui_mch_text_area_extra_height();
# endif
#endif
return base_height;
}
/*
* Should be called after the GUI shell has been resized. Its arguments are
* the new width and height of the shell in pixels.
*/
void
gui_resize_shell(pixel_width, pixel_height)
int pixel_width;
int pixel_height;
{
static int busy = FALSE;
if (!gui.shell_created) /* ignore when still initializing */
return;
/*
* Can't resize the screen while it is being redrawn. Remember the new
* size and handle it later.
*/
if (updating_screen || busy)
{
new_pixel_width = pixel_width;
new_pixel_height = pixel_height;
return;
}
again:
busy = TRUE;
/* Flush pending output before redrawing */
out_flush();
gui.num_cols = (pixel_width - gui_get_base_width()) / gui.char_width;
gui.num_rows = (pixel_height - gui_get_base_height()) / gui.char_height;
gui_position_components(pixel_width);
gui_reset_scroll_region();
/*
* At the "more" and ":confirm" prompt there is no redraw, put the cursor
* at the last line here (why does it have to be one row too low?).
*/
if (State == ASKMORE || State == CONFIRM)
gui.row = gui.num_rows;
/* Only comparing Rows and Columns may be sufficient, but let's stay on
* the safe side. */
if (gui.num_rows != screen_Rows || gui.num_cols != screen_Columns
|| gui.num_rows != Rows || gui.num_cols != Columns)
shell_resized();
gui_update_scrollbars(TRUE);
gui_update_cursor(FALSE, TRUE);
#if defined(FEAT_XIM) && !defined(FEAT_GUI_GTK)
xim_set_status_area();
#endif
busy = FALSE;
/*
* We could have been called again while redrawing the screen.
* Need to do it all again with the latest size then.
*/
if (new_pixel_height)
{
pixel_width = new_pixel_width;
pixel_height = new_pixel_height;
new_pixel_width = 0;
new_pixel_height = 0;
goto again;
}
}
/*
* Check if gui_resize_shell() must be called.
*/
void
gui_may_resize_shell()
{
int h, w;
if (new_pixel_height)
{
/* careful: gui_resize_shell() may postpone the resize again if we
* were called indirectly by it */
w = new_pixel_width;
h = new_pixel_height;
new_pixel_width = 0;
new_pixel_height = 0;
gui_resize_shell(w, h);
}
}
int
gui_get_shellsize()
{
Rows = gui.num_rows;
Columns = gui.num_cols;
return OK;
}
/*
* Set the size of the Vim shell according to Rows and Columns.
* If "fit_to_display" is TRUE then the size may be reduced to fit the window
* on the screen.
*/
void
gui_set_shellsize(mustset, fit_to_display, direction)
int mustset UNUSED; /* set by the user */
int fit_to_display;
int direction; /* RESIZE_HOR, RESIZE_VER */
{
int base_width;
int base_height;
int width;
int height;
int min_width;
int min_height;
int screen_w;
int screen_h;
#ifdef FEAT_GUI_GTK
int un_maximize = mustset;
int did_adjust = 0;
#endif
int x = -1, y = -1;
if (!gui.shell_created)
return;
#if defined(MSWIN) || defined(FEAT_GUI_GTK)
/* If not setting to a user specified size and maximized, calculate the
* number of characters that fit in the maximized window. */
if (!mustset && gui_mch_maximized())
{
gui_mch_newfont();
return;
}
#endif
base_width = gui_get_base_width();
base_height = gui_get_base_height();
if (fit_to_display)
/* Remember the original window position. */
gui_mch_get_winpos(&x, &y);
#ifdef USE_SUN_WORKSHOP
if (!mustset && usingSunWorkShop
&& workshop_get_width_height(&width, &height))
{
Columns = (width - base_width + gui.char_width - 1) / gui.char_width;
Rows = (height - base_height + gui.char_height - 1) / gui.char_height;
}
else
#endif
{
width = Columns * gui.char_width + base_width;
height = Rows * gui.char_height + base_height;
}
if (fit_to_display)
{
gui_mch_get_screen_dimensions(&screen_w, &screen_h);
if ((direction & RESIZE_HOR) && width > screen_w)
{
Columns = (screen_w - base_width) / gui.char_width;
if (Columns < MIN_COLUMNS)
Columns = MIN_COLUMNS;
width = Columns * gui.char_width + base_width;
#ifdef FEAT_GUI_GTK
++did_adjust;
#endif
}
if ((direction & RESIZE_VERT) && height > screen_h)
{
Rows = (screen_h - base_height) / gui.char_height;
check_shellsize();
height = Rows * gui.char_height + base_height;
#ifdef FEAT_GUI_GTK
++did_adjust;
#endif
}
#ifdef FEAT_GUI_GTK
if (did_adjust == 2 || (width + gui.char_width >= screen_w
&& height + gui.char_height >= screen_h))
/* don't unmaximize if at maximum size */
un_maximize = FALSE;
#endif
}
gui.num_cols = Columns;
gui.num_rows = Rows;
min_width = base_width + MIN_COLUMNS * gui.char_width;
min_height = base_height + MIN_LINES * gui.char_height;
#ifdef FEAT_WINDOWS
min_height += tabline_height() * gui.char_height;
#endif
#ifdef FEAT_GUI_GTK
if (un_maximize)
{
/* If the window size is smaller than the screen unmaximize the
* window, otherwise resizing won't work. */
gui_mch_get_screen_dimensions(&screen_w, &screen_h);
if ((width + gui.char_width < screen_w
|| height + gui.char_height * 2 < screen_h)
&& gui_mch_maximized())
gui_mch_unmaximize();
}
#endif
gui_mch_set_shellsize(width, height, min_width, min_height,
base_width, base_height, direction);
if (fit_to_display && x >= 0 && y >= 0)
{
/* Some window managers put the Vim window left of/above the screen.
* Only change the position if it wasn't already negative before
* (happens on MS-Windows with a secondary monitor). */
gui_mch_update();
if (gui_mch_get_winpos(&x, &y) == OK && (x < 0 || y < 0))
gui_mch_set_winpos(x < 0 ? 0 : x, y < 0 ? 0 : y);
}
gui_position_components(width);
gui_update_scrollbars(TRUE);
gui_reset_scroll_region();
}
/*
* Called when Rows and/or Columns has changed.
*/
void
gui_new_shellsize()
{
gui_reset_scroll_region();
}
/*
* Make scroll region cover whole screen.
*/
void
gui_reset_scroll_region()
{
gui.scroll_region_top = 0;
gui.scroll_region_bot = gui.num_rows - 1;
gui.scroll_region_left = 0;
gui.scroll_region_right = gui.num_cols - 1;
}
void
gui_start_highlight(mask)
int mask;
{
if (mask > HL_ALL) /* highlight code */
gui.highlight_mask = mask;
else /* mask */
gui.highlight_mask |= mask;
}
void
gui_stop_highlight(mask)
int mask;
{
if (mask > HL_ALL) /* highlight code */
gui.highlight_mask = HL_NORMAL;
else /* mask */
gui.highlight_mask &= ~mask;
}
/*
* Clear a rectangular region of the screen from text pos (row1, col1) to
* (row2, col2) inclusive.
*/
void
gui_clear_block(row1, col1, row2, col2)
int row1;
int col1;
int row2;
int col2;
{
/* Clear the selection if we are about to write over it */
clip_may_clear_selection(row1, row2);
gui_mch_clear_block(row1, col1, row2, col2);
/* Invalidate cursor if it was in this block */
if ( gui.cursor_row >= row1 && gui.cursor_row <= row2
&& gui.cursor_col >= col1 && gui.cursor_col <= col2)
gui.cursor_is_valid = FALSE;
}
/*
* Write code to update the cursor later. This avoids the need to flush the
* output buffer before calling gui_update_cursor().
*/
void
gui_update_cursor_later()
{
OUT_STR(IF_EB("\033|s", ESC_STR "|s"));
}
void
gui_write(s, len)
char_u *s;
int len;
{
char_u *p;
int arg1 = 0, arg2 = 0;
int force_cursor = FALSE; /* force cursor update */
int force_scrollbar = FALSE;
static win_T *old_curwin = NULL;
/* #define DEBUG_GUI_WRITE */
#ifdef DEBUG_GUI_WRITE
{
int i;
char_u *str;
printf("gui_write(%d):\n ", len);
for (i = 0; i < len; i++)
if (s[i] == ESC)
{
if (i != 0)
printf("\n ");
printf("<ESC>");
}
else
{
str = transchar_byte(s[i]);
if (str[0] && str[1])
printf("<%s>", (char *)str);
else
printf("%s", (char *)str);
}
printf("\n");
}
#endif
while (len)
{
if (s[0] == ESC && s[1] == '|')
{
p = s + 2;
if (VIM_ISDIGIT(*p))
{
arg1 = getdigits(&p);
if (p > s + len)
break;
if (*p == ';')
{
++p;
arg2 = getdigits(&p);
if (p > s + len)
break;
}
}
switch (*p)
{
case 'C': /* Clear screen */
clip_scroll_selection(9999);
gui_mch_clear_all();
gui.cursor_is_valid = FALSE;
force_scrollbar = TRUE;
break;
case 'M': /* Move cursor */
gui_set_cursor(arg1, arg2);
break;
case 's': /* force cursor (shape) update */
force_cursor = TRUE;
break;
case 'R': /* Set scroll region */
if (arg1 < arg2)
{
gui.scroll_region_top = arg1;
gui.scroll_region_bot = arg2;
}
else
{
gui.scroll_region_top = arg2;
gui.scroll_region_bot = arg1;
}
break;
#ifdef FEAT_VERTSPLIT
case 'V': /* Set vertical scroll region */
if (arg1 < arg2)
{
gui.scroll_region_left = arg1;
gui.scroll_region_right = arg2;
}
else
{
gui.scroll_region_left = arg2;
gui.scroll_region_right = arg1;
}
break;
#endif
case 'd': /* Delete line */
gui_delete_lines(gui.row, 1);
break;
case 'D': /* Delete lines */
gui_delete_lines(gui.row, arg1);
break;
case 'i': /* Insert line */
gui_insert_lines(gui.row, 1);
break;
case 'I': /* Insert lines */
gui_insert_lines(gui.row, arg1);
break;
case '$': /* Clear to end-of-line */
gui_clear_block(gui.row, gui.col, gui.row,
(int)Columns - 1);
break;
case 'h': /* Turn on highlighting */
gui_start_highlight(arg1);
break;
case 'H': /* Turn off highlighting */
gui_stop_highlight(arg1);
break;
case 'f': /* flash the window (visual bell) */
gui_mch_flash(arg1 == 0 ? 20 : arg1);
break;
default:
p = s + 1; /* Skip the ESC */
break;
}
len -= (int)(++p - s);
s = p;
}
else if (
#ifdef EBCDIC
CtrlChar(s[0]) != 0 /* Ctrl character */
#else
s[0] < 0x20 /* Ctrl character */
#endif
#ifdef FEAT_SIGN_ICONS
&& s[0] != SIGN_BYTE
# ifdef FEAT_NETBEANS_INTG
&& s[0] != MULTISIGN_BYTE
# endif
#endif
)
{
if (s[0] == '\n') /* NL */
{
gui.col = 0;
if (gui.row < gui.scroll_region_bot)
gui.row++;
else
gui_delete_lines(gui.scroll_region_top, 1);
}
else if (s[0] == '\r') /* CR */
{
gui.col = 0;
}
else if (s[0] == '\b') /* Backspace */
{
if (gui.col)
--gui.col;
}
else if (s[0] == Ctrl_L) /* cursor-right */
{
++gui.col;
}
else if (s[0] == Ctrl_G) /* Beep */
{
gui_mch_beep();
}
/* Other Ctrl character: shouldn't happen! */
--len; /* Skip this char */
++s;
}
else
{
p = s;
while (len > 0 && (
#ifdef EBCDIC
CtrlChar(*p) == 0
#else
*p >= 0x20
#endif
#ifdef FEAT_SIGN_ICONS
|| *p == SIGN_BYTE
# ifdef FEAT_NETBEANS_INTG
|| *p == MULTISIGN_BYTE
# endif
#endif
))
{
len--;
p++;
}
gui_outstr(s, (int)(p - s));
s = p;
}
}
/* Postponed update of the cursor (won't work if "can_update_cursor" isn't
* set). */
if (force_cursor)
gui_update_cursor(TRUE, TRUE);
/* When switching to another window the dragging must have stopped.
* Required for GTK, dragged_sb isn't reset. */
if (old_curwin != curwin)
gui.dragged_sb = SBAR_NONE;
/* Update the scrollbars after clearing the screen or when switched
* to another window.
* Update the horizontal scrollbar always, it's difficult to check all
* situations where it might change. */
if (force_scrollbar || old_curwin != curwin)
gui_update_scrollbars(force_scrollbar);
else
gui_update_horiz_scrollbar(FALSE);
old_curwin = curwin;
/*
* We need to make sure this is cleared since Athena doesn't tell us when
* he is done dragging. Do the same for GTK.
*/
#if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK)
gui.dragged_sb = SBAR_NONE;
#endif
gui_mch_flush(); /* In case vim decides to take a nap */
}
/*
* When ScreenLines[] is invalid, updating the cursor should not be done, it
* produces wrong results. Call gui_dont_update_cursor() before that code and
* gui_can_update_cursor() afterwards.
*/
void
gui_dont_update_cursor()
{
if (gui.in_use)
{
/* Undraw the cursor now, we probably can't do it after the change. */
gui_undraw_cursor();
can_update_cursor = FALSE;
}
}
void
gui_can_update_cursor()
{
can_update_cursor = TRUE;
/* No need to update the cursor right now, there is always more output
* after scrolling. */
}
static void
gui_outstr(s, len)
char_u *s;
int len;
{
int this_len;
#ifdef FEAT_MBYTE
int cells;
#endif
if (len == 0)
return;
if (len < 0)
len = (int)STRLEN(s);
while (len > 0)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Find out how many chars fit in the current line. */
cells = 0;
for (this_len = 0; this_len < len; )
{
cells += (*mb_ptr2cells)(s + this_len);
if (gui.col + cells > Columns)
break;
this_len += (*mb_ptr2len)(s + this_len);
}
if (this_len > len)
this_len = len; /* don't include following composing char */
}
else
#endif
if (gui.col + len > Columns)
this_len = Columns - gui.col;
else
this_len = len;
(void)gui_outstr_nowrap(s, this_len,
0, (guicolor_T)0, (guicolor_T)0, 0);
s += this_len;
len -= this_len;
#ifdef FEAT_MBYTE
/* fill up for a double-width char that doesn't fit. */
if (len > 0 && gui.col < Columns)
(void)gui_outstr_nowrap((char_u *)" ", 1,
0, (guicolor_T)0, (guicolor_T)0, 0);
#endif
/* The cursor may wrap to the next line. */
if (gui.col >= Columns)
{
gui.col = 0;
gui.row++;
}
}
}
/*
* Output one character (may be one or two display cells).
* Caller must check for valid "off".
* Returns FAIL or OK, just like gui_outstr_nowrap().
*/
static int
gui_screenchar(off, flags, fg, bg, back)
int off; /* Offset from start of screen */
int flags;
guicolor_T fg, bg; /* colors for cursor */
int back; /* backup this many chars when using bold trick */
{
#ifdef FEAT_MBYTE
char_u buf[MB_MAXBYTES + 1];
/* Don't draw right halve of a double-width UTF-8 char. "cannot happen" */
if (enc_utf8 && ScreenLines[off] == 0)
return OK;
if (enc_utf8 && ScreenLinesUC[off] != 0)
/* Draw UTF-8 multi-byte character. */
return gui_outstr_nowrap(buf, utfc_char2bytes(off, buf),
flags, fg, bg, back);
if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
{
buf[0] = ScreenLines[off];
buf[1] = ScreenLines2[off];
return gui_outstr_nowrap(buf, 2, flags, fg, bg, back);
}
/* Draw non-multi-byte character or DBCS character. */
return gui_outstr_nowrap(ScreenLines + off,
enc_dbcs ? (*mb_ptr2len)(ScreenLines + off) : 1,
flags, fg, bg, back);
#else
return gui_outstr_nowrap(ScreenLines + off, 1, flags, fg, bg, back);
#endif
}
#ifdef FEAT_GUI_GTK
/*
* Output the string at the given screen position. This is used in place
* of gui_screenchar() where possible because Pango needs as much context
* as possible to work nicely. It's a lot faster as well.
*/
static int
gui_screenstr(off, len, flags, fg, bg, back)
int off; /* Offset from start of screen */
int len; /* string length in screen cells */
int flags;
guicolor_T fg, bg; /* colors for cursor */
int back; /* backup this many chars when using bold trick */
{
char_u *buf;
int outlen = 0;
int i;
int retval;
if (len <= 0) /* "cannot happen"? */
return OK;
if (enc_utf8)
{
buf = alloc((unsigned)(len * MB_MAXBYTES + 1));
if (buf == NULL)
return OK; /* not much we could do here... */
for (i = off; i < off + len; ++i)
{
if (ScreenLines[i] == 0)
continue; /* skip second half of double-width char */
if (ScreenLinesUC[i] == 0)
buf[outlen++] = ScreenLines[i];
else
outlen += utfc_char2bytes(i, buf + outlen);
}
buf[outlen] = NUL; /* only to aid debugging */
retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
vim_free(buf);
return retval;
}
else if (enc_dbcs == DBCS_JPNU)
{
buf = alloc((unsigned)(len * 2 + 1));
if (buf == NULL)
return OK; /* not much we could do here... */
for (i = off; i < off + len; ++i)
{
buf[outlen++] = ScreenLines[i];
/* handle double-byte single-width char */
if (ScreenLines[i] == 0x8e)
buf[outlen++] = ScreenLines2[i];
else if (MB_BYTE2LEN(ScreenLines[i]) == 2)
buf[outlen++] = ScreenLines[++i];
}
buf[outlen] = NUL; /* only to aid debugging */
retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
vim_free(buf);
return retval;
}
else
{
return gui_outstr_nowrap(&ScreenLines[off], len,
flags, fg, bg, back);
}
}
#endif /* FEAT_GUI_GTK */
/*
* Output the given string at the current cursor position. If the string is
* too long to fit on the line, then it is truncated.
* "flags":
* GUI_MON_IS_CURSOR should only be used when this function is being called to
* actually draw (an inverted) cursor.
* GUI_MON_TRS_CURSOR is used to draw the cursor text with a transparent
* background.
* GUI_MON_NOCLEAR is used to avoid clearing the selection when drawing over
* it.
* Returns OK, unless "back" is non-zero and using the bold trick, then return
* FAIL (the caller should start drawing "back" chars back).
*/
int
gui_outstr_nowrap(s, len, flags, fg, bg, back)
char_u *s;
int len;
int flags;
guicolor_T fg, bg; /* colors for cursor */
int back; /* backup this many chars when using bold trick */
{
long_u highlight_mask;
long_u hl_mask_todo;
guicolor_T fg_color;
guicolor_T bg_color;
guicolor_T sp_color;
#if !defined(MSWIN16_FASTTEXT) && !defined(FEAT_GUI_GTK)
GuiFont font = NOFONT;
# ifdef FEAT_XFONTSET
GuiFontset fontset = NOFONTSET;
# endif
#endif
attrentry_T *aep = NULL;
int draw_flags;
int col = gui.col;
#ifdef FEAT_SIGN_ICONS
int draw_sign = FALSE;
# ifdef FEAT_NETBEANS_INTG
int multi_sign = FALSE;
# endif
#endif
if (len < 0)
len = (int)STRLEN(s);
if (len == 0)
return OK;
#ifdef FEAT_SIGN_ICONS
if (*s == SIGN_BYTE
# ifdef FEAT_NETBEANS_INTG
|| *s == MULTISIGN_BYTE
# endif
)
{
# ifdef FEAT_NETBEANS_INTG
if (*s == MULTISIGN_BYTE)
multi_sign = TRUE;
# endif
/* draw spaces instead */
s = (char_u *)" ";
if (len == 1 && col > 0)
--col;
len = 2;
draw_sign = TRUE;
highlight_mask = 0;
}
else
#endif
if (gui.highlight_mask > HL_ALL)
{
aep = syn_gui_attr2entry(gui.highlight_mask);
if (aep == NULL) /* highlighting not set */
highlight_mask = 0;
else
highlight_mask = aep->ae_attr;
}
else
highlight_mask = gui.highlight_mask;
hl_mask_todo = highlight_mask;
#if !defined(MSWIN16_FASTTEXT) && !defined(FEAT_GUI_GTK)
/* Set the font */
if (aep != NULL && aep->ae_u.gui.font != NOFONT)
font = aep->ae_u.gui.font;
# ifdef FEAT_XFONTSET
else if (aep != NULL && aep->ae_u.gui.fontset != NOFONTSET)
fontset = aep->ae_u.gui.fontset;
# endif
else
{
# ifdef FEAT_XFONTSET
if (gui.fontset != NOFONTSET)
fontset = gui.fontset;
else
# endif
if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
{
if ((hl_mask_todo & HL_ITALIC) && gui.boldital_font != NOFONT)
{
font = gui.boldital_font;
hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT | HL_ITALIC);
}
else if (gui.bold_font != NOFONT)
{
font = gui.bold_font;
hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT);
}
else
font = gui.norm_font;
}
else if ((hl_mask_todo & HL_ITALIC) && gui.ital_font != NOFONT)
{
font = gui.ital_font;
hl_mask_todo &= ~HL_ITALIC;
}
else
font = gui.norm_font;
}
# ifdef FEAT_XFONTSET
if (fontset != NOFONTSET)
gui_mch_set_fontset(fontset);
else
# endif
gui_mch_set_font(font);
#endif
draw_flags = 0;
/* Set the color */
bg_color = gui.back_pixel;
if ((flags & GUI_MON_IS_CURSOR) && gui.in_focus)
{
draw_flags |= DRAW_CURSOR;
fg_color = fg;
bg_color = bg;
sp_color = fg;
}
else if (aep != NULL)
{
fg_color = aep->ae_u.gui.fg_color;
if (fg_color == INVALCOLOR)
fg_color = gui.norm_pixel;
bg_color = aep->ae_u.gui.bg_color;
if (bg_color == INVALCOLOR)
bg_color = gui.back_pixel;
sp_color = aep->ae_u.gui.sp_color;
if (sp_color == INVALCOLOR)
sp_color = fg_color;
}
else
{
fg_color = gui.norm_pixel;
sp_color = fg_color;
}
if (highlight_mask & (HL_INVERSE | HL_STANDOUT))
{
#if defined(AMIGA)
gui_mch_set_colors(bg_color, fg_color);
#else
gui_mch_set_fg_color(bg_color);
gui_mch_set_bg_color(fg_color);
#endif
}
else
{
#if defined(AMIGA)
gui_mch_set_colors(fg_color, bg_color);
#else
gui_mch_set_fg_color(fg_color);
gui_mch_set_bg_color(bg_color);
#endif
}
gui_mch_set_sp_color(sp_color);
/* Clear the selection if we are about to write over it */
if (!(flags & GUI_MON_NOCLEAR))
clip_may_clear_selection(gui.row, gui.row);
#ifndef MSWIN16_FASTTEXT
/* If there's no bold font, then fake it */
if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
draw_flags |= DRAW_BOLD;
#endif
/*
* When drawing bold or italic characters the spill-over from the left
* neighbor may be destroyed. Let the caller backup to start redrawing
* just after a blank.
*/
if (back != 0 && ((draw_flags & DRAW_BOLD) || (highlight_mask & HL_ITALIC)))
return FAIL;
#if defined(FEAT_GUI_GTK)
/* If there's no italic font, then fake it.
* For GTK2, we don't need a different font for italic style. */
if (hl_mask_todo & HL_ITALIC)
draw_flags |= DRAW_ITALIC;
/* Do we underline the text? */
if (hl_mask_todo & HL_UNDERLINE)
draw_flags |= DRAW_UNDERL;
#else
/* Do we underline the text? */
if ((hl_mask_todo & HL_UNDERLINE)
# ifndef MSWIN16_FASTTEXT
|| (hl_mask_todo & HL_ITALIC)
# endif
)
draw_flags |= DRAW_UNDERL;
#endif
/* Do we undercurl the text? */
if (hl_mask_todo & HL_UNDERCURL)
draw_flags |= DRAW_UNDERC;
/* Do we draw transparently? */
if (flags & GUI_MON_TRS_CURSOR)
draw_flags |= DRAW_TRANSP;
/*
* Draw the text.
*/
#ifdef FEAT_GUI_GTK
/* The value returned is the length in display cells */
len = gui_gtk2_draw_string(gui.row, col, s, len, draw_flags);
#else
# ifdef FEAT_MBYTE
if (enc_utf8)
{
int start; /* index of bytes to be drawn */
int cells; /* cellwidth of bytes to be drawn */
int thislen; /* length of bytes to be drawin */
int cn; /* cellwidth of current char */
int i; /* index of current char */
int c; /* current char value */
int cl; /* byte length of current char */
int comping; /* current char is composing */
int scol = col; /* screen column */
int dowide; /* use 'guifontwide' */
/* Break the string at a composing character, it has to be drawn on
* top of the previous character. */
start = 0;
cells = 0;
for (i = 0; i < len; i += cl)
{
c = utf_ptr2char(s + i);
cn = utf_char2cells(c);
if (cn > 1
# ifdef FEAT_XFONTSET
&& fontset == NOFONTSET
# endif
&& gui.wide_font != NOFONT)
dowide = TRUE;
else
dowide = FALSE;
comping = utf_iscomposing(c);
if (!comping) /* count cells from non-composing chars */
cells += cn;
cl = utf_ptr2len(s + i);
if (cl == 0) /* hit end of string */
len = i + cl; /* len must be wrong "cannot happen" */
/* print the string so far if it's the last character or there is
* a composing character. */
if (i + cl >= len || (comping && i > start) || dowide
# if defined(FEAT_GUI_X11)
|| (cn > 1
# ifdef FEAT_XFONTSET
/* No fontset: At least draw char after wide char at
* right position. */
&& fontset == NOFONTSET
# endif
)
# endif
)
{
if (comping || dowide)
thislen = i - start;
else
thislen = i - start + cl;
if (thislen > 0)
{
gui_mch_draw_string(gui.row, scol, s + start, thislen,
draw_flags);
start += thislen;
}
scol += cells;
cells = 0;
if (dowide)
{
gui_mch_set_font(gui.wide_font);
gui_mch_draw_string(gui.row, scol - cn,
s + start, cl, draw_flags);
gui_mch_set_font(font);
start += cl;
}
# if defined(FEAT_GUI_X11)
/* No fontset: draw a space to fill the gap after a wide char
* */
if (cn > 1 && (draw_flags & DRAW_TRANSP) == 0
# ifdef FEAT_XFONTSET
&& fontset == NOFONTSET
# endif
&& !dowide)
gui_mch_draw_string(gui.row, scol - 1, (char_u *)" ",
1, draw_flags);
# endif
}
/* Draw a composing char on top of the previous char. */
if (comping)
{
# if (defined(__APPLE_CC__) || defined(__MRC__)) && TARGET_API_MAC_CARBON
/* Carbon ATSUI autodraws composing char over previous char */
gui_mch_draw_string(gui.row, scol, s + i, cl,
draw_flags | DRAW_TRANSP);
# else
gui_mch_draw_string(gui.row, scol - cn, s + i, cl,
draw_flags | DRAW_TRANSP);
# endif
start = i + cl;
}
}
/* The stuff below assumes "len" is the length in screen columns. */
len = scol - col;
}
else
# endif
{
gui_mch_draw_string(gui.row, col, s, len, draw_flags);
# ifdef FEAT_MBYTE
if (enc_dbcs == DBCS_JPNU)
{
/* Get the length in display cells, this can be different from the
* number of bytes for "euc-jp". */
len = mb_string2cells(s, len);
}
# endif
}
#endif /* !FEAT_GUI_GTK */
if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
gui.col = col + len;
/* May need to invert it when it's part of the selection. */
if (flags & GUI_MON_NOCLEAR)
clip_may_redraw_selection(gui.row, col, len);
if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
{
/* Invalidate the old physical cursor position if we wrote over it */
if (gui.cursor_row == gui.row
&& gui.cursor_col >= col
&& gui.cursor_col < col + len)
gui.cursor_is_valid = FALSE;
}
#ifdef FEAT_SIGN_ICONS
if (draw_sign)
/* Draw the sign on top of the spaces. */
gui_mch_drawsign(gui.row, col, gui.highlight_mask);
# if defined(FEAT_NETBEANS_INTG) && (defined(FEAT_GUI_X11) \
|| defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32))
if (multi_sign)
netbeans_draw_multisign_indicator(gui.row);
# endif
#endif
return OK;
}
/*
* Un-draw the cursor. Actually this just redraws the character at the given
* position. The character just before it too, for when it was in bold.
*/
void
gui_undraw_cursor()
{
if (gui.cursor_is_valid)
{
#ifdef FEAT_HANGULIN
if (composing_hangul
&& gui.col == gui.cursor_col && gui.row == gui.cursor_row)
(void)gui_outstr_nowrap(composing_hangul_buffer, 2,
GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR,
gui.norm_pixel, gui.back_pixel, 0);
else
{
#endif
if (gui_redraw_block(gui.cursor_row, gui.cursor_col,
gui.cursor_row, gui.cursor_col, GUI_MON_NOCLEAR)
&& gui.cursor_col > 0)
(void)gui_redraw_block(gui.cursor_row, gui.cursor_col - 1,
gui.cursor_row, gui.cursor_col - 1, GUI_MON_NOCLEAR);
#ifdef FEAT_HANGULIN
if (composing_hangul)
(void)gui_redraw_block(gui.cursor_row, gui.cursor_col + 1,
gui.cursor_row, gui.cursor_col + 1, GUI_MON_NOCLEAR);
}
#endif
/* Cursor_is_valid is reset when the cursor is undrawn, also reset it
* here in case it wasn't needed to undraw it. */
gui.cursor_is_valid = FALSE;
}
}
void
gui_redraw(x, y, w, h)
int x;
int y;
int w;
int h;
{
int row1, col1, row2, col2;
row1 = Y_2_ROW(y);
col1 = X_2_COL(x);
row2 = Y_2_ROW(y + h - 1);
col2 = X_2_COL(x + w - 1);
(void)gui_redraw_block(row1, col1, row2, col2, GUI_MON_NOCLEAR);
/*
* We may need to redraw the cursor, but don't take it upon us to change
* its location after a scroll.
* (maybe be more strict even and test col too?)
* These things may be outside the update/clipping region and reality may
* not reflect Vims internal ideas if these operations are clipped away.
*/
if (gui.row == gui.cursor_row)
gui_update_cursor(TRUE, TRUE);
}
/*
* Draw a rectangular block of characters, from row1 to row2 (inclusive) and
* from col1 to col2 (inclusive).
* Return TRUE when the character before the first drawn character has
* different attributes (may have to be redrawn too).
*/
int
gui_redraw_block(row1, col1, row2, col2, flags)
int row1;
int col1;
int row2;
int col2;
int flags; /* flags for gui_outstr_nowrap() */
{
int old_row, old_col;
long_u old_hl_mask;
int off;
sattr_T first_attr;
int idx, len;
int back, nback;
int retval = FALSE;
#ifdef FEAT_MBYTE
int orig_col1, orig_col2;
#endif
/* Don't try to update when ScreenLines is not valid */
if (!screen_cleared || ScreenLines == NULL)
return retval;
/* Don't try to draw outside the shell! */
/* Check everything, strange values may be caused by a big border width */
col1 = check_col(col1);
col2 = check_col(col2);
row1 = check_row(row1);
row2 = check_row(row2);
/* Remember where our cursor was */
old_row = gui.row;
old_col = gui.col;
old_hl_mask = gui.highlight_mask;
#ifdef FEAT_MBYTE
orig_col1 = col1;
orig_col2 = col2;
#endif
for (gui.row = row1; gui.row <= row2; gui.row++)
{
#ifdef FEAT_MBYTE
/* When only half of a double-wide character is in the block, include
* the other half. */
col1 = orig_col1;
col2 = orig_col2;
off = LineOffset[gui.row];
if (enc_dbcs != 0)
{
if (col1 > 0)
col1 -= dbcs_screen_head_off(ScreenLines + off,
ScreenLines + off + col1);
col2 += dbcs_screen_tail_off(ScreenLines + off,
ScreenLines + off + col2);
}
else if (enc_utf8)
{
if (ScreenLines[off + col1] == 0)
--col1;
# ifdef FEAT_GUI_GTK
if (col2 + 1 < Columns && ScreenLines[off + col2 + 1] == 0)
++col2;
# endif
}
#endif
gui.col = col1;
off = LineOffset[gui.row] + gui.col;
len = col2 - col1 + 1;
/* Find how many chars back this highlighting starts, or where a space
* is. Needed for when the bold trick is used */
for (back = 0; back < col1; ++back)
if (ScreenAttrs[off - 1 - back] != ScreenAttrs[off]
|| ScreenLines[off - 1 - back] == ' ')
break;
retval = (col1 > 0 && ScreenAttrs[off - 1] != 0 && back == 0
&& ScreenLines[off - 1] != ' ');
/* Break it up in strings of characters with the same attributes. */
/* Print UTF-8 characters individually. */
while (len > 0)
{
first_attr = ScreenAttrs[off];
gui.highlight_mask = first_attr;
#if defined(FEAT_MBYTE) && !defined(FEAT_GUI_GTK)
if (enc_utf8 && ScreenLinesUC[off] != 0)
{
/* output multi-byte character separately */
nback = gui_screenchar(off, flags,
(guicolor_T)0, (guicolor_T)0, back);
if (gui.col < Columns && ScreenLines[off + 1] == 0)
idx = 2;
else
idx = 1;
}
else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
{
/* output double-byte, single-width character separately */
nback = gui_screenchar(off, flags,
(guicolor_T)0, (guicolor_T)0, back);
idx = 1;
}
else
#endif
{
#ifdef FEAT_GUI_GTK
for (idx = 0; idx < len; ++idx)
{
if (enc_utf8 && ScreenLines[off + idx] == 0)
continue; /* skip second half of double-width char */
if (ScreenAttrs[off + idx] != first_attr)
break;
}
/* gui_screenstr() takes care of multibyte chars */
nback = gui_screenstr(off, idx, flags,
(guicolor_T)0, (guicolor_T)0, back);
#else
for (idx = 0; idx < len && ScreenAttrs[off + idx] == first_attr;
idx++)
{
# ifdef FEAT_MBYTE
/* Stop at a multi-byte Unicode character. */
if (enc_utf8 && ScreenLinesUC[off + idx] != 0)
break;
if (enc_dbcs == DBCS_JPNU)
{
/* Stop at a double-byte single-width char. */
if (ScreenLines[off + idx] == 0x8e)
break;
if (len > 1 && (*mb_ptr2len)(ScreenLines
+ off + idx) == 2)
++idx; /* skip second byte of double-byte char */
}
# endif
}
nback = gui_outstr_nowrap(ScreenLines + off, idx, flags,
(guicolor_T)0, (guicolor_T)0, back);
#endif
}
if (nback == FAIL)
{
/* Must back up to start drawing where a bold or italic word
* starts. */
off -= back;
len += back;
gui.col -= back;
}
else
{
off += idx;
len -= idx;
}
back = 0;
}
}
/* Put the cursor back where it was */
gui.row = old_row;
gui.col = old_col;
gui.highlight_mask = (int)old_hl_mask;
return retval;
}
static void
gui_delete_lines(row, count)
int row;
int count;
{
if (count <= 0)
return;
if (row + count > gui.scroll_region_bot)
/* Scrolled out of region, just blank the lines out */
gui_clear_block(row, gui.scroll_region_left,
gui.scroll_region_bot, gui.scroll_region_right);
else
{
gui_mch_delete_lines(row, count);
/* If the cursor was in the deleted lines it's now gone. If the
* cursor was in the scrolled lines adjust its position. */
if (gui.cursor_row >= row
&& gui.cursor_col >= gui.scroll_region_left
&& gui.cursor_col <= gui.scroll_region_right)
{
if (gui.cursor_row < row + count)
gui.cursor_is_valid = FALSE;
else if (gui.cursor_row <= gui.scroll_region_bot)
gui.cursor_row -= count;
}
}
}
static void
gui_insert_lines(row, count)
int row;
int count;
{
if (count <= 0)
return;
if (row + count > gui.scroll_region_bot)
/* Scrolled out of region, just blank the lines out */
gui_clear_block(row, gui.scroll_region_left,
gui.scroll_region_bot, gui.scroll_region_right);
else
{
gui_mch_insert_lines(row, count);
if (gui.cursor_row >= gui.row
&& gui.cursor_col >= gui.scroll_region_left
&& gui.cursor_col <= gui.scroll_region_right)
{
if (gui.cursor_row <= gui.scroll_region_bot - count)
gui.cursor_row += count;
else if (gui.cursor_row <= gui.scroll_region_bot)
gui.cursor_is_valid = FALSE;
}
}
}
/*
* The main GUI input routine. Waits for a character from the keyboard.
* wtime == -1 Wait forever.
* wtime == 0 Don't wait.
* 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_wait_for_chars(wtime)
long wtime;
{
int retval;
#ifdef FEAT_MENU
/*
* If we're going to wait a bit, update the menus and mouse shape for the
* current State.
*/
if (wtime != 0)
gui_update_menus(0);
#endif
gui_mch_update();
if (input_available()) /* Got char, return immediately */
return OK;
if (wtime == 0) /* Don't wait for char */
return FAIL;
/* Before waiting, flush any output to the screen. */
gui_mch_flush();
if (wtime > 0)
{
/* Blink when waiting for a character. Probably only does something
* for showmatch() */
gui_mch_start_blink();
retval = gui_mch_wait_for_chars(wtime);
gui_mch_stop_blink();
return retval;
}
/*
* While we are waiting indefinitely for a character, blink the cursor.
*/
gui_mch_start_blink();
retval = FAIL;
/*
* We may want to trigger the CursorHold event. First wait for
* 'updatetime' and if nothing is typed within that time put the
* K_CURSORHOLD key in the input buffer.
*/
if (gui_mch_wait_for_chars(p_ut) == OK)
retval = OK;
#ifdef FEAT_AUTOCMD
else if (trigger_cursorhold())
{
char_u buf[3];
/* Put K_CURSORHOLD in the input buffer. */
buf[0] = CSI;
buf[1] = KS_EXTRA;
buf[2] = (int)KE_CURSORHOLD;
add_to_input_buf(buf, 3);
retval = OK;
}
#endif
if (retval == FAIL)
{
/* Blocking wait. */
before_blocking();
retval = gui_mch_wait_for_chars(-1L);
}
gui_mch_stop_blink();
return retval;
}
/*
* Fill p[4] with mouse coordinates encoded for check_termcode().
*/
static void
fill_mouse_coord(p, col, row)
char_u *p;
int col;
int row;
{
p[0] = (char_u)(col / 128 + ' ' + 1);
p[1] = (char_u)(col % 128 + ' ' + 1);
p[2] = (char_u)(row / 128 + ' ' + 1);
p[3] = (char_u)(row % 128 + ' ' + 1);
}
/*
* Generic mouse support function. Add a mouse event to the input buffer with
* the given properties.
* button --- may be any of MOUSE_LEFT, MOUSE_MIDDLE, MOUSE_RIGHT,
* MOUSE_X1, MOUSE_X2
* MOUSE_DRAG, or MOUSE_RELEASE.
* MOUSE_4 and MOUSE_5 are used for vertical scroll wheel,
* MOUSE_6 and MOUSE_7 for horizontal scroll wheel.
* x, y --- Coordinates of mouse in pixels.
* repeated_click --- TRUE if this click comes only a short time after a
* previous click.
* modifiers --- Bit field which may be any of the following modifiers
* or'ed together: MOUSE_SHIFT | MOUSE_CTRL | MOUSE_ALT.
* This function will ignore drag events where the mouse has not moved to a new
* character.
*/
void
gui_send_mouse_event(button, x, y, repeated_click, modifiers)
int button;
int x;
int y;
int repeated_click;
int_u modifiers;
{
static int prev_row = 0, prev_col = 0;
static int prev_button = -1;
static int num_clicks = 1;
char_u string[10];
enum key_extra button_char;
int row, col;
#ifdef FEAT_CLIPBOARD
int checkfor;
int did_clip = FALSE;
#endif
/*
* Scrolling may happen at any time, also while a selection is present.
*/
switch (button)
{
case MOUSE_X1:
button_char = KE_X1MOUSE;
goto button_set;
case MOUSE_X2:
button_char = KE_X2MOUSE;
goto button_set;
case MOUSE_4:
button_char = KE_MOUSEDOWN;
goto button_set;
case MOUSE_5:
button_char = KE_MOUSEUP;
goto button_set;
case MOUSE_6:
button_char = KE_MOUSELEFT;
goto button_set;
case MOUSE_7:
button_char = KE_MOUSERIGHT;
button_set:
{
/* Don't put events in the input queue now. */
if (hold_gui_events)
return;
string[3] = CSI;
string[4] = KS_EXTRA;
string[5] = (int)button_char;
/* Pass the pointer coordinates of the scroll event so that we
* know which window to scroll. */
row = gui_xy2colrow(x, y, &col);
string[6] = (char_u)(col / 128 + ' ' + 1);
string[7] = (char_u)(col % 128 + ' ' + 1);
string[8] = (char_u)(row / 128 + ' ' + 1);
string[9] = (char_u)(row % 128 + ' ' + 1);
if (modifiers == 0)
add_to_input_buf(string + 3, 7);
else
{
string[0] = CSI;
string[1] = KS_MODIFIER;
string[2] = 0;
if (modifiers & MOUSE_SHIFT)
string[2] |= MOD_MASK_SHIFT;
if (modifiers & MOUSE_CTRL)
string[2] |= MOD_MASK_CTRL;
if (modifiers & MOUSE_ALT)
string[2] |= MOD_MASK_ALT;
add_to_input_buf(string, 10);
}
return;
}
}
#ifdef FEAT_CLIPBOARD
/* If a clipboard selection is in progress, handle it */
if (clip_star.state == SELECT_IN_PROGRESS)
{
clip_process_selection(button, X_2_COL(x), Y_2_ROW(y), repeated_click);
return;
}
/* Determine which mouse settings to look for based on the current mode */
switch (get_real_state())
{
case NORMAL_BUSY:
case OP_PENDING:
case NORMAL: checkfor = MOUSE_NORMAL; break;
case VISUAL: checkfor = MOUSE_VISUAL; break;
case SELECTMODE: checkfor = MOUSE_VISUAL; break;
case REPLACE:
case REPLACE+LANGMAP:
#ifdef FEAT_VREPLACE
case VREPLACE:
case VREPLACE+LANGMAP:
#endif
case INSERT:
case INSERT+LANGMAP: checkfor = MOUSE_INSERT; break;
case ASKMORE:
case HITRETURN: /* At the more- and hit-enter prompt pass the
mouse event for a click on or below the
message line. */
if (Y_2_ROW(y) >= msg_row)
checkfor = MOUSE_NORMAL;
else
checkfor = MOUSE_RETURN;
break;
/*
* On the command line, use the clipboard selection on all lines
* but the command line. But not when pasting.
*/
case CMDLINE:
case CMDLINE+LANGMAP:
if (Y_2_ROW(y) < cmdline_row && button != MOUSE_MIDDLE)
checkfor = MOUSE_NONE;
else
checkfor = MOUSE_COMMAND;
break;
default:
checkfor = MOUSE_NONE;
break;
};
/*
* Allow clipboard selection of text on the command line in "normal"
* modes. Don't do this when dragging the status line, or extending a
* Visual selection.
*/
if ((State == NORMAL || State == NORMAL_BUSY || (State & INSERT))
&& Y_2_ROW(y) >= topframe->fr_height
# ifdef FEAT_WINDOWS
+ firstwin->w_winrow
# endif
&& button != MOUSE_DRAG
# ifdef FEAT_MOUSESHAPE
&& !drag_status_line
# ifdef FEAT_VERTSPLIT
&& !drag_sep_line
# endif
# endif
)
checkfor = MOUSE_NONE;
/*
* Use modeless selection when holding CTRL and SHIFT pressed.
*/
if ((modifiers & MOUSE_CTRL) && (modifiers & MOUSE_SHIFT))
checkfor = MOUSE_NONEF;
/*
* In Ex mode, always use modeless selection.
*/
if (exmode_active)
checkfor = MOUSE_NONE;
/*
* If the mouse settings say to not use the mouse, use the modeless
* selection. But if Visual is active, assume that only the Visual area
* will be selected.
* Exception: On the command line, both the selection is used and a mouse
* key is send.
*/
if (!mouse_has(checkfor) || checkfor == MOUSE_COMMAND)
{
#ifdef FEAT_VISUAL
/* Don't do modeless selection in Visual mode. */
if (checkfor != MOUSE_NONEF && VIsual_active && (State & NORMAL))
return;
#endif
/*
* When 'mousemodel' is "popup", shift-left is translated to right.
* But not when also using Ctrl.
*/
if (mouse_model_popup() && button == MOUSE_LEFT
&& (modifiers & MOUSE_SHIFT) && !(modifiers & MOUSE_CTRL))
{
button = MOUSE_RIGHT;
modifiers &= ~ MOUSE_SHIFT;
}
/* If the selection is done, allow the right button to extend it.
* If the selection is cleared, allow the right button to start it
* from the cursor position. */
if (button == MOUSE_RIGHT)
{
if (clip_star.state == SELECT_CLEARED)
{
if (State & CMDLINE)
{
col = msg_col;
row = msg_row;
}
else
{
col = curwin->w_wcol;
row = curwin->w_wrow + W_WINROW(curwin);
}
clip_start_selection(col, row, FALSE);
}
clip_process_selection(button, X_2_COL(x), Y_2_ROW(y),
repeated_click);
did_clip = TRUE;
}
/* Allow the left button to start the selection */
else if (button == MOUSE_LEFT)
{
clip_start_selection(X_2_COL(x), Y_2_ROW(y), repeated_click);
did_clip = TRUE;
}
/* Always allow pasting */
if (button != MOUSE_MIDDLE)
{
if (!mouse_has(checkfor) || button == MOUSE_RELEASE)
return;
if (checkfor != MOUSE_COMMAND)
button = MOUSE_LEFT;
}
repeated_click = FALSE;
}
if (clip_star.state != SELECT_CLEARED && !did_clip)
clip_clear_selection();
#endif
/* Don't put events in the input queue now. */
if (hold_gui_events)
return;
row = gui_xy2colrow(x, y, &col);
/*
* If we are dragging and the mouse hasn't moved far enough to be on a
* different character, then don't send an event to vim.
*/
if (button == MOUSE_DRAG)
{
if (row == prev_row && col == prev_col)
return;
/* Dragging above the window, set "row" to -1 to cause a scroll. */
if (y < 0)
row = -1;
}
/*
* If topline has changed (window scrolled) since the last click, reset
* repeated_click, because we don't want starting Visual mode when
* clicking on a different character in the text.
*/
if (curwin->w_topline != gui_prev_topline
#ifdef FEAT_DIFF
|| curwin->w_topfill != gui_prev_topfill
#endif
)
repeated_click = FALSE;
string[0] = CSI; /* this sequence is recognized by check_termcode() */
string[1] = KS_MOUSE;
string[2] = KE_FILLER;
if (button != MOUSE_DRAG && button != MOUSE_RELEASE)
{
if (repeated_click)
{
/*
* Handle multiple clicks. They only count if the mouse is still
* pointing at the same character.
*/
if (button != prev_button || row != prev_row || col != prev_col)
num_clicks = 1;
else if (++num_clicks > 4)
num_clicks = 1;
}
else
num_clicks = 1;
prev_button = button;
gui_prev_topline = curwin->w_topline;
#ifdef FEAT_DIFF
gui_prev_topfill = curwin->w_topfill;
#endif
string[3] = (char_u)(button | 0x20);
SET_NUM_MOUSE_CLICKS(string[3], num_clicks);
}
else
string[3] = (char_u)button;
string[3] |= modifiers;
fill_mouse_coord(string + 4, col, row);
add_to_input_buf(string, 8);
if (row < 0)
prev_row = 0;
else
prev_row = row;
prev_col = col;
/*
* We need to make sure this is cleared since Athena doesn't tell us when
* he is done dragging. Neither does GTK+ 2 -- at least for now.
*/
#if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK)
gui.dragged_sb = SBAR_NONE;
#endif
}
/*
* Convert x and y coordinate to column and row in text window.
* Corrects for multi-byte character.
* returns column in "*colp" and row as return value;
*/
int
gui_xy2colrow(x, y, colp)
int x;
int y;
int *colp;
{
int col = check_col(X_2_COL(x));
int row = check_row(Y_2_ROW(y));
#ifdef FEAT_MBYTE
*colp = mb_fix_col(col, row);
#else
*colp = col;
#endif
return row;
}
#if defined(FEAT_MENU) || defined(PROTO)
/*
* Callback function for when a menu entry has been selected.
*/
void
gui_menu_cb(menu)
vimmenu_T *menu;
{
char_u bytes[sizeof(long_u)];
/* Don't put events in the input queue now. */
if (hold_gui_events)
return;
bytes[0] = CSI;
bytes[1] = KS_MENU;
bytes[2] = KE_FILLER;
add_to_input_buf(bytes, 3);
add_long_to_buf((long_u)menu, bytes);
add_to_input_buf_csi(bytes, sizeof(long_u));
}
#endif
static int prev_which_scrollbars[3];
/*
* Set which components are present.
* If "oldval" is not NULL, "oldval" is the previous value, the new value is
* in p_go.
*/
void
gui_init_which_components(oldval)
char_u *oldval UNUSED;
{
#ifdef FEAT_MENU
static int prev_menu_is_active = -1;
#endif
#ifdef FEAT_TOOLBAR
static int prev_toolbar = -1;
int using_toolbar = FALSE;
#endif
#ifdef FEAT_GUI_TABLINE
int using_tabline;
#endif
#ifdef FEAT_FOOTER
static int prev_footer = -1;
int using_footer = FALSE;
#endif
#if defined(FEAT_MENU) && !defined(WIN16)
static int prev_tearoff = -1;
int using_tearoff = FALSE;
#endif
char_u *p;
int i;
#ifdef FEAT_MENU
int grey_old, grey_new;
char_u *temp;
#endif
win_T *wp;
int need_set_size;
int fix_size;
#ifdef FEAT_MENU
if (oldval != NULL && gui.in_use)
{
/*
* Check if the menu's go from grey to non-grey or vise versa.
*/
grey_old = (vim_strchr(oldval, GO_GREY) != NULL);
grey_new = (vim_strchr(p_go, GO_GREY) != NULL);
if (grey_old != grey_new)
{
temp = p_go;
p_go = oldval;
gui_update_menus(MENU_ALL_MODES);
p_go = temp;
}
}
gui.menu_is_active = FALSE;
#endif
for (i = 0; i < 3; i++)
gui.which_scrollbars[i] = FALSE;
for (p = p_go; *p; p++)
switch (*p)
{
case GO_LEFT:
gui.which_scrollbars[SBAR_LEFT] = TRUE;
break;
case GO_RIGHT:
gui.which_scrollbars[SBAR_RIGHT] = TRUE;
break;
#ifdef FEAT_VERTSPLIT
case GO_VLEFT:
if (win_hasvertsplit())
gui.which_scrollbars[SBAR_LEFT] = TRUE;
break;
case GO_VRIGHT:
if (win_hasvertsplit())
gui.which_scrollbars[SBAR_RIGHT] = TRUE;
break;
#endif
case GO_BOT:
gui.which_scrollbars[SBAR_BOTTOM] = TRUE;
break;
#ifdef FEAT_MENU
case GO_MENUS:
gui.menu_is_active = TRUE;
break;
#endif
case GO_GREY:
/* make menu's have grey items, ignored here */
break;
#ifdef FEAT_TOOLBAR
case GO_TOOLBAR:
using_toolbar = TRUE;
break;
#endif
#ifdef FEAT_FOOTER
case GO_FOOTER:
using_footer = TRUE;
break;
#endif
case GO_TEAROFF:
#if defined(FEAT_MENU) && !defined(WIN16)
using_tearoff = TRUE;
#endif
break;
default:
/* Ignore options that are not supported */
break;
}
if (gui.in_use)
{
need_set_size = 0;
fix_size = FALSE;
#ifdef FEAT_GUI_TABLINE
/* Update the GUI tab line, it may appear or disappear. This may
* cause the non-GUI tab line to disappear or appear. */
using_tabline = gui_has_tabline();
if (!gui_mch_showing_tabline() != !using_tabline)
{
/* We don't want a resize event change "Rows" here, save and
* restore it. Resizing is handled below. */
i = Rows;
gui_update_tabline();
Rows = i;
need_set_size |= RESIZE_VERT;
if (using_tabline)
fix_size = TRUE;
if (!gui_use_tabline())
redraw_tabline = TRUE; /* may draw non-GUI tab line */
}
#endif
for (i = 0; i < 3; i++)
{
/* The scrollbar needs to be updated when it is shown/unshown and
* when switching tab pages. But the size only changes when it's
* shown/unshown. Thus we need two places to remember whether a
* scrollbar is there or not. */
if (gui.which_scrollbars[i] != prev_which_scrollbars[i]
#ifdef FEAT_WINDOWS
|| gui.which_scrollbars[i]
!= curtab->tp_prev_which_scrollbars[i]
#endif
)
{
if (i == SBAR_BOTTOM)
gui_mch_enable_scrollbar(&gui.bottom_sbar,
gui.which_scrollbars[i]);
else
{
FOR_ALL_WINDOWS(wp)
{
gui_do_scrollbar(wp, i, gui.which_scrollbars[i]);
}
}
if (gui.which_scrollbars[i] != prev_which_scrollbars[i])
{
if (i == SBAR_BOTTOM)
need_set_size |= RESIZE_VERT;
else
need_set_size |= RESIZE_HOR;
if (gui.which_scrollbars[i])
fix_size = TRUE;
}
}
#ifdef FEAT_WINDOWS
curtab->tp_prev_which_scrollbars[i] = gui.which_scrollbars[i];
#endif
prev_which_scrollbars[i] = gui.which_scrollbars[i];
}
#ifdef FEAT_MENU
if (gui.menu_is_active != prev_menu_is_active)
{
/* We don't want a resize event change "Rows" here, save and
* restore it. Resizing is handled below. */
i = Rows;
gui_mch_enable_menu(gui.menu_is_active);
Rows = i;
prev_menu_is_active = gui.menu_is_active;
need_set_size |= RESIZE_VERT;
if (gui.menu_is_active)
fix_size = TRUE;
}
#endif
#ifdef FEAT_TOOLBAR
if (using_toolbar != prev_toolbar)
{
gui_mch_show_toolbar(using_toolbar);
prev_toolbar = using_toolbar;
need_set_size |= RESIZE_VERT;
if (using_toolbar)
fix_size = TRUE;
}
#endif
#ifdef FEAT_FOOTER
if (using_footer != prev_footer)
{
gui_mch_enable_footer(using_footer);
prev_footer = using_footer;
need_set_size |= RESIZE_VERT;
if (using_footer)
fix_size = TRUE;
}
#endif
#if defined(FEAT_MENU) && !defined(WIN16) && !(defined(WIN3264) && !defined(FEAT_TEAROFF))
if (using_tearoff != prev_tearoff)
{
gui_mch_toggle_tearoffs(using_tearoff);
prev_tearoff = using_tearoff;
}
#endif
if (need_set_size != 0)
{
#ifdef FEAT_GUI_GTK
long prev_Columns = Columns;
long prev_Rows = Rows;
#endif
/* Adjust the size of the window to make the text area keep the
* same size and to avoid that part of our window is off-screen
* and a scrollbar can't be used, for example. */
gui_set_shellsize(FALSE, fix_size, need_set_size);
#ifdef FEAT_GUI_GTK
/* GTK has the annoying habit of sending us resize events when
* changing the window size ourselves. This mostly happens when
* waiting for a character to arrive, quite unpredictably, and may
* change Columns and Rows when we don't want it. Wait for a
* character here to avoid this effect.
* If you remove this, please test this command for resizing
* effects (with optional left scrollbar): ":vsp|q|vsp|q|vsp|q".
* Don't do this while starting up though.
* Don't change Rows when adding menu/toolbar/tabline.
* Don't change Columns when adding vertical toolbar. */
if (!gui.starting && need_set_size != (RESIZE_VERT | RESIZE_HOR))
(void)char_avail();
if ((need_set_size & RESIZE_VERT) == 0)
Rows = prev_Rows;
if ((need_set_size & RESIZE_HOR) == 0)
Columns = prev_Columns;
#endif
}
#ifdef FEAT_WINDOWS
/* When the console tabline appears or disappears the window positions
* change. */
if (firstwin->w_winrow != tabline_height())
shell_new_rows(); /* recompute window positions and heights */
#endif
}
}
#if defined(FEAT_GUI_TABLINE) || defined(PROTO)
/*
* Return TRUE if the GUI is taking care of the tabline.
* It may still be hidden if 'showtabline' is zero.
*/
int
gui_use_tabline()
{
return gui.in_use && vim_strchr(p_go, GO_TABLINE) != NULL;
}
/*
* Return TRUE if the GUI is showing the tabline.
* This uses 'showtabline'.
*/
static int
gui_has_tabline()
{
if (!gui_use_tabline()
|| p_stal == 0
|| (p_stal == 1 && first_tabpage->tp_next == NULL))
return FALSE;
return TRUE;
}
/*
* Update the tabline.
* This may display/undisplay the tabline and update the labels.
*/
void
gui_update_tabline()
{
int showit = gui_has_tabline();
int shown = gui_mch_showing_tabline();
if (!gui.starting && starting == 0)
{
/* Updating the tabline uses direct GUI commands, flush
* outstanding instructions first. (esp. clear screen) */
out_flush();
gui_mch_flush();
if (!showit != !shown)
gui_mch_show_tabline(showit);
if (showit != 0)
gui_mch_update_tabline();
/* When the tabs change from hidden to shown or from shown to
* hidden the size of the text area should remain the same. */
if (!showit != !shown)
gui_set_shellsize(FALSE, showit, RESIZE_VERT);
}
}
/*
* Get the label or tooltip for tab page "tp" into NameBuff[].
*/
void
get_tabline_label(tp, tooltip)
tabpage_T *tp;
int tooltip; /* TRUE: get tooltip */
{
int modified = FALSE;
char_u buf[40];
int wincount;
win_T *wp;
char_u **opt;
/* Use 'guitablabel' or 'guitabtooltip' if it's set. */
opt = (tooltip ? &p_gtt : &p_gtl);
if (**opt != NUL)
{
int use_sandbox = FALSE;
int save_called_emsg = called_emsg;
char_u res[MAXPATHL];
tabpage_T *save_curtab;
char_u *opt_name = (char_u *)(tooltip ? "guitabtooltip"
: "guitablabel");
called_emsg = FALSE;
printer_page_num = tabpage_index(tp);
# ifdef FEAT_EVAL
set_vim_var_nr(VV_LNUM, printer_page_num);
use_sandbox = was_set_insecurely(opt_name, 0);
# endif
/* It's almost as going to the tabpage, but without autocommands. */
curtab->tp_firstwin = firstwin;
curtab->tp_lastwin = lastwin;
curtab->tp_curwin = curwin;
save_curtab = curtab;
curtab = tp;
topframe = curtab->tp_topframe;
firstwin = curtab->tp_firstwin;
lastwin = curtab->tp_lastwin;
curwin = curtab->tp_curwin;
curbuf = curwin->w_buffer;
/* Can't use NameBuff directly, build_stl_str_hl() uses it. */
build_stl_str_hl(curwin, res, MAXPATHL, *opt, use_sandbox,
0, (int)Columns, NULL, NULL);
STRCPY(NameBuff, res);
/* Back to the original curtab. */
curtab = save_curtab;
topframe = curtab->tp_topframe;
firstwin = curtab->tp_firstwin;
lastwin = curtab->tp_lastwin;
curwin = curtab->tp_curwin;
curbuf = curwin->w_buffer;
if (called_emsg)
set_string_option_direct(opt_name, -1,
(char_u *)"", OPT_FREE, SID_ERROR);
called_emsg |= save_called_emsg;
}
/* If 'guitablabel'/'guitabtooltip' is not set or the result is empty then
* use a default label. */
if (**opt == NUL || *NameBuff == NUL)
{
/* Get the buffer name into NameBuff[] and shorten it. */
get_trans_bufname(tp == curtab ? curbuf : tp->tp_curwin->w_buffer);
if (!tooltip)
shorten_dir(NameBuff);
wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
if (bufIsChanged(wp->w_buffer))
modified = TRUE;
if (modified || wincount > 1)
{
if (wincount > 1)
vim_snprintf((char *)buf, sizeof(buf), "%d", wincount);
else
buf[0] = NUL;
if (modified)
STRCAT(buf, "+");
STRCAT(buf, " ");
STRMOVE(NameBuff + STRLEN(buf), NameBuff);
mch_memmove(NameBuff, buf, STRLEN(buf));
}
}
}
/*
* Send the event for clicking to select tab page "nr".
* Returns TRUE if it was done, FALSE when skipped because we are already at
* that tab page or the cmdline window is open.
*/
int
send_tabline_event(nr)
int nr;
{
char_u string[3];
if (nr == tabpage_index(curtab))
return FALSE;
/* Don't put events in the input queue now. */
if (hold_gui_events
# ifdef FEAT_CMDWIN
|| cmdwin_type != 0
# endif
)
{
/* Set it back to the current tab page. */
gui_mch_set_curtab(tabpage_index(curtab));
return FALSE;
}
string[0] = CSI;
string[1] = KS_TABLINE;
string[2] = KE_FILLER;
add_to_input_buf(string, 3);
string[0] = nr;
add_to_input_buf_csi(string, 1);
return TRUE;
}
/*
* Send a tabline menu event
*/
void
send_tabline_menu_event(tabidx, event)
int tabidx;
int event;
{
char_u string[3];
/* Don't put events in the input queue now. */
if (hold_gui_events)
return;
string[0] = CSI;
string[1] = KS_TABMENU;
string[2] = KE_FILLER;
add_to_input_buf(string, 3);
string[0] = tabidx;
string[1] = (char_u)(long)event;
add_to_input_buf_csi(string, 2);
}
#endif
/*
* Scrollbar stuff:
*/
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Remove all scrollbars. Used before switching to another tab page.
*/
void
gui_remove_scrollbars()
{
int i;
win_T *wp;
for (i = 0; i < 3; i++)
{
if (i == SBAR_BOTTOM)
gui_mch_enable_scrollbar(&gui.bottom_sbar, FALSE);
else
{
FOR_ALL_WINDOWS(wp)
{
gui_do_scrollbar(wp, i, FALSE);
}
}
curtab->tp_prev_which_scrollbars[i] = -1;
}
}
#endif
void
gui_create_scrollbar(sb, type, wp)
scrollbar_T *sb;
int type;
win_T *wp;
{
static int sbar_ident = 0;
sb->ident = sbar_ident++; /* No check for too big, but would it happen? */
sb->wp = wp;
sb->type = type;
sb->value = 0;
#ifdef FEAT_GUI_ATHENA
sb->pixval = 0;
#endif
sb->size = 1;
sb->max = 1;
sb->top = 0;
sb->height = 0;
#ifdef FEAT_VERTSPLIT
sb->width = 0;
#endif
sb->status_height = 0;
gui_mch_create_scrollbar(sb, (wp == NULL) ? SBAR_HORIZ : SBAR_VERT);
}
/*
* Find the scrollbar with the given index.
*/
scrollbar_T *
gui_find_scrollbar(ident)
long ident;
{
win_T *wp;
if (gui.bottom_sbar.ident == ident)
return &gui.bottom_sbar;
FOR_ALL_WINDOWS(wp)
{
if (wp->w_scrollbars[SBAR_LEFT].ident == ident)
return &wp->w_scrollbars[SBAR_LEFT];
if (wp->w_scrollbars[SBAR_RIGHT].ident == ident)
return &wp->w_scrollbars[SBAR_RIGHT];
}
return NULL;
}
/*
* For most systems: Put a code in the input buffer for a dragged scrollbar.
*
* For Win32, Macintosh and GTK+ 2:
* Scrollbars seem to grab focus and vim doesn't read the input queue until
* you stop dragging the scrollbar. We get here each time the scrollbar is
* dragged another pixel, but as far as the rest of vim goes, it thinks
* we're just hanging in the call to DispatchMessage() in
* process_message(). The DispatchMessage() call that hangs was passed a
* mouse button click event in the scrollbar window. -- webb.
*
* Solution: Do the scrolling right here. But only when allowed.
* Ignore the scrollbars while executing an external command or when there
* are still characters to be processed.
*/
void
gui_drag_scrollbar(sb, value, still_dragging)
scrollbar_T *sb;
long value;
int still_dragging;
{
#ifdef FEAT_WINDOWS
win_T *wp;
#endif
int sb_num;
#ifdef USE_ON_FLY_SCROLL
colnr_T old_leftcol = curwin->w_leftcol;
# ifdef FEAT_SCROLLBIND
linenr_T old_topline = curwin->w_topline;
# endif
# ifdef FEAT_DIFF
int old_topfill = curwin->w_topfill;
# endif
#else
char_u bytes[sizeof(long_u)];
int byte_count;
#endif
if (sb == NULL)
return;
/* Don't put events in the input queue now. */
if (hold_gui_events)
return;
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0 && sb->wp != curwin)
return;
#endif
if (still_dragging)
{
if (sb->wp == NULL)
gui.dragged_sb = SBAR_BOTTOM;
else if (sb == &sb->wp->w_scrollbars[SBAR_LEFT])
gui.dragged_sb = SBAR_LEFT;
else
gui.dragged_sb = SBAR_RIGHT;
gui.dragged_wp = sb->wp;
}
else
{
gui.dragged_sb = SBAR_NONE;
#ifdef FEAT_GUI_GTK
/* Keep the "dragged_wp" value until after the scrolling, for when the
* moust button is released. GTK2 doesn't send the button-up event. */
gui.dragged_wp = NULL;
#endif
}
/* Vertical sbar info is kept in the first sbar (the left one) */
if (sb->wp != NULL)
sb = &sb->wp->w_scrollbars[0];
/*
* Check validity of value
*/
if (value < 0)
value = 0;
#ifdef SCROLL_PAST_END
else if (value > sb->max)
value = sb->max;
#else
if (value > sb->max - sb->size + 1)
value = sb->max - sb->size + 1;
#endif
sb->value = value;
#ifdef USE_ON_FLY_SCROLL
/* When not allowed to do the scrolling right now, return.
* This also checked input_available(), but that causes the first click in
* a scrollbar to be ignored when Vim doesn't have focus. */
if (dont_scroll)
return;
#endif
#ifdef FEAT_INS_EXPAND
/* Disallow scrolling the current window when the completion popup menu is
* visible. */
if ((sb->wp == NULL || sb->wp == curwin) && pum_visible())
return;
#endif
#ifdef FEAT_RIGHTLEFT
if (sb->wp == NULL && curwin->w_p_rl)
{
value = sb->max + 1 - sb->size - value;
if (value < 0)
value = 0;
}
#endif
if (sb->wp != NULL) /* vertical scrollbar */
{
sb_num = 0;
#ifdef FEAT_WINDOWS
for (wp = firstwin; wp != sb->wp && wp != NULL; wp = wp->w_next)
sb_num++;
if (wp == NULL)
return;
#else
if (sb->wp != curwin)
return;
#endif
#ifdef USE_ON_FLY_SCROLL
current_scrollbar = sb_num;
scrollbar_value = value;
if (State & NORMAL)
{
gui_do_scroll();
setcursor();
}
else if (State & INSERT)
{
ins_scroll();
setcursor();
}
else if (State & CMDLINE)
{
if (msg_scrolled == 0)
{
gui_do_scroll();
redrawcmdline();
}
}
# ifdef FEAT_FOLDING
/* Value may have been changed for closed fold. */
sb->value = sb->wp->w_topline - 1;
# endif
/* When dragging one scrollbar and there is another one at the other
* side move the thumb of that one too. */
if (gui.which_scrollbars[SBAR_RIGHT] && gui.which_scrollbars[SBAR_LEFT])
gui_mch_set_scrollbar_thumb(
&sb->wp->w_scrollbars[
sb == &sb->wp->w_scrollbars[SBAR_RIGHT]
? SBAR_LEFT : SBAR_RIGHT],
sb->value, sb->size, sb->max);
#else
bytes[0] = CSI;
bytes[1] = KS_VER_SCROLLBAR;
bytes[2] = KE_FILLER;
bytes[3] = (char_u)sb_num;
byte_count = 4;
#endif
}
else
{
#ifdef USE_ON_FLY_SCROLL
scrollbar_value = value;
if (State & NORMAL)
gui_do_horiz_scroll(scrollbar_value, FALSE);
else if (State & INSERT)
ins_horscroll();
else if (State & CMDLINE)
{
if (msg_scrolled == 0)
{
gui_do_horiz_scroll(scrollbar_value, FALSE);
redrawcmdline();
}
}
if (old_leftcol != curwin->w_leftcol)
{
updateWindow(curwin); /* update window, status and cmdline */
setcursor();
}
#else
bytes[0] = CSI;
bytes[1] = KS_HOR_SCROLLBAR;
bytes[2] = KE_FILLER;
byte_count = 3;
#endif
}
#ifdef USE_ON_FLY_SCROLL
# ifdef FEAT_SCROLLBIND
/*
* synchronize other windows, as necessary according to 'scrollbind'
*/
if (curwin->w_p_scb
&& ((sb->wp == NULL && curwin->w_leftcol != old_leftcol)
|| (sb->wp == curwin && (curwin->w_topline != old_topline
# ifdef FEAT_DIFF
|| curwin->w_topfill != old_topfill
# endif
))))
{
do_check_scrollbind(TRUE);
/* need to update the window right here */
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_redr_type > 0)
updateWindow(wp);
setcursor();
}
# endif
out_flush();
gui_update_cursor(FALSE, TRUE);
#else
add_to_input_buf(bytes, byte_count);
add_long_to_buf((long_u)value, bytes);
add_to_input_buf_csi(bytes, sizeof(long_u));
#endif
}
/*
* Scrollbar stuff:
*/
#if defined(FEAT_AUTOCMD) || defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Called when something in the window layout has changed.
*/
void
gui_may_update_scrollbars()
{
if (gui.in_use && starting == 0)
{
out_flush();
gui_init_which_components(NULL);
gui_update_scrollbars(TRUE);
}
need_mouse_correct = TRUE;
}
#endif
void
gui_update_scrollbars(force)
int force; /* Force all scrollbars to get updated */
{
win_T *wp;
scrollbar_T *sb;
long val, size, max; /* need 32 bits here */
int which_sb;
int h, y;
#ifdef FEAT_VERTSPLIT
static win_T *prev_curwin = NULL;
#endif
/* Update the horizontal scrollbar */
gui_update_horiz_scrollbar(force);
#ifndef WIN3264
/* Return straight away if there is neither a left nor right scrollbar.
* On MS-Windows this is required anyway for scrollwheel messages. */
if (!gui.which_scrollbars[SBAR_LEFT] && !gui.which_scrollbars[SBAR_RIGHT])
return;
#endif
/*
* Don't want to update a scrollbar while we're dragging it. But if we
* have both a left and right scrollbar, and we drag one of them, we still
* need to update the other one.
*/
if (!force && (gui.dragged_sb == SBAR_LEFT || gui.dragged_sb == SBAR_RIGHT)
&& gui.which_scrollbars[SBAR_LEFT]
&& gui.which_scrollbars[SBAR_RIGHT])
{
/*
* If we have two scrollbars and one of them is being dragged, just
* copy the scrollbar position from the dragged one to the other one.
*/
which_sb = SBAR_LEFT + SBAR_RIGHT - gui.dragged_sb;
if (gui.dragged_wp != NULL)
gui_mch_set_scrollbar_thumb(
&gui.dragged_wp->w_scrollbars[which_sb],
gui.dragged_wp->w_scrollbars[0].value,
gui.dragged_wp->w_scrollbars[0].size,
gui.dragged_wp->w_scrollbars[0].max);
}
/* avoid that moving components around generates events */
++hold_gui_events;
for (wp = firstwin; wp != NULL; wp = W_NEXT(wp))
{
if (wp->w_buffer == NULL) /* just in case */
continue;
/* Skip a scrollbar that is being dragged. */
if (!force && (gui.dragged_sb == SBAR_LEFT
|| gui.dragged_sb == SBAR_RIGHT)
&& gui.dragged_wp == wp)
continue;
#ifdef SCROLL_PAST_END
max = wp->w_buffer->b_ml.ml_line_count - 1;
#else
max = wp->w_buffer->b_ml.ml_line_count + wp->w_height - 2;
#endif
if (max < 0) /* empty buffer */
max = 0;
val = wp->w_topline - 1;
size = wp->w_height;
#ifdef SCROLL_PAST_END
if (val > max) /* just in case */
val = max;
#else
if (size > max + 1) /* just in case */
size = max + 1;
if (val > max - size + 1)
val = max - size + 1;
#endif
if (val < 0) /* minimal value is 0 */
val = 0;
/*
* Scrollbar at index 0 (the left one) contains all the information.
* It would be the same info for left and right so we just store it for
* one of them.
*/
sb = &wp->w_scrollbars[0];
/*
* Note: no check for valid w_botline. If it's not valid the
* scrollbars will be updated later anyway.
*/
if (size < 1 || wp->w_botline - 2 > max)
{
/*
* This can happen during changing files. Just don't update the
* scrollbar for now.
*/
sb->height = 0; /* Force update next time */
if (gui.which_scrollbars[SBAR_LEFT])
gui_do_scrollbar(wp, SBAR_LEFT, FALSE);
if (gui.which_scrollbars[SBAR_RIGHT])
gui_do_scrollbar(wp, SBAR_RIGHT, FALSE);
continue;
}
if (force || sb->height != wp->w_height
#ifdef FEAT_WINDOWS
|| sb->top != wp->w_winrow
|| sb->status_height != wp->w_status_height
# ifdef FEAT_VERTSPLIT
|| sb->width != wp->w_width
|| prev_curwin != curwin
# endif
#endif
)
{
/* Height, width or position of scrollbar has changed. For
* vertical split: curwin changed. */
sb->height = wp->w_height;
#ifdef FEAT_WINDOWS
sb->top = wp->w_winrow;
sb->status_height = wp->w_status_height;
# ifdef FEAT_VERTSPLIT
sb->width = wp->w_width;
# endif
#endif
/* Calculate height and position in pixels */
h = (sb->height + sb->status_height) * gui.char_height;
y = sb->top * gui.char_height + gui.border_offset;
#if defined(FEAT_MENU) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF) && !defined(FEAT_GUI_PHOTON)
if (gui.menu_is_active)
y += gui.menu_height;
#endif
#if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_ATHENA))
if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
# ifdef FEAT_GUI_ATHENA
y += gui.toolbar_height;
# else
# ifdef FEAT_GUI_MSWIN
y += TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
# endif
# endif
#endif
#if defined(FEAT_GUI_TABLINE) && defined(FEAT_GUI_MSWIN)
if (gui_has_tabline())
y += gui.tabline_height;
#endif
#ifdef FEAT_WINDOWS
if (wp->w_winrow == 0)
#endif
{
/* Height of top scrollbar includes width of top border */
h += gui.border_offset;
y -= gui.border_offset;
}
if (gui.which_scrollbars[SBAR_LEFT])
{
gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_LEFT],
gui.left_sbar_x, y,
gui.scrollbar_width, h);
gui_do_scrollbar(wp, SBAR_LEFT, TRUE);
}
if (gui.which_scrollbars[SBAR_RIGHT])
{
gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_RIGHT],
gui.right_sbar_x, y,
gui.scrollbar_width, h);
gui_do_scrollbar(wp, SBAR_RIGHT, TRUE);
}
}
/* Reduce the number of calls to gui_mch_set_scrollbar_thumb() by
* checking if the thumb moved at least a pixel. Only do this for
* Athena, most other GUIs require the update anyway to make the
* arrows work. */
#ifdef FEAT_GUI_ATHENA
if (max == 0)
y = 0;
else
y = (val * (sb->height + 2) * gui.char_height + max / 2) / max;
if (force || sb->pixval != y || sb->size != size || sb->max != max)
#else
if (force || sb->value != val || sb->size != size || sb->max != max)
#endif
{
/* Thumb of scrollbar has moved */
sb->value = val;
#ifdef FEAT_GUI_ATHENA
sb->pixval = y;
#endif
sb->size = size;
sb->max = max;
if (gui.which_scrollbars[SBAR_LEFT]
&& (gui.dragged_sb != SBAR_LEFT || gui.dragged_wp != wp))
gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_LEFT],
val, size, max);
if (gui.which_scrollbars[SBAR_RIGHT]
&& (gui.dragged_sb != SBAR_RIGHT || gui.dragged_wp != wp))
gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_RIGHT],
val, size, max);
}
}
#ifdef FEAT_VERTSPLIT
prev_curwin = curwin;
#endif
--hold_gui_events;
}
/*
* Enable or disable a scrollbar.
* Check for scrollbars for vertically split windows which are not enabled
* sometimes.
*/
static void
gui_do_scrollbar(wp, which, enable)
win_T *wp;
int which; /* SBAR_LEFT or SBAR_RIGHT */
int enable; /* TRUE to enable scrollbar */
{
#ifdef FEAT_VERTSPLIT
int midcol = curwin->w_wincol + curwin->w_width / 2;
int has_midcol = (wp->w_wincol <= midcol
&& wp->w_wincol + wp->w_width >= midcol);
/* Only enable scrollbars that contain the middle column of the current
* window. */
if (gui.which_scrollbars[SBAR_RIGHT] != gui.which_scrollbars[SBAR_LEFT])
{
/* Scrollbars only on one side. Don't enable scrollbars that don't
* contain the middle column of the current window. */
if (!has_midcol)
enable = FALSE;
}
else
{
/* Scrollbars on both sides. Don't enable scrollbars that neither
* contain the middle column of the current window nor are on the far
* side. */
if (midcol > Columns / 2)
{
if (which == SBAR_LEFT ? wp->w_wincol != 0 : !has_midcol)
enable = FALSE;
}
else
{
if (which == SBAR_RIGHT ? wp->w_wincol + wp->w_width != Columns
: !has_midcol)
enable = FALSE;
}
}
#endif
gui_mch_enable_scrollbar(&wp->w_scrollbars[which], enable);
}
/*
* Scroll a window according to the values set in the globals current_scrollbar
* and scrollbar_value. Return TRUE if the cursor in the current window moved
* or FALSE otherwise.
*/
int
gui_do_scroll()
{
win_T *wp, *save_wp;
int i;
long nlines;
pos_T old_cursor;
linenr_T old_topline;
#ifdef FEAT_DIFF
int old_topfill;
#endif
for (wp = firstwin, i = 0; i < current_scrollbar; wp = W_NEXT(wp), i++)
if (wp == NULL)
break;
if (wp == NULL)
/* Couldn't find window */
return FALSE;
/*
* Compute number of lines to scroll. If zero, nothing to do.
*/
nlines = (long)scrollbar_value + 1 - (long)wp->w_topline;
if (nlines == 0)
return FALSE;
save_wp = curwin;
old_topline = wp->w_topline;
#ifdef FEAT_DIFF
old_topfill = wp->w_topfill;
#endif
old_cursor = wp->w_cursor;
curwin = wp;
curbuf = wp->w_buffer;
if (nlines < 0)
scrolldown(-nlines, gui.dragged_wp == NULL);
else
scrollup(nlines, gui.dragged_wp == NULL);
/* Reset dragged_wp after using it. "dragged_sb" will have been reset for
* the mouse-up event already, but we still want it to behave like when
* dragging. But not the next click in an arrow. */
if (gui.dragged_sb == SBAR_NONE)
gui.dragged_wp = NULL;
if (old_topline != wp->w_topline
#ifdef FEAT_DIFF
|| old_topfill != wp->w_topfill
#endif
)
{
if (p_so != 0)
{
cursor_correct(); /* fix window for 'so' */
update_topline(); /* avoid up/down jump */
}
if (old_cursor.lnum != wp->w_cursor.lnum)
coladvance(wp->w_curswant);
#ifdef FEAT_SCROLLBIND
wp->w_scbind_pos = wp->w_topline;
#endif
}
/* Make sure wp->w_leftcol and wp->w_skipcol are correct. */
validate_cursor();
curwin = save_wp;
curbuf = save_wp->w_buffer;
/*
* Don't call updateWindow() when nothing has changed (it will overwrite
* the status line!).
*/
if (old_topline != wp->w_topline
|| wp->w_redr_type != 0
#ifdef FEAT_DIFF
|| old_topfill != wp->w_topfill
#endif
)
{
int type = VALID;
#ifdef FEAT_INS_EXPAND
if (pum_visible())
{
type = NOT_VALID;
wp->w_lines_valid = 0;
}
#endif
/* Don't set must_redraw here, it may cause the popup menu to
* disappear when losing focus after a scrollbar drag. */
if (wp->w_redr_type < type)
wp->w_redr_type = type;
updateWindow(wp); /* update window, status line, and cmdline */
}
#ifdef FEAT_INS_EXPAND
/* May need to redraw the popup menu. */
if (pum_visible())
pum_redraw();
#endif
return (wp == curwin && !equalpos(curwin->w_cursor, old_cursor));
}
/*
* Horizontal scrollbar stuff:
*/
/*
* Return length of line "lnum" for horizontal scrolling.
*/
static colnr_T
scroll_line_len(lnum)
linenr_T lnum;
{
char_u *p;
colnr_T col;
int w;
p = ml_get(lnum);
col = 0;
if (*p != NUL)
for (;;)
{
w = chartabsize(p, col);
mb_ptr_adv(p);
if (*p == NUL) /* don't count the last character */
break;
col += w;
}
return col;
}
/* Remember which line is currently the longest, so that we don't have to
* search for it when scrolling horizontally. */
static linenr_T longest_lnum = 0;
/*
* Find longest visible line number. If this is not possible (or not desired,
* by setting 'h' in "guioptions") then the current line number is returned.
*/
static linenr_T
gui_find_longest_lnum()
{
linenr_T ret = 0;
/* Calculate maximum for horizontal scrollbar. Check for reasonable
* line numbers, topline and botline can be invalid when displaying is
* postponed. */
if (vim_strchr(p_go, GO_HORSCROLL) == NULL
&& curwin->w_topline <= curwin->w_cursor.lnum
&& curwin->w_botline > curwin->w_cursor.lnum
&& curwin->w_botline <= curbuf->b_ml.ml_line_count + 1)
{
linenr_T lnum;
colnr_T n;
long max = 0;
/* Use maximum of all visible lines. Remember the lnum of the
* longest line, closest to the cursor line. Used when scrolling
* below. */
for (lnum = curwin->w_topline; lnum < curwin->w_botline; ++lnum)
{
n = scroll_line_len(lnum);
if (n > (colnr_T)max)
{
max = n;
ret = lnum;
}
else if (n == (colnr_T)max
&& abs((int)(lnum - curwin->w_cursor.lnum))
< abs((int)(ret - curwin->w_cursor.lnum)))
ret = lnum;
}
}
else
/* Use cursor line only. */
ret = curwin->w_cursor.lnum;
return ret;
}
static void
gui_update_horiz_scrollbar(force)
int force;
{
long value, size, max; /* need 32 bit ints here */
if (!gui.which_scrollbars[SBAR_BOTTOM])
return;
if (!force && gui.dragged_sb == SBAR_BOTTOM)
return;
if (!force && curwin->w_p_wrap && gui.prev_wrap)
return;
/*
* It is possible for the cursor to be invalid if we're in the middle of
* something (like changing files). If so, don't do anything for now.
*/
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
{
gui.bottom_sbar.value = -1;
return;
}
size = W_WIDTH(curwin);
if (curwin->w_p_wrap)
{
value = 0;
#ifdef SCROLL_PAST_END
max = 0;
#else
max = W_WIDTH(curwin) - 1;
#endif
}
else
{
value = curwin->w_leftcol;
longest_lnum = gui_find_longest_lnum();
max = scroll_line_len(longest_lnum);
#ifdef FEAT_VIRTUALEDIT
if (virtual_active())
{
/* May move the cursor even further to the right. */
if (curwin->w_virtcol >= (colnr_T)max)
max = curwin->w_virtcol;
}
#endif
#ifndef SCROLL_PAST_END
max += W_WIDTH(curwin) - 1;
#endif
/* The line number isn't scrolled, thus there is less space when
* 'number' or 'relativenumber' is set (also for 'foldcolumn'). */
size -= curwin_col_off();
#ifndef SCROLL_PAST_END
max -= curwin_col_off();
#endif
}
#ifndef SCROLL_PAST_END
if (value > max - size + 1)
value = max - size + 1; /* limit the value to allowable range */
#endif
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl)
{
value = max + 1 - size - value;
if (value < 0)
{
size += value;
value = 0;
}
}
#endif
if (!force && value == gui.bottom_sbar.value && size == gui.bottom_sbar.size
&& max == gui.bottom_sbar.max)
return;
gui.bottom_sbar.value = value;
gui.bottom_sbar.size = size;
gui.bottom_sbar.max = max;
gui.prev_wrap = curwin->w_p_wrap;
gui_mch_set_scrollbar_thumb(&gui.bottom_sbar, value, size, max);
}
/*
* Do a horizontal scroll. Return TRUE if the cursor moved, FALSE otherwise.
*/
int
gui_do_horiz_scroll(leftcol, compute_longest_lnum)
long_u leftcol;
int compute_longest_lnum;
{
/* no wrapping, no scrolling */
if (curwin->w_p_wrap)
return FALSE;
if (curwin->w_leftcol == (colnr_T)leftcol)
return FALSE;
curwin->w_leftcol = (colnr_T)leftcol;
/* When the line of the cursor is too short, move the cursor to the
* longest visible line. */
if (vim_strchr(p_go, GO_HORSCROLL) == NULL
&& !virtual_active()
&& (colnr_T)leftcol > scroll_line_len(curwin->w_cursor.lnum))
{
if (compute_longest_lnum)
{
curwin->w_cursor.lnum = gui_find_longest_lnum();
curwin->w_cursor.col = 0;
}
/* Do a sanity check on "longest_lnum", just in case. */
else if (longest_lnum >= curwin->w_topline
&& longest_lnum < curwin->w_botline)
{
curwin->w_cursor.lnum = longest_lnum;
curwin->w_cursor.col = 0;
}
}
return leftcol_changed();
}
/*
* Check that none of the colors are the same as the background color
*/
void
gui_check_colors()
{
if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
{
gui_set_bg_color((char_u *)"White");
if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
gui_set_fg_color((char_u *)"Black");
}
}
static void
gui_set_fg_color(name)
char_u *name;
{
gui.norm_pixel = gui_get_color(name);
hl_set_fg_color_name(vim_strsave(name));
}
static void
gui_set_bg_color(name)
char_u *name;
{
gui.back_pixel = gui_get_color(name);
hl_set_bg_color_name(vim_strsave(name));
}
/*
* Allocate a color by name.
* Returns INVALCOLOR and gives an error message when failed.
*/
guicolor_T
gui_get_color(name)
char_u *name;
{
guicolor_T t;
if (*name == NUL)
return INVALCOLOR;
t = gui_mch_get_color(name);
if (t == INVALCOLOR
#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
&& gui.in_use
#endif
)
EMSG2(_("E254: Cannot allocate color %s"), name);
return t;
}
/*
* Return the grey value of a color (range 0-255).
*/
int
gui_get_lightness(pixel)
guicolor_T pixel;
{
long_u rgb = gui_mch_get_rgb(pixel);
return (int)( (((rgb >> 16) & 0xff) * 299)
+ (((rgb >> 8) & 0xff) * 587)
+ ((rgb & 0xff) * 114)) / 1000;
}
#if defined(FEAT_GUI_X11) || defined(PROTO)
void
gui_new_scrollbar_colors()
{
win_T *wp;
/* Nothing to do if GUI hasn't started yet. */
if (!gui.in_use)
return;
FOR_ALL_WINDOWS(wp)
{
gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_LEFT]));
gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_RIGHT]));
}
gui_mch_set_scrollbar_colors(&gui.bottom_sbar);
}
#endif
/*
* Call this when focus has changed.
*/
void
gui_focus_change(in_focus)
int in_focus;
{
/*
* Skip this code to avoid drawing the cursor when debugging and switching
* between the debugger window and gvim.
*/
#if 1
gui.in_focus = in_focus;
out_flush(); /* make sure output has been written */
gui_update_cursor(TRUE, FALSE);
# ifdef FEAT_XIM
xim_set_focus(in_focus);
# endif
/* Put events in the input queue only when allowed.
* ui_focus_change() isn't called directly, because it invokes
* autocommands and that must not happen asynchronously. */
if (!hold_gui_events)
{
char_u bytes[3];
bytes[0] = CSI;
bytes[1] = KS_EXTRA;
bytes[2] = in_focus ? (int)KE_FOCUSGAINED : (int)KE_FOCUSLOST;
add_to_input_buf(bytes, 3);
}
#endif
}
/*
* Called when the mouse moved (but not when dragging).
*/
void
gui_mouse_moved(x, y)
int x;
int y;
{
win_T *wp;
char_u st[8];
/* Ignore this while still starting up. */
if (!gui.in_use || gui.starting)
return;
#ifdef FEAT_MOUSESHAPE
/* Get window pointer, and update mouse shape as well. */
wp = xy2win(x, y);
#endif
/* Only handle this when 'mousefocus' set and ... */
if (p_mousef
&& !hold_gui_events /* not holding events */
&& (State & (NORMAL|INSERT))/* Normal/Visual/Insert mode */
&& State != HITRETURN /* but not hit-return prompt */
&& msg_scrolled == 0 /* no scrolled message */
&& !need_mouse_correct /* not moving the pointer */
&& gui.in_focus) /* gvim in focus */
{
/* Don't move the mouse when it's left or right of the Vim window */
if (x < 0 || x > Columns * gui.char_width)
return;
#ifndef FEAT_MOUSESHAPE
wp = xy2win(x, y);
#endif
if (wp == curwin || wp == NULL)
return; /* still in the same old window, or none at all */
#ifdef FEAT_WINDOWS
/* Ignore position in the tab pages line. */
if (Y_2_ROW(y) < tabline_height())
return;
#endif
/*
* format a mouse click on status line input
* ala gui_send_mouse_event(0, x, y, 0, 0);
* Trick: Use a column number -1, so that get_pseudo_mouse_code() will
* generate a K_LEFTMOUSE_NM key code.
*/
if (finish_op)
{
/* abort the current operator first */
st[0] = ESC;
add_to_input_buf(st, 1);
}
st[0] = CSI;
st[1] = KS_MOUSE;
st[2] = KE_FILLER;
st[3] = (char_u)MOUSE_LEFT;
fill_mouse_coord(st + 4,
#ifdef FEAT_VERTSPLIT
wp->w_wincol == 0 ? -1 : wp->w_wincol + MOUSE_COLOFF,
#else
-1,
#endif
wp->w_height + W_WINROW(wp));
add_to_input_buf(st, 8);
st[3] = (char_u)MOUSE_RELEASE;
add_to_input_buf(st, 8);
#ifdef FEAT_GUI_GTK
/* Need to wake up the main loop */
if (gtk_main_level() > 0)
gtk_main_quit();
#endif
}
}
/*
* Called when mouse should be moved to window with focus.
*/
void
gui_mouse_correct()
{
int x, y;
win_T *wp = NULL;
need_mouse_correct = FALSE;
if (!(gui.in_use && p_mousef))
return;
gui_mch_getmouse(&x, &y);
/* Don't move the mouse when it's left or right of the Vim window */
if (x < 0 || x > Columns * gui.char_width)
return;
if (y >= 0
# ifdef FEAT_WINDOWS
&& Y_2_ROW(y) >= tabline_height()
# endif
)
wp = xy2win(x, y);
if (wp != curwin && wp != NULL) /* If in other than current window */
{
validate_cline_row();
gui_mch_setmouse((int)W_ENDCOL(curwin) * gui.char_width - 3,
(W_WINROW(curwin) + curwin->w_wrow) * gui.char_height
+ (gui.char_height) / 2);
}
}
/*
* Find window where the mouse pointer "y" coordinate is in.
*/
static win_T *
xy2win(x, y)
int x UNUSED;
int y UNUSED;
{
#ifdef FEAT_WINDOWS
int row;
int col;
win_T *wp;
row = Y_2_ROW(y);
col = X_2_COL(x);
if (row < 0 || col < 0) /* before first window */
return NULL;
wp = mouse_find_win(&row, &col);
# ifdef FEAT_MOUSESHAPE
if (State == HITRETURN || State == ASKMORE)
{
if (Y_2_ROW(y) >= msg_row)
update_mouseshape(SHAPE_IDX_MOREL);
else
update_mouseshape(SHAPE_IDX_MORE);
}
else if (row > wp->w_height) /* below status line */
update_mouseshape(SHAPE_IDX_CLINE);
# ifdef FEAT_VERTSPLIT
else if (!(State & CMDLINE) && W_VSEP_WIDTH(wp) > 0 && col == wp->w_width
&& (row != wp->w_height || !stl_connected(wp)) && msg_scrolled == 0)
update_mouseshape(SHAPE_IDX_VSEP);
# endif
else if (!(State & CMDLINE) && W_STATUS_HEIGHT(wp) > 0
&& row == wp->w_height && msg_scrolled == 0)
update_mouseshape(SHAPE_IDX_STATUS);
else
update_mouseshape(-2);
# endif
return wp;
#else
return firstwin;
#endif
}
/*
* ":gui" and ":gvim": Change from the terminal version to the GUI version.
* File names may be given to redefine the args list.
*/
void
ex_gui(eap)
exarg_T *eap;
{
char_u *arg = eap->arg;
/*
* Check for "-f" argument: foreground, don't fork.
* Also don't fork when started with "gvim -f".
* Do fork when using "gui -b".
*/
if (arg[0] == '-'
&& (arg[1] == 'f' || arg[1] == 'b')
&& (arg[2] == NUL || vim_iswhite(arg[2])))
{
gui.dofork = (arg[1] == 'b');
eap->arg = skipwhite(eap->arg + 2);
}
if (!gui.in_use)
{
/* Clear the command. Needed for when forking+exiting, to avoid part
* of the argument ending up after the shell prompt. */
msg_clr_eos_force();
gui_start();
#ifdef FEAT_NETBEANS_INTG
netbeans_gui_register();
#endif
}
if (!ends_excmd(*eap->arg))
ex_next(eap);
}
#if ((defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32) \
|| defined(FEAT_GUI_PHOTON)) && defined(FEAT_TOOLBAR)) || defined(PROTO)
/*
* This is shared between Athena, Motif and GTK.
*/
static void gfp_setname __ARGS((char_u *fname, void *cookie));
/*
* Callback function for do_in_runtimepath().
*/
static void
gfp_setname(fname, cookie)
char_u *fname;
void *cookie;
{
char_u *gfp_buffer = cookie;
if (STRLEN(fname) >= MAXPATHL)
*gfp_buffer = NUL;
else
STRCPY(gfp_buffer, fname);
}
/*
* Find the path of bitmap "name" with extension "ext" in 'runtimepath'.
* Return FAIL for failure and OK if buffer[MAXPATHL] contains the result.
*/
int
gui_find_bitmap(name, buffer, ext)
char_u *name;
char_u *buffer;
char *ext;
{
if (STRLEN(name) > MAXPATHL - 14)
return FAIL;
vim_snprintf((char *)buffer, MAXPATHL, "bitmaps/%s.%s", name, ext);
if (do_in_runtimepath(buffer, FALSE, gfp_setname, buffer) == FAIL
|| *buffer == NUL)
return FAIL;
return OK;
}
# if !defined(FEAT_GUI_GTK) || defined(PROTO)
/*
* Given the name of the "icon=" argument, try finding the bitmap file for the
* icon. If it is an absolute path name, use it as it is. Otherwise append
* "ext" and search for it in 'runtimepath'.
* The result is put in "buffer[MAXPATHL]". If something fails "buffer"
* contains "name".
*/
void
gui_find_iconfile(name, buffer, ext)
char_u *name;
char_u *buffer;
char *ext;
{
char_u buf[MAXPATHL + 1];
expand_env(name, buffer, MAXPATHL);
if (!mch_isFullName(buffer) && gui_find_bitmap(buffer, buf, ext) == OK)
STRCPY(buffer, buf);
}
# endif
#endif
#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) || defined(PROTO)
void
display_errors()
{
char_u *p;
if (isatty(2))
fflush(stderr);
else if (error_ga.ga_data != NULL)
{
/* avoid putting up a message box with blanks only */
for (p = (char_u *)error_ga.ga_data; *p != NUL; ++p)
if (!isspace(*p))
{
/* Truncate a very long message, it will go off-screen. */
if (STRLEN(p) > 2000)
STRCPY(p + 2000 - 14, "...(truncated)");
(void)do_dialog(VIM_ERROR, (char_u *)_("Error"),
p, (char_u *)_("&Ok"), 1, NULL, FALSE);
break;
}
ga_clear(&error_ga);
}
}
#endif
#if defined(NO_CONSOLE_INPUT) || defined(PROTO)
/*
* Return TRUE if still starting up and there is no place to enter text.
* For GTK and X11 we check if stderr is not a tty, which means we were
* (probably) started from the desktop. Also check stdin, "vim >& file" does
* allow typing on stdin.
*/
int
no_console_input()
{
return ((!gui.in_use || gui.starting)
# ifndef NO_CONSOLE
&& !isatty(0) && !isatty(2)
# endif
);
}
#endif
#if defined(FIND_REPLACE_DIALOG) || defined(FEAT_SUN_WORKSHOP) \
|| defined(NEED_GUI_UPDATE_SCREEN) \
|| defined(PROTO)
/*
* Update the current window and the screen.
*/
void
gui_update_screen()
{
#ifdef FEAT_CONCEAL
linenr_T conceal_old_cursor_line = 0;
linenr_T conceal_new_cursor_line = 0;
int conceal_update_lines = FALSE;
#endif
update_topline();
validate_cursor();
#if defined(FEAT_AUTOCMD) || defined(FEAT_CONCEAL)
/* Trigger CursorMoved if the cursor moved. */
if (!finish_op && (
# ifdef FEAT_AUTOCMD
has_cursormoved()
# 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_AUTOCMD
if (has_cursormoved())
apply_autocmds(EVENT_CURSORMOVED, 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
update_screen(0); /* may need to update the screen */
setcursor();
# 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);
curwin->w_valid &= ~VALID_CROW;
}
# endif
out_flush(); /* make sure output has been written */
gui_update_cursor(TRUE, FALSE);
gui_mch_flush();
}
#endif
#if defined(FIND_REPLACE_DIALOG) || defined(PROTO)
static void concat_esc __ARGS((garray_T *gap, char_u *text, int what));
/*
* Get the text to use in a find/replace dialog. Uses the last search pattern
* if the argument is empty.
* Returns an allocated string.
*/
char_u *
get_find_dialog_text(arg, wwordp, mcasep)
char_u *arg;
int *wwordp; /* return: TRUE if \< \> found */
int *mcasep; /* return: TRUE if \C found */
{
char_u *text;
if (*arg == NUL)
text = last_search_pat();
else
text = arg;
if (text != NULL)
{
text = vim_strsave(text);
if (text != NULL)
{
int len = (int)STRLEN(text);
int i;
/* Remove "\V" */
if (len >= 2 && STRNCMP(text, "\\V", 2) == 0)
{
mch_memmove(text, text + 2, (size_t)(len - 1));
len -= 2;
}
/* Recognize "\c" and "\C" and remove. */
if (len >= 2 && *text == '\\' && (text[1] == 'c' || text[1] == 'C'))
{
*mcasep = (text[1] == 'C');
mch_memmove(text, text + 2, (size_t)(len - 1));
len -= 2;
}
/* Recognize "\<text\>" and remove. */
if (len >= 4
&& STRNCMP(text, "\\<", 2) == 0
&& STRNCMP(text + len - 2, "\\>", 2) == 0)
{
*wwordp = TRUE;
mch_memmove(text, text + 2, (size_t)(len - 4));
text[len - 4] = NUL;
}
/* Recognize "\/" or "\?" and remove. */
for (i = 0; i + 1 < len; ++i)
if (text[i] == '\\' && (text[i + 1] == '/'
|| text[i + 1] == '?'))
{
mch_memmove(text + i, text + i + 1, (size_t)(len - i));
--len;
}
}
}
return text;
}
/*
* Concatenate "text" to grow array "gap", escaping "what" with a backslash.
*/
static void
concat_esc(gap, text, what)
garray_T *gap;
char_u *text;
int what;
{
while (*text != NUL)
{
#ifdef FEAT_MBYTE
int l = (*mb_ptr2len)(text);
if (l > 1)
{
while (--l >= 0)
ga_append(gap, *text++);
continue;
}
#endif
if (*text == what)
ga_append(gap, '\\');
ga_append(gap, *text);
++text;
}
}
/*
* Handle the press of a button in the find-replace dialog.
* Return TRUE when something was added to the input buffer.
*/
int
gui_do_findrepl(flags, find_text, repl_text, down)
int flags; /* one of FRD_REPLACE, FRD_FINDNEXT, etc. */
char_u *find_text;
char_u *repl_text;
int down; /* Search downwards. */
{
garray_T ga;
int i;
int type = (flags & FRD_TYPE_MASK);
char_u *p;
regmatch_T regmatch;
int save_did_emsg = did_emsg;
static int busy = FALSE;
/* When the screen is being updated we should not change buffers and
* windows structures, it may cause freed memory to be used. Also don't
* do this recursively (pressing "Find" quickly several times. */
if (updating_screen || busy)
return FALSE;
/* refuse replace when text cannot be changed */
if ((type == FRD_REPLACE || type == FRD_REPLACEALL) && text_locked())
return FALSE;
busy = TRUE;
ga_init2(&ga, 1, 100);
if (type == FRD_REPLACEALL)
ga_concat(&ga, (char_u *)"%s/");
ga_concat(&ga, (char_u *)"\\V");
if (flags & FRD_MATCH_CASE)
ga_concat(&ga, (char_u *)"\\C");
else
ga_concat(&ga, (char_u *)"\\c");
if (flags & FRD_WHOLE_WORD)
ga_concat(&ga, (char_u *)"\\<");
if (type == FRD_REPLACEALL || down)
concat_esc(&ga, find_text, '/'); /* escape slashes */
else
concat_esc(&ga, find_text, '?'); /* escape '?' */
if (flags & FRD_WHOLE_WORD)
ga_concat(&ga, (char_u *)"\\>");
if (type == FRD_REPLACEALL)
{
ga_concat(&ga, (char_u *)"/");
/* escape / and \ */
p = vim_strsave_escaped(repl_text, (char_u *)"/\\");
if (p != NULL)
ga_concat(&ga, p);
vim_free(p);
ga_concat(&ga, (char_u *)"/g");
}
ga_append(&ga, NUL);
if (type == FRD_REPLACE)
{
/* Do the replacement when the text at the cursor matches. Thus no
* replacement is done if the cursor was moved! */
regmatch.regprog = vim_regcomp(ga.ga_data, RE_MAGIC + RE_STRING);
regmatch.rm_ic = 0;
if (regmatch.regprog != NULL)
{
p = ml_get_cursor();
if (vim_regexec_nl(®match, p, (colnr_T)0)
&& regmatch.startp[0] == p)
{
/* Clear the command line to remove any old "No match"
* error. */
msg_end_prompt();
if (u_save_cursor() == OK)
{
/* A button was pressed thus undo should be synced. */
u_sync(FALSE);
del_bytes((long)(regmatch.endp[0] - regmatch.startp[0]),
FALSE, FALSE);
ins_str(repl_text);
}
}
else
MSG(_("No match at cursor, finding next"));
vim_free(regmatch.regprog);
}
}
if (type == FRD_REPLACEALL)
{
/* A button was pressed, thus undo should be synced. */
u_sync(FALSE);
do_cmdline_cmd(ga.ga_data);
}
else
{
/* Search for the next match. */
i = msg_scroll;
do_search(NULL, down ? '/' : '?', ga.ga_data, 1L,
SEARCH_MSG + SEARCH_MARK, NULL);
msg_scroll = i; /* don't let an error message set msg_scroll */
}
/* Don't want to pass did_emsg to other code, it may cause disabling
* syntax HL if we were busy redrawing. */
did_emsg = save_did_emsg;
if (State & (NORMAL | INSERT))
{
gui_update_screen(); /* update the screen */
msg_didout = 0; /* overwrite any message */
need_wait_return = FALSE; /* don't wait for return */
}
vim_free(ga.ga_data);
busy = FALSE;
return (ga.ga_len > 0);
}
#endif
#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
|| defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MAC) \
|| defined(PROTO)
#ifdef FEAT_WINDOWS
static void gui_wingoto_xy __ARGS((int x, int y));
/*
* Jump to the window at specified point (x, y).
*/
static void
gui_wingoto_xy(x, y)
int x;
int y;
{
int row = Y_2_ROW(y);
int col = X_2_COL(x);
win_T *wp;
if (row >= 0 && col >= 0)
{
wp = mouse_find_win(&row, &col);
if (wp != NULL && wp != curwin)
win_goto(wp);
}
}
#endif
/*
* Process file drop. Mouse cursor position, key modifiers, name of files
* and count of files are given. Argument "fnames[count]" has full pathnames
* of dropped files, they will be freed in this function, and caller can't use
* fnames after call this function.
*/
void
gui_handle_drop(x, y, modifiers, fnames, count)
int x UNUSED;
int y UNUSED;
int_u modifiers;
char_u **fnames;
int count;
{
int i;
char_u *p;
static int entered = FALSE;
/*
* This function is called by event handlers. Just in case we get a
* second event before the first one is handled, ignore the second one.
* Not sure if this can ever happen, just in case.
*/
if (entered)
return;
entered = TRUE;
/*
* When the cursor is at the command line, add the file names to the
* command line, don't edit the files.
*/
if (State & CMDLINE)
{
shorten_filenames(fnames, count);
for (i = 0; i < count; ++i)
{
if (fnames[i] != NULL)
{
if (i > 0)
add_to_input_buf((char_u*)" ", 1);
/* We don't know what command is used thus we can't be sure
* about which characters need to be escaped. Only escape the
* most common ones. */
# ifdef BACKSLASH_IN_FILENAME
p = vim_strsave_escaped(fnames[i], (char_u *)" \t\"|");
# else
p = vim_strsave_escaped(fnames[i], (char_u *)"\\ \t\"|");
# endif
if (p != NULL)
add_to_input_buf_csi(p, (int)STRLEN(p));
vim_free(p);
vim_free(fnames[i]);
}
}
vim_free(fnames);
}
else
{
/* Go to the window under mouse cursor, then shorten given "fnames" by
* current window, because a window can have local current dir. */
# ifdef FEAT_WINDOWS
gui_wingoto_xy(x, y);
# endif
shorten_filenames(fnames, count);
/* If Shift held down, remember the first item. */
if ((modifiers & MOUSE_SHIFT) != 0)
p = vim_strsave(fnames[0]);
else
p = NULL;
/* Handle the drop, :edit or :split to get to the file. This also
* frees fnames[]. Skip this if there is only one item it's a
* directory and Shift is held down. */
if (count == 1 && (modifiers & MOUSE_SHIFT) != 0
&& mch_isdir(fnames[0]))
{
vim_free(fnames[0]);
vim_free(fnames);
}
else
handle_drop(count, fnames, (modifiers & MOUSE_CTRL) != 0);
/* If Shift held down, change to first file's directory. If the first
* item is a directory, change to that directory (and let the explorer
* plugin show the contents). */
if (p != NULL)
{
if (mch_isdir(p))
{
if (mch_chdir((char *)p) == 0)
shorten_fnames(TRUE);
}
else if (vim_chdirfile(p) == OK)
shorten_fnames(TRUE);
vim_free(p);
}
/* Update the screen display */
update_screen(NOT_VALID);
# ifdef FEAT_MENU
gui_update_menus(0);
# endif
#ifdef FEAT_TITLE
maketitle();
#endif
setcursor();
out_flush();
gui_update_cursor(FALSE, FALSE);
gui_mch_flush();
}
entered = FALSE;
}
#endif
| zyz2011-vim | src/gui.c | C | gpl2 | 137,783 |
/* vi:set ts=8 sts=4 sw=4:
*
* Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
*
* NOTICE:
*
* This is NOT the original regular expression code as written by Henry
* Spencer. This code has been modified specifically for use with the VIM
* editor, and should not be used separately from Vim. If you want a good
* regular expression library, get the original code. The copyright notice
* that follows is from the original.
*
* END NOTICE
*
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes in
* regular-expression syntax might require a total rethink.
*
* Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
* Webb, Ciaran McCreesh and Bram Moolenaar.
* Named character class support added by Walter Briscoe (1998 Jul 01)
*/
#include "vim.h"
#undef DEBUG
/*
* The "internal use only" fields in regexp.h are present to pass info from
* compile to execute that permits the execute phase to run lots faster on
* simple cases. They are:
*
* regstart char that must begin a match; NUL if none obvious; Can be a
* multi-byte character.
* reganch is the match anchored (at beginning-of-line only)?
* regmust string (pointer into program) that match must include, or NULL
* regmlen length of regmust string
* regflags RF_ values or'ed together
*
* Regstart and reganch permit very fast decisions on suitable starting points
* for a match, cutting down the work a lot. Regmust permits fast rejection
* of lines that cannot possibly match. The regmust tests are costly enough
* that vim_regcomp() supplies a regmust only if the r.e. contains something
* potentially expensive (at present, the only such thing detected is * or +
* at the start of the r.e., which can involve a lot of backup). Regmlen is
* supplied because the test in vim_regexec() needs it and vim_regcomp() is
* computing it anyway.
*/
/*
* Structure for regexp "program". This is essentially a linear encoding
* of a nondeterministic finite-state machine (aka syntax charts or
* "railroad normal form" in parsing technology). Each node is an opcode
* plus a "next" pointer, possibly plus an operand. "Next" pointers of
* all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
* pointer with a BRANCH on both ends of it is connecting two alternatives.
* (Here we have one of the subtle syntax dependencies: an individual BRANCH
* (as opposed to a collection of them) is never concatenated with anything
* because of operator precedence). The "next" pointer of a BRACES_COMPLEX
* node points to the node after the stuff to be repeated.
* The operand of some types of node is a literal string; for others, it is a
* node leading into a sub-FSM. In particular, the operand of a BRANCH node
* is the first node of the branch.
* (NB this is *not* a tree structure: the tail of the branch connects to the
* thing following the set of BRANCHes.)
*
* pattern is coded like:
*
* +-----------------+
* | V
* <aa>\|<bb> BRANCH <aa> BRANCH <bb> --> END
* | ^ | ^
* +------+ +----------+
*
*
* +------------------+
* V |
* <aa>* BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
* | | ^ ^
* | +---------------+ |
* +---------------------------------------------+
*
*
* +----------------------+
* V |
* <aa>\+ BRANCH <aa> --> BRANCH --> BACK BRANCH --> NOTHING --> END
* | | ^ ^
* | +-----------+ |
* +--------------------------------------------------+
*
*
* +-------------------------+
* V |
* <aa>\{} BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK END
* | | ^
* | +----------------+
* +-----------------------------------------------+
*
*
* <aa>\@!<bb> BRANCH NOMATCH <aa> --> END <bb> --> END
* | | ^ ^
* | +----------------+ |
* +--------------------------------+
*
* +---------+
* | V
* \z[abc] BRANCH BRANCH a BRANCH b BRANCH c BRANCH NOTHING --> END
* | | | | ^ ^
* | | | +-----+ |
* | | +----------------+ |
* | +---------------------------+ |
* +------------------------------------------------------+
*
* They all start with a BRANCH for "\|" alternatives, even when there is only
* one alternative.
*/
/*
* The opcodes are:
*/
/* definition number opnd? meaning */
#define END 0 /* End of program or NOMATCH operand. */
#define BOL 1 /* Match "" at beginning of line. */
#define EOL 2 /* Match "" at end of line. */
#define BRANCH 3 /* node Match this alternative, or the
* next... */
#define BACK 4 /* Match "", "next" ptr points backward. */
#define EXACTLY 5 /* str Match this string. */
#define NOTHING 6 /* Match empty string. */
#define STAR 7 /* node Match this (simple) thing 0 or more
* times. */
#define PLUS 8 /* node Match this (simple) thing 1 or more
* times. */
#define MATCH 9 /* node match the operand zero-width */
#define NOMATCH 10 /* node check for no match with operand */
#define BEHIND 11 /* node look behind for a match with operand */
#define NOBEHIND 12 /* node look behind for no match with operand */
#define SUBPAT 13 /* node match the operand here */
#define BRACE_SIMPLE 14 /* node Match this (simple) thing between m and
* n times (\{m,n\}). */
#define BOW 15 /* Match "" after [^a-zA-Z0-9_] */
#define EOW 16 /* Match "" at [^a-zA-Z0-9_] */
#define BRACE_LIMITS 17 /* nr nr define the min & max for BRACE_SIMPLE
* and BRACE_COMPLEX. */
#define NEWL 18 /* Match line-break */
#define BHPOS 19 /* End position for BEHIND or NOBEHIND */
/* character classes: 20-48 normal, 50-78 include a line-break */
#define ADD_NL 30
#define FIRST_NL ANY + ADD_NL
#define ANY 20 /* Match any one character. */
#define ANYOF 21 /* str Match any character in this string. */
#define ANYBUT 22 /* str Match any character not in this
* string. */
#define IDENT 23 /* Match identifier char */
#define SIDENT 24 /* Match identifier char but no digit */
#define KWORD 25 /* Match keyword char */
#define SKWORD 26 /* Match word char but no digit */
#define FNAME 27 /* Match file name char */
#define SFNAME 28 /* Match file name char but no digit */
#define PRINT 29 /* Match printable char */
#define SPRINT 30 /* Match printable char but no digit */
#define WHITE 31 /* Match whitespace char */
#define NWHITE 32 /* Match non-whitespace char */
#define DIGIT 33 /* Match digit char */
#define NDIGIT 34 /* Match non-digit char */
#define HEX 35 /* Match hex char */
#define NHEX 36 /* Match non-hex char */
#define OCTAL 37 /* Match octal char */
#define NOCTAL 38 /* Match non-octal char */
#define WORD 39 /* Match word char */
#define NWORD 40 /* Match non-word char */
#define HEAD 41 /* Match head char */
#define NHEAD 42 /* Match non-head char */
#define ALPHA 43 /* Match alpha char */
#define NALPHA 44 /* Match non-alpha char */
#define LOWER 45 /* Match lowercase char */
#define NLOWER 46 /* Match non-lowercase char */
#define UPPER 47 /* Match uppercase char */
#define NUPPER 48 /* Match non-uppercase char */
#define LAST_NL NUPPER + ADD_NL
#define WITH_NL(op) ((op) >= FIRST_NL && (op) <= LAST_NL)
#define MOPEN 80 /* -89 Mark this point in input as start of
* \( subexpr. MOPEN + 0 marks start of
* match. */
#define MCLOSE 90 /* -99 Analogous to MOPEN. MCLOSE + 0 marks
* end of match. */
#define BACKREF 100 /* -109 node Match same string again \1-\9 */
#ifdef FEAT_SYN_HL
# define ZOPEN 110 /* -119 Mark this point in input as start of
* \z( subexpr. */
# define ZCLOSE 120 /* -129 Analogous to ZOPEN. */
# define ZREF 130 /* -139 node Match external submatch \z1-\z9 */
#endif
#define BRACE_COMPLEX 140 /* -149 node Match nodes between m & n times */
#define NOPEN 150 /* Mark this point in input as start of
\%( subexpr. */
#define NCLOSE 151 /* Analogous to NOPEN. */
#define MULTIBYTECODE 200 /* mbc Match one multi-byte character */
#define RE_BOF 201 /* Match "" at beginning of file. */
#define RE_EOF 202 /* Match "" at end of file. */
#define CURSOR 203 /* Match location of cursor. */
#define RE_LNUM 204 /* nr cmp Match line number */
#define RE_COL 205 /* nr cmp Match column number */
#define RE_VCOL 206 /* nr cmp Match virtual column number */
#define RE_MARK 207 /* mark cmp Match mark position */
#define RE_VISUAL 208 /* Match Visual area */
/*
* Magic characters have a special meaning, they don't match literally.
* Magic characters are negative. This separates them from literal characters
* (possibly multi-byte). Only ASCII characters can be Magic.
*/
#define Magic(x) ((int)(x) - 256)
#define un_Magic(x) ((x) + 256)
#define is_Magic(x) ((x) < 0)
static int no_Magic __ARGS((int x));
static int toggle_Magic __ARGS((int x));
static int
no_Magic(x)
int x;
{
if (is_Magic(x))
return un_Magic(x);
return x;
}
static int
toggle_Magic(x)
int x;
{
if (is_Magic(x))
return un_Magic(x);
return Magic(x);
}
/*
* The first byte of the regexp internal "program" is actually this magic
* number; the start node begins in the second byte. It's used to catch the
* most severe mutilation of the program by the caller.
*/
#define REGMAGIC 0234
/*
* Opcode notes:
*
* BRANCH The set of branches constituting a single choice are hooked
* together with their "next" pointers, since precedence prevents
* anything being concatenated to any individual branch. The
* "next" pointer of the last BRANCH in a choice points to the
* thing following the whole choice. This is also where the
* final "next" pointer of each individual branch points; each
* branch starts with the operand node of a BRANCH node.
*
* BACK Normal "next" pointers all implicitly point forward; BACK
* exists to make loop structures possible.
*
* STAR,PLUS '=', and complex '*' and '+', are implemented as circular
* BRANCH structures using BACK. Simple cases (one character
* per match) are implemented with STAR and PLUS for speed
* and to minimize recursive plunges.
*
* BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
* node, and defines the min and max limits to be used for that
* node.
*
* MOPEN,MCLOSE ...are numbered at compile time.
* ZOPEN,ZCLOSE ...ditto
*/
/*
* A node is one char of opcode followed by two chars of "next" pointer.
* "Next" pointers are stored as two 8-bit bytes, high order first. The
* value is a positive offset from the opcode of the node containing it.
* An operand, if any, simply follows the node. (Note that much of the
* code generation knows about this implicit relationship.)
*
* Using two bytes for the "next" pointer is vast overkill for most things,
* but allows patterns to get big without disasters.
*/
#define OP(p) ((int)*(p))
#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
#define OPERAND(p) ((p) + 3)
/* Obtain an operand that was stored as four bytes, MSB first. */
#define OPERAND_MIN(p) (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
+ ((long)(p)[5] << 8) + (long)(p)[6])
/* Obtain a second operand stored as four bytes. */
#define OPERAND_MAX(p) OPERAND_MIN((p) + 4)
/* Obtain a second single-byte operand stored after a four bytes operand. */
#define OPERAND_CMP(p) (p)[7]
/*
* Utility definitions.
*/
#define UCHARAT(p) ((int)*(char_u *)(p))
/* Used for an error (down from) vim_regcomp(): give the error message, set
* rc_did_emsg and return NULL */
#define EMSG_RET_NULL(m) return (EMSG(m), rc_did_emsg = TRUE, (void *)NULL)
#define EMSG_M_RET_NULL(m, c) return (EMSG2((m), (c) ? "" : "\\"), rc_did_emsg = TRUE, (void *)NULL)
#define EMSG_RET_FAIL(m) return (EMSG(m), rc_did_emsg = TRUE, FAIL)
#define EMSG_ONE_RET_NULL EMSG_M_RET_NULL(_("E369: invalid item in %s%%[]"), reg_magic == MAGIC_ALL)
#define MAX_LIMIT (32767L << 16L)
static int re_multi_type __ARGS((int));
static int cstrncmp __ARGS((char_u *s1, char_u *s2, int *n));
static char_u *cstrchr __ARGS((char_u *, int));
#ifdef DEBUG
static void regdump __ARGS((char_u *, regprog_T *));
static char_u *regprop __ARGS((char_u *));
#endif
#define NOT_MULTI 0
#define MULTI_ONE 1
#define MULTI_MULT 2
/*
* Return NOT_MULTI if c is not a "multi" operator.
* Return MULTI_ONE if c is a single "multi" operator.
* Return MULTI_MULT if c is a multi "multi" operator.
*/
static int
re_multi_type(c)
int c;
{
if (c == Magic('@') || c == Magic('=') || c == Magic('?'))
return MULTI_ONE;
if (c == Magic('*') || c == Magic('+') || c == Magic('{'))
return MULTI_MULT;
return NOT_MULTI;
}
/*
* Flags to be passed up and down.
*/
#define HASWIDTH 0x1 /* Known never to match null string. */
#define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
#define SPSTART 0x4 /* Starts with * or +. */
#define HASNL 0x8 /* Contains some \n. */
#define HASLOOKBH 0x10 /* Contains "\@<=" or "\@<!". */
#define WORST 0 /* Worst case. */
/*
* When regcode is set to this value, code is not emitted and size is computed
* instead.
*/
#define JUST_CALC_SIZE ((char_u *) -1)
static char_u *reg_prev_sub = NULL;
/*
* REGEXP_INRANGE contains all characters which are always special in a []
* range after '\'.
* REGEXP_ABBR contains all characters which act as abbreviations after '\'.
* These are:
* \n - New line (NL).
* \r - Carriage Return (CR).
* \t - Tab (TAB).
* \e - Escape (ESC).
* \b - Backspace (Ctrl_H).
* \d - Character code in decimal, eg \d123
* \o - Character code in octal, eg \o80
* \x - Character code in hex, eg \x4a
* \u - Multibyte character code, eg \u20ac
* \U - Long multibyte character code, eg \U12345678
*/
static char_u REGEXP_INRANGE[] = "]^-n\\";
static char_u REGEXP_ABBR[] = "nrtebdoxuU";
static int backslash_trans __ARGS((int c));
static int get_char_class __ARGS((char_u **pp));
static int get_equi_class __ARGS((char_u **pp));
static void reg_equi_class __ARGS((int c));
static int get_coll_element __ARGS((char_u **pp));
static char_u *skip_anyof __ARGS((char_u *p));
static void init_class_tab __ARGS((void));
/*
* Translate '\x' to its control character, except "\n", which is Magic.
*/
static int
backslash_trans(c)
int c;
{
switch (c)
{
case 'r': return CAR;
case 't': return TAB;
case 'e': return ESC;
case 'b': return BS;
}
return c;
}
/*
* Check for a character class name "[:name:]". "pp" points to the '['.
* Returns one of the CLASS_ items. CLASS_NONE means that no item was
* recognized. Otherwise "pp" is advanced to after the item.
*/
static int
get_char_class(pp)
char_u **pp;
{
static const char *(class_names[]) =
{
"alnum:]",
#define CLASS_ALNUM 0
"alpha:]",
#define CLASS_ALPHA 1
"blank:]",
#define CLASS_BLANK 2
"cntrl:]",
#define CLASS_CNTRL 3
"digit:]",
#define CLASS_DIGIT 4
"graph:]",
#define CLASS_GRAPH 5
"lower:]",
#define CLASS_LOWER 6
"print:]",
#define CLASS_PRINT 7
"punct:]",
#define CLASS_PUNCT 8
"space:]",
#define CLASS_SPACE 9
"upper:]",
#define CLASS_UPPER 10
"xdigit:]",
#define CLASS_XDIGIT 11
"tab:]",
#define CLASS_TAB 12
"return:]",
#define CLASS_RETURN 13
"backspace:]",
#define CLASS_BACKSPACE 14
"escape:]",
#define CLASS_ESCAPE 15
};
#define CLASS_NONE 99
int i;
if ((*pp)[1] == ':')
{
for (i = 0; i < (int)(sizeof(class_names) / sizeof(*class_names)); ++i)
if (STRNCMP(*pp + 2, class_names[i], STRLEN(class_names[i])) == 0)
{
*pp += STRLEN(class_names[i]) + 2;
return i;
}
}
return CLASS_NONE;
}
/*
* Specific version of character class functions.
* Using a table to keep this fast.
*/
static short class_tab[256];
#define RI_DIGIT 0x01
#define RI_HEX 0x02
#define RI_OCTAL 0x04
#define RI_WORD 0x08
#define RI_HEAD 0x10
#define RI_ALPHA 0x20
#define RI_LOWER 0x40
#define RI_UPPER 0x80
#define RI_WHITE 0x100
static void
init_class_tab()
{
int i;
static int done = FALSE;
if (done)
return;
for (i = 0; i < 256; ++i)
{
if (i >= '0' && i <= '7')
class_tab[i] = RI_DIGIT + RI_HEX + RI_OCTAL + RI_WORD;
else if (i >= '8' && i <= '9')
class_tab[i] = RI_DIGIT + RI_HEX + RI_WORD;
else if (i >= 'a' && i <= 'f')
class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
#ifdef EBCDIC
else if ((i >= 'g' && i <= 'i') || (i >= 'j' && i <= 'r')
|| (i >= 's' && i <= 'z'))
#else
else if (i >= 'g' && i <= 'z')
#endif
class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
else if (i >= 'A' && i <= 'F')
class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
#ifdef EBCDIC
else if ((i >= 'G' && i <= 'I') || ( i >= 'J' && i <= 'R')
|| (i >= 'S' && i <= 'Z'))
#else
else if (i >= 'G' && i <= 'Z')
#endif
class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
else if (i == '_')
class_tab[i] = RI_WORD + RI_HEAD;
else
class_tab[i] = 0;
}
class_tab[' '] |= RI_WHITE;
class_tab['\t'] |= RI_WHITE;
done = TRUE;
}
#ifdef FEAT_MBYTE
# define ri_digit(c) (c < 0x100 && (class_tab[c] & RI_DIGIT))
# define ri_hex(c) (c < 0x100 && (class_tab[c] & RI_HEX))
# define ri_octal(c) (c < 0x100 && (class_tab[c] & RI_OCTAL))
# define ri_word(c) (c < 0x100 && (class_tab[c] & RI_WORD))
# define ri_head(c) (c < 0x100 && (class_tab[c] & RI_HEAD))
# define ri_alpha(c) (c < 0x100 && (class_tab[c] & RI_ALPHA))
# define ri_lower(c) (c < 0x100 && (class_tab[c] & RI_LOWER))
# define ri_upper(c) (c < 0x100 && (class_tab[c] & RI_UPPER))
# define ri_white(c) (c < 0x100 && (class_tab[c] & RI_WHITE))
#else
# define ri_digit(c) (class_tab[c] & RI_DIGIT)
# define ri_hex(c) (class_tab[c] & RI_HEX)
# define ri_octal(c) (class_tab[c] & RI_OCTAL)
# define ri_word(c) (class_tab[c] & RI_WORD)
# define ri_head(c) (class_tab[c] & RI_HEAD)
# define ri_alpha(c) (class_tab[c] & RI_ALPHA)
# define ri_lower(c) (class_tab[c] & RI_LOWER)
# define ri_upper(c) (class_tab[c] & RI_UPPER)
# define ri_white(c) (class_tab[c] & RI_WHITE)
#endif
/* flags for regflags */
#define RF_ICASE 1 /* ignore case */
#define RF_NOICASE 2 /* don't ignore case */
#define RF_HASNL 4 /* can match a NL */
#define RF_ICOMBINE 8 /* ignore combining characters */
#define RF_LOOKBH 16 /* uses "\@<=" or "\@<!" */
/*
* Global work variables for vim_regcomp().
*/
static char_u *regparse; /* Input-scan pointer. */
static int prevchr_len; /* byte length of previous char */
static int num_complex_braces; /* Complex \{...} count */
static int regnpar; /* () count. */
#ifdef FEAT_SYN_HL
static int regnzpar; /* \z() count. */
static int re_has_z; /* \z item detected */
#endif
static char_u *regcode; /* Code-emit pointer, or JUST_CALC_SIZE */
static long regsize; /* Code size. */
static int reg_toolong; /* TRUE when offset out of range */
static char_u had_endbrace[NSUBEXP]; /* flags, TRUE if end of () found */
static unsigned regflags; /* RF_ flags for prog */
static long brace_min[10]; /* Minimums for complex brace repeats */
static long brace_max[10]; /* Maximums for complex brace repeats */
static int brace_count[10]; /* Current counts for complex brace repeats */
#if defined(FEAT_SYN_HL) || defined(PROTO)
static int had_eol; /* TRUE when EOL found by vim_regcomp() */
#endif
static int one_exactly = FALSE; /* only do one char for EXACTLY */
static int reg_magic; /* magicness of the pattern: */
#define MAGIC_NONE 1 /* "\V" very unmagic */
#define MAGIC_OFF 2 /* "\M" or 'magic' off */
#define MAGIC_ON 3 /* "\m" or 'magic' */
#define MAGIC_ALL 4 /* "\v" very magic */
static int reg_string; /* matching with a string instead of a buffer
line */
static int reg_strict; /* "[abc" is illegal */
/*
* META contains all characters that may be magic, except '^' and '$'.
*/
#ifdef EBCDIC
static char_u META[] = "%&()*+.123456789<=>?@ACDFHIKLMOPSUVWX[_acdfhiklmnopsuvwxz{|~";
#else
/* META[] is used often enough to justify turning it into a table. */
static char_u META_flags[] = {
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, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
/* 1 2 3 4 5 6 7 8 9 < = > ? */
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
/* @ A C D F H I K L M O */
1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
/* P S U V W X Z [ _ */
1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
/* a c d f h i k l m n o */
0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
/* p s u v w x z { | ~ */
1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
};
#endif
static int curchr;
/* arguments for reg() */
#define REG_NOPAREN 0 /* toplevel reg() */
#define REG_PAREN 1 /* \(\) */
#define REG_ZPAREN 2 /* \z(\) */
#define REG_NPAREN 3 /* \%(\) */
/*
* Forward declarations for vim_regcomp()'s friends.
*/
static void initchr __ARGS((char_u *));
static int getchr __ARGS((void));
static void skipchr_keepstart __ARGS((void));
static int peekchr __ARGS((void));
static void skipchr __ARGS((void));
static void ungetchr __ARGS((void));
static int gethexchrs __ARGS((int maxinputlen));
static int getoctchrs __ARGS((void));
static int getdecchrs __ARGS((void));
static int coll_get_char __ARGS((void));
static void regcomp_start __ARGS((char_u *expr, int flags));
static char_u *reg __ARGS((int, int *));
static char_u *regbranch __ARGS((int *flagp));
static char_u *regconcat __ARGS((int *flagp));
static char_u *regpiece __ARGS((int *));
static char_u *regatom __ARGS((int *));
static char_u *regnode __ARGS((int));
#ifdef FEAT_MBYTE
static int use_multibytecode __ARGS((int c));
#endif
static int prog_magic_wrong __ARGS((void));
static char_u *regnext __ARGS((char_u *));
static void regc __ARGS((int b));
#ifdef FEAT_MBYTE
static void regmbc __ARGS((int c));
# define REGMBC(x) regmbc(x);
# define CASEMBC(x) case x:
#else
# define regmbc(c) regc(c)
# define REGMBC(x)
# define CASEMBC(x)
#endif
static void reginsert __ARGS((int, char_u *));
static void reginsert_limits __ARGS((int, long, long, char_u *));
static char_u *re_put_long __ARGS((char_u *pr, long_u val));
static int read_limits __ARGS((long *, long *));
static void regtail __ARGS((char_u *, char_u *));
static void regoptail __ARGS((char_u *, char_u *));
/*
* Return TRUE if compiled regular expression "prog" can match a line break.
*/
int
re_multiline(prog)
regprog_T *prog;
{
return (prog->regflags & RF_HASNL);
}
/*
* Return TRUE if compiled regular expression "prog" looks before the start
* position (pattern contains "\@<=" or "\@<!").
*/
int
re_lookbehind(prog)
regprog_T *prog;
{
return (prog->regflags & RF_LOOKBH);
}
/*
* Check for an equivalence class name "[=a=]". "pp" points to the '['.
* Returns a character representing the class. Zero means that no item was
* recognized. Otherwise "pp" is advanced to after the item.
*/
static int
get_equi_class(pp)
char_u **pp;
{
int c;
int l = 1;
char_u *p = *pp;
if (p[1] == '=')
{
#ifdef FEAT_MBYTE
if (has_mbyte)
l = (*mb_ptr2len)(p + 2);
#endif
if (p[l + 2] == '=' && p[l + 3] == ']')
{
#ifdef FEAT_MBYTE
if (has_mbyte)
c = mb_ptr2char(p + 2);
else
#endif
c = p[2];
*pp += l + 4;
return c;
}
}
return 0;
}
#ifdef EBCDIC
/*
* Table for equivalence class "c". (IBM-1047)
*/
char *EQUIVAL_CLASS_C[16] = {
"A\x62\x63\x64\x65\x66\x67",
"C\x68",
"E\x71\x72\x73\x74",
"I\x75\x76\x77\x78",
"N\x69",
"O\xEB\xEC\xED\xEE\xEF",
"U\xFB\xFC\xFD\xFE",
"Y\xBA",
"a\x42\x43\x44\x45\x46\x47",
"c\x48",
"e\x51\x52\x53\x54",
"i\x55\x56\x57\x58",
"n\x49",
"o\xCB\xCC\xCD\xCE\xCF",
"u\xDB\xDC\xDD\xDE",
"y\x8D\xDF",
};
#endif
/*
* Produce the bytes for equivalence class "c".
* Currently only handles latin1, latin9 and utf-8.
*/
static void
reg_equi_class(c)
int c;
{
#ifdef FEAT_MBYTE
if (enc_utf8 || STRCMP(p_enc, "latin1") == 0
|| STRCMP(p_enc, "iso-8859-15") == 0)
#endif
{
#ifdef EBCDIC
int i;
/* This might be slower than switch/case below. */
for (i = 0; i < 16; i++)
{
if (vim_strchr(EQUIVAL_CLASS_C[i], c) != NULL)
{
char *p = EQUIVAL_CLASS_C[i];
while (*p != 0)
regmbc(*p++);
return;
}
}
#else
switch (c)
{
case 'A': case '\300': case '\301': case '\302':
CASEMBC(0x100) CASEMBC(0x102) CASEMBC(0x104) CASEMBC(0x1cd)
CASEMBC(0x1de) CASEMBC(0x1e0) CASEMBC(0x1ea2)
case '\303': case '\304': case '\305':
regmbc('A'); regmbc('\300'); regmbc('\301');
regmbc('\302'); regmbc('\303'); regmbc('\304');
regmbc('\305');
REGMBC(0x100) REGMBC(0x102) REGMBC(0x104)
REGMBC(0x1cd) REGMBC(0x1de) REGMBC(0x1e0)
REGMBC(0x1ea2)
return;
case 'B': CASEMBC(0x1e02) CASEMBC(0x1e06)
regmbc('B'); REGMBC(0x1e02) REGMBC(0x1e06)
return;
case 'C': case '\307':
CASEMBC(0x106) CASEMBC(0x108) CASEMBC(0x10a) CASEMBC(0x10c)
regmbc('C'); regmbc('\307');
REGMBC(0x106) REGMBC(0x108) REGMBC(0x10a)
REGMBC(0x10c)
return;
case 'D': CASEMBC(0x10e) CASEMBC(0x110) CASEMBC(0x1e0a)
CASEMBC(0x1e0e) CASEMBC(0x1e10)
regmbc('D'); REGMBC(0x10e) REGMBC(0x110)
REGMBC(0x1e0a) REGMBC(0x1e0e) REGMBC(0x1e10)
return;
case 'E': case '\310': case '\311': case '\312': case '\313':
CASEMBC(0x112) CASEMBC(0x114) CASEMBC(0x116) CASEMBC(0x118)
CASEMBC(0x11a) CASEMBC(0x1eba) CASEMBC(0x1ebc)
regmbc('E'); regmbc('\310'); regmbc('\311');
regmbc('\312'); regmbc('\313');
REGMBC(0x112) REGMBC(0x114) REGMBC(0x116)
REGMBC(0x118) REGMBC(0x11a) REGMBC(0x1eba)
REGMBC(0x1ebc)
return;
case 'F': CASEMBC(0x1e1e)
regmbc('F'); REGMBC(0x1e1e)
return;
case 'G': CASEMBC(0x11c) CASEMBC(0x11e) CASEMBC(0x120)
CASEMBC(0x122) CASEMBC(0x1e4) CASEMBC(0x1e6) CASEMBC(0x1f4)
CASEMBC(0x1e20)
regmbc('G'); REGMBC(0x11c) REGMBC(0x11e)
REGMBC(0x120) REGMBC(0x122) REGMBC(0x1e4)
REGMBC(0x1e6) REGMBC(0x1f4) REGMBC(0x1e20)
return;
case 'H': CASEMBC(0x124) CASEMBC(0x126) CASEMBC(0x1e22)
CASEMBC(0x1e26) CASEMBC(0x1e28)
regmbc('H'); REGMBC(0x124) REGMBC(0x126)
REGMBC(0x1e22) REGMBC(0x1e26) REGMBC(0x1e28)
return;
case 'I': case '\314': case '\315': case '\316': case '\317':
CASEMBC(0x128) CASEMBC(0x12a) CASEMBC(0x12c) CASEMBC(0x12e)
CASEMBC(0x130) CASEMBC(0x1cf) CASEMBC(0x1ec8)
regmbc('I'); regmbc('\314'); regmbc('\315');
regmbc('\316'); regmbc('\317');
REGMBC(0x128) REGMBC(0x12a) REGMBC(0x12c)
REGMBC(0x12e) REGMBC(0x130) REGMBC(0x1cf)
REGMBC(0x1ec8)
return;
case 'J': CASEMBC(0x134)
regmbc('J'); REGMBC(0x134)
return;
case 'K': CASEMBC(0x136) CASEMBC(0x1e8) CASEMBC(0x1e30)
CASEMBC(0x1e34)
regmbc('K'); REGMBC(0x136) REGMBC(0x1e8)
REGMBC(0x1e30) REGMBC(0x1e34)
return;
case 'L': CASEMBC(0x139) CASEMBC(0x13b) CASEMBC(0x13d)
CASEMBC(0x13f) CASEMBC(0x141) CASEMBC(0x1e3a)
regmbc('L'); REGMBC(0x139) REGMBC(0x13b)
REGMBC(0x13d) REGMBC(0x13f) REGMBC(0x141)
REGMBC(0x1e3a)
return;
case 'M': CASEMBC(0x1e3e) CASEMBC(0x1e40)
regmbc('M'); REGMBC(0x1e3e) REGMBC(0x1e40)
return;
case 'N': case '\321':
CASEMBC(0x143) CASEMBC(0x145) CASEMBC(0x147) CASEMBC(0x1e44)
CASEMBC(0x1e48)
regmbc('N'); regmbc('\321');
REGMBC(0x143) REGMBC(0x145) REGMBC(0x147)
REGMBC(0x1e44) REGMBC(0x1e48)
return;
case 'O': case '\322': case '\323': case '\324': case '\325':
case '\326': case '\330':
CASEMBC(0x14c) CASEMBC(0x14e) CASEMBC(0x150) CASEMBC(0x1a0)
CASEMBC(0x1d1) CASEMBC(0x1ea) CASEMBC(0x1ec) CASEMBC(0x1ece)
regmbc('O'); regmbc('\322'); regmbc('\323');
regmbc('\324'); regmbc('\325'); regmbc('\326');
regmbc('\330');
REGMBC(0x14c) REGMBC(0x14e) REGMBC(0x150)
REGMBC(0x1a0) REGMBC(0x1d1) REGMBC(0x1ea)
REGMBC(0x1ec) REGMBC(0x1ece)
return;
case 'P': case 0x1e54: case 0x1e56:
regmbc('P'); REGMBC(0x1e54) REGMBC(0x1e56)
return;
case 'R': CASEMBC(0x154) CASEMBC(0x156) CASEMBC(0x158)
CASEMBC(0x1e58) CASEMBC(0x1e5e)
regmbc('R'); REGMBC(0x154) REGMBC(0x156) REGMBC(0x158)
REGMBC(0x1e58) REGMBC(0x1e5e)
return;
case 'S': CASEMBC(0x15a) CASEMBC(0x15c) CASEMBC(0x15e)
CASEMBC(0x160) CASEMBC(0x1e60)
regmbc('S'); REGMBC(0x15a) REGMBC(0x15c)
REGMBC(0x15e) REGMBC(0x160) REGMBC(0x1e60)
return;
case 'T': CASEMBC(0x162) CASEMBC(0x164) CASEMBC(0x166)
CASEMBC(0x1e6a) CASEMBC(0x1e6e)
regmbc('T'); REGMBC(0x162) REGMBC(0x164)
REGMBC(0x166) REGMBC(0x1e6a) REGMBC(0x1e6e)
return;
case 'U': case '\331': case '\332': case '\333': case '\334':
CASEMBC(0x168) CASEMBC(0x16a) CASEMBC(0x16c) CASEMBC(0x16e)
CASEMBC(0x170) CASEMBC(0x172) CASEMBC(0x1af) CASEMBC(0x1d3)
CASEMBC(0x1ee6)
regmbc('U'); regmbc('\331'); regmbc('\332');
regmbc('\333'); regmbc('\334');
REGMBC(0x168) REGMBC(0x16a) REGMBC(0x16c)
REGMBC(0x16e) REGMBC(0x170) REGMBC(0x172)
REGMBC(0x1af) REGMBC(0x1d3) REGMBC(0x1ee6)
return;
case 'V': CASEMBC(0x1e7c)
regmbc('V'); REGMBC(0x1e7c)
return;
case 'W': CASEMBC(0x174) CASEMBC(0x1e80) CASEMBC(0x1e82)
CASEMBC(0x1e84) CASEMBC(0x1e86)
regmbc('W'); REGMBC(0x174) REGMBC(0x1e80)
REGMBC(0x1e82) REGMBC(0x1e84) REGMBC(0x1e86)
return;
case 'X': CASEMBC(0x1e8a) CASEMBC(0x1e8c)
regmbc('X'); REGMBC(0x1e8a) REGMBC(0x1e8c)
return;
case 'Y': case '\335':
CASEMBC(0x176) CASEMBC(0x178) CASEMBC(0x1e8e) CASEMBC(0x1ef2)
CASEMBC(0x1ef6) CASEMBC(0x1ef8)
regmbc('Y'); regmbc('\335');
REGMBC(0x176) REGMBC(0x178) REGMBC(0x1e8e)
REGMBC(0x1ef2) REGMBC(0x1ef6) REGMBC(0x1ef8)
return;
case 'Z': CASEMBC(0x179) CASEMBC(0x17b) CASEMBC(0x17d)
CASEMBC(0x1b5) CASEMBC(0x1e90) CASEMBC(0x1e94)
regmbc('Z'); REGMBC(0x179) REGMBC(0x17b)
REGMBC(0x17d) REGMBC(0x1b5) REGMBC(0x1e90)
REGMBC(0x1e94)
return;
case 'a': case '\340': case '\341': case '\342':
case '\343': case '\344': case '\345':
CASEMBC(0x101) CASEMBC(0x103) CASEMBC(0x105) CASEMBC(0x1ce)
CASEMBC(0x1df) CASEMBC(0x1e1) CASEMBC(0x1ea3)
regmbc('a'); regmbc('\340'); regmbc('\341');
regmbc('\342'); regmbc('\343'); regmbc('\344');
regmbc('\345');
REGMBC(0x101) REGMBC(0x103) REGMBC(0x105)
REGMBC(0x1ce) REGMBC(0x1df) REGMBC(0x1e1)
REGMBC(0x1ea3)
return;
case 'b': CASEMBC(0x1e03) CASEMBC(0x1e07)
regmbc('b'); REGMBC(0x1e03) REGMBC(0x1e07)
return;
case 'c': case '\347':
CASEMBC(0x107) CASEMBC(0x109) CASEMBC(0x10b) CASEMBC(0x10d)
regmbc('c'); regmbc('\347');
REGMBC(0x107) REGMBC(0x109) REGMBC(0x10b)
REGMBC(0x10d)
return;
case 'd': CASEMBC(0x10f) CASEMBC(0x111) CASEMBC(0x1d0b)
CASEMBC(0x1e11)
regmbc('d'); REGMBC(0x10f) REGMBC(0x111)
REGMBC(0x1e0b) REGMBC(0x01e0f) REGMBC(0x1e11)
return;
case 'e': case '\350': case '\351': case '\352': case '\353':
CASEMBC(0x113) CASEMBC(0x115) CASEMBC(0x117) CASEMBC(0x119)
CASEMBC(0x11b) CASEMBC(0x1ebb) CASEMBC(0x1ebd)
regmbc('e'); regmbc('\350'); regmbc('\351');
regmbc('\352'); regmbc('\353');
REGMBC(0x113) REGMBC(0x115) REGMBC(0x117)
REGMBC(0x119) REGMBC(0x11b) REGMBC(0x1ebb)
REGMBC(0x1ebd)
return;
case 'f': CASEMBC(0x1e1f)
regmbc('f'); REGMBC(0x1e1f)
return;
case 'g': CASEMBC(0x11d) CASEMBC(0x11f) CASEMBC(0x121)
CASEMBC(0x123) CASEMBC(0x1e5) CASEMBC(0x1e7) CASEMBC(0x1f5)
CASEMBC(0x1e21)
regmbc('g'); REGMBC(0x11d) REGMBC(0x11f)
REGMBC(0x121) REGMBC(0x123) REGMBC(0x1e5)
REGMBC(0x1e7) REGMBC(0x1f5) REGMBC(0x1e21)
return;
case 'h': CASEMBC(0x125) CASEMBC(0x127) CASEMBC(0x1e23)
CASEMBC(0x1e27) CASEMBC(0x1e29) CASEMBC(0x1e96)
regmbc('h'); REGMBC(0x125) REGMBC(0x127)
REGMBC(0x1e23) REGMBC(0x1e27) REGMBC(0x1e29)
REGMBC(0x1e96)
return;
case 'i': case '\354': case '\355': case '\356': case '\357':
CASEMBC(0x129) CASEMBC(0x12b) CASEMBC(0x12d) CASEMBC(0x12f)
CASEMBC(0x1d0) CASEMBC(0x1ec9)
regmbc('i'); regmbc('\354'); regmbc('\355');
regmbc('\356'); regmbc('\357');
REGMBC(0x129) REGMBC(0x12b) REGMBC(0x12d)
REGMBC(0x12f) REGMBC(0x1d0) REGMBC(0x1ec9)
return;
case 'j': CASEMBC(0x135) CASEMBC(0x1f0)
regmbc('j'); REGMBC(0x135) REGMBC(0x1f0)
return;
case 'k': CASEMBC(0x137) CASEMBC(0x1e9) CASEMBC(0x1e31)
CASEMBC(0x1e35)
regmbc('k'); REGMBC(0x137) REGMBC(0x1e9)
REGMBC(0x1e31) REGMBC(0x1e35)
return;
case 'l': CASEMBC(0x13a) CASEMBC(0x13c) CASEMBC(0x13e)
CASEMBC(0x140) CASEMBC(0x142) CASEMBC(0x1e3b)
regmbc('l'); REGMBC(0x13a) REGMBC(0x13c)
REGMBC(0x13e) REGMBC(0x140) REGMBC(0x142)
REGMBC(0x1e3b)
return;
case 'm': CASEMBC(0x1e3f) CASEMBC(0x1e41)
regmbc('m'); REGMBC(0x1e3f) REGMBC(0x1e41)
return;
case 'n': case '\361':
CASEMBC(0x144) CASEMBC(0x146) CASEMBC(0x148) CASEMBC(0x149)
CASEMBC(0x1e45) CASEMBC(0x1e49)
regmbc('n'); regmbc('\361');
REGMBC(0x144) REGMBC(0x146) REGMBC(0x148)
REGMBC(0x149) REGMBC(0x1e45) REGMBC(0x1e49)
return;
case 'o': case '\362': case '\363': case '\364': case '\365':
case '\366': case '\370':
CASEMBC(0x14d) CASEMBC(0x14f) CASEMBC(0x151) CASEMBC(0x1a1)
CASEMBC(0x1d2) CASEMBC(0x1eb) CASEMBC(0x1ed) CASEMBC(0x1ecf)
regmbc('o'); regmbc('\362'); regmbc('\363');
regmbc('\364'); regmbc('\365'); regmbc('\366');
regmbc('\370');
REGMBC(0x14d) REGMBC(0x14f) REGMBC(0x151)
REGMBC(0x1a1) REGMBC(0x1d2) REGMBC(0x1eb)
REGMBC(0x1ed) REGMBC(0x1ecf)
return;
case 'p': CASEMBC(0x1e55) CASEMBC(0x1e57)
regmbc('p'); REGMBC(0x1e55) REGMBC(0x1e57)
return;
case 'r': CASEMBC(0x155) CASEMBC(0x157) CASEMBC(0x159)
CASEMBC(0x1e59) CASEMBC(0x1e5f)
regmbc('r'); REGMBC(0x155) REGMBC(0x157) REGMBC(0x159)
REGMBC(0x1e59) REGMBC(0x1e5f)
return;
case 's': CASEMBC(0x15b) CASEMBC(0x15d) CASEMBC(0x15f)
CASEMBC(0x161) CASEMBC(0x1e61)
regmbc('s'); REGMBC(0x15b) REGMBC(0x15d)
REGMBC(0x15f) REGMBC(0x161) REGMBC(0x1e61)
return;
case 't': CASEMBC(0x163) CASEMBC(0x165) CASEMBC(0x167)
CASEMBC(0x1e6b) CASEMBC(0x1e6f) CASEMBC(0x1e97)
regmbc('t'); REGMBC(0x163) REGMBC(0x165) REGMBC(0x167)
REGMBC(0x1e6b) REGMBC(0x1e6f) REGMBC(0x1e97)
return;
case 'u': case '\371': case '\372': case '\373': case '\374':
CASEMBC(0x169) CASEMBC(0x16b) CASEMBC(0x16d) CASEMBC(0x16f)
CASEMBC(0x171) CASEMBC(0x173) CASEMBC(0x1b0) CASEMBC(0x1d4)
CASEMBC(0x1ee7)
regmbc('u'); regmbc('\371'); regmbc('\372');
regmbc('\373'); regmbc('\374');
REGMBC(0x169) REGMBC(0x16b) REGMBC(0x16d)
REGMBC(0x16f) REGMBC(0x171) REGMBC(0x173)
REGMBC(0x1b0) REGMBC(0x1d4) REGMBC(0x1ee7)
return;
case 'v': CASEMBC(0x1e7d)
regmbc('v'); REGMBC(0x1e7d)
return;
case 'w': CASEMBC(0x175) CASEMBC(0x1e81) CASEMBC(0x1e83)
CASEMBC(0x1e85) CASEMBC(0x1e87) CASEMBC(0x1e98)
regmbc('w'); REGMBC(0x175) REGMBC(0x1e81)
REGMBC(0x1e83) REGMBC(0x1e85) REGMBC(0x1e87)
REGMBC(0x1e98)
return;
case 'x': CASEMBC(0x1e8b) CASEMBC(0x1e8d)
regmbc('x'); REGMBC(0x1e8b) REGMBC(0x1e8d)
return;
case 'y': case '\375': case '\377':
CASEMBC(0x177) CASEMBC(0x1e8f) CASEMBC(0x1e99)
CASEMBC(0x1ef3) CASEMBC(0x1ef7) CASEMBC(0x1ef9)
regmbc('y'); regmbc('\375'); regmbc('\377');
REGMBC(0x177) REGMBC(0x1e8f) REGMBC(0x1e99)
REGMBC(0x1ef3) REGMBC(0x1ef7) REGMBC(0x1ef9)
return;
case 'z': CASEMBC(0x17a) CASEMBC(0x17c) CASEMBC(0x17e)
CASEMBC(0x1b6) CASEMBC(0x1e91) CASEMBC(0x1e95)
regmbc('z'); REGMBC(0x17a) REGMBC(0x17c)
REGMBC(0x17e) REGMBC(0x1b6) REGMBC(0x1e91)
REGMBC(0x1e95)
return;
}
#endif
}
regmbc(c);
}
/*
* Check for a collating element "[.a.]". "pp" points to the '['.
* Returns a character. Zero means that no item was recognized. Otherwise
* "pp" is advanced to after the item.
* Currently only single characters are recognized!
*/
static int
get_coll_element(pp)
char_u **pp;
{
int c;
int l = 1;
char_u *p = *pp;
if (p[1] == '.')
{
#ifdef FEAT_MBYTE
if (has_mbyte)
l = (*mb_ptr2len)(p + 2);
#endif
if (p[l + 2] == '.' && p[l + 3] == ']')
{
#ifdef FEAT_MBYTE
if (has_mbyte)
c = mb_ptr2char(p + 2);
else
#endif
c = p[2];
*pp += l + 4;
return c;
}
}
return 0;
}
/*
* Skip over a "[]" range.
* "p" must point to the character after the '['.
* The returned pointer is on the matching ']', or the terminating NUL.
*/
static char_u *
skip_anyof(p)
char_u *p;
{
int cpo_lit; /* 'cpoptions' contains 'l' flag */
int cpo_bsl; /* 'cpoptions' contains '\' flag */
#ifdef FEAT_MBYTE
int l;
#endif
cpo_lit = vim_strchr(p_cpo, CPO_LITERAL) != NULL;
cpo_bsl = vim_strchr(p_cpo, CPO_BACKSL) != NULL;
if (*p == '^') /* Complement of range. */
++p;
if (*p == ']' || *p == '-')
++p;
while (*p != NUL && *p != ']')
{
#ifdef FEAT_MBYTE
if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
p += l;
else
#endif
if (*p == '-')
{
++p;
if (*p != ']' && *p != NUL)
mb_ptr_adv(p);
}
else if (*p == '\\'
&& !cpo_bsl
&& (vim_strchr(REGEXP_INRANGE, p[1]) != NULL
|| (!cpo_lit && vim_strchr(REGEXP_ABBR, p[1]) != NULL)))
p += 2;
else if (*p == '[')
{
if (get_char_class(&p) == CLASS_NONE
&& get_equi_class(&p) == 0
&& get_coll_element(&p) == 0)
++p; /* It was not a class name */
}
else
++p;
}
return p;
}
/*
* Skip past regular expression.
* Stop at end of "startp" or where "dirc" is found ('/', '?', etc).
* Take care of characters with a backslash in front of it.
* Skip strings inside [ and ].
* When "newp" is not NULL and "dirc" is '?', make an allocated copy of the
* expression and change "\?" to "?". If "*newp" is not NULL the expression
* is changed in-place.
*/
char_u *
skip_regexp(startp, dirc, magic, newp)
char_u *startp;
int dirc;
int magic;
char_u **newp;
{
int mymagic;
char_u *p = startp;
if (magic)
mymagic = MAGIC_ON;
else
mymagic = MAGIC_OFF;
for (; p[0] != NUL; mb_ptr_adv(p))
{
if (p[0] == dirc) /* found end of regexp */
break;
if ((p[0] == '[' && mymagic >= MAGIC_ON)
|| (p[0] == '\\' && p[1] == '[' && mymagic <= MAGIC_OFF))
{
p = skip_anyof(p + 1);
if (p[0] == NUL)
break;
}
else if (p[0] == '\\' && p[1] != NUL)
{
if (dirc == '?' && newp != NULL && p[1] == '?')
{
/* change "\?" to "?", make a copy first. */
if (*newp == NULL)
{
*newp = vim_strsave(startp);
if (*newp != NULL)
p = *newp + (p - startp);
}
if (*newp != NULL)
STRMOVE(p, p + 1);
else
++p;
}
else
++p; /* skip next character */
if (*p == 'v')
mymagic = MAGIC_ALL;
else if (*p == 'V')
mymagic = MAGIC_NONE;
}
}
return p;
}
/*
* vim_regcomp() - compile a regular expression into internal code
* Returns the program in allocated space. Returns NULL for an error.
*
* We can't allocate space until we know how big the compiled form will be,
* but we can't compile it (and thus know how big it is) until we've got a
* place to put the code. So we cheat: we compile it twice, once with code
* generation turned off and size counting turned on, and once "for real".
* This also means that we don't allocate space until we are sure that the
* thing really will compile successfully, and we never have to move the
* code and thus invalidate pointers into it. (Note that it has to be in
* one piece because vim_free() must be able to free it all.)
*
* Whether upper/lower case is to be ignored is decided when executing the
* program, it does not matter here.
*
* Beware that the optimization-preparation code in here knows about some
* of the structure of the compiled regexp.
* "re_flags": RE_MAGIC and/or RE_STRING.
*/
regprog_T *
vim_regcomp(expr, re_flags)
char_u *expr;
int re_flags;
{
regprog_T *r;
char_u *scan;
char_u *longest;
int len;
int flags;
if (expr == NULL)
EMSG_RET_NULL(_(e_null));
init_class_tab();
/*
* First pass: determine size, legality.
*/
regcomp_start(expr, re_flags);
regcode = JUST_CALC_SIZE;
regc(REGMAGIC);
if (reg(REG_NOPAREN, &flags) == NULL)
return NULL;
/* Small enough for pointer-storage convention? */
#ifdef SMALL_MALLOC /* 16 bit storage allocation */
if (regsize >= 65536L - 256L)
EMSG_RET_NULL(_("E339: Pattern too long"));
#endif
/* Allocate space. */
r = (regprog_T *)lalloc(sizeof(regprog_T) + regsize, TRUE);
if (r == NULL)
return NULL;
/*
* Second pass: emit code.
*/
regcomp_start(expr, re_flags);
regcode = r->program;
regc(REGMAGIC);
if (reg(REG_NOPAREN, &flags) == NULL || reg_toolong)
{
vim_free(r);
if (reg_toolong)
EMSG_RET_NULL(_("E339: Pattern too long"));
return NULL;
}
/* Dig out information for optimizations. */
r->regstart = NUL; /* Worst-case defaults. */
r->reganch = 0;
r->regmust = NULL;
r->regmlen = 0;
r->regflags = regflags;
if (flags & HASNL)
r->regflags |= RF_HASNL;
if (flags & HASLOOKBH)
r->regflags |= RF_LOOKBH;
#ifdef FEAT_SYN_HL
/* Remember whether this pattern has any \z specials in it. */
r->reghasz = re_has_z;
#endif
scan = r->program + 1; /* First BRANCH. */
if (OP(regnext(scan)) == END) /* Only one top-level choice. */
{
scan = OPERAND(scan);
/* Starting-point info. */
if (OP(scan) == BOL || OP(scan) == RE_BOF)
{
r->reganch++;
scan = regnext(scan);
}
if (OP(scan) == EXACTLY)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
r->regstart = (*mb_ptr2char)(OPERAND(scan));
else
#endif
r->regstart = *OPERAND(scan);
}
else if ((OP(scan) == BOW
|| OP(scan) == EOW
|| OP(scan) == NOTHING
|| OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
|| OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE)
&& OP(regnext(scan)) == EXACTLY)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
r->regstart = (*mb_ptr2char)(OPERAND(regnext(scan)));
else
#endif
r->regstart = *OPERAND(regnext(scan));
}
/*
* If there's something expensive in the r.e., find the longest
* literal string that must appear and make it the regmust. Resolve
* ties in favor of later strings, since the regstart check works
* with the beginning of the r.e. and avoiding duplication
* strengthens checking. Not a strong reason, but sufficient in the
* absence of others.
*/
/*
* When the r.e. starts with BOW, it is faster to look for a regmust
* first. Used a lot for "#" and "*" commands. (Added by mool).
*/
if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
&& !(flags & HASNL))
{
longest = NULL;
len = 0;
for (; scan != NULL; scan = regnext(scan))
if (OP(scan) == EXACTLY && STRLEN(OPERAND(scan)) >= (size_t)len)
{
longest = OPERAND(scan);
len = (int)STRLEN(OPERAND(scan));
}
r->regmust = longest;
r->regmlen = len;
}
}
#ifdef DEBUG
regdump(expr, r);
#endif
return r;
}
/*
* Setup to parse the regexp. Used once to get the length and once to do it.
*/
static void
regcomp_start(expr, re_flags)
char_u *expr;
int re_flags; /* see vim_regcomp() */
{
initchr(expr);
if (re_flags & RE_MAGIC)
reg_magic = MAGIC_ON;
else
reg_magic = MAGIC_OFF;
reg_string = (re_flags & RE_STRING);
reg_strict = (re_flags & RE_STRICT);
num_complex_braces = 0;
regnpar = 1;
vim_memset(had_endbrace, 0, sizeof(had_endbrace));
#ifdef FEAT_SYN_HL
regnzpar = 1;
re_has_z = 0;
#endif
regsize = 0L;
reg_toolong = FALSE;
regflags = 0;
#if defined(FEAT_SYN_HL) || defined(PROTO)
had_eol = FALSE;
#endif
}
#if defined(FEAT_SYN_HL) || defined(PROTO)
/*
* Check if during the previous call to vim_regcomp the EOL item "$" has been
* found. This is messy, but it works fine.
*/
int
vim_regcomp_had_eol()
{
return had_eol;
}
#endif
/*
* reg - regular expression, i.e. main body or parenthesized thing
*
* Caller must absorb opening parenthesis.
*
* Combining parenthesis handling with the base level of regular expression
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
static char_u *
reg(paren, flagp)
int paren; /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
int *flagp;
{
char_u *ret;
char_u *br;
char_u *ender;
int parno = 0;
int flags;
*flagp = HASWIDTH; /* Tentatively. */
#ifdef FEAT_SYN_HL
if (paren == REG_ZPAREN)
{
/* Make a ZOPEN node. */
if (regnzpar >= NSUBEXP)
EMSG_RET_NULL(_("E50: Too many \\z("));
parno = regnzpar;
regnzpar++;
ret = regnode(ZOPEN + parno);
}
else
#endif
if (paren == REG_PAREN)
{
/* Make a MOPEN node. */
if (regnpar >= NSUBEXP)
EMSG_M_RET_NULL(_("E51: Too many %s("), reg_magic == MAGIC_ALL);
parno = regnpar;
++regnpar;
ret = regnode(MOPEN + parno);
}
else if (paren == REG_NPAREN)
{
/* Make a NOPEN node. */
ret = regnode(NOPEN);
}
else
ret = NULL;
/* Pick up the branches, linking them together. */
br = regbranch(&flags);
if (br == NULL)
return NULL;
if (ret != NULL)
regtail(ret, br); /* [MZ]OPEN -> first. */
else
ret = br;
/* If one of the branches can be zero-width, the whole thing can.
* If one of the branches has * at start or matches a line-break, the
* whole thing can. */
if (!(flags & HASWIDTH))
*flagp &= ~HASWIDTH;
*flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
while (peekchr() == Magic('|'))
{
skipchr();
br = regbranch(&flags);
if (br == NULL || reg_toolong)
return NULL;
regtail(ret, br); /* BRANCH -> BRANCH. */
if (!(flags & HASWIDTH))
*flagp &= ~HASWIDTH;
*flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
}
/* Make a closing node, and hook it on the end. */
ender = regnode(
#ifdef FEAT_SYN_HL
paren == REG_ZPAREN ? ZCLOSE + parno :
#endif
paren == REG_PAREN ? MCLOSE + parno :
paren == REG_NPAREN ? NCLOSE : END);
regtail(ret, ender);
/* Hook the tails of the branches to the closing node. */
for (br = ret; br != NULL; br = regnext(br))
regoptail(br, ender);
/* Check for proper termination. */
if (paren != REG_NOPAREN && getchr() != Magic(')'))
{
#ifdef FEAT_SYN_HL
if (paren == REG_ZPAREN)
EMSG_RET_NULL(_("E52: Unmatched \\z("));
else
#endif
if (paren == REG_NPAREN)
EMSG_M_RET_NULL(_("E53: Unmatched %s%%("), reg_magic == MAGIC_ALL);
else
EMSG_M_RET_NULL(_("E54: Unmatched %s("), reg_magic == MAGIC_ALL);
}
else if (paren == REG_NOPAREN && peekchr() != NUL)
{
if (curchr == Magic(')'))
EMSG_M_RET_NULL(_("E55: Unmatched %s)"), reg_magic == MAGIC_ALL);
else
EMSG_RET_NULL(_(e_trailing)); /* "Can't happen". */
/* NOTREACHED */
}
/*
* Here we set the flag allowing back references to this set of
* parentheses.
*/
if (paren == REG_PAREN)
had_endbrace[parno] = TRUE; /* have seen the close paren */
return ret;
}
/*
* Handle one alternative of an | operator.
* Implements the & operator.
*/
static char_u *
regbranch(flagp)
int *flagp;
{
char_u *ret;
char_u *chain = NULL;
char_u *latest;
int flags;
*flagp = WORST | HASNL; /* Tentatively. */
ret = regnode(BRANCH);
for (;;)
{
latest = regconcat(&flags);
if (latest == NULL)
return NULL;
/* If one of the branches has width, the whole thing has. If one of
* the branches anchors at start-of-line, the whole thing does.
* If one of the branches uses look-behind, the whole thing does. */
*flagp |= flags & (HASWIDTH | SPSTART | HASLOOKBH);
/* If one of the branches doesn't match a line-break, the whole thing
* doesn't. */
*flagp &= ~HASNL | (flags & HASNL);
if (chain != NULL)
regtail(chain, latest);
if (peekchr() != Magic('&'))
break;
skipchr();
regtail(latest, regnode(END)); /* operand ends */
if (reg_toolong)
break;
reginsert(MATCH, latest);
chain = latest;
}
return ret;
}
/*
* Handle one alternative of an | or & operator.
* Implements the concatenation operator.
*/
static char_u *
regconcat(flagp)
int *flagp;
{
char_u *first = NULL;
char_u *chain = NULL;
char_u *latest;
int flags;
int cont = TRUE;
*flagp = WORST; /* Tentatively. */
while (cont)
{
switch (peekchr())
{
case NUL:
case Magic('|'):
case Magic('&'):
case Magic(')'):
cont = FALSE;
break;
case Magic('Z'):
#ifdef FEAT_MBYTE
regflags |= RF_ICOMBINE;
#endif
skipchr_keepstart();
break;
case Magic('c'):
regflags |= RF_ICASE;
skipchr_keepstart();
break;
case Magic('C'):
regflags |= RF_NOICASE;
skipchr_keepstart();
break;
case Magic('v'):
reg_magic = MAGIC_ALL;
skipchr_keepstart();
curchr = -1;
break;
case Magic('m'):
reg_magic = MAGIC_ON;
skipchr_keepstart();
curchr = -1;
break;
case Magic('M'):
reg_magic = MAGIC_OFF;
skipchr_keepstart();
curchr = -1;
break;
case Magic('V'):
reg_magic = MAGIC_NONE;
skipchr_keepstart();
curchr = -1;
break;
default:
latest = regpiece(&flags);
if (latest == NULL || reg_toolong)
return NULL;
*flagp |= flags & (HASWIDTH | HASNL | HASLOOKBH);
if (chain == NULL) /* First piece. */
*flagp |= flags & SPSTART;
else
regtail(chain, latest);
chain = latest;
if (first == NULL)
first = latest;
break;
}
}
if (first == NULL) /* Loop ran zero times. */
first = regnode(NOTHING);
return first;
}
/*
* regpiece - something followed by possible [*+=]
*
* Note that the branching code sequences used for = and the general cases
* of * and + are somewhat optimized: they use the same NOTHING node as
* both the endmarker for their branch list and the body of the last branch.
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*/
static char_u *
regpiece(flagp)
int *flagp;
{
char_u *ret;
int op;
char_u *next;
int flags;
long minval;
long maxval;
ret = regatom(&flags);
if (ret == NULL)
return NULL;
op = peekchr();
if (re_multi_type(op) == NOT_MULTI)
{
*flagp = flags;
return ret;
}
/* default flags */
*flagp = (WORST | SPSTART | (flags & (HASNL | HASLOOKBH)));
skipchr();
switch (op)
{
case Magic('*'):
if (flags & SIMPLE)
reginsert(STAR, ret);
else
{
/* Emit x* as (x&|), where & means "self". */
reginsert(BRANCH, ret); /* Either x */
regoptail(ret, regnode(BACK)); /* and loop */
regoptail(ret, ret); /* back */
regtail(ret, regnode(BRANCH)); /* or */
regtail(ret, regnode(NOTHING)); /* null. */
}
break;
case Magic('+'):
if (flags & SIMPLE)
reginsert(PLUS, ret);
else
{
/* Emit x+ as x(&|), where & means "self". */
next = regnode(BRANCH); /* Either */
regtail(ret, next);
regtail(regnode(BACK), ret); /* loop back */
regtail(next, regnode(BRANCH)); /* or */
regtail(ret, regnode(NOTHING)); /* null. */
}
*flagp = (WORST | HASWIDTH | (flags & (HASNL | HASLOOKBH)));
break;
case Magic('@'):
{
int lop = END;
switch (no_Magic(getchr()))
{
case '=': lop = MATCH; break; /* \@= */
case '!': lop = NOMATCH; break; /* \@! */
case '>': lop = SUBPAT; break; /* \@> */
case '<': switch (no_Magic(getchr()))
{
case '=': lop = BEHIND; break; /* \@<= */
case '!': lop = NOBEHIND; break; /* \@<! */
}
}
if (lop == END)
EMSG_M_RET_NULL(_("E59: invalid character after %s@"),
reg_magic == MAGIC_ALL);
/* Look behind must match with behind_pos. */
if (lop == BEHIND || lop == NOBEHIND)
{
regtail(ret, regnode(BHPOS));
*flagp |= HASLOOKBH;
}
regtail(ret, regnode(END)); /* operand ends */
reginsert(lop, ret);
break;
}
case Magic('?'):
case Magic('='):
/* Emit x= as (x|) */
reginsert(BRANCH, ret); /* Either x */
regtail(ret, regnode(BRANCH)); /* or */
next = regnode(NOTHING); /* null. */
regtail(ret, next);
regoptail(ret, next);
break;
case Magic('{'):
if (!read_limits(&minval, &maxval))
return NULL;
if (flags & SIMPLE)
{
reginsert(BRACE_SIMPLE, ret);
reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
}
else
{
if (num_complex_braces >= 10)
EMSG_M_RET_NULL(_("E60: Too many complex %s{...}s"),
reg_magic == MAGIC_ALL);
reginsert(BRACE_COMPLEX + num_complex_braces, ret);
regoptail(ret, regnode(BACK));
regoptail(ret, ret);
reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
++num_complex_braces;
}
if (minval > 0 && maxval > 0)
*flagp = (HASWIDTH | (flags & (HASNL | HASLOOKBH)));
break;
}
if (re_multi_type(peekchr()) != NOT_MULTI)
{
/* Can't have a multi follow a multi. */
if (peekchr() == Magic('*'))
sprintf((char *)IObuff, _("E61: Nested %s*"),
reg_magic >= MAGIC_ON ? "" : "\\");
else
sprintf((char *)IObuff, _("E62: Nested %s%c"),
reg_magic == MAGIC_ALL ? "" : "\\", no_Magic(peekchr()));
EMSG_RET_NULL(IObuff);
}
return ret;
}
/*
* regatom - the lowest level
*
* Optimization: gobbles an entire sequence of ordinary characters so that
* it can turn them into a single node, which is smaller to store and
* faster to run. Don't do this when one_exactly is set.
*/
static char_u *
regatom(flagp)
int *flagp;
{
char_u *ret;
int flags;
int cpo_lit; /* 'cpoptions' contains 'l' flag */
int cpo_bsl; /* 'cpoptions' contains '\' flag */
int c;
static char_u *classchars = (char_u *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
static int classcodes[] = {ANY, IDENT, SIDENT, KWORD, SKWORD,
FNAME, SFNAME, PRINT, SPRINT,
WHITE, NWHITE, DIGIT, NDIGIT,
HEX, NHEX, OCTAL, NOCTAL,
WORD, NWORD, HEAD, NHEAD,
ALPHA, NALPHA, LOWER, NLOWER,
UPPER, NUPPER
};
char_u *p;
int extra = 0;
*flagp = WORST; /* Tentatively. */
cpo_lit = vim_strchr(p_cpo, CPO_LITERAL) != NULL;
cpo_bsl = vim_strchr(p_cpo, CPO_BACKSL) != NULL;
c = getchr();
switch (c)
{
case Magic('^'):
ret = regnode(BOL);
break;
case Magic('$'):
ret = regnode(EOL);
#if defined(FEAT_SYN_HL) || defined(PROTO)
had_eol = TRUE;
#endif
break;
case Magic('<'):
ret = regnode(BOW);
break;
case Magic('>'):
ret = regnode(EOW);
break;
case Magic('_'):
c = no_Magic(getchr());
if (c == '^') /* "\_^" is start-of-line */
{
ret = regnode(BOL);
break;
}
if (c == '$') /* "\_$" is end-of-line */
{
ret = regnode(EOL);
#if defined(FEAT_SYN_HL) || defined(PROTO)
had_eol = TRUE;
#endif
break;
}
extra = ADD_NL;
*flagp |= HASNL;
/* "\_[" is character range plus newline */
if (c == '[')
goto collection;
/* "\_x" is character class plus newline */
/*FALLTHROUGH*/
/*
* Character classes.
*/
case Magic('.'):
case Magic('i'):
case Magic('I'):
case Magic('k'):
case Magic('K'):
case Magic('f'):
case Magic('F'):
case Magic('p'):
case Magic('P'):
case Magic('s'):
case Magic('S'):
case Magic('d'):
case Magic('D'):
case Magic('x'):
case Magic('X'):
case Magic('o'):
case Magic('O'):
case Magic('w'):
case Magic('W'):
case Magic('h'):
case Magic('H'):
case Magic('a'):
case Magic('A'):
case Magic('l'):
case Magic('L'):
case Magic('u'):
case Magic('U'):
p = vim_strchr(classchars, no_Magic(c));
if (p == NULL)
EMSG_RET_NULL(_("E63: invalid use of \\_"));
#ifdef FEAT_MBYTE
/* When '.' is followed by a composing char ignore the dot, so that
* the composing char is matched here. */
if (enc_utf8 && c == Magic('.') && utf_iscomposing(peekchr()))
{
c = getchr();
goto do_multibyte;
}
#endif
ret = regnode(classcodes[p - classchars] + extra);
*flagp |= HASWIDTH | SIMPLE;
break;
case Magic('n'):
if (reg_string)
{
/* In a string "\n" matches a newline character. */
ret = regnode(EXACTLY);
regc(NL);
regc(NUL);
*flagp |= HASWIDTH | SIMPLE;
}
else
{
/* In buffer text "\n" matches the end of a line. */
ret = regnode(NEWL);
*flagp |= HASWIDTH | HASNL;
}
break;
case Magic('('):
if (one_exactly)
EMSG_ONE_RET_NULL;
ret = reg(REG_PAREN, &flags);
if (ret == NULL)
return NULL;
*flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
break;
case NUL:
case Magic('|'):
case Magic('&'):
case Magic(')'):
if (one_exactly)
EMSG_ONE_RET_NULL;
EMSG_RET_NULL(_(e_internal)); /* Supposed to be caught earlier. */
/* NOTREACHED */
case Magic('='):
case Magic('?'):
case Magic('+'):
case Magic('@'):
case Magic('{'):
case Magic('*'):
c = no_Magic(c);
sprintf((char *)IObuff, _("E64: %s%c follows nothing"),
(c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL)
? "" : "\\", c);
EMSG_RET_NULL(IObuff);
/* NOTREACHED */
case Magic('~'): /* previous substitute pattern */
if (reg_prev_sub != NULL)
{
char_u *lp;
ret = regnode(EXACTLY);
lp = reg_prev_sub;
while (*lp != NUL)
regc(*lp++);
regc(NUL);
if (*reg_prev_sub != NUL)
{
*flagp |= HASWIDTH;
if ((lp - reg_prev_sub) == 1)
*flagp |= SIMPLE;
}
}
else
EMSG_RET_NULL(_(e_nopresub));
break;
case Magic('1'):
case Magic('2'):
case Magic('3'):
case Magic('4'):
case Magic('5'):
case Magic('6'):
case Magic('7'):
case Magic('8'):
case Magic('9'):
{
int refnum;
refnum = c - Magic('0');
/*
* Check if the back reference is legal. We must have seen the
* close brace.
* TODO: Should also check that we don't refer to something
* that is repeated (+*=): what instance of the repetition
* should we match?
*/
if (!had_endbrace[refnum])
{
/* Trick: check if "@<=" or "@<!" follows, in which case
* the \1 can appear before the referenced match. */
for (p = regparse; *p != NUL; ++p)
if (p[0] == '@' && p[1] == '<'
&& (p[2] == '!' || p[2] == '='))
break;
if (*p == NUL)
EMSG_RET_NULL(_("E65: Illegal back reference"));
}
ret = regnode(BACKREF + refnum);
}
break;
case Magic('z'):
{
c = no_Magic(getchr());
switch (c)
{
#ifdef FEAT_SYN_HL
case '(': if (reg_do_extmatch != REX_SET)
EMSG_RET_NULL(_("E66: \\z( not allowed here"));
if (one_exactly)
EMSG_ONE_RET_NULL;
ret = reg(REG_ZPAREN, &flags);
if (ret == NULL)
return NULL;
*flagp |= flags & (HASWIDTH|SPSTART|HASNL|HASLOOKBH);
re_has_z = REX_SET;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': if (reg_do_extmatch != REX_USE)
EMSG_RET_NULL(_("E67: \\z1 et al. not allowed here"));
ret = regnode(ZREF + c - '0');
re_has_z = REX_USE;
break;
#endif
case 's': ret = regnode(MOPEN + 0);
break;
case 'e': ret = regnode(MCLOSE + 0);
break;
default: EMSG_RET_NULL(_("E68: Invalid character after \\z"));
}
}
break;
case Magic('%'):
{
c = no_Magic(getchr());
switch (c)
{
/* () without a back reference */
case '(':
if (one_exactly)
EMSG_ONE_RET_NULL;
ret = reg(REG_NPAREN, &flags);
if (ret == NULL)
return NULL;
*flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
break;
/* Catch \%^ and \%$ regardless of where they appear in the
* pattern -- regardless of whether or not it makes sense. */
case '^':
ret = regnode(RE_BOF);
break;
case '$':
ret = regnode(RE_EOF);
break;
case '#':
ret = regnode(CURSOR);
break;
case 'V':
ret = regnode(RE_VISUAL);
break;
/* \%[abc]: Emit as a list of branches, all ending at the last
* branch which matches nothing. */
case '[':
if (one_exactly) /* doesn't nest */
EMSG_ONE_RET_NULL;
{
char_u *lastbranch;
char_u *lastnode = NULL;
char_u *br;
ret = NULL;
while ((c = getchr()) != ']')
{
if (c == NUL)
EMSG_M_RET_NULL(_("E69: Missing ] after %s%%["),
reg_magic == MAGIC_ALL);
br = regnode(BRANCH);
if (ret == NULL)
ret = br;
else
regtail(lastnode, br);
ungetchr();
one_exactly = TRUE;
lastnode = regatom(flagp);
one_exactly = FALSE;
if (lastnode == NULL)
return NULL;
}
if (ret == NULL)
EMSG_M_RET_NULL(_("E70: Empty %s%%[]"),
reg_magic == MAGIC_ALL);
lastbranch = regnode(BRANCH);
br = regnode(NOTHING);
if (ret != JUST_CALC_SIZE)
{
regtail(lastnode, br);
regtail(lastbranch, br);
/* connect all branches to the NOTHING
* branch at the end */
for (br = ret; br != lastnode; )
{
if (OP(br) == BRANCH)
{
regtail(br, lastbranch);
br = OPERAND(br);
}
else
br = regnext(br);
}
}
*flagp &= ~(HASWIDTH | SIMPLE);
break;
}
case 'd': /* %d123 decimal */
case 'o': /* %o123 octal */
case 'x': /* %xab hex 2 */
case 'u': /* %uabcd hex 4 */
case 'U': /* %U1234abcd hex 8 */
{
int i;
switch (c)
{
case 'd': i = getdecchrs(); break;
case 'o': i = getoctchrs(); break;
case 'x': i = gethexchrs(2); break;
case 'u': i = gethexchrs(4); break;
case 'U': i = gethexchrs(8); break;
default: i = -1; break;
}
if (i < 0)
EMSG_M_RET_NULL(
_("E678: Invalid character after %s%%[dxouU]"),
reg_magic == MAGIC_ALL);
#ifdef FEAT_MBYTE
if (use_multibytecode(i))
ret = regnode(MULTIBYTECODE);
else
#endif
ret = regnode(EXACTLY);
if (i == 0)
regc(0x0a);
else
#ifdef FEAT_MBYTE
regmbc(i);
#else
regc(i);
#endif
regc(NUL);
*flagp |= HASWIDTH;
break;
}
default:
if (VIM_ISDIGIT(c) || c == '<' || c == '>'
|| c == '\'')
{
long_u n = 0;
int cmp;
cmp = c;
if (cmp == '<' || cmp == '>')
c = getchr();
while (VIM_ISDIGIT(c))
{
n = n * 10 + (c - '0');
c = getchr();
}
if (c == '\'' && n == 0)
{
/* "\%'m", "\%<'m" and "\%>'m": Mark */
c = getchr();
ret = regnode(RE_MARK);
if (ret == JUST_CALC_SIZE)
regsize += 2;
else
{
*regcode++ = c;
*regcode++ = cmp;
}
break;
}
else if (c == 'l' || c == 'c' || c == 'v')
{
if (c == 'l')
ret = regnode(RE_LNUM);
else if (c == 'c')
ret = regnode(RE_COL);
else
ret = regnode(RE_VCOL);
if (ret == JUST_CALC_SIZE)
regsize += 5;
else
{
/* put the number and the optional
* comparator after the opcode */
regcode = re_put_long(regcode, n);
*regcode++ = cmp;
}
break;
}
}
EMSG_M_RET_NULL(_("E71: Invalid character after %s%%"),
reg_magic == MAGIC_ALL);
}
}
break;
case Magic('['):
collection:
{
char_u *lp;
/*
* If there is no matching ']', we assume the '[' is a normal
* character. This makes 'incsearch' and ":help [" work.
*/
lp = skip_anyof(regparse);
if (*lp == ']') /* there is a matching ']' */
{
int startc = -1; /* > 0 when next '-' is a range */
int endc;
/*
* In a character class, different parsing rules apply.
* Not even \ is special anymore, nothing is.
*/
if (*regparse == '^') /* Complement of range. */
{
ret = regnode(ANYBUT + extra);
regparse++;
}
else
ret = regnode(ANYOF + extra);
/* At the start ']' and '-' mean the literal character. */
if (*regparse == ']' || *regparse == '-')
{
startc = *regparse;
regc(*regparse++);
}
while (*regparse != NUL && *regparse != ']')
{
if (*regparse == '-')
{
++regparse;
/* The '-' is not used for a range at the end and
* after or before a '\n'. */
if (*regparse == ']' || *regparse == NUL
|| startc == -1
|| (regparse[0] == '\\' && regparse[1] == 'n'))
{
regc('-');
startc = '-'; /* [--x] is a range */
}
else
{
/* Also accept "a-[.z.]" */
endc = 0;
if (*regparse == '[')
endc = get_coll_element(®parse);
if (endc == 0)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
endc = mb_ptr2char_adv(®parse);
else
#endif
endc = *regparse++;
}
/* Handle \o40, \x20 and \u20AC style sequences */
if (endc == '\\' && !cpo_lit && !cpo_bsl)
endc = coll_get_char();
if (startc > endc)
EMSG_RET_NULL(_(e_invrange));
#ifdef FEAT_MBYTE
if (has_mbyte && ((*mb_char2len)(startc) > 1
|| (*mb_char2len)(endc) > 1))
{
/* Limit to a range of 256 chars */
if (endc > startc + 256)
EMSG_RET_NULL(_(e_invrange));
while (++startc <= endc)
regmbc(startc);
}
else
#endif
{
#ifdef EBCDIC
int alpha_only = FALSE;
/* for alphabetical range skip the gaps
* 'i'-'j', 'r'-'s', 'I'-'J' and 'R'-'S'. */
if (isalpha(startc) && isalpha(endc))
alpha_only = TRUE;
#endif
while (++startc <= endc)
#ifdef EBCDIC
if (!alpha_only || isalpha(startc))
#endif
regc(startc);
}
startc = -1;
}
}
/*
* Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
* accepts "\t", "\e", etc., but only when the 'l' flag in
* 'cpoptions' is not included.
* Posix doesn't recognize backslash at all.
*/
else if (*regparse == '\\'
&& !cpo_bsl
&& (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
|| (!cpo_lit
&& vim_strchr(REGEXP_ABBR,
regparse[1]) != NULL)))
{
regparse++;
if (*regparse == 'n')
{
/* '\n' in range: also match NL */
if (ret != JUST_CALC_SIZE)
{
if (*ret == ANYBUT)
*ret = ANYBUT + ADD_NL;
else if (*ret == ANYOF)
*ret = ANYOF + ADD_NL;
/* else: must have had a \n already */
}
*flagp |= HASNL;
regparse++;
startc = -1;
}
else if (*regparse == 'd'
|| *regparse == 'o'
|| *regparse == 'x'
|| *regparse == 'u'
|| *regparse == 'U')
{
startc = coll_get_char();
if (startc == 0)
regc(0x0a);
else
#ifdef FEAT_MBYTE
regmbc(startc);
#else
regc(startc);
#endif
}
else
{
startc = backslash_trans(*regparse++);
regc(startc);
}
}
else if (*regparse == '[')
{
int c_class;
int cu;
c_class = get_char_class(®parse);
startc = -1;
/* Characters assumed to be 8 bits! */
switch (c_class)
{
case CLASS_NONE:
c_class = get_equi_class(®parse);
if (c_class != 0)
{
/* produce equivalence class */
reg_equi_class(c_class);
}
else if ((c_class =
get_coll_element(®parse)) != 0)
{
/* produce a collating element */
regmbc(c_class);
}
else
{
/* literal '[', allow [[-x] as a range */
startc = *regparse++;
regc(startc);
}
break;
case CLASS_ALNUM:
for (cu = 1; cu <= 255; cu++)
if (isalnum(cu))
regc(cu);
break;
case CLASS_ALPHA:
for (cu = 1; cu <= 255; cu++)
if (isalpha(cu))
regc(cu);
break;
case CLASS_BLANK:
regc(' ');
regc('\t');
break;
case CLASS_CNTRL:
for (cu = 1; cu <= 255; cu++)
if (iscntrl(cu))
regc(cu);
break;
case CLASS_DIGIT:
for (cu = 1; cu <= 255; cu++)
if (VIM_ISDIGIT(cu))
regc(cu);
break;
case CLASS_GRAPH:
for (cu = 1; cu <= 255; cu++)
if (isgraph(cu))
regc(cu);
break;
case CLASS_LOWER:
for (cu = 1; cu <= 255; cu++)
if (MB_ISLOWER(cu))
regc(cu);
break;
case CLASS_PRINT:
for (cu = 1; cu <= 255; cu++)
if (vim_isprintc(cu))
regc(cu);
break;
case CLASS_PUNCT:
for (cu = 1; cu <= 255; cu++)
if (ispunct(cu))
regc(cu);
break;
case CLASS_SPACE:
for (cu = 9; cu <= 13; cu++)
regc(cu);
regc(' ');
break;
case CLASS_UPPER:
for (cu = 1; cu <= 255; cu++)
if (MB_ISUPPER(cu))
regc(cu);
break;
case CLASS_XDIGIT:
for (cu = 1; cu <= 255; cu++)
if (vim_isxdigit(cu))
regc(cu);
break;
case CLASS_TAB:
regc('\t');
break;
case CLASS_RETURN:
regc('\r');
break;
case CLASS_BACKSPACE:
regc('\b');
break;
case CLASS_ESCAPE:
regc('\033');
break;
}
}
else
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int len;
/* produce a multibyte character, including any
* following composing characters */
startc = mb_ptr2char(regparse);
len = (*mb_ptr2len)(regparse);
if (enc_utf8 && utf_char2len(startc) != len)
startc = -1; /* composing chars */
while (--len >= 0)
regc(*regparse++);
}
else
#endif
{
startc = *regparse++;
regc(startc);
}
}
}
regc(NUL);
prevchr_len = 1; /* last char was the ']' */
if (*regparse != ']')
EMSG_RET_NULL(_(e_toomsbra)); /* Cannot happen? */
skipchr(); /* let's be friends with the lexer again */
*flagp |= HASWIDTH | SIMPLE;
break;
}
else if (reg_strict)
EMSG_M_RET_NULL(_("E769: Missing ] after %s["),
reg_magic > MAGIC_OFF);
}
/* FALLTHROUGH */
default:
{
int len;
#ifdef FEAT_MBYTE
/* A multi-byte character is handled as a separate atom if it's
* before a multi and when it's a composing char. */
if (use_multibytecode(c))
{
do_multibyte:
ret = regnode(MULTIBYTECODE);
regmbc(c);
*flagp |= HASWIDTH | SIMPLE;
break;
}
#endif
ret = regnode(EXACTLY);
/*
* Append characters as long as:
* - there is no following multi, we then need the character in
* front of it as a single character operand
* - not running into a Magic character
* - "one_exactly" is not set
* But always emit at least one character. Might be a Multi,
* e.g., a "[" without matching "]".
*/
for (len = 0; c != NUL && (len == 0
|| (re_multi_type(peekchr()) == NOT_MULTI
&& !one_exactly
&& !is_Magic(c))); ++len)
{
c = no_Magic(c);
#ifdef FEAT_MBYTE
if (has_mbyte)
{
regmbc(c);
if (enc_utf8)
{
int l;
/* Need to get composing character too. */
for (;;)
{
l = utf_ptr2len(regparse);
if (!UTF_COMPOSINGLIKE(regparse, regparse + l))
break;
regmbc(utf_ptr2char(regparse));
skipchr();
}
}
}
else
#endif
regc(c);
c = getchr();
}
ungetchr();
regc(NUL);
*flagp |= HASWIDTH;
if (len == 1)
*flagp |= SIMPLE;
}
break;
}
return ret;
}
#ifdef FEAT_MBYTE
/*
* Return TRUE if MULTIBYTECODE should be used instead of EXACTLY for
* character "c".
*/
static int
use_multibytecode(c)
int c;
{
return has_mbyte && (*mb_char2len)(c) > 1
&& (re_multi_type(peekchr()) != NOT_MULTI
|| (enc_utf8 && utf_iscomposing(c)));
}
#endif
/*
* emit a node
* Return pointer to generated code.
*/
static char_u *
regnode(op)
int op;
{
char_u *ret;
ret = regcode;
if (ret == JUST_CALC_SIZE)
regsize += 3;
else
{
*regcode++ = op;
*regcode++ = NUL; /* Null "next" pointer. */
*regcode++ = NUL;
}
return ret;
}
/*
* Emit (if appropriate) a byte of code
*/
static void
regc(b)
int b;
{
if (regcode == JUST_CALC_SIZE)
regsize++;
else
*regcode++ = b;
}
#ifdef FEAT_MBYTE
/*
* Emit (if appropriate) a multi-byte character of code
*/
static void
regmbc(c)
int c;
{
if (!has_mbyte && c > 0xff)
return;
if (regcode == JUST_CALC_SIZE)
regsize += (*mb_char2len)(c);
else
regcode += (*mb_char2bytes)(c, regcode);
}
#endif
/*
* reginsert - insert an operator in front of already-emitted operand
*
* Means relocating the operand.
*/
static void
reginsert(op, opnd)
int op;
char_u *opnd;
{
char_u *src;
char_u *dst;
char_u *place;
if (regcode == JUST_CALC_SIZE)
{
regsize += 3;
return;
}
src = regcode;
regcode += 3;
dst = regcode;
while (src > opnd)
*--dst = *--src;
place = opnd; /* Op node, where operand used to be. */
*place++ = op;
*place++ = NUL;
*place = NUL;
}
/*
* reginsert_limits - insert an operator in front of already-emitted operand.
* The operator has the given limit values as operands. Also set next pointer.
*
* Means relocating the operand.
*/
static void
reginsert_limits(op, minval, maxval, opnd)
int op;
long minval;
long maxval;
char_u *opnd;
{
char_u *src;
char_u *dst;
char_u *place;
if (regcode == JUST_CALC_SIZE)
{
regsize += 11;
return;
}
src = regcode;
regcode += 11;
dst = regcode;
while (src > opnd)
*--dst = *--src;
place = opnd; /* Op node, where operand used to be. */
*place++ = op;
*place++ = NUL;
*place++ = NUL;
place = re_put_long(place, (long_u)minval);
place = re_put_long(place, (long_u)maxval);
regtail(opnd, place);
}
/*
* Write a long as four bytes at "p" and return pointer to the next char.
*/
static char_u *
re_put_long(p, val)
char_u *p;
long_u val;
{
*p++ = (char_u) ((val >> 24) & 0377);
*p++ = (char_u) ((val >> 16) & 0377);
*p++ = (char_u) ((val >> 8) & 0377);
*p++ = (char_u) (val & 0377);
return p;
}
/*
* regtail - set the next-pointer at the end of a node chain
*/
static void
regtail(p, val)
char_u *p;
char_u *val;
{
char_u *scan;
char_u *temp;
int offset;
if (p == JUST_CALC_SIZE)
return;
/* Find last node. */
scan = p;
for (;;)
{
temp = regnext(scan);
if (temp == NULL)
break;
scan = temp;
}
if (OP(scan) == BACK)
offset = (int)(scan - val);
else
offset = (int)(val - scan);
/* When the offset uses more than 16 bits it can no longer fit in the two
* bytes available. Use a global flag to avoid having to check return
* values in too many places. */
if (offset > 0xffff)
reg_toolong = TRUE;
else
{
*(scan + 1) = (char_u) (((unsigned)offset >> 8) & 0377);
*(scan + 2) = (char_u) (offset & 0377);
}
}
/*
* regoptail - regtail on item after a BRANCH; nop if none
*/
static void
regoptail(p, val)
char_u *p;
char_u *val;
{
/* When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless" */
if (p == NULL || p == JUST_CALC_SIZE
|| (OP(p) != BRANCH
&& (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9)))
return;
regtail(OPERAND(p), val);
}
/*
* getchr() - get the next character from the pattern. We know about
* magic and such, so therefore we need a lexical analyzer.
*/
/* static int curchr; */
static int prevprevchr;
static int prevchr;
static int nextchr; /* used for ungetchr() */
/*
* Note: prevchr is sometimes -1 when we are not at the start,
* eg in /[ ^I]^ the pattern was never found even if it existed, because ^ was
* taken to be magic -- webb
*/
static int at_start; /* True when on the first character */
static int prev_at_start; /* True when on the second character */
static void
initchr(str)
char_u *str;
{
regparse = str;
prevchr_len = 0;
curchr = prevprevchr = prevchr = nextchr = -1;
at_start = TRUE;
prev_at_start = FALSE;
}
static int
peekchr()
{
static int after_slash = FALSE;
if (curchr == -1)
{
switch (curchr = regparse[0])
{
case '.':
case '[':
case '~':
/* magic when 'magic' is on */
if (reg_magic >= MAGIC_ON)
curchr = Magic(curchr);
break;
case '(':
case ')':
case '{':
case '%':
case '+':
case '=':
case '?':
case '@':
case '!':
case '&':
case '|':
case '<':
case '>':
case '#': /* future ext. */
case '"': /* future ext. */
case '\'': /* future ext. */
case ',': /* future ext. */
case '-': /* future ext. */
case ':': /* future ext. */
case ';': /* future ext. */
case '`': /* future ext. */
case '/': /* Can't be used in / command */
/* magic only after "\v" */
if (reg_magic == MAGIC_ALL)
curchr = Magic(curchr);
break;
case '*':
/* * is not magic as the very first character, eg "?*ptr", when
* after '^', eg "/^*ptr" and when after "\(", "\|", "\&". But
* "\(\*" is not magic, thus must be magic if "after_slash" */
if (reg_magic >= MAGIC_ON
&& !at_start
&& !(prev_at_start && prevchr == Magic('^'))
&& (after_slash
|| (prevchr != Magic('(')
&& prevchr != Magic('&')
&& prevchr != Magic('|'))))
curchr = Magic('*');
break;
case '^':
/* '^' is only magic as the very first character and if it's after
* "\(", "\|", "\&' or "\n" */
if (reg_magic >= MAGIC_OFF
&& (at_start
|| reg_magic == MAGIC_ALL
|| prevchr == Magic('(')
|| prevchr == Magic('|')
|| prevchr == Magic('&')
|| prevchr == Magic('n')
|| (no_Magic(prevchr) == '('
&& prevprevchr == Magic('%'))))
{
curchr = Magic('^');
at_start = TRUE;
prev_at_start = FALSE;
}
break;
case '$':
/* '$' is only magic as the very last char and if it's in front of
* either "\|", "\)", "\&", or "\n" */
if (reg_magic >= MAGIC_OFF)
{
char_u *p = regparse + 1;
/* ignore \c \C \m and \M after '$' */
while (p[0] == '\\' && (p[1] == 'c' || p[1] == 'C'
|| p[1] == 'm' || p[1] == 'M' || p[1] == 'Z'))
p += 2;
if (p[0] == NUL
|| (p[0] == '\\'
&& (p[1] == '|' || p[1] == '&' || p[1] == ')'
|| p[1] == 'n'))
|| reg_magic == MAGIC_ALL)
curchr = Magic('$');
}
break;
case '\\':
{
int c = regparse[1];
if (c == NUL)
curchr = '\\'; /* trailing '\' */
else if (
#ifdef EBCDIC
vim_strchr(META, c)
#else
c <= '~' && META_flags[c]
#endif
)
{
/*
* META contains everything that may be magic sometimes,
* except ^ and $ ("\^" and "\$" are only magic after
* "\v"). We now fetch the next character and toggle its
* magicness. Therefore, \ is so meta-magic that it is
* not in META.
*/
curchr = -1;
prev_at_start = at_start;
at_start = FALSE; /* be able to say "/\*ptr" */
++regparse;
++after_slash;
peekchr();
--regparse;
--after_slash;
curchr = toggle_Magic(curchr);
}
else if (vim_strchr(REGEXP_ABBR, c))
{
/*
* Handle abbreviations, like "\t" for TAB -- webb
*/
curchr = backslash_trans(c);
}
else if (reg_magic == MAGIC_NONE && (c == '$' || c == '^'))
curchr = toggle_Magic(c);
else
{
/*
* Next character can never be (made) magic?
* Then backslashing it won't do anything.
*/
#ifdef FEAT_MBYTE
if (has_mbyte)
curchr = (*mb_ptr2char)(regparse + 1);
else
#endif
curchr = c;
}
break;
}
#ifdef FEAT_MBYTE
default:
if (has_mbyte)
curchr = (*mb_ptr2char)(regparse);
#endif
}
}
return curchr;
}
/*
* Eat one lexed character. Do this in a way that we can undo it.
*/
static void
skipchr()
{
/* peekchr() eats a backslash, do the same here */
if (*regparse == '\\')
prevchr_len = 1;
else
prevchr_len = 0;
if (regparse[prevchr_len] != NUL)
{
#ifdef FEAT_MBYTE
if (enc_utf8)
/* exclude composing chars that mb_ptr2len does include */
prevchr_len += utf_ptr2len(regparse + prevchr_len);
else if (has_mbyte)
prevchr_len += (*mb_ptr2len)(regparse + prevchr_len);
else
#endif
++prevchr_len;
}
regparse += prevchr_len;
prev_at_start = at_start;
at_start = FALSE;
prevprevchr = prevchr;
prevchr = curchr;
curchr = nextchr; /* use previously unget char, or -1 */
nextchr = -1;
}
/*
* Skip a character while keeping the value of prev_at_start for at_start.
* prevchr and prevprevchr are also kept.
*/
static void
skipchr_keepstart()
{
int as = prev_at_start;
int pr = prevchr;
int prpr = prevprevchr;
skipchr();
at_start = as;
prevchr = pr;
prevprevchr = prpr;
}
static int
getchr()
{
int chr = peekchr();
skipchr();
return chr;
}
/*
* put character back. Works only once!
*/
static void
ungetchr()
{
nextchr = curchr;
curchr = prevchr;
prevchr = prevprevchr;
at_start = prev_at_start;
prev_at_start = FALSE;
/* Backup regparse, so that it's at the same position as before the
* getchr(). */
regparse -= prevchr_len;
}
/*
* Get and return the value of the hex string at the current position.
* Return -1 if there is no valid hex number.
* The position is updated:
* blahblah\%x20asdf
* before-^ ^-after
* The parameter controls the maximum number of input characters. This will be
* 2 when reading a \%x20 sequence and 4 when reading a \%u20AC sequence.
*/
static int
gethexchrs(maxinputlen)
int maxinputlen;
{
int nr = 0;
int c;
int i;
for (i = 0; i < maxinputlen; ++i)
{
c = regparse[0];
if (!vim_isxdigit(c))
break;
nr <<= 4;
nr |= hex2nr(c);
++regparse;
}
if (i == 0)
return -1;
return nr;
}
/*
* get and return the value of the decimal string immediately after the
* current position. Return -1 for invalid. Consumes all digits.
*/
static int
getdecchrs()
{
int nr = 0;
int c;
int i;
for (i = 0; ; ++i)
{
c = regparse[0];
if (c < '0' || c > '9')
break;
nr *= 10;
nr += c - '0';
++regparse;
}
if (i == 0)
return -1;
return nr;
}
/*
* get and return the value of the octal string immediately after the current
* position. Return -1 for invalid, or 0-255 for valid. Smart enough to handle
* numbers > 377 correctly (for example, 400 is treated as 40) and doesn't
* treat 8 or 9 as recognised characters. Position is updated:
* blahblah\%o210asdf
* before-^ ^-after
*/
static int
getoctchrs()
{
int nr = 0;
int c;
int i;
for (i = 0; i < 3 && nr < 040; ++i)
{
c = regparse[0];
if (c < '0' || c > '7')
break;
nr <<= 3;
nr |= hex2nr(c);
++regparse;
}
if (i == 0)
return -1;
return nr;
}
/*
* Get a number after a backslash that is inside [].
* When nothing is recognized return a backslash.
*/
static int
coll_get_char()
{
int nr = -1;
switch (*regparse++)
{
case 'd': nr = getdecchrs(); break;
case 'o': nr = getoctchrs(); break;
case 'x': nr = gethexchrs(2); break;
case 'u': nr = gethexchrs(4); break;
case 'U': nr = gethexchrs(8); break;
}
if (nr < 0)
{
/* If getting the number fails be backwards compatible: the character
* is a backslash. */
--regparse;
nr = '\\';
}
return nr;
}
/*
* read_limits - Read two integers to be taken as a minimum and maximum.
* If the first character is '-', then the range is reversed.
* Should end with 'end'. If minval is missing, zero is default, if maxval is
* missing, a very big number is the default.
*/
static int
read_limits(minval, maxval)
long *minval;
long *maxval;
{
int reverse = FALSE;
char_u *first_char;
long tmp;
if (*regparse == '-')
{
/* Starts with '-', so reverse the range later */
regparse++;
reverse = TRUE;
}
first_char = regparse;
*minval = getdigits(®parse);
if (*regparse == ',') /* There is a comma */
{
if (vim_isdigit(*++regparse))
*maxval = getdigits(®parse);
else
*maxval = MAX_LIMIT;
}
else if (VIM_ISDIGIT(*first_char))
*maxval = *minval; /* It was \{n} or \{-n} */
else
*maxval = MAX_LIMIT; /* It was \{} or \{-} */
if (*regparse == '\\')
regparse++; /* Allow either \{...} or \{...\} */
if (*regparse != '}')
{
sprintf((char *)IObuff, _("E554: Syntax error in %s{...}"),
reg_magic == MAGIC_ALL ? "" : "\\");
EMSG_RET_FAIL(IObuff);
}
/*
* Reverse the range if there was a '-', or make sure it is in the right
* order otherwise.
*/
if ((!reverse && *minval > *maxval) || (reverse && *minval < *maxval))
{
tmp = *minval;
*minval = *maxval;
*maxval = tmp;
}
skipchr(); /* let's be friends with the lexer again */
return OK;
}
/*
* vim_regexec and friends
*/
/*
* Global work variables for vim_regexec().
*/
/* The current match-position is remembered with these variables: */
static linenr_T reglnum; /* line number, relative to first line */
static char_u *regline; /* start of current line */
static char_u *reginput; /* current input, points into "regline" */
static int need_clear_subexpr; /* subexpressions still need to be
* cleared */
#ifdef FEAT_SYN_HL
static int need_clear_zsubexpr = FALSE; /* extmatch subexpressions
* still need to be cleared */
#endif
/*
* Structure used to save the current input state, when it needs to be
* restored after trying a match. Used by reg_save() and reg_restore().
* Also stores the length of "backpos".
*/
typedef struct
{
union
{
char_u *ptr; /* reginput pointer, for single-line regexp */
lpos_T pos; /* reginput pos, for multi-line regexp */
} rs_u;
int rs_len;
} regsave_T;
/* struct to save start/end pointer/position in for \(\) */
typedef struct
{
union
{
char_u *ptr;
lpos_T pos;
} se_u;
} save_se_T;
/* used for BEHIND and NOBEHIND matching */
typedef struct regbehind_S
{
regsave_T save_after;
regsave_T save_behind;
int save_need_clear_subexpr;
save_se_T save_start[NSUBEXP];
save_se_T save_end[NSUBEXP];
} regbehind_T;
static char_u *reg_getline __ARGS((linenr_T lnum));
static long vim_regexec_both __ARGS((char_u *line, colnr_T col, proftime_T *tm));
static long regtry __ARGS((regprog_T *prog, colnr_T col));
static void cleanup_subexpr __ARGS((void));
#ifdef FEAT_SYN_HL
static void cleanup_zsubexpr __ARGS((void));
#endif
static void save_subexpr __ARGS((regbehind_T *bp));
static void restore_subexpr __ARGS((regbehind_T *bp));
static void reg_nextline __ARGS((void));
static void reg_save __ARGS((regsave_T *save, garray_T *gap));
static void reg_restore __ARGS((regsave_T *save, garray_T *gap));
static int reg_save_equal __ARGS((regsave_T *save));
static void save_se_multi __ARGS((save_se_T *savep, lpos_T *posp));
static void save_se_one __ARGS((save_se_T *savep, char_u **pp));
/* Save the sub-expressions before attempting a match. */
#define save_se(savep, posp, pp) \
REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
/* After a failed match restore the sub-expressions. */
#define restore_se(savep, posp, pp) { \
if (REG_MULTI) \
*(posp) = (savep)->se_u.pos; \
else \
*(pp) = (savep)->se_u.ptr; }
static int re_num_cmp __ARGS((long_u val, char_u *scan));
static int regmatch __ARGS((char_u *prog));
static int regrepeat __ARGS((char_u *p, long maxcount));
#ifdef DEBUG
int regnarrate = 0;
#endif
/*
* Internal copy of 'ignorecase'. It is set at each call to vim_regexec().
* Normally it gets the value of "rm_ic" or "rmm_ic", but when the pattern
* contains '\c' or '\C' the value is overruled.
*/
static int ireg_ic;
#ifdef FEAT_MBYTE
/*
* Similar to ireg_ic, but only for 'combining' characters. Set with \Z flag
* in the regexp. Defaults to false, always.
*/
static int ireg_icombine;
#endif
/*
* Copy of "rmm_maxcol": maximum column to search for a match. Zero when
* there is no maximum.
*/
static colnr_T ireg_maxcol;
/*
* Sometimes need to save a copy of a line. Since alloc()/free() is very
* slow, we keep one allocated piece of memory and only re-allocate it when
* it's too small. It's freed in vim_regexec_both() when finished.
*/
static char_u *reg_tofree = NULL;
static unsigned reg_tofreelen;
/*
* These variables are set when executing a regexp to speed up the execution.
* Which ones are set depends on whether a single-line or multi-line match is
* done:
* single-line multi-line
* reg_match ®match_T NULL
* reg_mmatch NULL ®mmatch_T
* reg_startp reg_match->startp <invalid>
* reg_endp reg_match->endp <invalid>
* reg_startpos <invalid> reg_mmatch->startpos
* reg_endpos <invalid> reg_mmatch->endpos
* reg_win NULL window in which to search
* reg_buf <invalid> buffer in which to search
* reg_firstlnum <invalid> first line in which to search
* reg_maxline 0 last line nr
* reg_line_lbr FALSE or TRUE FALSE
*/
static regmatch_T *reg_match;
static regmmatch_T *reg_mmatch;
static char_u **reg_startp = NULL;
static char_u **reg_endp = NULL;
static lpos_T *reg_startpos = NULL;
static lpos_T *reg_endpos = NULL;
static win_T *reg_win;
static buf_T *reg_buf;
static linenr_T reg_firstlnum;
static linenr_T reg_maxline;
static int reg_line_lbr; /* "\n" in string is line break */
/* Values for rs_state in regitem_T. */
typedef enum regstate_E
{
RS_NOPEN = 0 /* NOPEN and NCLOSE */
, RS_MOPEN /* MOPEN + [0-9] */
, RS_MCLOSE /* MCLOSE + [0-9] */
#ifdef FEAT_SYN_HL
, RS_ZOPEN /* ZOPEN + [0-9] */
, RS_ZCLOSE /* ZCLOSE + [0-9] */
#endif
, RS_BRANCH /* BRANCH */
, RS_BRCPLX_MORE /* BRACE_COMPLEX and trying one more match */
, RS_BRCPLX_LONG /* BRACE_COMPLEX and trying longest match */
, RS_BRCPLX_SHORT /* BRACE_COMPLEX and trying shortest match */
, RS_NOMATCH /* NOMATCH */
, RS_BEHIND1 /* BEHIND / NOBEHIND matching rest */
, RS_BEHIND2 /* BEHIND / NOBEHIND matching behind part */
, RS_STAR_LONG /* STAR/PLUS/BRACE_SIMPLE longest match */
, RS_STAR_SHORT /* STAR/PLUS/BRACE_SIMPLE shortest match */
} regstate_T;
/*
* When there are alternatives a regstate_T is put on the regstack to remember
* what we are doing.
* Before it may be another type of item, depending on rs_state, to remember
* more things.
*/
typedef struct regitem_S
{
regstate_T rs_state; /* what we are doing, one of RS_ above */
char_u *rs_scan; /* current node in program */
union
{
save_se_T sesave;
regsave_T regsave;
} rs_un; /* room for saving reginput */
short rs_no; /* submatch nr or BEHIND/NOBEHIND */
} regitem_T;
static regitem_T *regstack_push __ARGS((regstate_T state, char_u *scan));
static void regstack_pop __ARGS((char_u **scan));
/* used for STAR, PLUS and BRACE_SIMPLE matching */
typedef struct regstar_S
{
int nextb; /* next byte */
int nextb_ic; /* next byte reverse case */
long count;
long minval;
long maxval;
} regstar_T;
/* used to store input position when a BACK was encountered, so that we now if
* we made any progress since the last time. */
typedef struct backpos_S
{
char_u *bp_scan; /* "scan" where BACK was encountered */
regsave_T bp_pos; /* last input position */
} backpos_T;
/*
* "regstack" and "backpos" are used by regmatch(). They are kept over calls
* to avoid invoking malloc() and free() often.
* "regstack" is a stack with regitem_T items, sometimes preceded by regstar_T
* or regbehind_T.
* "backpos_T" is a table with backpos_T for BACK
*/
static garray_T regstack = {0, 0, 0, 0, NULL};
static garray_T backpos = {0, 0, 0, 0, NULL};
/*
* Both for regstack and backpos tables we use the following strategy of
* allocation (to reduce malloc/free calls):
* - Initial size is fairly small.
* - When needed, the tables are grown bigger (8 times at first, double after
* that).
* - After executing the match we free the memory only if the array has grown.
* Thus the memory is kept allocated when it's at the initial size.
* This makes it fast while not keeping a lot of memory allocated.
* A three times speed increase was observed when using many simple patterns.
*/
#define REGSTACK_INITIAL 2048
#define BACKPOS_INITIAL 64
#if defined(EXITFREE) || defined(PROTO)
void
free_regexp_stuff()
{
ga_clear(®stack);
ga_clear(&backpos);
vim_free(reg_tofree);
vim_free(reg_prev_sub);
}
#endif
/*
* Get pointer to the line "lnum", which is relative to "reg_firstlnum".
*/
static char_u *
reg_getline(lnum)
linenr_T lnum;
{
/* when looking behind for a match/no-match lnum is negative. But we
* can't go before line 1 */
if (reg_firstlnum + lnum < 1)
return NULL;
if (lnum > reg_maxline)
/* Must have matched the "\n" in the last line. */
return (char_u *)"";
return ml_get_buf(reg_buf, reg_firstlnum + lnum, FALSE);
}
static regsave_T behind_pos;
#ifdef FEAT_SYN_HL
static char_u *reg_startzp[NSUBEXP]; /* Workspace to mark beginning */
static char_u *reg_endzp[NSUBEXP]; /* and end of \z(...\) matches */
static lpos_T reg_startzpos[NSUBEXP]; /* idem, beginning pos */
static lpos_T reg_endzpos[NSUBEXP]; /* idem, end pos */
#endif
/* TRUE if using multi-line regexp. */
#define REG_MULTI (reg_match == NULL)
/*
* Match a regexp against a string.
* "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
* Uses curbuf for line count and 'iskeyword'.
*
* Return TRUE if there is a match, FALSE if not.
*/
int
vim_regexec(rmp, line, col)
regmatch_T *rmp;
char_u *line; /* string to match against */
colnr_T col; /* column to start looking for match */
{
reg_match = rmp;
reg_mmatch = NULL;
reg_maxline = 0;
reg_line_lbr = FALSE;
reg_win = NULL;
ireg_ic = rmp->rm_ic;
#ifdef FEAT_MBYTE
ireg_icombine = FALSE;
#endif
ireg_maxcol = 0;
return (vim_regexec_both(line, col, NULL) != 0);
}
#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) \
|| defined(FIND_REPLACE_DIALOG) || defined(PROTO)
/*
* Like vim_regexec(), but consider a "\n" in "line" to be a line break.
*/
int
vim_regexec_nl(rmp, line, col)
regmatch_T *rmp;
char_u *line; /* string to match against */
colnr_T col; /* column to start looking for match */
{
reg_match = rmp;
reg_mmatch = NULL;
reg_maxline = 0;
reg_line_lbr = TRUE;
reg_win = NULL;
ireg_ic = rmp->rm_ic;
#ifdef FEAT_MBYTE
ireg_icombine = FALSE;
#endif
ireg_maxcol = 0;
return (vim_regexec_both(line, col, NULL) != 0);
}
#endif
/*
* Match a regexp against multiple lines.
* "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
* Uses curbuf for line count and 'iskeyword'.
*
* Return zero if there is no match. Return number of lines contained in the
* match otherwise.
*/
long
vim_regexec_multi(rmp, win, buf, lnum, col, tm)
regmmatch_T *rmp;
win_T *win; /* window in which to search or NULL */
buf_T *buf; /* buffer in which to search */
linenr_T lnum; /* nr of line to start looking for match */
colnr_T col; /* column to start looking for match */
proftime_T *tm; /* timeout limit or NULL */
{
long r;
buf_T *save_curbuf = curbuf;
reg_match = NULL;
reg_mmatch = rmp;
reg_buf = buf;
reg_win = win;
reg_firstlnum = lnum;
reg_maxline = reg_buf->b_ml.ml_line_count - lnum;
reg_line_lbr = FALSE;
ireg_ic = rmp->rmm_ic;
#ifdef FEAT_MBYTE
ireg_icombine = FALSE;
#endif
ireg_maxcol = rmp->rmm_maxcol;
/* Need to switch to buffer "buf" to make vim_iswordc() work. */
curbuf = buf;
r = vim_regexec_both(NULL, col, tm);
curbuf = save_curbuf;
return r;
}
/*
* Match a regexp against a string ("line" points to the string) or multiple
* lines ("line" is NULL, use reg_getline()).
*/
static long
vim_regexec_both(line, col, tm)
char_u *line;
colnr_T col; /* column to start looking for match */
proftime_T *tm UNUSED; /* timeout limit or NULL */
{
regprog_T *prog;
char_u *s;
long retval = 0L;
/* Create "regstack" and "backpos" if they are not allocated yet.
* We allocate *_INITIAL amount of bytes first and then set the grow size
* to much bigger value to avoid many malloc calls in case of deep regular
* expressions. */
if (regstack.ga_data == NULL)
{
/* Use an item size of 1 byte, since we push different things
* onto the regstack. */
ga_init2(®stack, 1, REGSTACK_INITIAL);
ga_grow(®stack, REGSTACK_INITIAL);
regstack.ga_growsize = REGSTACK_INITIAL * 8;
}
if (backpos.ga_data == NULL)
{
ga_init2(&backpos, sizeof(backpos_T), BACKPOS_INITIAL);
ga_grow(&backpos, BACKPOS_INITIAL);
backpos.ga_growsize = BACKPOS_INITIAL * 8;
}
if (REG_MULTI)
{
prog = reg_mmatch->regprog;
line = reg_getline((linenr_T)0);
reg_startpos = reg_mmatch->startpos;
reg_endpos = reg_mmatch->endpos;
}
else
{
prog = reg_match->regprog;
reg_startp = reg_match->startp;
reg_endp = reg_match->endp;
}
/* Be paranoid... */
if (prog == NULL || line == NULL)
{
EMSG(_(e_null));
goto theend;
}
/* Check validity of program. */
if (prog_magic_wrong())
goto theend;
/* If the start column is past the maximum column: no need to try. */
if (ireg_maxcol > 0 && col >= ireg_maxcol)
goto theend;
/* If pattern contains "\c" or "\C": overrule value of ireg_ic */
if (prog->regflags & RF_ICASE)
ireg_ic = TRUE;
else if (prog->regflags & RF_NOICASE)
ireg_ic = FALSE;
#ifdef FEAT_MBYTE
/* If pattern contains "\Z" overrule value of ireg_icombine */
if (prog->regflags & RF_ICOMBINE)
ireg_icombine = TRUE;
#endif
/* If there is a "must appear" string, look for it. */
if (prog->regmust != NULL)
{
int c;
#ifdef FEAT_MBYTE
if (has_mbyte)
c = (*mb_ptr2char)(prog->regmust);
else
#endif
c = *prog->regmust;
s = line + col;
/*
* This is used very often, esp. for ":global". Use three versions of
* the loop to avoid overhead of conditions.
*/
if (!ireg_ic
#ifdef FEAT_MBYTE
&& !has_mbyte
#endif
)
while ((s = vim_strbyte(s, c)) != NULL)
{
if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
break; /* Found it. */
++s;
}
#ifdef FEAT_MBYTE
else if (!ireg_ic || (!enc_utf8 && mb_char2len(c) > 1))
while ((s = vim_strchr(s, c)) != NULL)
{
if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
break; /* Found it. */
mb_ptr_adv(s);
}
#endif
else
while ((s = cstrchr(s, c)) != NULL)
{
if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0)
break; /* Found it. */
mb_ptr_adv(s);
}
if (s == NULL) /* Not present. */
goto theend;
}
regline = line;
reglnum = 0;
reg_toolong = FALSE;
/* Simplest case: Anchored match need be tried only once. */
if (prog->reganch)
{
int c;
#ifdef FEAT_MBYTE
if (has_mbyte)
c = (*mb_ptr2char)(regline + col);
else
#endif
c = regline[col];
if (prog->regstart == NUL
|| prog->regstart == c
|| (ireg_ic && ((
#ifdef FEAT_MBYTE
(enc_utf8 && utf_fold(prog->regstart) == utf_fold(c)))
|| (c < 255 && prog->regstart < 255 &&
#endif
MB_TOLOWER(prog->regstart) == MB_TOLOWER(c)))))
retval = regtry(prog, col);
else
retval = 0;
}
else
{
#ifdef FEAT_RELTIME
int tm_count = 0;
#endif
/* Messy cases: unanchored match. */
while (!got_int)
{
if (prog->regstart != NUL)
{
/* Skip until the char we know it must start with.
* Used often, do some work to avoid call overhead. */
if (!ireg_ic
#ifdef FEAT_MBYTE
&& !has_mbyte
#endif
)
s = vim_strbyte(regline + col, prog->regstart);
else
s = cstrchr(regline + col, prog->regstart);
if (s == NULL)
{
retval = 0;
break;
}
col = (int)(s - regline);
}
/* Check for maximum column to try. */
if (ireg_maxcol > 0 && col >= ireg_maxcol)
{
retval = 0;
break;
}
retval = regtry(prog, col);
if (retval > 0)
break;
/* if not currently on the first line, get it again */
if (reglnum != 0)
{
reglnum = 0;
regline = reg_getline((linenr_T)0);
}
if (regline[col] == NUL)
break;
#ifdef FEAT_MBYTE
if (has_mbyte)
col += (*mb_ptr2len)(regline + col);
else
#endif
++col;
#ifdef FEAT_RELTIME
/* Check for timeout once in a twenty times to avoid overhead. */
if (tm != NULL && ++tm_count == 20)
{
tm_count = 0;
if (profile_passed_limit(tm))
break;
}
#endif
}
}
theend:
/* Free "reg_tofree" when it's a bit big.
* Free regstack and backpos if they are bigger than their initial size. */
if (reg_tofreelen > 400)
{
vim_free(reg_tofree);
reg_tofree = NULL;
}
if (regstack.ga_maxlen > REGSTACK_INITIAL)
ga_clear(®stack);
if (backpos.ga_maxlen > BACKPOS_INITIAL)
ga_clear(&backpos);
return retval;
}
#ifdef FEAT_SYN_HL
static reg_extmatch_T *make_extmatch __ARGS((void));
/*
* Create a new extmatch and mark it as referenced once.
*/
static reg_extmatch_T *
make_extmatch()
{
reg_extmatch_T *em;
em = (reg_extmatch_T *)alloc_clear((unsigned)sizeof(reg_extmatch_T));
if (em != NULL)
em->refcnt = 1;
return em;
}
/*
* Add a reference to an extmatch.
*/
reg_extmatch_T *
ref_extmatch(em)
reg_extmatch_T *em;
{
if (em != NULL)
em->refcnt++;
return em;
}
/*
* Remove a reference to an extmatch. If there are no references left, free
* the info.
*/
void
unref_extmatch(em)
reg_extmatch_T *em;
{
int i;
if (em != NULL && --em->refcnt <= 0)
{
for (i = 0; i < NSUBEXP; ++i)
vim_free(em->matches[i]);
vim_free(em);
}
}
#endif
/*
* regtry - try match of "prog" with at regline["col"].
* Returns 0 for failure, number of lines contained in the match otherwise.
*/
static long
regtry(prog, col)
regprog_T *prog;
colnr_T col;
{
reginput = regline + col;
need_clear_subexpr = TRUE;
#ifdef FEAT_SYN_HL
/* Clear the external match subpointers if necessary. */
if (prog->reghasz == REX_SET)
need_clear_zsubexpr = TRUE;
#endif
if (regmatch(prog->program + 1) == 0)
return 0;
cleanup_subexpr();
if (REG_MULTI)
{
if (reg_startpos[0].lnum < 0)
{
reg_startpos[0].lnum = 0;
reg_startpos[0].col = col;
}
if (reg_endpos[0].lnum < 0)
{
reg_endpos[0].lnum = reglnum;
reg_endpos[0].col = (int)(reginput - regline);
}
else
/* Use line number of "\ze". */
reglnum = reg_endpos[0].lnum;
}
else
{
if (reg_startp[0] == NULL)
reg_startp[0] = regline + col;
if (reg_endp[0] == NULL)
reg_endp[0] = reginput;
}
#ifdef FEAT_SYN_HL
/* Package any found \z(...\) matches for export. Default is none. */
unref_extmatch(re_extmatch_out);
re_extmatch_out = NULL;
if (prog->reghasz == REX_SET)
{
int i;
cleanup_zsubexpr();
re_extmatch_out = make_extmatch();
for (i = 0; i < NSUBEXP; i++)
{
if (REG_MULTI)
{
/* Only accept single line matches. */
if (reg_startzpos[i].lnum >= 0
&& reg_endzpos[i].lnum == reg_startzpos[i].lnum)
re_extmatch_out->matches[i] =
vim_strnsave(reg_getline(reg_startzpos[i].lnum)
+ reg_startzpos[i].col,
reg_endzpos[i].col - reg_startzpos[i].col);
}
else
{
if (reg_startzp[i] != NULL && reg_endzp[i] != NULL)
re_extmatch_out->matches[i] =
vim_strnsave(reg_startzp[i],
(int)(reg_endzp[i] - reg_startzp[i]));
}
}
}
#endif
return 1 + reglnum;
}
#ifdef FEAT_MBYTE
static int reg_prev_class __ARGS((void));
/*
* Get class of previous character.
*/
static int
reg_prev_class()
{
if (reginput > regline)
return mb_get_class(reginput - 1
- (*mb_head_off)(regline, reginput - 1));
return -1;
}
#endif
#define ADVANCE_REGINPUT() mb_ptr_adv(reginput)
/*
* The arguments from BRACE_LIMITS are stored here. They are actually local
* to regmatch(), but they are here to reduce the amount of stack space used
* (it can be called recursively many times).
*/
static long bl_minval;
static long bl_maxval;
/*
* regmatch - main matching routine
*
* Conceptually the strategy is simple: Check to see whether the current node
* matches, push an item onto the regstack and loop to see whether the rest
* matches, and then act accordingly. In practice we make some effort to
* avoid using the regstack, in particular by going through "ordinary" nodes
* (that don't need to know whether the rest of the match failed) by a nested
* loop.
*
* Returns TRUE when there is a match. Leaves reginput and reglnum just after
* the last matched character.
* Returns FALSE when there is no match. Leaves reginput and reglnum in an
* undefined state!
*/
static int
regmatch(scan)
char_u *scan; /* Current node. */
{
char_u *next; /* Next node. */
int op;
int c;
regitem_T *rp;
int no;
int status; /* one of the RA_ values: */
#define RA_FAIL 1 /* something failed, abort */
#define RA_CONT 2 /* continue in inner loop */
#define RA_BREAK 3 /* break inner loop */
#define RA_MATCH 4 /* successful match */
#define RA_NOMATCH 5 /* didn't match */
/* Make "regstack" and "backpos" empty. They are allocated and freed in
* vim_regexec_both() to reduce malloc()/free() calls. */
regstack.ga_len = 0;
backpos.ga_len = 0;
/*
* Repeat until "regstack" is empty.
*/
for (;;)
{
/* Some patterns my cause a long time to match, even though they are not
* illegal. E.g., "\([a-z]\+\)\+Q". Allow breaking them with CTRL-C. */
fast_breakcheck();
#ifdef DEBUG
if (scan != NULL && regnarrate)
{
mch_errmsg(regprop(scan));
mch_errmsg("(\n");
}
#endif
/*
* Repeat for items that can be matched sequentially, without using the
* regstack.
*/
for (;;)
{
if (got_int || scan == NULL)
{
status = RA_FAIL;
break;
}
status = RA_CONT;
#ifdef DEBUG
if (regnarrate)
{
mch_errmsg(regprop(scan));
mch_errmsg("...\n");
# ifdef FEAT_SYN_HL
if (re_extmatch_in != NULL)
{
int i;
mch_errmsg(_("External submatches:\n"));
for (i = 0; i < NSUBEXP; i++)
{
mch_errmsg(" \"");
if (re_extmatch_in->matches[i] != NULL)
mch_errmsg(re_extmatch_in->matches[i]);
mch_errmsg("\"\n");
}
}
# endif
}
#endif
next = regnext(scan);
op = OP(scan);
/* Check for character class with NL added. */
if (!reg_line_lbr && WITH_NL(op) && REG_MULTI
&& *reginput == NUL && reglnum <= reg_maxline)
{
reg_nextline();
}
else if (reg_line_lbr && WITH_NL(op) && *reginput == '\n')
{
ADVANCE_REGINPUT();
}
else
{
if (WITH_NL(op))
op -= ADD_NL;
#ifdef FEAT_MBYTE
if (has_mbyte)
c = (*mb_ptr2char)(reginput);
else
#endif
c = *reginput;
switch (op)
{
case BOL:
if (reginput != regline)
status = RA_NOMATCH;
break;
case EOL:
if (c != NUL)
status = RA_NOMATCH;
break;
case RE_BOF:
/* We're not at the beginning of the file when below the first
* line where we started, not at the start of the line or we
* didn't start at the first line of the buffer. */
if (reglnum != 0 || reginput != regline
|| (REG_MULTI && reg_firstlnum > 1))
status = RA_NOMATCH;
break;
case RE_EOF:
if (reglnum != reg_maxline || c != NUL)
status = RA_NOMATCH;
break;
case CURSOR:
/* Check if the buffer is in a window and compare the
* reg_win->w_cursor position to the match position. */
if (reg_win == NULL
|| (reglnum + reg_firstlnum != reg_win->w_cursor.lnum)
|| ((colnr_T)(reginput - regline) != reg_win->w_cursor.col))
status = RA_NOMATCH;
break;
case RE_MARK:
/* Compare the mark position to the match position. NOTE: Always
* uses the current buffer. */
{
int mark = OPERAND(scan)[0];
int cmp = OPERAND(scan)[1];
pos_T *pos;
pos = getmark(mark, FALSE);
if (pos == NULL /* mark doesn't exist */
|| pos->lnum <= 0 /* mark isn't set (in curbuf) */
|| (pos->lnum == reglnum + reg_firstlnum
? (pos->col == (colnr_T)(reginput - regline)
? (cmp == '<' || cmp == '>')
: (pos->col < (colnr_T)(reginput - regline)
? cmp != '>'
: cmp != '<'))
: (pos->lnum < reglnum + reg_firstlnum
? cmp != '>'
: cmp != '<')))
status = RA_NOMATCH;
}
break;
case RE_VISUAL:
#ifdef FEAT_VISUAL
/* Check if the buffer is the current buffer. and whether the
* position is inside the Visual area. */
if (reg_buf != curbuf || VIsual.lnum == 0)
status = RA_NOMATCH;
else
{
pos_T top, bot;
linenr_T lnum;
colnr_T col;
win_T *wp = reg_win == NULL ? curwin : reg_win;
int mode;
if (VIsual_active)
{
if (lt(VIsual, wp->w_cursor))
{
top = VIsual;
bot = wp->w_cursor;
}
else
{
top = wp->w_cursor;
bot = VIsual;
}
mode = VIsual_mode;
}
else
{
if (lt(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end))
{
top = curbuf->b_visual.vi_start;
bot = curbuf->b_visual.vi_end;
}
else
{
top = curbuf->b_visual.vi_end;
bot = curbuf->b_visual.vi_start;
}
mode = curbuf->b_visual.vi_mode;
}
lnum = reglnum + reg_firstlnum;
col = (colnr_T)(reginput - regline);
if (lnum < top.lnum || lnum > bot.lnum)
status = RA_NOMATCH;
else if (mode == 'v')
{
if ((lnum == top.lnum && col < top.col)
|| (lnum == bot.lnum
&& col >= bot.col + (*p_sel != 'e')))
status = RA_NOMATCH;
}
else if (mode == Ctrl_V)
{
colnr_T start, end;
colnr_T start2, end2;
colnr_T cols;
getvvcol(wp, &top, &start, NULL, &end);
getvvcol(wp, &bot, &start2, NULL, &end2);
if (start2 < start)
start = start2;
if (end2 > end)
end = end2;
if (top.col == MAXCOL || bot.col == MAXCOL)
end = MAXCOL;
cols = win_linetabsize(wp,
regline, (colnr_T)(reginput - regline));
if (cols < start || cols > end - (*p_sel == 'e'))
status = RA_NOMATCH;
}
}
#else
status = RA_NOMATCH;
#endif
break;
case RE_LNUM:
if (!REG_MULTI || !re_num_cmp((long_u)(reglnum + reg_firstlnum),
scan))
status = RA_NOMATCH;
break;
case RE_COL:
if (!re_num_cmp((long_u)(reginput - regline) + 1, scan))
status = RA_NOMATCH;
break;
case RE_VCOL:
if (!re_num_cmp((long_u)win_linetabsize(
reg_win == NULL ? curwin : reg_win,
regline, (colnr_T)(reginput - regline)) + 1, scan))
status = RA_NOMATCH;
break;
case BOW: /* \<word; reginput points to w */
if (c == NUL) /* Can't match at end of line */
status = RA_NOMATCH;
#ifdef FEAT_MBYTE
else if (has_mbyte)
{
int this_class;
/* Get class of current and previous char (if it exists). */
this_class = mb_get_class(reginput);
if (this_class <= 1)
status = RA_NOMATCH; /* not on a word at all */
else if (reg_prev_class() == this_class)
status = RA_NOMATCH; /* previous char is in same word */
}
#endif
else
{
if (!vim_iswordc(c)
|| (reginput > regline && vim_iswordc(reginput[-1])))
status = RA_NOMATCH;
}
break;
case EOW: /* word\>; reginput points after d */
if (reginput == regline) /* Can't match at start of line */
status = RA_NOMATCH;
#ifdef FEAT_MBYTE
else if (has_mbyte)
{
int this_class, prev_class;
/* Get class of current and previous char (if it exists). */
this_class = mb_get_class(reginput);
prev_class = reg_prev_class();
if (this_class == prev_class
|| prev_class == 0 || prev_class == 1)
status = RA_NOMATCH;
}
#endif
else
{
if (!vim_iswordc(reginput[-1])
|| (reginput[0] != NUL && vim_iswordc(c)))
status = RA_NOMATCH;
}
break; /* Matched with EOW */
case ANY:
if (c == NUL)
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case IDENT:
if (!vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SIDENT:
if (VIM_ISDIGIT(*reginput) || !vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case KWORD:
if (!vim_iswordp(reginput))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SKWORD:
if (VIM_ISDIGIT(*reginput) || !vim_iswordp(reginput))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case FNAME:
if (!vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SFNAME:
if (VIM_ISDIGIT(*reginput) || !vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case PRINT:
if (ptr2cells(reginput) != 1)
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SPRINT:
if (VIM_ISDIGIT(*reginput) || ptr2cells(reginput) != 1)
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WHITE:
if (!vim_iswhite(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWHITE:
if (c == NUL || vim_iswhite(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case DIGIT:
if (!ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NDIGIT:
if (c == NUL || ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEX:
if (!ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEX:
if (c == NUL || ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case OCTAL:
if (!ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NOCTAL:
if (c == NUL || ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WORD:
if (!ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWORD:
if (c == NUL || ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEAD:
if (!ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEAD:
if (c == NUL || ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case ALPHA:
if (!ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NALPHA:
if (c == NUL || ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case LOWER:
if (!ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NLOWER:
if (c == NUL || ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case UPPER:
if (!ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NUPPER:
if (c == NUL || ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case EXACTLY:
{
int len;
char_u *opnd;
opnd = OPERAND(scan);
/* Inline the first byte, for speed. */
if (*opnd != *reginput
&& (!ireg_ic || (
#ifdef FEAT_MBYTE
!enc_utf8 &&
#endif
MB_TOLOWER(*opnd) != MB_TOLOWER(*reginput))))
status = RA_NOMATCH;
else if (*opnd == NUL)
{
/* match empty string always works; happens when "~" is
* empty. */
}
else if (opnd[1] == NUL
#ifdef FEAT_MBYTE
&& !(enc_utf8 && ireg_ic)
#endif
)
++reginput; /* matched a single char */
else
{
len = (int)STRLEN(opnd);
/* Need to match first byte again for multi-byte. */
if (cstrncmp(opnd, reginput, &len) != 0)
status = RA_NOMATCH;
#ifdef FEAT_MBYTE
/* Check for following composing character. */
else if (enc_utf8
&& UTF_COMPOSINGLIKE(reginput, reginput + len))
{
/* raaron: This code makes a composing character get
* ignored, which is the correct behavior (sometimes)
* for voweled Hebrew texts. */
if (!ireg_icombine)
status = RA_NOMATCH;
}
#endif
else
reginput += len;
}
}
break;
case ANYOF:
case ANYBUT:
if (c == NUL)
status = RA_NOMATCH;
else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
#ifdef FEAT_MBYTE
case MULTIBYTECODE:
if (has_mbyte)
{
int i, len;
char_u *opnd;
int opndc = 0, inpc;
opnd = OPERAND(scan);
/* Safety check (just in case 'encoding' was changed since
* compiling the program). */
if ((len = (*mb_ptr2len)(opnd)) < 2)
{
status = RA_NOMATCH;
break;
}
if (enc_utf8)
opndc = mb_ptr2char(opnd);
if (enc_utf8 && utf_iscomposing(opndc))
{
/* When only a composing char is given match at any
* position where that composing char appears. */
status = RA_NOMATCH;
for (i = 0; reginput[i] != NUL; i += utf_char2len(inpc))
{
inpc = mb_ptr2char(reginput + i);
if (!utf_iscomposing(inpc))
{
if (i > 0)
break;
}
else if (opndc == inpc)
{
/* Include all following composing chars. */
len = i + mb_ptr2len(reginput + i);
status = RA_MATCH;
break;
}
}
}
else
for (i = 0; i < len; ++i)
if (opnd[i] != reginput[i])
{
status = RA_NOMATCH;
break;
}
reginput += len;
}
else
status = RA_NOMATCH;
break;
#endif
case NOTHING:
break;
case BACK:
{
int i;
backpos_T *bp;
/*
* When we run into BACK we need to check if we don't keep
* looping without matching any input. The second and later
* times a BACK is encountered it fails if the input is still
* at the same position as the previous time.
* The positions are stored in "backpos" and found by the
* current value of "scan", the position in the RE program.
*/
bp = (backpos_T *)backpos.ga_data;
for (i = 0; i < backpos.ga_len; ++i)
if (bp[i].bp_scan == scan)
break;
if (i == backpos.ga_len)
{
/* First time at this BACK, make room to store the pos. */
if (ga_grow(&backpos, 1) == FAIL)
status = RA_FAIL;
else
{
/* get "ga_data" again, it may have changed */
bp = (backpos_T *)backpos.ga_data;
bp[i].bp_scan = scan;
++backpos.ga_len;
}
}
else if (reg_save_equal(&bp[i].bp_pos))
/* Still at same position as last time, fail. */
status = RA_NOMATCH;
if (status != RA_FAIL && status != RA_NOMATCH)
reg_save(&bp[i].bp_pos, &backpos);
}
break;
case MOPEN + 0: /* Match start: \zs */
case MOPEN + 1: /* \( */
case MOPEN + 2:
case MOPEN + 3:
case MOPEN + 4:
case MOPEN + 5:
case MOPEN + 6:
case MOPEN + 7:
case MOPEN + 8:
case MOPEN + 9:
{
no = op - MOPEN;
cleanup_subexpr();
rp = regstack_push(RS_MOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_startpos[no],
®_startp[no]);
/* We simply continue and handle the result when done. */
}
}
break;
case NOPEN: /* \%( */
case NCLOSE: /* \) after \%( */
if (regstack_push(RS_NOPEN, scan) == NULL)
status = RA_FAIL;
/* We simply continue and handle the result when done. */
break;
#ifdef FEAT_SYN_HL
case ZOPEN + 1:
case ZOPEN + 2:
case ZOPEN + 3:
case ZOPEN + 4:
case ZOPEN + 5:
case ZOPEN + 6:
case ZOPEN + 7:
case ZOPEN + 8:
case ZOPEN + 9:
{
no = op - ZOPEN;
cleanup_zsubexpr();
rp = regstack_push(RS_ZOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_startzpos[no],
®_startzp[no]);
/* We simply continue and handle the result when done. */
}
}
break;
#endif
case MCLOSE + 0: /* Match end: \ze */
case MCLOSE + 1: /* \) */
case MCLOSE + 2:
case MCLOSE + 3:
case MCLOSE + 4:
case MCLOSE + 5:
case MCLOSE + 6:
case MCLOSE + 7:
case MCLOSE + 8:
case MCLOSE + 9:
{
no = op - MCLOSE;
cleanup_subexpr();
rp = regstack_push(RS_MCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_endpos[no], ®_endp[no]);
/* We simply continue and handle the result when done. */
}
}
break;
#ifdef FEAT_SYN_HL
case ZCLOSE + 1: /* \) after \z( */
case ZCLOSE + 2:
case ZCLOSE + 3:
case ZCLOSE + 4:
case ZCLOSE + 5:
case ZCLOSE + 6:
case ZCLOSE + 7:
case ZCLOSE + 8:
case ZCLOSE + 9:
{
no = op - ZCLOSE;
cleanup_zsubexpr();
rp = regstack_push(RS_ZCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_endzpos[no],
®_endzp[no]);
/* We simply continue and handle the result when done. */
}
}
break;
#endif
case BACKREF + 1:
case BACKREF + 2:
case BACKREF + 3:
case BACKREF + 4:
case BACKREF + 5:
case BACKREF + 6:
case BACKREF + 7:
case BACKREF + 8:
case BACKREF + 9:
{
int len;
linenr_T clnum;
colnr_T ccol;
char_u *p;
no = op - BACKREF;
cleanup_subexpr();
if (!REG_MULTI) /* Single-line regexp */
{
if (reg_startp[no] == NULL || reg_endp[no] == NULL)
{
/* Backref was not set: Match an empty string. */
len = 0;
}
else
{
/* Compare current input with back-ref in the same
* line. */
len = (int)(reg_endp[no] - reg_startp[no]);
if (cstrncmp(reg_startp[no], reginput, &len) != 0)
status = RA_NOMATCH;
}
}
else /* Multi-line regexp */
{
if (reg_startpos[no].lnum < 0 || reg_endpos[no].lnum < 0)
{
/* Backref was not set: Match an empty string. */
len = 0;
}
else
{
if (reg_startpos[no].lnum == reglnum
&& reg_endpos[no].lnum == reglnum)
{
/* Compare back-ref within the current line. */
len = reg_endpos[no].col - reg_startpos[no].col;
if (cstrncmp(regline + reg_startpos[no].col,
reginput, &len) != 0)
status = RA_NOMATCH;
}
else
{
/* Messy situation: Need to compare between two
* lines. */
ccol = reg_startpos[no].col;
clnum = reg_startpos[no].lnum;
for (;;)
{
/* Since getting one line may invalidate
* the other, need to make copy. Slow! */
if (regline != reg_tofree)
{
len = (int)STRLEN(regline);
if (reg_tofree == NULL
|| len >= (int)reg_tofreelen)
{
len += 50; /* get some extra */
vim_free(reg_tofree);
reg_tofree = alloc(len);
if (reg_tofree == NULL)
{
status = RA_FAIL; /* outof memory!*/
break;
}
reg_tofreelen = len;
}
STRCPY(reg_tofree, regline);
reginput = reg_tofree
+ (reginput - regline);
regline = reg_tofree;
}
/* Get the line to compare with. */
p = reg_getline(clnum);
if (clnum == reg_endpos[no].lnum)
len = reg_endpos[no].col - ccol;
else
len = (int)STRLEN(p + ccol);
if (cstrncmp(p + ccol, reginput, &len) != 0)
{
status = RA_NOMATCH; /* doesn't match */
break;
}
if (clnum == reg_endpos[no].lnum)
break; /* match and at end! */
if (reglnum >= reg_maxline)
{
status = RA_NOMATCH; /* text too short */
break;
}
/* Advance to next line. */
reg_nextline();
++clnum;
ccol = 0;
if (got_int)
{
status = RA_FAIL;
break;
}
}
/* found a match! Note that regline may now point
* to a copy of the line, that should not matter. */
}
}
}
/* Matched the backref, skip over it. */
reginput += len;
}
break;
#ifdef FEAT_SYN_HL
case ZREF + 1:
case ZREF + 2:
case ZREF + 3:
case ZREF + 4:
case ZREF + 5:
case ZREF + 6:
case ZREF + 7:
case ZREF + 8:
case ZREF + 9:
{
int len;
cleanup_zsubexpr();
no = op - ZREF;
if (re_extmatch_in != NULL
&& re_extmatch_in->matches[no] != NULL)
{
len = (int)STRLEN(re_extmatch_in->matches[no]);
if (cstrncmp(re_extmatch_in->matches[no],
reginput, &len) != 0)
status = RA_NOMATCH;
else
reginput += len;
}
else
{
/* Backref was not set: Match an empty string. */
}
}
break;
#endif
case BRANCH:
{
if (OP(next) != BRANCH) /* No choice. */
next = OPERAND(scan); /* Avoid recursion. */
else
{
rp = regstack_push(RS_BRANCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
status = RA_BREAK; /* rest is below */
}
}
break;
case BRACE_LIMITS:
{
if (OP(next) == BRACE_SIMPLE)
{
bl_minval = OPERAND_MIN(scan);
bl_maxval = OPERAND_MAX(scan);
}
else if (OP(next) >= BRACE_COMPLEX
&& OP(next) < BRACE_COMPLEX + 10)
{
no = OP(next) - BRACE_COMPLEX;
brace_min[no] = OPERAND_MIN(scan);
brace_max[no] = OPERAND_MAX(scan);
brace_count[no] = 0;
}
else
{
EMSG(_(e_internal)); /* Shouldn't happen */
status = RA_FAIL;
}
}
break;
case BRACE_COMPLEX + 0:
case BRACE_COMPLEX + 1:
case BRACE_COMPLEX + 2:
case BRACE_COMPLEX + 3:
case BRACE_COMPLEX + 4:
case BRACE_COMPLEX + 5:
case BRACE_COMPLEX + 6:
case BRACE_COMPLEX + 7:
case BRACE_COMPLEX + 8:
case BRACE_COMPLEX + 9:
{
no = op - BRACE_COMPLEX;
++brace_count[no];
/* If not matched enough times yet, try one more */
if (brace_count[no] <= (brace_min[no] <= brace_max[no]
? brace_min[no] : brace_max[no]))
{
rp = regstack_push(RS_BRCPLX_MORE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
/* We continue and handle the result when done. */
}
break;
}
/* If matched enough times, may try matching some more */
if (brace_min[no] <= brace_max[no])
{
/* Range is the normal way around, use longest match */
if (brace_count[no] <= brace_max[no])
{
rp = regstack_push(RS_BRCPLX_LONG, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
/* We continue and handle the result when done. */
}
}
}
else
{
/* Range is backwards, use shortest match first */
if (brace_count[no] <= brace_min[no])
{
rp = regstack_push(RS_BRCPLX_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
reg_save(&rp->rs_un.regsave, &backpos);
/* We continue and handle the result when done. */
}
}
}
}
break;
case BRACE_SIMPLE:
case STAR:
case PLUS:
{
regstar_T rst;
/*
* Lookahead to avoid useless match attempts when we know
* what character comes next.
*/
if (OP(next) == EXACTLY)
{
rst.nextb = *OPERAND(next);
if (ireg_ic)
{
if (MB_ISUPPER(rst.nextb))
rst.nextb_ic = MB_TOLOWER(rst.nextb);
else
rst.nextb_ic = MB_TOUPPER(rst.nextb);
}
else
rst.nextb_ic = rst.nextb;
}
else
{
rst.nextb = NUL;
rst.nextb_ic = NUL;
}
if (op != BRACE_SIMPLE)
{
rst.minval = (op == STAR) ? 0 : 1;
rst.maxval = MAX_LIMIT;
}
else
{
rst.minval = bl_minval;
rst.maxval = bl_maxval;
}
/*
* When maxval > minval, try matching as much as possible, up
* to maxval. When maxval < minval, try matching at least the
* minimal number (since the range is backwards, that's also
* maxval!).
*/
rst.count = regrepeat(OPERAND(scan), rst.maxval);
if (got_int)
{
status = RA_FAIL;
break;
}
if (rst.minval <= rst.maxval
? rst.count >= rst.minval : rst.count >= rst.maxval)
{
/* It could match. Prepare for trying to match what
* follows. The code is below. Parameters are stored in
* a regstar_T on the regstack. */
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
EMSG(_(e_maxmempat));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regstar_T);
rp = regstack_push(rst.minval <= rst.maxval
? RS_STAR_LONG : RS_STAR_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
*(((regstar_T *)rp) - 1) = rst;
status = RA_BREAK; /* skip the restore bits */
}
}
}
else
status = RA_NOMATCH;
}
break;
case NOMATCH:
case MATCH:
case SUBPAT:
rp = regstack_push(RS_NOMATCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
/* We continue and handle the result when done. */
}
break;
case BEHIND:
case NOBEHIND:
/* Need a bit of room to store extra positions. */
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
EMSG(_(e_maxmempat));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regbehind_T);
rp = regstack_push(RS_BEHIND1, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
/* Need to save the subexpr to be able to restore them
* when there is a match but we don't use it. */
save_subexpr(((regbehind_T *)rp) - 1);
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
/* First try if what follows matches. If it does then we
* check the behind match by looping. */
}
}
break;
case BHPOS:
if (REG_MULTI)
{
if (behind_pos.rs_u.pos.col != (colnr_T)(reginput - regline)
|| behind_pos.rs_u.pos.lnum != reglnum)
status = RA_NOMATCH;
}
else if (behind_pos.rs_u.ptr != reginput)
status = RA_NOMATCH;
break;
case NEWL:
if ((c != NUL || !REG_MULTI || reglnum > reg_maxline
|| reg_line_lbr) && (c != '\n' || !reg_line_lbr))
status = RA_NOMATCH;
else if (reg_line_lbr)
ADVANCE_REGINPUT();
else
reg_nextline();
break;
case END:
status = RA_MATCH; /* Success! */
break;
default:
EMSG(_(e_re_corr));
#ifdef DEBUG
printf("Illegal op code %d\n", op);
#endif
status = RA_FAIL;
break;
}
}
/* If we can't continue sequentially, break the inner loop. */
if (status != RA_CONT)
break;
/* Continue in inner loop, advance to next item. */
scan = next;
} /* end of inner loop */
/*
* If there is something on the regstack execute the code for the state.
* If the state is popped then loop and use the older state.
*/
while (regstack.ga_len > 0 && status != RA_FAIL)
{
rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
switch (rp->rs_state)
{
case RS_NOPEN:
/* Result is passed on as-is, simply pop the state. */
regstack_pop(&scan);
break;
case RS_MOPEN:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_startpos[rp->rs_no],
®_startp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZOPEN:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],
®_startzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_MCLOSE:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_endpos[rp->rs_no],
®_endp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZCLOSE:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],
®_endzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_BRANCH:
if (status == RA_MATCH)
/* this branch matched, use it */
regstack_pop(&scan);
else
{
if (status != RA_BREAK)
{
/* After a non-matching branch: try next one. */
reg_restore(&rp->rs_un.regsave, &backpos);
scan = rp->rs_scan;
}
if (scan == NULL || OP(scan) != BRANCH)
{
/* no more branches, didn't find a match */
status = RA_NOMATCH;
regstack_pop(&scan);
}
else
{
/* Prepare to try a branch. */
rp->rs_scan = regnext(scan);
reg_save(&rp->rs_un.regsave, &backpos);
scan = OPERAND(scan);
}
}
break;
case RS_BRCPLX_MORE:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
{
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no]; /* decrement match count */
}
regstack_pop(&scan);
break;
case RS_BRCPLX_LONG:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
{
/* There was no match, but we did find enough matches. */
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no];
/* continue with the items after "\{}" */
status = RA_CONT;
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BRCPLX_SHORT:
/* Pop the state. Restore pointers when there is no match. */
if (status == RA_NOMATCH)
/* There was no match, try to match one more item. */
reg_restore(&rp->rs_un.regsave, &backpos);
regstack_pop(&scan);
if (status == RA_NOMATCH)
{
scan = OPERAND(scan);
status = RA_CONT;
}
break;
case RS_NOMATCH:
/* Pop the state. If the operand matches for NOMATCH or
* doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
* except for SUBPAT, and continue with the next item. */
if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
status = RA_NOMATCH;
else
{
status = RA_CONT;
if (rp->rs_no != SUBPAT) /* zero-width */
reg_restore(&rp->rs_un.regsave, &backpos);
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BEHIND1:
if (status == RA_NOMATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
/* The stuff after BEHIND/NOBEHIND matches. Now try if
* the behind part does (not) match before the current
* position in the input. This must be done at every
* position in the input and checking if the match ends at
* the current position. */
/* save the position after the found match for next */
reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
/* start looking for a match with operand at the current
* position. Go back one character until we find the
* result, hitting the start of the line or the previous
* line (for multi-line matching).
* Set behind_pos to where the match should end, BHPOS
* will match it. Save the current value. */
(((regbehind_T *)rp) - 1)->save_behind = behind_pos;
behind_pos = rp->rs_un.regsave;
rp->rs_state = RS_BEHIND2;
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan);
}
break;
case RS_BEHIND2:
/*
* Looping for BEHIND / NOBEHIND match.
*/
if (status == RA_MATCH && reg_save_equal(&behind_pos))
{
/* found a match that ends where "next" started */
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == BEHIND)
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
else
{
/* But we didn't want a match. Need to restore the
* subexpr, because what follows matched, so they have
* been set. */
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
/* No match or a match that doesn't end where we want it: Go
* back one character. May go to previous line once. */
no = OK;
if (REG_MULTI)
{
if (rp->rs_un.regsave.rs_u.pos.col == 0)
{
if (rp->rs_un.regsave.rs_u.pos.lnum
< behind_pos.rs_u.pos.lnum
|| reg_getline(
--rp->rs_un.regsave.rs_u.pos.lnum)
== NULL)
no = FAIL;
else
{
reg_restore(&rp->rs_un.regsave, &backpos);
rp->rs_un.regsave.rs_u.pos.col =
(colnr_T)STRLEN(regline);
}
}
else
--rp->rs_un.regsave.rs_u.pos.col;
}
else
{
if (rp->rs_un.regsave.rs_u.ptr == regline)
no = FAIL;
else
--rp->rs_un.regsave.rs_u.ptr;
}
if (no == OK)
{
/* Advanced, prepare for finding match again. */
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan);
if (status == RA_MATCH)
{
/* We did match, so subexpr may have been changed,
* need to restore them for the next try. */
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
else
{
/* Can't advance. For NOBEHIND that's a match. */
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == NOBEHIND)
{
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
status = RA_MATCH;
}
else
{
/* We do want a proper match. Need to restore the
* subexpr if we had a match, because they may have
* been set. */
if (status == RA_MATCH)
{
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
}
break;
case RS_STAR_LONG:
case RS_STAR_SHORT:
{
regstar_T *rst = ((regstar_T *)rp) - 1;
if (status == RA_MATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
break;
}
/* Tried once already, restore input pointers. */
if (status != RA_BREAK)
reg_restore(&rp->rs_un.regsave, &backpos);
/* Repeat until we found a position where it could match. */
for (;;)
{
if (status != RA_BREAK)
{
/* Tried first position already, advance. */
if (rp->rs_state == RS_STAR_LONG)
{
/* Trying for longest match, but couldn't or
* didn't match -- back up one char. */
if (--rst->count < rst->minval)
break;
if (reginput == regline)
{
/* backup to last char of previous line */
--reglnum;
regline = reg_getline(reglnum);
/* Just in case regrepeat() didn't count
* right. */
if (regline == NULL)
break;
reginput = regline + STRLEN(regline);
fast_breakcheck();
}
else
mb_ptr_back(regline, reginput);
}
else
{
/* Range is backwards, use shortest match first.
* Careful: maxval and minval are exchanged!
* Couldn't or didn't match: try advancing one
* char. */
if (rst->count == rst->minval
|| regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
break;
++rst->count;
}
if (got_int)
break;
}
else
status = RA_NOMATCH;
/* If it could match, try it. */
if (rst->nextb == NUL || *reginput == rst->nextb
|| *reginput == rst->nextb_ic)
{
reg_save(&rp->rs_un.regsave, &backpos);
scan = regnext(rp->rs_scan);
status = RA_CONT;
break;
}
}
if (status != RA_CONT)
{
/* Failed. */
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
status = RA_NOMATCH;
}
}
break;
}
/* If we want to continue the inner loop or didn't pop a state
* continue matching loop */
if (status == RA_CONT || rp == (regitem_T *)
((char *)regstack.ga_data + regstack.ga_len) - 1)
break;
}
/* May need to continue with the inner loop, starting at "scan". */
if (status == RA_CONT)
continue;
/*
* If the regstack is empty or something failed we are done.
*/
if (regstack.ga_len == 0 || status == RA_FAIL)
{
if (scan == NULL)
{
/*
* We get here only if there's trouble -- normally "case END" is
* the terminating point.
*/
EMSG(_(e_re_corr));
#ifdef DEBUG
printf("Premature EOL\n");
#endif
}
if (status == RA_FAIL)
got_int = TRUE;
return (status == RA_MATCH);
}
} /* End of loop until the regstack is empty. */
/* NOTREACHED */
}
/*
* Push an item onto the regstack.
* Returns pointer to new item. Returns NULL when out of memory.
*/
static regitem_T *
regstack_push(state, scan)
regstate_T state;
char_u *scan;
{
regitem_T *rp;
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
EMSG(_(e_maxmempat));
return NULL;
}
if (ga_grow(®stack, sizeof(regitem_T)) == FAIL)
return NULL;
rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len);
rp->rs_state = state;
rp->rs_scan = scan;
regstack.ga_len += sizeof(regitem_T);
return rp;
}
/*
* Pop an item from the regstack.
*/
static void
regstack_pop(scan)
char_u **scan;
{
regitem_T *rp;
rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
*scan = rp->rs_scan;
regstack.ga_len -= sizeof(regitem_T);
}
/*
* regrepeat - repeatedly match something simple, return how many.
* Advances reginput (and reglnum) to just after the matched chars.
*/
static int
regrepeat(p, maxcount)
char_u *p;
long maxcount; /* maximum number of matches allowed */
{
long count = 0;
char_u *scan;
char_u *opnd;
int mask;
int testval = 0;
scan = reginput; /* Make local copy of reginput for speed. */
opnd = OPERAND(p);
switch (OP(p))
{
case ANY:
case ANY + ADD_NL:
while (count < maxcount)
{
/* Matching anything means we continue until end-of-line (or
* end-of-file for ANY + ADD_NL), only limited by maxcount. */
while (*scan != NUL && count < maxcount)
{
++count;
mb_ptr_adv(scan);
}
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr || count == maxcount)
break;
++count; /* count the line-break */
reg_nextline();
scan = reginput;
if (got_int)
break;
}
break;
case IDENT:
case IDENT + ADD_NL:
testval = TRUE;
/*FALLTHROUGH*/
case SIDENT:
case SIDENT + ADD_NL:
while (count < maxcount)
{
if (vim_isIDc(*scan) && (testval || !VIM_ISDIGIT(*scan)))
{
mb_ptr_adv(scan);
}
else if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
else
break;
++count;
}
break;
case KWORD:
case KWORD + ADD_NL:
testval = TRUE;
/*FALLTHROUGH*/
case SKWORD:
case SKWORD + ADD_NL:
while (count < maxcount)
{
if (vim_iswordp(scan) && (testval || !VIM_ISDIGIT(*scan)))
{
mb_ptr_adv(scan);
}
else if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
else
break;
++count;
}
break;
case FNAME:
case FNAME + ADD_NL:
testval = TRUE;
/*FALLTHROUGH*/
case SFNAME:
case SFNAME + ADD_NL:
while (count < maxcount)
{
if (vim_isfilec(*scan) && (testval || !VIM_ISDIGIT(*scan)))
{
mb_ptr_adv(scan);
}
else if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
else
break;
++count;
}
break;
case PRINT:
case PRINT + ADD_NL:
testval = TRUE;
/*FALLTHROUGH*/
case SPRINT:
case SPRINT + ADD_NL:
while (count < maxcount)
{
if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
else if (ptr2cells(scan) == 1 && (testval || !VIM_ISDIGIT(*scan)))
{
mb_ptr_adv(scan);
}
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
else
break;
++count;
}
break;
case WHITE:
case WHITE + ADD_NL:
testval = mask = RI_WHITE;
do_class:
while (count < maxcount)
{
#ifdef FEAT_MBYTE
int l;
#endif
if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
#ifdef FEAT_MBYTE
else if (has_mbyte && (l = (*mb_ptr2len)(scan)) > 1)
{
if (testval != 0)
break;
scan += l;
}
#endif
else if ((class_tab[*scan] & mask) == testval)
++scan;
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
else
break;
++count;
}
break;
case NWHITE:
case NWHITE + ADD_NL:
mask = RI_WHITE;
goto do_class;
case DIGIT:
case DIGIT + ADD_NL:
testval = mask = RI_DIGIT;
goto do_class;
case NDIGIT:
case NDIGIT + ADD_NL:
mask = RI_DIGIT;
goto do_class;
case HEX:
case HEX + ADD_NL:
testval = mask = RI_HEX;
goto do_class;
case NHEX:
case NHEX + ADD_NL:
mask = RI_HEX;
goto do_class;
case OCTAL:
case OCTAL + ADD_NL:
testval = mask = RI_OCTAL;
goto do_class;
case NOCTAL:
case NOCTAL + ADD_NL:
mask = RI_OCTAL;
goto do_class;
case WORD:
case WORD + ADD_NL:
testval = mask = RI_WORD;
goto do_class;
case NWORD:
case NWORD + ADD_NL:
mask = RI_WORD;
goto do_class;
case HEAD:
case HEAD + ADD_NL:
testval = mask = RI_HEAD;
goto do_class;
case NHEAD:
case NHEAD + ADD_NL:
mask = RI_HEAD;
goto do_class;
case ALPHA:
case ALPHA + ADD_NL:
testval = mask = RI_ALPHA;
goto do_class;
case NALPHA:
case NALPHA + ADD_NL:
mask = RI_ALPHA;
goto do_class;
case LOWER:
case LOWER + ADD_NL:
testval = mask = RI_LOWER;
goto do_class;
case NLOWER:
case NLOWER + ADD_NL:
mask = RI_LOWER;
goto do_class;
case UPPER:
case UPPER + ADD_NL:
testval = mask = RI_UPPER;
goto do_class;
case NUPPER:
case NUPPER + ADD_NL:
mask = RI_UPPER;
goto do_class;
case EXACTLY:
{
int cu, cl;
/* This doesn't do a multi-byte character, because a MULTIBYTECODE
* would have been used for it. It does handle single-byte
* characters, such as latin1. */
if (ireg_ic)
{
cu = MB_TOUPPER(*opnd);
cl = MB_TOLOWER(*opnd);
while (count < maxcount && (*scan == cu || *scan == cl))
{
count++;
scan++;
}
}
else
{
cu = *opnd;
while (count < maxcount && *scan == cu)
{
count++;
scan++;
}
}
break;
}
#ifdef FEAT_MBYTE
case MULTIBYTECODE:
{
int i, len, cf = 0;
/* Safety check (just in case 'encoding' was changed since
* compiling the program). */
if ((len = (*mb_ptr2len)(opnd)) > 1)
{
if (ireg_ic && enc_utf8)
cf = utf_fold(utf_ptr2char(opnd));
while (count < maxcount)
{
for (i = 0; i < len; ++i)
if (opnd[i] != scan[i])
break;
if (i < len && (!ireg_ic || !enc_utf8
|| utf_fold(utf_ptr2char(scan)) != cf))
break;
scan += len;
++count;
}
}
}
break;
#endif
case ANYOF:
case ANYOF + ADD_NL:
testval = TRUE;
/*FALLTHROUGH*/
case ANYBUT:
case ANYBUT + ADD_NL:
while (count < maxcount)
{
#ifdef FEAT_MBYTE
int len;
#endif
if (*scan == NUL)
{
if (!REG_MULTI || !WITH_NL(OP(p)) || reglnum > reg_maxline
|| reg_line_lbr)
break;
reg_nextline();
scan = reginput;
if (got_int)
break;
}
else if (reg_line_lbr && *scan == '\n' && WITH_NL(OP(p)))
++scan;
#ifdef FEAT_MBYTE
else if (has_mbyte && (len = (*mb_ptr2len)(scan)) > 1)
{
if ((cstrchr(opnd, (*mb_ptr2char)(scan)) == NULL) == testval)
break;
scan += len;
}
#endif
else
{
if ((cstrchr(opnd, *scan) == NULL) == testval)
break;
++scan;
}
++count;
}
break;
case NEWL:
while (count < maxcount
&& ((*scan == NUL && reglnum <= reg_maxline && !reg_line_lbr
&& REG_MULTI) || (*scan == '\n' && reg_line_lbr)))
{
count++;
if (reg_line_lbr)
ADVANCE_REGINPUT();
else
reg_nextline();
scan = reginput;
if (got_int)
break;
}
break;
default: /* Oh dear. Called inappropriately. */
EMSG(_(e_re_corr));
#ifdef DEBUG
printf("Called regrepeat with op code %d\n", OP(p));
#endif
break;
}
reginput = scan;
return (int)count;
}
/*
* regnext - dig the "next" pointer out of a node
* Returns NULL when calculating size, when there is no next item and when
* there is an error.
*/
static char_u *
regnext(p)
char_u *p;
{
int offset;
if (p == JUST_CALC_SIZE || reg_toolong)
return NULL;
offset = NEXT(p);
if (offset == 0)
return NULL;
if (OP(p) == BACK)
return p - offset;
else
return p + offset;
}
/*
* Check the regexp program for its magic number.
* Return TRUE if it's wrong.
*/
static int
prog_magic_wrong()
{
if (UCHARAT(REG_MULTI
? reg_mmatch->regprog->program
: reg_match->regprog->program) != REGMAGIC)
{
EMSG(_(e_re_corr));
return TRUE;
}
return FALSE;
}
/*
* Cleanup the subexpressions, if this wasn't done yet.
* This construction is used to clear the subexpressions only when they are
* used (to increase speed).
*/
static void
cleanup_subexpr()
{
if (need_clear_subexpr)
{
if (REG_MULTI)
{
/* Use 0xff to set lnum to -1 */
vim_memset(reg_startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
vim_memset(reg_endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
}
else
{
vim_memset(reg_startp, 0, sizeof(char_u *) * NSUBEXP);
vim_memset(reg_endp, 0, sizeof(char_u *) * NSUBEXP);
}
need_clear_subexpr = FALSE;
}
}
#ifdef FEAT_SYN_HL
static void
cleanup_zsubexpr()
{
if (need_clear_zsubexpr)
{
if (REG_MULTI)
{
/* Use 0xff to set lnum to -1 */
vim_memset(reg_startzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
vim_memset(reg_endzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
}
else
{
vim_memset(reg_startzp, 0, sizeof(char_u *) * NSUBEXP);
vim_memset(reg_endzp, 0, sizeof(char_u *) * NSUBEXP);
}
need_clear_zsubexpr = FALSE;
}
}
#endif
/*
* Save the current subexpr to "bp", so that they can be restored
* later by restore_subexpr().
*/
static void
save_subexpr(bp)
regbehind_T *bp;
{
int i;
/* When "need_clear_subexpr" is set we don't need to save the values, only
* remember that this flag needs to be set again when restoring. */
bp->save_need_clear_subexpr = need_clear_subexpr;
if (!need_clear_subexpr)
{
for (i = 0; i < NSUBEXP; ++i)
{
if (REG_MULTI)
{
bp->save_start[i].se_u.pos = reg_startpos[i];
bp->save_end[i].se_u.pos = reg_endpos[i];
}
else
{
bp->save_start[i].se_u.ptr = reg_startp[i];
bp->save_end[i].se_u.ptr = reg_endp[i];
}
}
}
}
/*
* Restore the subexpr from "bp".
*/
static void
restore_subexpr(bp)
regbehind_T *bp;
{
int i;
/* Only need to restore saved values when they are not to be cleared. */
need_clear_subexpr = bp->save_need_clear_subexpr;
if (!need_clear_subexpr)
{
for (i = 0; i < NSUBEXP; ++i)
{
if (REG_MULTI)
{
reg_startpos[i] = bp->save_start[i].se_u.pos;
reg_endpos[i] = bp->save_end[i].se_u.pos;
}
else
{
reg_startp[i] = bp->save_start[i].se_u.ptr;
reg_endp[i] = bp->save_end[i].se_u.ptr;
}
}
}
}
/*
* Advance reglnum, regline and reginput to the next line.
*/
static void
reg_nextline()
{
regline = reg_getline(++reglnum);
reginput = regline;
fast_breakcheck();
}
/*
* Save the input line and position in a regsave_T.
*/
static void
reg_save(save, gap)
regsave_T *save;
garray_T *gap;
{
if (REG_MULTI)
{
save->rs_u.pos.col = (colnr_T)(reginput - regline);
save->rs_u.pos.lnum = reglnum;
}
else
save->rs_u.ptr = reginput;
save->rs_len = gap->ga_len;
}
/*
* Restore the input line and position from a regsave_T.
*/
static void
reg_restore(save, gap)
regsave_T *save;
garray_T *gap;
{
if (REG_MULTI)
{
if (reglnum != save->rs_u.pos.lnum)
{
/* only call reg_getline() when the line number changed to save
* a bit of time */
reglnum = save->rs_u.pos.lnum;
regline = reg_getline(reglnum);
}
reginput = regline + save->rs_u.pos.col;
}
else
reginput = save->rs_u.ptr;
gap->ga_len = save->rs_len;
}
/*
* Return TRUE if current position is equal to saved position.
*/
static int
reg_save_equal(save)
regsave_T *save;
{
if (REG_MULTI)
return reglnum == save->rs_u.pos.lnum
&& reginput == regline + save->rs_u.pos.col;
return reginput == save->rs_u.ptr;
}
/*
* Tentatively set the sub-expression start to the current position (after
* calling regmatch() they will have changed). Need to save the existing
* values for when there is no match.
* Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
* depending on REG_MULTI.
*/
static void
save_se_multi(savep, posp)
save_se_T *savep;
lpos_T *posp;
{
savep->se_u.pos = *posp;
posp->lnum = reglnum;
posp->col = (colnr_T)(reginput - regline);
}
static void
save_se_one(savep, pp)
save_se_T *savep;
char_u **pp;
{
savep->se_u.ptr = *pp;
*pp = reginput;
}
/*
* Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
*/
static int
re_num_cmp(val, scan)
long_u val;
char_u *scan;
{
long_u n = OPERAND_MIN(scan);
if (OPERAND_CMP(scan) == '>')
return val > n;
if (OPERAND_CMP(scan) == '<')
return val < n;
return val == n;
}
#ifdef DEBUG
/*
* regdump - dump a regexp onto stdout in vaguely comprehensible form
*/
static void
regdump(pattern, r)
char_u *pattern;
regprog_T *r;
{
char_u *s;
int op = EXACTLY; /* Arbitrary non-END op. */
char_u *next;
char_u *end = NULL;
printf("\r\nregcomp(%s):\r\n", pattern);
s = r->program + 1;
/*
* Loop until we find the END that isn't before a referred next (an END
* can also appear in a NOMATCH operand).
*/
while (op != END || s <= end)
{
op = OP(s);
printf("%2d%s", (int)(s - r->program), regprop(s)); /* Where, what. */
next = regnext(s);
if (next == NULL) /* Next ptr. */
printf("(0)");
else
printf("(%d)", (int)((s - r->program) + (next - s)));
if (end < next)
end = next;
if (op == BRACE_LIMITS)
{
/* Two short ints */
printf(" minval %ld, maxval %ld", OPERAND_MIN(s), OPERAND_MAX(s));
s += 8;
}
s += 3;
if (op == ANYOF || op == ANYOF + ADD_NL
|| op == ANYBUT || op == ANYBUT + ADD_NL
|| op == EXACTLY)
{
/* Literal string, where present. */
while (*s != NUL)
printf("%c", *s++);
s++;
}
printf("\r\n");
}
/* Header fields of interest. */
if (r->regstart != NUL)
printf("start `%s' 0x%x; ", r->regstart < 256
? (char *)transchar(r->regstart)
: "multibyte", r->regstart);
if (r->reganch)
printf("anchored; ");
if (r->regmust != NULL)
printf("must have \"%s\"", r->regmust);
printf("\r\n");
}
/*
* regprop - printable representation of opcode
*/
static char_u *
regprop(op)
char_u *op;
{
char_u *p;
static char_u buf[50];
(void) strcpy(buf, ":");
switch (OP(op))
{
case BOL:
p = "BOL";
break;
case EOL:
p = "EOL";
break;
case RE_BOF:
p = "BOF";
break;
case RE_EOF:
p = "EOF";
break;
case CURSOR:
p = "CURSOR";
break;
case RE_VISUAL:
p = "RE_VISUAL";
break;
case RE_LNUM:
p = "RE_LNUM";
break;
case RE_MARK:
p = "RE_MARK";
break;
case RE_COL:
p = "RE_COL";
break;
case RE_VCOL:
p = "RE_VCOL";
break;
case BOW:
p = "BOW";
break;
case EOW:
p = "EOW";
break;
case ANY:
p = "ANY";
break;
case ANY + ADD_NL:
p = "ANY+NL";
break;
case ANYOF:
p = "ANYOF";
break;
case ANYOF + ADD_NL:
p = "ANYOF+NL";
break;
case ANYBUT:
p = "ANYBUT";
break;
case ANYBUT + ADD_NL:
p = "ANYBUT+NL";
break;
case IDENT:
p = "IDENT";
break;
case IDENT + ADD_NL:
p = "IDENT+NL";
break;
case SIDENT:
p = "SIDENT";
break;
case SIDENT + ADD_NL:
p = "SIDENT+NL";
break;
case KWORD:
p = "KWORD";
break;
case KWORD + ADD_NL:
p = "KWORD+NL";
break;
case SKWORD:
p = "SKWORD";
break;
case SKWORD + ADD_NL:
p = "SKWORD+NL";
break;
case FNAME:
p = "FNAME";
break;
case FNAME + ADD_NL:
p = "FNAME+NL";
break;
case SFNAME:
p = "SFNAME";
break;
case SFNAME + ADD_NL:
p = "SFNAME+NL";
break;
case PRINT:
p = "PRINT";
break;
case PRINT + ADD_NL:
p = "PRINT+NL";
break;
case SPRINT:
p = "SPRINT";
break;
case SPRINT + ADD_NL:
p = "SPRINT+NL";
break;
case WHITE:
p = "WHITE";
break;
case WHITE + ADD_NL:
p = "WHITE+NL";
break;
case NWHITE:
p = "NWHITE";
break;
case NWHITE + ADD_NL:
p = "NWHITE+NL";
break;
case DIGIT:
p = "DIGIT";
break;
case DIGIT + ADD_NL:
p = "DIGIT+NL";
break;
case NDIGIT:
p = "NDIGIT";
break;
case NDIGIT + ADD_NL:
p = "NDIGIT+NL";
break;
case HEX:
p = "HEX";
break;
case HEX + ADD_NL:
p = "HEX+NL";
break;
case NHEX:
p = "NHEX";
break;
case NHEX + ADD_NL:
p = "NHEX+NL";
break;
case OCTAL:
p = "OCTAL";
break;
case OCTAL + ADD_NL:
p = "OCTAL+NL";
break;
case NOCTAL:
p = "NOCTAL";
break;
case NOCTAL + ADD_NL:
p = "NOCTAL+NL";
break;
case WORD:
p = "WORD";
break;
case WORD + ADD_NL:
p = "WORD+NL";
break;
case NWORD:
p = "NWORD";
break;
case NWORD + ADD_NL:
p = "NWORD+NL";
break;
case HEAD:
p = "HEAD";
break;
case HEAD + ADD_NL:
p = "HEAD+NL";
break;
case NHEAD:
p = "NHEAD";
break;
case NHEAD + ADD_NL:
p = "NHEAD+NL";
break;
case ALPHA:
p = "ALPHA";
break;
case ALPHA + ADD_NL:
p = "ALPHA+NL";
break;
case NALPHA:
p = "NALPHA";
break;
case NALPHA + ADD_NL:
p = "NALPHA+NL";
break;
case LOWER:
p = "LOWER";
break;
case LOWER + ADD_NL:
p = "LOWER+NL";
break;
case NLOWER:
p = "NLOWER";
break;
case NLOWER + ADD_NL:
p = "NLOWER+NL";
break;
case UPPER:
p = "UPPER";
break;
case UPPER + ADD_NL:
p = "UPPER+NL";
break;
case NUPPER:
p = "NUPPER";
break;
case NUPPER + ADD_NL:
p = "NUPPER+NL";
break;
case BRANCH:
p = "BRANCH";
break;
case EXACTLY:
p = "EXACTLY";
break;
case NOTHING:
p = "NOTHING";
break;
case BACK:
p = "BACK";
break;
case END:
p = "END";
break;
case MOPEN + 0:
p = "MATCH START";
break;
case MOPEN + 1:
case MOPEN + 2:
case MOPEN + 3:
case MOPEN + 4:
case MOPEN + 5:
case MOPEN + 6:
case MOPEN + 7:
case MOPEN + 8:
case MOPEN + 9:
sprintf(buf + STRLEN(buf), "MOPEN%d", OP(op) - MOPEN);
p = NULL;
break;
case MCLOSE + 0:
p = "MATCH END";
break;
case MCLOSE + 1:
case MCLOSE + 2:
case MCLOSE + 3:
case MCLOSE + 4:
case MCLOSE + 5:
case MCLOSE + 6:
case MCLOSE + 7:
case MCLOSE + 8:
case MCLOSE + 9:
sprintf(buf + STRLEN(buf), "MCLOSE%d", OP(op) - MCLOSE);
p = NULL;
break;
case BACKREF + 1:
case BACKREF + 2:
case BACKREF + 3:
case BACKREF + 4:
case BACKREF + 5:
case BACKREF + 6:
case BACKREF + 7:
case BACKREF + 8:
case BACKREF + 9:
sprintf(buf + STRLEN(buf), "BACKREF%d", OP(op) - BACKREF);
p = NULL;
break;
case NOPEN:
p = "NOPEN";
break;
case NCLOSE:
p = "NCLOSE";
break;
#ifdef FEAT_SYN_HL
case ZOPEN + 1:
case ZOPEN + 2:
case ZOPEN + 3:
case ZOPEN + 4:
case ZOPEN + 5:
case ZOPEN + 6:
case ZOPEN + 7:
case ZOPEN + 8:
case ZOPEN + 9:
sprintf(buf + STRLEN(buf), "ZOPEN%d", OP(op) - ZOPEN);
p = NULL;
break;
case ZCLOSE + 1:
case ZCLOSE + 2:
case ZCLOSE + 3:
case ZCLOSE + 4:
case ZCLOSE + 5:
case ZCLOSE + 6:
case ZCLOSE + 7:
case ZCLOSE + 8:
case ZCLOSE + 9:
sprintf(buf + STRLEN(buf), "ZCLOSE%d", OP(op) - ZCLOSE);
p = NULL;
break;
case ZREF + 1:
case ZREF + 2:
case ZREF + 3:
case ZREF + 4:
case ZREF + 5:
case ZREF + 6:
case ZREF + 7:
case ZREF + 8:
case ZREF + 9:
sprintf(buf + STRLEN(buf), "ZREF%d", OP(op) - ZREF);
p = NULL;
break;
#endif
case STAR:
p = "STAR";
break;
case PLUS:
p = "PLUS";
break;
case NOMATCH:
p = "NOMATCH";
break;
case MATCH:
p = "MATCH";
break;
case BEHIND:
p = "BEHIND";
break;
case NOBEHIND:
p = "NOBEHIND";
break;
case SUBPAT:
p = "SUBPAT";
break;
case BRACE_LIMITS:
p = "BRACE_LIMITS";
break;
case BRACE_SIMPLE:
p = "BRACE_SIMPLE";
break;
case BRACE_COMPLEX + 0:
case BRACE_COMPLEX + 1:
case BRACE_COMPLEX + 2:
case BRACE_COMPLEX + 3:
case BRACE_COMPLEX + 4:
case BRACE_COMPLEX + 5:
case BRACE_COMPLEX + 6:
case BRACE_COMPLEX + 7:
case BRACE_COMPLEX + 8:
case BRACE_COMPLEX + 9:
sprintf(buf + STRLEN(buf), "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
p = NULL;
break;
#ifdef FEAT_MBYTE
case MULTIBYTECODE:
p = "MULTIBYTECODE";
break;
#endif
case NEWL:
p = "NEWL";
break;
default:
sprintf(buf + STRLEN(buf), "corrupt %d", OP(op));
p = NULL;
break;
}
if (p != NULL)
(void) strcat(buf, p);
return buf;
}
#endif
#ifdef FEAT_MBYTE
static void mb_decompose __ARGS((int c, int *c1, int *c2, int *c3));
typedef struct
{
int a, b, c;
} decomp_T;
/* 0xfb20 - 0xfb4f */
static decomp_T decomp_table[0xfb4f-0xfb20+1] =
{
{0x5e2,0,0}, /* 0xfb20 alt ayin */
{0x5d0,0,0}, /* 0xfb21 alt alef */
{0x5d3,0,0}, /* 0xfb22 alt dalet */
{0x5d4,0,0}, /* 0xfb23 alt he */
{0x5db,0,0}, /* 0xfb24 alt kaf */
{0x5dc,0,0}, /* 0xfb25 alt lamed */
{0x5dd,0,0}, /* 0xfb26 alt mem-sofit */
{0x5e8,0,0}, /* 0xfb27 alt resh */
{0x5ea,0,0}, /* 0xfb28 alt tav */
{'+', 0, 0}, /* 0xfb29 alt plus */
{0x5e9, 0x5c1, 0}, /* 0xfb2a shin+shin-dot */
{0x5e9, 0x5c2, 0}, /* 0xfb2b shin+sin-dot */
{0x5e9, 0x5c1, 0x5bc}, /* 0xfb2c shin+shin-dot+dagesh */
{0x5e9, 0x5c2, 0x5bc}, /* 0xfb2d shin+sin-dot+dagesh */
{0x5d0, 0x5b7, 0}, /* 0xfb2e alef+patah */
{0x5d0, 0x5b8, 0}, /* 0xfb2f alef+qamats */
{0x5d0, 0x5b4, 0}, /* 0xfb30 alef+hiriq */
{0x5d1, 0x5bc, 0}, /* 0xfb31 bet+dagesh */
{0x5d2, 0x5bc, 0}, /* 0xfb32 gimel+dagesh */
{0x5d3, 0x5bc, 0}, /* 0xfb33 dalet+dagesh */
{0x5d4, 0x5bc, 0}, /* 0xfb34 he+dagesh */
{0x5d5, 0x5bc, 0}, /* 0xfb35 vav+dagesh */
{0x5d6, 0x5bc, 0}, /* 0xfb36 zayin+dagesh */
{0xfb37, 0, 0}, /* 0xfb37 -- UNUSED */
{0x5d8, 0x5bc, 0}, /* 0xfb38 tet+dagesh */
{0x5d9, 0x5bc, 0}, /* 0xfb39 yud+dagesh */
{0x5da, 0x5bc, 0}, /* 0xfb3a kaf sofit+dagesh */
{0x5db, 0x5bc, 0}, /* 0xfb3b kaf+dagesh */
{0x5dc, 0x5bc, 0}, /* 0xfb3c lamed+dagesh */
{0xfb3d, 0, 0}, /* 0xfb3d -- UNUSED */
{0x5de, 0x5bc, 0}, /* 0xfb3e mem+dagesh */
{0xfb3f, 0, 0}, /* 0xfb3f -- UNUSED */
{0x5e0, 0x5bc, 0}, /* 0xfb40 nun+dagesh */
{0x5e1, 0x5bc, 0}, /* 0xfb41 samech+dagesh */
{0xfb42, 0, 0}, /* 0xfb42 -- UNUSED */
{0x5e3, 0x5bc, 0}, /* 0xfb43 pe sofit+dagesh */
{0x5e4, 0x5bc,0}, /* 0xfb44 pe+dagesh */
{0xfb45, 0, 0}, /* 0xfb45 -- UNUSED */
{0x5e6, 0x5bc, 0}, /* 0xfb46 tsadi+dagesh */
{0x5e7, 0x5bc, 0}, /* 0xfb47 qof+dagesh */
{0x5e8, 0x5bc, 0}, /* 0xfb48 resh+dagesh */
{0x5e9, 0x5bc, 0}, /* 0xfb49 shin+dagesh */
{0x5ea, 0x5bc, 0}, /* 0xfb4a tav+dagesh */
{0x5d5, 0x5b9, 0}, /* 0xfb4b vav+holam */
{0x5d1, 0x5bf, 0}, /* 0xfb4c bet+rafe */
{0x5db, 0x5bf, 0}, /* 0xfb4d kaf+rafe */
{0x5e4, 0x5bf, 0}, /* 0xfb4e pe+rafe */
{0x5d0, 0x5dc, 0} /* 0xfb4f alef-lamed */
};
static void
mb_decompose(c, c1, c2, c3)
int c, *c1, *c2, *c3;
{
decomp_T d;
if (c >= 0x4b20 && c <= 0xfb4f)
{
d = decomp_table[c - 0xfb20];
*c1 = d.a;
*c2 = d.b;
*c3 = d.c;
}
else
{
*c1 = c;
*c2 = *c3 = 0;
}
}
#endif
/*
* Compare two strings, ignore case if ireg_ic set.
* Return 0 if strings match, non-zero otherwise.
* Correct the length "*n" when composing characters are ignored.
*/
static int
cstrncmp(s1, s2, n)
char_u *s1, *s2;
int *n;
{
int result;
if (!ireg_ic)
result = STRNCMP(s1, s2, *n);
else
result = MB_STRNICMP(s1, s2, *n);
#ifdef FEAT_MBYTE
/* if it failed and it's utf8 and we want to combineignore: */
if (result != 0 && enc_utf8 && ireg_icombine)
{
char_u *str1, *str2;
int c1, c2, c11, c12;
int junk;
/* we have to handle the strcmp ourselves, since it is necessary to
* deal with the composing characters by ignoring them: */
str1 = s1;
str2 = s2;
c1 = c2 = 0;
while ((int)(str1 - s1) < *n)
{
c1 = mb_ptr2char_adv(&str1);
c2 = mb_ptr2char_adv(&str2);
/* decompose the character if necessary, into 'base' characters
* because I don't care about Arabic, I will hard-code the Hebrew
* which I *do* care about! So sue me... */
if (c1 != c2 && (!ireg_ic || utf_fold(c1) != utf_fold(c2)))
{
/* decomposition necessary? */
mb_decompose(c1, &c11, &junk, &junk);
mb_decompose(c2, &c12, &junk, &junk);
c1 = c11;
c2 = c12;
if (c11 != c12 && (!ireg_ic || utf_fold(c11) != utf_fold(c12)))
break;
}
}
result = c2 - c1;
if (result == 0)
*n = (int)(str2 - s2);
}
#endif
return result;
}
/*
* cstrchr: This function is used a lot for simple searches, keep it fast!
*/
static char_u *
cstrchr(s, c)
char_u *s;
int c;
{
char_u *p;
int cc;
if (!ireg_ic
#ifdef FEAT_MBYTE
|| (!enc_utf8 && mb_char2len(c) > 1)
#endif
)
return vim_strchr(s, c);
/* tolower() and toupper() can be slow, comparing twice should be a lot
* faster (esp. when using MS Visual C++!).
* For UTF-8 need to use folded case. */
#ifdef FEAT_MBYTE
if (enc_utf8 && c > 0x80)
cc = utf_fold(c);
else
#endif
if (MB_ISUPPER(c))
cc = MB_TOLOWER(c);
else if (MB_ISLOWER(c))
cc = MB_TOUPPER(c);
else
return vim_strchr(s, c);
#ifdef FEAT_MBYTE
if (has_mbyte)
{
for (p = s; *p != NUL; p += (*mb_ptr2len)(p))
{
if (enc_utf8 && c > 0x80)
{
if (utf_fold(utf_ptr2char(p)) == cc)
return p;
}
else if (*p == c || *p == cc)
return p;
}
}
else
#endif
/* Faster version for when there are no multi-byte characters. */
for (p = s; *p != NUL; ++p)
if (*p == c || *p == cc)
return p;
return NULL;
}
/***************************************************************
* regsub stuff *
***************************************************************/
/* This stuff below really confuses cc on an SGI -- webb */
#ifdef __sgi
# undef __ARGS
# define __ARGS(x) ()
#endif
/*
* We should define ftpr as a pointer to a function returning a pointer to
* a function returning a pointer to a function ...
* This is impossible, so we declare a pointer to a function returning a
* pointer to a function returning void. This should work for all compilers.
*/
typedef void (*(*fptr_T) __ARGS((int *, int)))();
static fptr_T do_upper __ARGS((int *, int));
static fptr_T do_Upper __ARGS((int *, int));
static fptr_T do_lower __ARGS((int *, int));
static fptr_T do_Lower __ARGS((int *, int));
static int vim_regsub_both __ARGS((char_u *source, char_u *dest, int copy, int magic, int backslash));
static fptr_T
do_upper(d, c)
int *d;
int c;
{
*d = MB_TOUPPER(c);
return (fptr_T)NULL;
}
static fptr_T
do_Upper(d, c)
int *d;
int c;
{
*d = MB_TOUPPER(c);
return (fptr_T)do_Upper;
}
static fptr_T
do_lower(d, c)
int *d;
int c;
{
*d = MB_TOLOWER(c);
return (fptr_T)NULL;
}
static fptr_T
do_Lower(d, c)
int *d;
int c;
{
*d = MB_TOLOWER(c);
return (fptr_T)do_Lower;
}
/*
* regtilde(): Replace tildes in the pattern by the old pattern.
*
* Short explanation of the tilde: It stands for the previous replacement
* pattern. If that previous pattern also contains a ~ we should go back a
* step further... But we insert the previous pattern into the current one
* and remember that.
* This still does not handle the case where "magic" changes. So require the
* user to keep his hands off of "magic".
*
* The tildes are parsed once before the first call to vim_regsub().
*/
char_u *
regtilde(source, magic)
char_u *source;
int magic;
{
char_u *newsub = source;
char_u *tmpsub;
char_u *p;
int len;
int prevlen;
for (p = newsub; *p; ++p)
{
if ((*p == '~' && magic) || (*p == '\\' && *(p + 1) == '~' && !magic))
{
if (reg_prev_sub != NULL)
{
/* length = len(newsub) - 1 + len(prev_sub) + 1 */
prevlen = (int)STRLEN(reg_prev_sub);
tmpsub = alloc((unsigned)(STRLEN(newsub) + prevlen));
if (tmpsub != NULL)
{
/* copy prefix */
len = (int)(p - newsub); /* not including ~ */
mch_memmove(tmpsub, newsub, (size_t)len);
/* interpret tilde */
mch_memmove(tmpsub + len, reg_prev_sub, (size_t)prevlen);
/* copy postfix */
if (!magic)
++p; /* back off \ */
STRCPY(tmpsub + len + prevlen, p + 1);
if (newsub != source) /* already allocated newsub */
vim_free(newsub);
newsub = tmpsub;
p = newsub + len + prevlen;
}
}
else if (magic)
STRMOVE(p, p + 1); /* remove '~' */
else
STRMOVE(p, p + 2); /* remove '\~' */
--p;
}
else
{
if (*p == '\\' && p[1]) /* skip escaped characters */
++p;
#ifdef FEAT_MBYTE
if (has_mbyte)
p += (*mb_ptr2len)(p) - 1;
#endif
}
}
vim_free(reg_prev_sub);
if (newsub != source) /* newsub was allocated, just keep it */
reg_prev_sub = newsub;
else /* no ~ found, need to save newsub */
reg_prev_sub = vim_strsave(newsub);
return newsub;
}
#ifdef FEAT_EVAL
static int can_f_submatch = FALSE; /* TRUE when submatch() can be used */
/* These pointers are used instead of reg_match and reg_mmatch for
* reg_submatch(). Needed for when the substitution string is an expression
* that contains a call to substitute() and submatch(). */
static regmatch_T *submatch_match;
static regmmatch_T *submatch_mmatch;
static linenr_T submatch_firstlnum;
static linenr_T submatch_maxline;
static int submatch_line_lbr;
#endif
#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
/*
* vim_regsub() - perform substitutions after a vim_regexec() or
* vim_regexec_multi() match.
*
* If "copy" is TRUE really copy into "dest".
* If "copy" is FALSE nothing is copied, this is just to find out the length
* of the result.
*
* If "backslash" is TRUE, a backslash will be removed later, need to double
* them to keep them, and insert a backslash before a CR to avoid it being
* replaced with a line break later.
*
* Note: The matched text must not change between the call of
* vim_regexec()/vim_regexec_multi() and vim_regsub()! It would make the back
* references invalid!
*
* Returns the size of the replacement, including terminating NUL.
*/
int
vim_regsub(rmp, source, dest, copy, magic, backslash)
regmatch_T *rmp;
char_u *source;
char_u *dest;
int copy;
int magic;
int backslash;
{
reg_match = rmp;
reg_mmatch = NULL;
reg_maxline = 0;
return vim_regsub_both(source, dest, copy, magic, backslash);
}
#endif
int
vim_regsub_multi(rmp, lnum, source, dest, copy, magic, backslash)
regmmatch_T *rmp;
linenr_T lnum;
char_u *source;
char_u *dest;
int copy;
int magic;
int backslash;
{
reg_match = NULL;
reg_mmatch = rmp;
reg_buf = curbuf; /* always works on the current buffer! */
reg_firstlnum = lnum;
reg_maxline = curbuf->b_ml.ml_line_count - lnum;
return vim_regsub_both(source, dest, copy, magic, backslash);
}
static int
vim_regsub_both(source, dest, copy, magic, backslash)
char_u *source;
char_u *dest;
int copy;
int magic;
int backslash;
{
char_u *src;
char_u *dst;
char_u *s;
int c;
int cc;
int no = -1;
fptr_T func = (fptr_T)NULL;
linenr_T clnum = 0; /* init for GCC */
int len = 0; /* init for GCC */
#ifdef FEAT_EVAL
static char_u *eval_result = NULL;
#endif
/* Be paranoid... */
if (source == NULL || dest == NULL)
{
EMSG(_(e_null));
return 0;
}
if (prog_magic_wrong())
return 0;
src = source;
dst = dest;
/*
* When the substitute part starts with "\=" evaluate it as an expression.
*/
if (source[0] == '\\' && source[1] == '='
#ifdef FEAT_EVAL
&& !can_f_submatch /* can't do this recursively */
#endif
)
{
#ifdef FEAT_EVAL
/* To make sure that the length doesn't change between checking the
* length and copying the string, and to speed up things, the
* resulting string is saved from the call with "copy" == FALSE to the
* call with "copy" == TRUE. */
if (copy)
{
if (eval_result != NULL)
{
STRCPY(dest, eval_result);
dst += STRLEN(eval_result);
vim_free(eval_result);
eval_result = NULL;
}
}
else
{
win_T *save_reg_win;
int save_ireg_ic;
vim_free(eval_result);
/* The expression may contain substitute(), which calls us
* recursively. Make sure submatch() gets the text from the first
* level. Don't need to save "reg_buf", because
* vim_regexec_multi() can't be called recursively. */
submatch_match = reg_match;
submatch_mmatch = reg_mmatch;
submatch_firstlnum = reg_firstlnum;
submatch_maxline = reg_maxline;
submatch_line_lbr = reg_line_lbr;
save_reg_win = reg_win;
save_ireg_ic = ireg_ic;
can_f_submatch = TRUE;
eval_result = eval_to_string(source + 2, NULL, TRUE);
if (eval_result != NULL)
{
int had_backslash = FALSE;
for (s = eval_result; *s != NUL; mb_ptr_adv(s))
{
/* Change NL to CR, so that it becomes a line break,
* unless called from vim_regexec_nl().
* Skip over a backslashed character. */
if (*s == NL && !submatch_line_lbr)
*s = CAR;
else if (*s == '\\' && s[1] != NUL)
{
++s;
/* Change NL to CR here too, so that this works:
* :s/abc\\\ndef/\="aaa\\\nbbb"/ on text:
* abc\
* def
* Not when called from vim_regexec_nl().
*/
if (*s == NL && !submatch_line_lbr)
*s = CAR;
had_backslash = TRUE;
}
}
if (had_backslash && backslash)
{
/* Backslashes will be consumed, need to double them. */
s = vim_strsave_escaped(eval_result, (char_u *)"\\");
if (s != NULL)
{
vim_free(eval_result);
eval_result = s;
}
}
dst += STRLEN(eval_result);
}
reg_match = submatch_match;
reg_mmatch = submatch_mmatch;
reg_firstlnum = submatch_firstlnum;
reg_maxline = submatch_maxline;
reg_line_lbr = submatch_line_lbr;
reg_win = save_reg_win;
ireg_ic = save_ireg_ic;
can_f_submatch = FALSE;
}
#endif
}
else
while ((c = *src++) != NUL)
{
if (c == '&' && magic)
no = 0;
else if (c == '\\' && *src != NUL)
{
if (*src == '&' && !magic)
{
++src;
no = 0;
}
else if ('0' <= *src && *src <= '9')
{
no = *src++ - '0';
}
else if (vim_strchr((char_u *)"uUlLeE", *src))
{
switch (*src++)
{
case 'u': func = (fptr_T)do_upper;
continue;
case 'U': func = (fptr_T)do_Upper;
continue;
case 'l': func = (fptr_T)do_lower;
continue;
case 'L': func = (fptr_T)do_Lower;
continue;
case 'e':
case 'E': func = (fptr_T)NULL;
continue;
}
}
}
if (no < 0) /* Ordinary character. */
{
if (c == K_SPECIAL && src[0] != NUL && src[1] != NUL)
{
/* Copy a special key as-is. */
if (copy)
{
*dst++ = c;
*dst++ = *src++;
*dst++ = *src++;
}
else
{
dst += 3;
src += 2;
}
continue;
}
if (c == '\\' && *src != NUL)
{
/* Check for abbreviations -- webb */
switch (*src)
{
case 'r': c = CAR; ++src; break;
case 'n': c = NL; ++src; break;
case 't': c = TAB; ++src; break;
/* Oh no! \e already has meaning in subst pat :-( */
/* case 'e': c = ESC; ++src; break; */
case 'b': c = Ctrl_H; ++src; break;
/* If "backslash" is TRUE the backslash will be removed
* later. Used to insert a literal CR. */
default: if (backslash)
{
if (copy)
*dst = '\\';
++dst;
}
c = *src++;
}
}
#ifdef FEAT_MBYTE
else if (has_mbyte)
c = mb_ptr2char(src - 1);
#endif
/* Write to buffer, if copy is set. */
if (func == (fptr_T)NULL) /* just copy */
cc = c;
else
/* Turbo C complains without the typecast */
func = (fptr_T)(func(&cc, c));
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int totlen = mb_ptr2len(src - 1);
if (copy)
mb_char2bytes(cc, dst);
dst += mb_char2len(cc) - 1;
if (enc_utf8)
{
int clen = utf_ptr2len(src - 1);
/* If the character length is shorter than "totlen", there
* are composing characters; copy them as-is. */
if (clen < totlen)
{
if (copy)
mch_memmove(dst + 1, src - 1 + clen,
(size_t)(totlen - clen));
dst += totlen - clen;
}
}
src += totlen - 1;
}
else
#endif
if (copy)
*dst = cc;
dst++;
}
else
{
if (REG_MULTI)
{
clnum = reg_mmatch->startpos[no].lnum;
if (clnum < 0 || reg_mmatch->endpos[no].lnum < 0)
s = NULL;
else
{
s = reg_getline(clnum) + reg_mmatch->startpos[no].col;
if (reg_mmatch->endpos[no].lnum == clnum)
len = reg_mmatch->endpos[no].col
- reg_mmatch->startpos[no].col;
else
len = (int)STRLEN(s);
}
}
else
{
s = reg_match->startp[no];
if (reg_match->endp[no] == NULL)
s = NULL;
else
len = (int)(reg_match->endp[no] - s);
}
if (s != NULL)
{
for (;;)
{
if (len == 0)
{
if (REG_MULTI)
{
if (reg_mmatch->endpos[no].lnum == clnum)
break;
if (copy)
*dst = CAR;
++dst;
s = reg_getline(++clnum);
if (reg_mmatch->endpos[no].lnum == clnum)
len = reg_mmatch->endpos[no].col;
else
len = (int)STRLEN(s);
}
else
break;
}
else if (*s == NUL) /* we hit NUL. */
{
if (copy)
EMSG(_(e_re_damg));
goto exit;
}
else
{
if (backslash && (*s == CAR || *s == '\\'))
{
/*
* Insert a backslash in front of a CR, otherwise
* it will be replaced by a line break.
* Number of backslashes will be halved later,
* double them here.
*/
if (copy)
{
dst[0] = '\\';
dst[1] = *s;
}
dst += 2;
}
else
{
#ifdef FEAT_MBYTE
if (has_mbyte)
c = mb_ptr2char(s);
else
#endif
c = *s;
if (func == (fptr_T)NULL) /* just copy */
cc = c;
else
/* Turbo C complains without the typecast */
func = (fptr_T)(func(&cc, c));
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int l;
/* Copy composing characters separately, one
* at a time. */
if (enc_utf8)
l = utf_ptr2len(s) - 1;
else
l = mb_ptr2len(s) - 1;
s += l;
len -= l;
if (copy)
mb_char2bytes(cc, dst);
dst += mb_char2len(cc) - 1;
}
else
#endif
if (copy)
*dst = cc;
dst++;
}
++s;
--len;
}
}
}
no = -1;
}
}
if (copy)
*dst = NUL;
exit:
return (int)((dst - dest) + 1);
}
#ifdef FEAT_EVAL
static char_u *reg_getline_submatch __ARGS((linenr_T lnum));
/*
* Call reg_getline() with the line numbers from the submatch. If a
* substitute() was used the reg_maxline and other values have been
* overwritten.
*/
static char_u *
reg_getline_submatch(lnum)
linenr_T lnum;
{
char_u *s;
linenr_T save_first = reg_firstlnum;
linenr_T save_max = reg_maxline;
reg_firstlnum = submatch_firstlnum;
reg_maxline = submatch_maxline;
s = reg_getline(lnum);
reg_firstlnum = save_first;
reg_maxline = save_max;
return s;
}
/*
* Used for the submatch() function: get the string from the n'th submatch in
* allocated memory.
* Returns NULL when not in a ":s" command and for a non-existing submatch.
*/
char_u *
reg_submatch(no)
int no;
{
char_u *retval = NULL;
char_u *s;
int len;
int round;
linenr_T lnum;
if (!can_f_submatch || no < 0)
return NULL;
if (submatch_match == NULL)
{
/*
* First round: compute the length and allocate memory.
* Second round: copy the text.
*/
for (round = 1; round <= 2; ++round)
{
lnum = submatch_mmatch->startpos[no].lnum;
if (lnum < 0 || submatch_mmatch->endpos[no].lnum < 0)
return NULL;
s = reg_getline_submatch(lnum) + submatch_mmatch->startpos[no].col;
if (s == NULL) /* anti-crash check, cannot happen? */
break;
if (submatch_mmatch->endpos[no].lnum == lnum)
{
/* Within one line: take form start to end col. */
len = submatch_mmatch->endpos[no].col
- submatch_mmatch->startpos[no].col;
if (round == 2)
vim_strncpy(retval, s, len);
++len;
}
else
{
/* Multiple lines: take start line from start col, middle
* lines completely and end line up to end col. */
len = (int)STRLEN(s);
if (round == 2)
{
STRCPY(retval, s);
retval[len] = '\n';
}
++len;
++lnum;
while (lnum < submatch_mmatch->endpos[no].lnum)
{
s = reg_getline_submatch(lnum++);
if (round == 2)
STRCPY(retval + len, s);
len += (int)STRLEN(s);
if (round == 2)
retval[len] = '\n';
++len;
}
if (round == 2)
STRNCPY(retval + len, reg_getline_submatch(lnum),
submatch_mmatch->endpos[no].col);
len += submatch_mmatch->endpos[no].col;
if (round == 2)
retval[len] = NUL;
++len;
}
if (retval == NULL)
{
retval = lalloc((long_u)len, TRUE);
if (retval == NULL)
return NULL;
}
}
}
else
{
s = submatch_match->startp[no];
if (s == NULL || submatch_match->endp[no] == NULL)
retval = NULL;
else
retval = vim_strnsave(s, (int)(submatch_match->endp[no] - s));
}
return retval;
}
#endif
| zyz2011-vim | src/regexp.c | C | gpl2 | 186,756 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved by Bram Moolenaar
* 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.
*/
#ifdef FEAT_GUI_MOTIF
# include <Xm/Xm.h>
#endif
#ifdef FEAT_GUI_ATHENA
# include <X11/Intrinsic.h>
# include <X11/StringDefs.h>
#endif
#ifdef FEAT_BEVAL
# include "gui_beval.h"
#endif
#ifdef FEAT_GUI_GTK
# ifdef VMS /* undef MIN and MAX because Intrinsic.h redefines them anyway */
# ifdef MAX
# undef MAX
# endif
# ifdef MIN
# undef MIN
# endif
# endif
# include <X11/Intrinsic.h>
# include <gtk/gtk.h>
#endif
#ifdef FEAT_GUI_MAC
# include <Types.h>
/*# include <Memory.h>*/
# include <Quickdraw.h>
# include <Fonts.h>
# include <Events.h>
# include <Menus.h>
# if !(defined (TARGET_API_MAC_CARBON) && (TARGET_API_MAC_CARBON))
# include <Windows.h>
# endif
# include <Controls.h>
/*# include <TextEdit.h>*/
# include <Dialogs.h>
# include <OSUtils.h>
/*
# include <ToolUtils.h>
# include <SegLoad.h>*/
#endif
#ifdef FEAT_GUI_PHOTON
# include <Ph.h>
# include <Pt.h>
# include "photon/PxProto.h"
#endif
/*
* On some systems, when we compile with the GUI, we always use it. On Mac
* there is no terminal version, and on Windows we can't figure out how to
* fork one off with :gui.
*/
#if defined(FEAT_GUI_MSWIN) || (defined(FEAT_GUI_MAC) && !defined(MACOS_X_UNIX))
# define ALWAYS_USE_GUI
#endif
/*
* On some systems scrolling needs to be done right away instead of in the
* main loop.
*/
#if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
# define USE_ON_FLY_SCROLL
#endif
/*
* GUIs that support dropping files on a running Vim.
*/
#if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_MAC) \
|| defined(FEAT_GUI_GTK)
# define HAVE_DROP_FILE
#endif
/*
* This define makes menus always use a fontset.
* We're not sure if this code always works, thus it can be disabled.
*/
#ifdef FEAT_XFONTSET
# define FONTSET_ALWAYS
#endif
/*
* These macros convert between character row/column and pixel coordinates.
* TEXT_X - Convert character column into X pixel coord for drawing strings.
* TEXT_Y - Convert character row into Y pixel coord for drawing strings.
* FILL_X - Convert character column into X pixel coord for filling the area
* under the character.
* FILL_Y - Convert character row into Y pixel coord for filling the area
* under the character.
* X_2_COL - Convert X pixel coord into character column.
* Y_2_ROW - Convert Y pixel coord into character row.
*/
#ifdef FEAT_GUI_W32
# define TEXT_X(col) ((col) * gui.char_width)
# define TEXT_Y(row) ((row) * gui.char_height + gui.char_ascent)
# define FILL_X(col) ((col) * gui.char_width)
# define FILL_Y(row) ((row) * gui.char_height)
# define X_2_COL(x) ((x) / gui.char_width)
# define Y_2_ROW(y) ((y) / gui.char_height)
#else
# define TEXT_X(col) ((col) * gui.char_width + gui.border_offset)
# define FILL_X(col) ((col) * gui.char_width + gui.border_offset)
# define X_2_COL(x) (((x) - gui.border_offset) / gui.char_width)
# define TEXT_Y(row) ((row) * gui.char_height + gui.char_ascent \
+ gui.border_offset)
# define FILL_Y(row) ((row) * gui.char_height + gui.border_offset)
# define Y_2_ROW(y) (((y) - gui.border_offset) / gui.char_height)
#endif
/* Indices for arrays of scrollbars */
#define SBAR_NONE -1
#define SBAR_LEFT 0
#define SBAR_RIGHT 1
#define SBAR_BOTTOM 2
/* Orientations for scrollbars */
#define SBAR_VERT 0
#define SBAR_HORIZ 1
/* Default size of scrollbar */
#define SB_DEFAULT_WIDTH 16
/* Default height of the menu bar */
#define MENU_DEFAULT_HEIGHT 1 /* figure it out at runtime */
/* Flags for gui_mch_outstr_nowrap() */
#define GUI_MON_WRAP_CURSOR 0x01 /* wrap cursor at end of line */
#define GUI_MON_INVERT 0x02 /* invert the characters */
#define GUI_MON_IS_CURSOR 0x04 /* drawing cursor */
#define GUI_MON_TRS_CURSOR 0x08 /* drawing transparent cursor */
#define GUI_MON_NOCLEAR 0x10 /* don't clear selection */
/* Flags for gui_mch_draw_string() */
#define DRAW_TRANSP 0x01 /* draw with transparent bg */
#define DRAW_BOLD 0x02 /* draw bold text */
#define DRAW_UNDERL 0x04 /* draw underline text */
#define DRAW_UNDERC 0x08 /* draw undercurl text */
#if defined(FEAT_GUI_GTK)
# define DRAW_ITALIC 0x10 /* draw italic text */
#endif
#define DRAW_CURSOR 0x20 /* drawing block cursor (win32) */
/* For our own tearoff menu item */
#define TEAR_STRING "-->Detach"
#define TEAR_LEN (9) /* length of above string */
/* for the toolbar */
#ifdef FEAT_GUI_W16
# define TOOLBAR_BUTTON_HEIGHT 15
# define TOOLBAR_BUTTON_WIDTH 16
#else
# define TOOLBAR_BUTTON_HEIGHT 18
# define TOOLBAR_BUTTON_WIDTH 18
#endif
#define TOOLBAR_BORDER_HEIGHT 12 /* room above+below buttons for MSWindows */
#ifdef FEAT_GUI_MSWIN
# define TABLINE_HEIGHT 22
#endif
#ifdef FEAT_GUI_MOTIF
# define TABLINE_HEIGHT 30
#endif
#if defined(NO_CONSOLE) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)
# define NO_CONSOLE_INPUT /* use no_console_input() to check if there
is no console input possible */
#endif
typedef struct GuiScrollbar
{
long ident; /* Unique identifier for each scrollbar */
win_T *wp; /* Scrollbar's window, NULL for bottom */
int type; /* one of SBAR_{LEFT,RIGHT,BOTTOM} */
long value; /* Represents top line number visible */
#ifdef FEAT_GUI_ATHENA
int pixval; /* pixel count of value */
#endif
long size; /* Size of scrollbar thumb */
long max; /* Number of lines in buffer */
/* Values measured in characters: */
int top; /* Top of scroll bar (chars from row 0) */
int height; /* Current height of scroll bar in rows */
#ifdef FEAT_VERTSPLIT
int width; /* Current width of scroll bar in cols */
#endif
int status_height; /* Height of status line */
#ifdef FEAT_GUI_X11
Widget id; /* Id of real scroll bar */
#endif
#ifdef FEAT_GUI_GTK
GtkWidget *id; /* Id of real scroll bar */
unsigned long handler_id; /* Id of "value_changed" signal handler */
#endif
#ifdef FEAT_GUI_MSWIN
HWND id; /* Id of real scroll bar */
int scroll_shift; /* The scrollbar stuff can handle only up to
32767 lines. When the file is longer,
scroll_shift is set to the number of shifts
to reduce the count. */
#endif
#ifdef FEAT_GUI_MAC
ControlHandle id; /* A handle to the scrollbar */
#endif
#ifdef FEAT_GUI_PHOTON
PtWidget_t *id;
#endif
} scrollbar_T;
typedef long guicolor_T; /* handle for a GUI color; for X11 this should
be "Pixel", but that's an unsigned and we
need a signed value */
#define INVALCOLOR (guicolor_T)-11111 /* number for invalid color; on 32 bit
displays there is a tiny chance this is an
actual color */
#ifdef FEAT_GUI_GTK
typedef PangoFontDescription *GuiFont; /* handle for a GUI font */
typedef PangoFontDescription *GuiFontset; /* handle for a GUI fontset */
# define NOFONT (GuiFont)NULL
# define NOFONTSET (GuiFontset)NULL
#else
# ifdef FEAT_GUI_PHOTON
typedef char *GuiFont;
typedef char *GuiFontset;
# define NOFONT (GuiFont)NULL
# define NOFONTSET (GuiFontset)NULL
# else
# ifdef FEAT_GUI_X11
typedef XFontStruct *GuiFont; /* handle for a GUI font */
typedef XFontSet GuiFontset; /* handle for a GUI fontset */
# define NOFONT (GuiFont)0
# define NOFONTSET (GuiFontset)0
# else
typedef long_u GuiFont; /* handle for a GUI font */
typedef long_u GuiFontset; /* handle for a GUI fontset */
# define NOFONT (GuiFont)0
# define NOFONTSET (GuiFontset)0
# endif
# endif
#endif
typedef struct Gui
{
int in_focus; /* Vim has input focus */
int in_use; /* Is the GUI being used? */
int starting; /* GUI will start in a little while */
int shell_created; /* Has the shell been created yet? */
int dying; /* Is vim dying? Then output to terminal */
int dofork; /* Use fork() when GUI is starting */
int dragged_sb; /* Which scrollbar being dragged, if any? */
win_T *dragged_wp; /* Which WIN's sb being dragged, if any? */
int pointer_hidden; /* Is the mouse pointer hidden? */
int col; /* Current cursor column in GUI display */
int row; /* Current cursor row in GUI display */
int cursor_col; /* Physical cursor column in GUI display */
int cursor_row; /* Physical cursor row in GUI display */
char cursor_is_valid; /* There is a cursor at cursor_row/col */
int num_cols; /* Number of columns */
int num_rows; /* Number of rows */
int scroll_region_top; /* Top (first) line of scroll region */
int scroll_region_bot; /* Bottom (last) line of scroll region */
int scroll_region_left; /* Left (first) column of scroll region */
int scroll_region_right; /* Right (last) col. of scroll region */
int highlight_mask; /* Highlight attribute mask */
int scrollbar_width; /* Width of vertical scrollbars */
int scrollbar_height; /* Height of horizontal scrollbar */
int left_sbar_x; /* Calculated x coord for left scrollbar */
int right_sbar_x; /* Calculated x coord for right scrollbar */
#ifdef FEAT_MENU
# ifndef FEAT_GUI_GTK
int menu_height; /* Height of the menu bar */
int menu_width; /* Width of the menu bar */
# endif
char menu_is_active; /* TRUE if menu is present */
# ifdef FEAT_GUI_ATHENA
char menu_height_fixed; /* TRUE if menu height fixed */
# endif
#endif
scrollbar_T bottom_sbar; /* Bottom scrollbar */
int which_scrollbars[3];/* Which scrollbar boxes are active? */
int prev_wrap; /* For updating the horizontal scrollbar */
int char_width; /* Width of char cell in pixels */
int char_height; /* Height of char cell in pixels, includes
'linespace' */
int char_ascent; /* Ascent of char in pixels */
int border_width; /* Width of our border around text area */
int border_offset; /* Total pixel offset for all borders */
GuiFont norm_font; /* Normal font */
#ifndef FEAT_GUI_GTK
GuiFont bold_font; /* Bold font */
GuiFont ital_font; /* Italic font */
GuiFont boldital_font; /* Bold-Italic font */
#else
int font_can_bold; /* Whether norm_font supports bold weight.
* The styled font variants are not used. */
#endif
#if defined(FEAT_MENU) && !defined(FEAT_GUI_GTK)
# ifdef FONTSET_ALWAYS
GuiFontset menu_fontset; /* set of fonts for multi-byte chars */
# else
GuiFont menu_font; /* menu item font */
# endif
#endif
#ifdef FEAT_MBYTE
GuiFont wide_font; /* 'guifontwide' font */
#endif
#ifdef FEAT_XFONTSET
GuiFontset fontset; /* set of fonts for multi-byte chars */
#endif
guicolor_T back_pixel; /* Color of background */
guicolor_T norm_pixel; /* Color of normal text */
guicolor_T def_back_pixel; /* default Color of background */
guicolor_T def_norm_pixel; /* default Color of normal text */
#ifdef FEAT_GUI_X11
char *rsrc_menu_fg_name; /* Color of menu & dialog foreground */
guicolor_T menu_fg_pixel; /* Same in Pixel format */
char *rsrc_menu_bg_name; /* Color of menu & dialog background */
guicolor_T menu_bg_pixel; /* Same in Pixel format */
char *rsrc_scroll_fg_name; /* Color of scrollbar foreground */
guicolor_T scroll_fg_pixel; /* Same in Pixel format */
char *rsrc_scroll_bg_name; /* Color of scrollbar background */
guicolor_T scroll_bg_pixel; /* Same in Pixel format */
# ifdef FEAT_GUI_MOTIF
guicolor_T menu_def_fg_pixel; /* Default menu foreground */
guicolor_T menu_def_bg_pixel; /* Default menu background */
guicolor_T scroll_def_fg_pixel; /* Default scrollbar foreground */
guicolor_T scroll_def_bg_pixel; /* Default scrollbar background */
# endif
Display *dpy; /* X display */
Window wid; /* Window id of text area */
int visibility; /* Is shell partially/fully obscured? */
GC text_gc;
GC back_gc;
GC invert_gc;
Cursor blank_pointer; /* Blank pointer */
/* X Resources */
char_u *rsrc_font_name; /* Resource font name, used if 'guifont'
not set */
char_u *rsrc_bold_font_name; /* Resource bold font name */
char_u *rsrc_ital_font_name; /* Resource italic font name */
char_u *rsrc_boldital_font_name; /* Resource bold-italic font name */
char_u *rsrc_menu_font_name; /* Resource menu Font name */
Bool rsrc_rev_video; /* Use reverse video? */
char_u *geom; /* Geometry, eg "80x24" */
Bool color_approx; /* Some color was approximated */
#endif
#ifdef FEAT_GUI_GTK
int visibility; /* Is shell partially/fully obscured? */
GdkCursor *blank_pointer; /* Blank pointer */
/* X Resources */
char_u *geom; /* Geometry, eg "80x24" */
GtkWidget *mainwin; /* top level GTK window */
GtkWidget *formwin; /* manages all the windows below */
GtkWidget *drawarea; /* the "text" area */
# ifdef FEAT_MENU
GtkWidget *menubar; /* menubar */
# endif
# ifdef FEAT_TOOLBAR
GtkWidget *toolbar; /* toolbar */
# endif
# ifdef FEAT_GUI_GNOME
GtkWidget *menubar_h; /* menubar handle */
GtkWidget *toolbar_h; /* toolbar handle */
# endif
GdkColor *fgcolor; /* GDK-styled foreground color */
GdkColor *bgcolor; /* GDK-styled background color */
GdkColor *spcolor; /* GDK-styled special color */
GdkGC *text_gc; /* cached GC for normal text */
PangoContext *text_context; /* the context used for all text */
PangoFont *ascii_font; /* cached font for ASCII strings */
PangoGlyphString *ascii_glyphs; /* cached code point -> glyph map */
# ifdef FEAT_GUI_TABLINE
GtkWidget *tabline; /* tab pages line handle */
# endif
GtkAccelGroup *accel_group;
GtkWidget *filedlg; /* file selection dialog */
char_u *browse_fname; /* file name from filedlg */
guint32 event_time;
#endif /* FEAT_GUI_GTK */
#if defined(FEAT_GUI_TABLINE) \
&& (defined(FEAT_GUI_W32) || defined(FEAT_GUI_MOTIF) \
|| defined(FEAT_GUI_MAC))
int tabline_height;
#endif
#ifdef FEAT_FOOTER
int footer_height; /* height of the message footer */
#endif
#if defined(FEAT_TOOLBAR) \
&& (defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MOTIF))
int toolbar_height; /* height of the toolbar */
#endif
#ifdef FEAT_BEVAL_TIP
/* Tooltip properties; also used for balloon evaluation */
char_u *rsrc_tooltip_font_name; /* tooltip font name */
char *rsrc_tooltip_fg_name; /* tooltip foreground color name */
char *rsrc_tooltip_bg_name; /* tooltip background color name */
guicolor_T tooltip_fg_pixel; /* tooltip foreground color */
guicolor_T tooltip_bg_pixel; /* tooltip background color */
XFontSet tooltip_fontset; /* tooltip fontset */
#endif
#ifdef FEAT_GUI_MSWIN
GuiFont currFont; /* Current font */
guicolor_T currFgColor; /* Current foreground text color */
guicolor_T currBgColor; /* Current background text color */
guicolor_T currSpColor; /* Current special text color */
#endif
#ifdef FEAT_GUI_MAC
WindowPtr VimWindow;
MenuHandle MacOSHelpMenu; /* Help menu provided by the MacOS */
int MacOSHelpItems; /* Nr of help-items supplied by MacOS */
WindowPtr wid; /* Window id of text area */
int visibility; /* Is window partially/fully obscured? */
#endif
#ifdef FEAT_GUI_PHOTON
PtWidget_t *vimWindow; /* PtWindow */
PtWidget_t *vimTextArea; /* PtRaw */
PtWidget_t *vimContainer; /* PtPanel */
# if defined(FEAT_MENU) || defined(FEAT_TOOLBAR)
PtWidget_t *vimToolBarGroup;
# endif
# ifdef FEAT_MENU
PtWidget_t *vimMenuBar;
# endif
# ifdef FEAT_TOOLBAR
PtWidget_t *vimToolBar;
int toolbar_height;
# endif
PhEvent_t *event_buffer;
#endif
#ifdef FEAT_XIM
char *rsrc_input_method;
char *rsrc_preedit_type_name;
#endif
} gui_T;
extern gui_T gui; /* this is defined in gui.c */
/* definitions of available window positionings for gui_*_position_in_parent()
*/
typedef enum
{
VW_POS_MOUSE,
VW_POS_CENTER,
VW_POS_TOP_CENTER
} gui_win_pos_T;
#ifdef FIND_REPLACE_DIALOG
/*
* Flags used to distinguish the different contexts in which the
* find/replace callback may be called.
*/
# define FRD_FINDNEXT 1 /* Find next in find dialog */
# define FRD_R_FINDNEXT 2 /* Find next in repl dialog */
# define FRD_REPLACE 3 /* Replace once */
# define FRD_REPLACEALL 4 /* Replace remaining matches */
# define FRD_UNDO 5 /* Undo replaced text */
# define FRD_TYPE_MASK 7 /* Mask for the callback type */
/* Flags which change the way searching is done. */
# define FRD_WHOLE_WORD 0x08 /* match whole word only */
# define FRD_MATCH_CASE 0x10 /* match case */
#endif
#ifdef FEAT_GUI_GTK
/*
* Convenience macros to convert from 'encoding' to 'termencoding' and
* vice versa. If no conversion is necessary the passed-in pointer is
* returned as is, without allocating any memory. Thus additional _FREE()
* macros are provided. The _FREE() macros also set the pointer to NULL,
* in order to avoid bugs due to illegal memory access only happening if
* 'encoding' != utf-8...
*
* Defining these macros as pure expressions looks a bit tricky but
* avoids depending on the context of the macro expansion. One of the
* rare occasions where the comma operator comes in handy :)
*
* Note: Do NOT keep the result around when handling control back to
* the main Vim! The user could change 'encoding' at any time.
*/
# define CONVERT_TO_UTF8(String) \
((output_conv.vc_type == CONV_NONE || (String) == NULL) \
? (String) \
: string_convert(&output_conv, (String), NULL))
# define CONVERT_TO_UTF8_FREE(String) \
((String) = ((output_conv.vc_type == CONV_NONE) \
? (char_u *)NULL \
: (vim_free(String), (char_u *)NULL)))
# define CONVERT_FROM_UTF8(String) \
((input_conv.vc_type == CONV_NONE || (String) == NULL) \
? (String) \
: string_convert(&input_conv, (String), NULL))
# define CONVERT_FROM_UTF8_FREE(String) \
((String) = ((input_conv.vc_type == CONV_NONE) \
? (char_u *)NULL \
: (vim_free(String), (char_u *)NULL)))
#else
# define CONVERT_TO_UTF8(String) (String)
# define CONVERT_TO_UTF8_FREE(String) ((String) = (char_u *)NULL)
# define CONVERT_FROM_UTF8(String) (String)
# define CONVERT_FROM_UTF8_FREE(String) ((String) = (char_u *)NULL)
#endif /* FEAT_GUI_GTK */
| zyz2011-vim | src/gui.h | C | gpl2 | 18,652 |
/* 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.
*/
/*
* Common MS-DOS and Win32 (Windows NT and Windows 95) defines.
*
* Names for the EXRC, HELP and temporary files.
* Some of these may have been defined in the makefile or feature.h.
*/
#ifndef SYS_VIMRC_FILE
# define SYS_VIMRC_FILE "$VIM\\vimrc"
#endif
#ifndef USR_VIMRC_FILE
# define USR_VIMRC_FILE "$HOME\\_vimrc"
#endif
#ifndef USR_VIMRC_FILE2
# define USR_VIMRC_FILE2 "$VIM\\_vimrc"
#endif
#ifndef EVIM_FILE
# define EVIM_FILE "$VIMRUNTIME\\evim.vim"
#endif
#ifndef USR_EXRC_FILE
# define USR_EXRC_FILE "$HOME\\_exrc"
#endif
#ifndef USR_EXRC_FILE2
# define USR_EXRC_FILE2 "$VIM\\_exrc"
#endif
#ifdef FEAT_GUI
# ifndef SYS_GVIMRC_FILE
# define SYS_GVIMRC_FILE "$VIM\\gvimrc"
# endif
# ifndef USR_GVIMRC_FILE
# define USR_GVIMRC_FILE "$HOME\\_gvimrc"
# endif
# ifndef USR_GVIMRC_FILE2
# define USR_GVIMRC_FILE2 "$VIM\\_gvimrc"
# endif
# ifndef SYS_MENU_FILE
# define SYS_MENU_FILE "$VIMRUNTIME\\menu.vim"
# endif
#endif
#ifndef SYS_OPTWIN_FILE
# define SYS_OPTWIN_FILE "$VIMRUNTIME\\optwin.vim"
#endif
#ifdef FEAT_VIMINFO
# ifndef VIMINFO_FILE
# define VIMINFO_FILE "$HOME\\_viminfo"
# endif
# ifndef VIMINFO_FILE2
# define VIMINFO_FILE2 "$VIM\\_viminfo"
# endif
#endif
#ifndef VIMRC_FILE
# define VIMRC_FILE "_vimrc"
#endif
#ifndef EXRC_FILE
# define EXRC_FILE "_exrc"
#endif
#ifdef FEAT_GUI
# ifndef GVIMRC_FILE
# define GVIMRC_FILE "_gvimrc"
# endif
#endif
#ifndef DFLT_HELPFILE
# define DFLT_HELPFILE "$VIMRUNTIME\\doc\\help.txt"
#endif
#ifndef FILETYPE_FILE
# define FILETYPE_FILE "filetype.vim"
#endif
#ifndef FTPLUGIN_FILE
# define FTPLUGIN_FILE "ftplugin.vim"
#endif
#ifndef INDENT_FILE
# define INDENT_FILE "indent.vim"
#endif
#ifndef FTOFF_FILE
# define FTOFF_FILE "ftoff.vim"
#endif
#ifndef FTPLUGOF_FILE
# define FTPLUGOF_FILE "ftplugof.vim"
#endif
#ifndef INDOFF_FILE
# define INDOFF_FILE "indoff.vim"
#endif
#ifndef SYNTAX_FNAME
# define SYNTAX_FNAME "$VIMRUNTIME\\syntax\\%s.vim"
#endif
#ifndef DFLT_BDIR
# define DFLT_BDIR ".,c:\\tmp,c:\\temp" /* default for 'backupdir' */
#endif
#ifndef DFLT_VDIR
# define DFLT_VDIR "$VIM/vimfiles/view" /* default for 'viewdir' */
#endif
#ifndef DFLT_DIR
# define DFLT_DIR ".,c:\\tmp,c:\\temp" /* default for 'directory' */
#endif
#define DFLT_ERRORFILE "errors.err"
#define DFLT_RUNTIMEPATH "$HOME/vimfiles,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,$HOME/vimfiles/after"
#define CASE_INSENSITIVE_FILENAME /* ignore case when comparing file names */
#define SPACE_IN_FILENAME
#define BACKSLASH_IN_FILENAME
#define USE_CRNL /* lines end in CR-NL instead of NL */
#define HAVE_DUP /* have dup() */
#define HAVE_ST_MODE /* have stat.st_mode */
| zyz2011-vim | src/os_dos.h | C | gpl2 | 2,857 |
#! /bin/sh
# Start Vim on a copy of the tutor file.
# Usage: vimtutor [-g] [xx]
# Where optional argument -g starts vimtutor in gvim (GUI) instead of vim.
# and xx is a language code like "es" or "nl".
# When an argument is given, it tries loading that tutor.
# When this fails or no argument was given, it tries using 'v:lang'
# When that also fails, it uses the English version.
# Vim could be called "vim" or "vi". Also check for "vimN", for people who
# have Vim installed with its version number.
# We anticipate up to a future Vim 8 version :-).
seq="vim vim8 vim75 vim74 vim73 vim72 vim71 vim70 vim7 vim6 vi"
if test "$1" = "-g"; then
# Try to use the GUI version of Vim if possible, it will fall back
# on Vim if Gvim is not installed.
seq="gvim gvim8 gvim75 gvim74 gvim73 gvim72 gvim71 gvim70 gvim7 gvim6 $seq"
shift
fi
xx=$1
export xx
# We need a temp file for the copy. First try using a standard command.
tmp="${TMPDIR-/tmp}"
TUTORCOPY=`mktemp $tmp/tutorXXXXXX || tempfile -p tutor || echo none`
# If the standard commands failed then create a directory to put the copy in.
# That is a secure way to make a temp file.
if test "$TUTORCOPY" = none; then
tmpdir=$tmp/vimtutor$$
OLD_UMASK=`umask`
umask 077
getout=no
mkdir $tmpdir || getout=yes
umask $OLD_UMASK
if test $getout = yes; then
echo "Could not create directory for tutor copy, exiting."
exit 1
fi
TUTORCOPY=$tmpdir/tutorcopy
touch $TUTORCOPY
TODELETE=$tmpdir
else
TODELETE=$TUTORCOPY
fi
export TUTORCOPY
# remove the copy of the tutor on exit
trap "rm -rf $TODELETE" 0 1 2 3 9 11 13 15
for i in $seq; do
testvim=`which $i 2>/dev/null`
if test -f "$testvim"; then
VIM=$i
break
fi
done
# When no Vim version was found fall back to "vim", you'll get an error message
# below.
if test -z "$VIM"; then
VIM=vim
fi
# Use Vim to copy the tutor, it knows the value of $VIMRUNTIME
# The script tutor.vim tells Vim which file to copy
$VIM -f -u NONE -c 'so $VIMRUNTIME/tutor/tutor.vim'
# Start vim without any .vimrc, set 'nocompatible'
$VIM -f -u NONE -c "set nocp" $TUTORCOPY
| zyz2011-vim | src/vimtutor | Shell | gpl2 | 2,084 |
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Lua interface by Luis Carvalho
*
* 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"
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
/* Only do the following when the feature is enabled. Needed for "make
* depend". */
#if defined(FEAT_LUA) || defined(PROTO)
#define LUAVIM_CHUNKNAME "vim chunk"
#define LUAVIM_NAME "vim"
#define LUAVIM_EVALNAME "luaeval"
#define LUAVIM_EVALHEADER "local _A=select(1,...) return "
typedef buf_T *luaV_Buffer;
typedef win_T *luaV_Window;
typedef dict_T *luaV_Dict;
typedef list_T *luaV_List;
typedef void (*msgfunc_T)(char_u *);
static const char LUAVIM_DICT[] = "dict";
static const char LUAVIM_LIST[] = "list";
static const char LUAVIM_BUFFER[] = "buffer";
static const char LUAVIM_WINDOW[] = "window";
static const char LUAVIM_FREE[] = "luaV_free";
static const char LUAVIM_LUAEVAL[] = "luaV_luaeval";
static const char LUAVIM_SETREF[] = "luaV_setref";
/* most functions are closures with a cache table as first upvalue;
* get/setudata manage references to vim userdata in cache table through
* object pointers (light userdata) */
#define luaV_getudata(L, v) \
lua_pushlightuserdata((L), (void *) (v)); \
lua_rawget((L), lua_upvalueindex(1))
#define luaV_setudata(L, v) \
lua_pushlightuserdata((L), (void *) (v)); \
lua_pushvalue((L), -2); \
lua_rawset((L), lua_upvalueindex(1))
#define luaV_getfield(L, s) \
lua_pushlightuserdata((L), (void *)(s)); \
lua_rawget((L), LUA_REGISTRYINDEX)
#define luaV_checksandbox(L) \
if (sandbox) luaL_error((L), "not allowed in sandbox")
#define luaV_msg(L) luaV_msgfunc((L), (msgfunc_T) msg)
#define luaV_emsg(L) luaV_msgfunc((L), (msgfunc_T) emsg)
static luaV_List *luaV_pushlist (lua_State *L, list_T *lis);
static luaV_Dict *luaV_pushdict (lua_State *L, dict_T *dic);
#if LUA_VERSION_NUM <= 501
#define luaV_openlib(L, l, n) luaL_openlib(L, NULL, l, n)
#define luaL_typeerror luaL_typerror
#else
#define luaV_openlib luaL_setfuncs
#endif
#ifdef DYNAMIC_LUA
#ifndef WIN3264
# include <dlfcn.h>
# define HANDLE void*
# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
# define symbol_from_dll dlsym
# define close_dll dlclose
#else
# define load_dll vimLoadLib
# define symbol_from_dll GetProcAddress
# define close_dll FreeLibrary
#endif
/* lauxlib */
#if LUA_VERSION_NUM <= 501
#define luaL_register dll_luaL_register
#define luaL_prepbuffer dll_luaL_prepbuffer
#define luaL_openlib dll_luaL_openlib
#define luaL_typerror dll_luaL_typerror
#define luaL_loadfile dll_luaL_loadfile
#define luaL_loadbuffer dll_luaL_loadbuffer
#else
#define luaL_prepbuffsize dll_luaL_prepbuffsize
#define luaL_setfuncs dll_luaL_setfuncs
#define luaL_loadfilex dll_luaL_loadfilex
#define luaL_loadbufferx dll_luaL_loadbufferx
#define luaL_argerror dll_luaL_argerror
#endif
#define luaL_checkany dll_luaL_checkany
#define luaL_checklstring dll_luaL_checklstring
#define luaL_checkinteger dll_luaL_checkinteger
#define luaL_optinteger dll_luaL_optinteger
#define luaL_checktype dll_luaL_checktype
#define luaL_error dll_luaL_error
#define luaL_newstate dll_luaL_newstate
#define luaL_buffinit dll_luaL_buffinit
#define luaL_addlstring dll_luaL_addlstring
#define luaL_pushresult dll_luaL_pushresult
/* lua */
#if LUA_VERSION_NUM <= 501
#define lua_tonumber dll_lua_tonumber
#define lua_tointeger dll_lua_tointeger
#define lua_call dll_lua_call
#define lua_pcall dll_lua_pcall
#else
#define lua_tonumberx dll_lua_tonumberx
#define lua_tointegerx dll_lua_tointegerx
#define lua_callk dll_lua_callk
#define lua_pcallk dll_lua_pcallk
#define lua_getglobal dll_lua_getglobal
#define lua_setglobal dll_lua_setglobal
#endif
#define lua_typename dll_lua_typename
#define lua_close dll_lua_close
#define lua_gettop dll_lua_gettop
#define lua_settop dll_lua_settop
#define lua_pushvalue dll_lua_pushvalue
#define lua_replace dll_lua_replace
#define lua_remove dll_lua_remove
#define lua_isnumber dll_lua_isnumber
#define lua_isstring dll_lua_isstring
#define lua_type dll_lua_type
#define lua_rawequal dll_lua_rawequal
#define lua_toboolean dll_lua_toboolean
#define lua_tolstring dll_lua_tolstring
#define lua_touserdata dll_lua_touserdata
#define lua_pushnil dll_lua_pushnil
#define lua_pushnumber dll_lua_pushnumber
#define lua_pushinteger dll_lua_pushinteger
#define lua_pushlstring dll_lua_pushlstring
#define lua_pushstring dll_lua_pushstring
#define lua_pushfstring dll_lua_pushfstring
#define lua_pushcclosure dll_lua_pushcclosure
#define lua_pushboolean dll_lua_pushboolean
#define lua_pushlightuserdata dll_lua_pushlightuserdata
#define lua_getfield dll_lua_getfield
#define lua_rawget dll_lua_rawget
#define lua_rawgeti dll_lua_rawgeti
#define lua_createtable dll_lua_createtable
#define lua_newuserdata dll_lua_newuserdata
#define lua_getmetatable dll_lua_getmetatable
#define lua_setfield dll_lua_setfield
#define lua_rawset dll_lua_rawset
#define lua_rawseti dll_lua_rawseti
#define lua_setmetatable dll_lua_setmetatable
#define lua_next dll_lua_next
/* libs */
#define luaopen_base dll_luaopen_base
#define luaopen_table dll_luaopen_table
#define luaopen_string dll_luaopen_string
#define luaopen_math dll_luaopen_math
#define luaopen_io dll_luaopen_io
#define luaopen_os dll_luaopen_os
#define luaopen_package dll_luaopen_package
#define luaopen_debug dll_luaopen_debug
#define luaL_openlibs dll_luaL_openlibs
/* lauxlib */
#if LUA_VERSION_NUM <= 501
void (*dll_luaL_register) (lua_State *L, const char *libname, const luaL_Reg *l);
char *(*dll_luaL_prepbuffer) (luaL_Buffer *B);
void (*dll_luaL_openlib) (lua_State *L, const char *libname, const luaL_Reg *l, int nup);
int (*dll_luaL_typerror) (lua_State *L, int narg, const char *tname);
int (*dll_luaL_loadfile) (lua_State *L, const char *filename);
int (*dll_luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, const char *name);
#else
char *(*dll_luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
void (*dll_luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
int (*dll_luaL_loadfilex) (lua_State *L, const char *filename, const char *mode);
int (*dll_luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, const char *name, const char *mode);
int (*dll_luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
#endif
void (*dll_luaL_checkany) (lua_State *L, int narg);
const char *(*dll_luaL_checklstring) (lua_State *L, int numArg, size_t *l);
lua_Integer (*dll_luaL_checkinteger) (lua_State *L, int numArg);
lua_Integer (*dll_luaL_optinteger) (lua_State *L, int nArg, lua_Integer def);
void (*dll_luaL_checktype) (lua_State *L, int narg, int t);
int (*dll_luaL_error) (lua_State *L, const char *fmt, ...);
lua_State *(*dll_luaL_newstate) (void);
void (*dll_luaL_buffinit) (lua_State *L, luaL_Buffer *B);
void (*dll_luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
void (*dll_luaL_pushresult) (luaL_Buffer *B);
/* lua */
#if LUA_VERSION_NUM <= 501
lua_Number (*dll_lua_tonumber) (lua_State *L, int idx);
lua_Integer (*dll_lua_tointeger) (lua_State *L, int idx);
void (*dll_lua_call) (lua_State *L, int nargs, int nresults);
int (*dll_lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc);
#else
lua_Number (*dll_lua_tonumberx) (lua_State *L, int idx, int *isnum);
lua_Integer (*dll_lua_tointegerx) (lua_State *L, int idx, int *isnum);
void (*dll_lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
lua_CFunction k);
int (*dll_lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
int ctx, lua_CFunction k);
void (*dll_lua_getglobal) (lua_State *L, const char *var);
void (*dll_lua_setglobal) (lua_State *L, const char *var);
#endif
const char *(*dll_lua_typename) (lua_State *L, int tp);
void (*dll_lua_close) (lua_State *L);
int (*dll_lua_gettop) (lua_State *L);
void (*dll_lua_settop) (lua_State *L, int idx);
void (*dll_lua_pushvalue) (lua_State *L, int idx);
void (*dll_lua_replace) (lua_State *L, int idx);
void (*dll_lua_remove) (lua_State *L, int idx);
int (*dll_lua_isnumber) (lua_State *L, int idx);
int (*dll_lua_isstring) (lua_State *L, int idx);
int (*dll_lua_type) (lua_State *L, int idx);
int (*dll_lua_rawequal) (lua_State *L, int idx1, int idx2);
int (*dll_lua_toboolean) (lua_State *L, int idx);
const char *(*dll_lua_tolstring) (lua_State *L, int idx, size_t *len);
void *(*dll_lua_touserdata) (lua_State *L, int idx);
void (*dll_lua_pushnil) (lua_State *L);
void (*dll_lua_pushnumber) (lua_State *L, lua_Number n);
void (*dll_lua_pushinteger) (lua_State *L, lua_Integer n);
void (*dll_lua_pushlstring) (lua_State *L, const char *s, size_t l);
void (*dll_lua_pushstring) (lua_State *L, const char *s);
const char *(*dll_lua_pushfstring) (lua_State *L, const char *fmt, ...);
void (*dll_lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
void (*dll_lua_pushboolean) (lua_State *L, int b);
void (*dll_lua_pushlightuserdata) (lua_State *L, void *p);
void (*dll_lua_getfield) (lua_State *L, int idx, const char *k);
void (*dll_lua_rawget) (lua_State *L, int idx);
void (*dll_lua_rawgeti) (lua_State *L, int idx, int n);
void (*dll_lua_createtable) (lua_State *L, int narr, int nrec);
void *(*dll_lua_newuserdata) (lua_State *L, size_t sz);
int (*dll_lua_getmetatable) (lua_State *L, int objindex);
void (*dll_lua_setfield) (lua_State *L, int idx, const char *k);
void (*dll_lua_rawset) (lua_State *L, int idx);
void (*dll_lua_rawseti) (lua_State *L, int idx, int n);
int (*dll_lua_setmetatable) (lua_State *L, int objindex);
int (*dll_lua_next) (lua_State *L, int idx);
/* libs */
int (*dll_luaopen_base) (lua_State *L);
int (*dll_luaopen_table) (lua_State *L);
int (*dll_luaopen_string) (lua_State *L);
int (*dll_luaopen_math) (lua_State *L);
int (*dll_luaopen_io) (lua_State *L);
int (*dll_luaopen_os) (lua_State *L);
int (*dll_luaopen_package) (lua_State *L);
int (*dll_luaopen_debug) (lua_State *L);
void (*dll_luaL_openlibs) (lua_State *L);
typedef void **luaV_function;
typedef struct {
const char *name;
luaV_function func;
} luaV_Reg;
static const luaV_Reg luaV_dll[] = {
/* lauxlib */
#if LUA_VERSION_NUM <= 501
{"luaL_register", (luaV_function) &dll_luaL_register},
{"luaL_prepbuffer", (luaV_function) &dll_luaL_prepbuffer},
{"luaL_openlib", (luaV_function) &dll_luaL_openlib},
{"luaL_typerror", (luaV_function) &dll_luaL_typerror},
{"luaL_loadfile", (luaV_function) &dll_luaL_loadfile},
{"luaL_loadbuffer", (luaV_function) &dll_luaL_loadbuffer},
#else
{"luaL_prepbuffsize", (luaV_function) &dll_luaL_prepbuffsize},
{"luaL_setfuncs", (luaV_function) &dll_luaL_setfuncs},
{"luaL_loadfilex", (luaV_function) &dll_luaL_loadfilex},
{"luaL_loadbufferx", (luaV_function) &dll_luaL_loadbufferx},
{"luaL_argerror", (luaV_function) &dll_luaL_argerror},
#endif
{"luaL_checkany", (luaV_function) &dll_luaL_checkany},
{"luaL_checklstring", (luaV_function) &dll_luaL_checklstring},
{"luaL_checkinteger", (luaV_function) &dll_luaL_checkinteger},
{"luaL_optinteger", (luaV_function) &dll_luaL_optinteger},
{"luaL_checktype", (luaV_function) &dll_luaL_checktype},
{"luaL_error", (luaV_function) &dll_luaL_error},
{"luaL_newstate", (luaV_function) &dll_luaL_newstate},
{"luaL_buffinit", (luaV_function) &dll_luaL_buffinit},
{"luaL_addlstring", (luaV_function) &dll_luaL_addlstring},
{"luaL_pushresult", (luaV_function) &dll_luaL_pushresult},
/* lua */
#if LUA_VERSION_NUM <= 501
{"lua_tonumber", (luaV_function) &dll_lua_tonumber},
{"lua_tointeger", (luaV_function) &dll_lua_tointeger},
{"lua_call", (luaV_function) &dll_lua_call},
{"lua_pcall", (luaV_function) &dll_lua_pcall},
#else
{"lua_tonumberx", (luaV_function) &dll_lua_tonumberx},
{"lua_tointegerx", (luaV_function) &dll_lua_tointegerx},
{"lua_callk", (luaV_function) &dll_lua_callk},
{"lua_pcallk", (luaV_function) &dll_lua_pcallk},
{"lua_getglobal", (luaV_function) &dll_lua_getglobal},
{"lua_setglobal", (luaV_function) &dll_lua_setglobal},
#endif
{"lua_typename", (luaV_function) &dll_lua_typename},
{"lua_close", (luaV_function) &dll_lua_close},
{"lua_gettop", (luaV_function) &dll_lua_gettop},
{"lua_settop", (luaV_function) &dll_lua_settop},
{"lua_pushvalue", (luaV_function) &dll_lua_pushvalue},
{"lua_replace", (luaV_function) &dll_lua_replace},
{"lua_remove", (luaV_function) &dll_lua_remove},
{"lua_isnumber", (luaV_function) &dll_lua_isnumber},
{"lua_isstring", (luaV_function) &dll_lua_isstring},
{"lua_type", (luaV_function) &dll_lua_type},
{"lua_rawequal", (luaV_function) &dll_lua_rawequal},
{"lua_toboolean", (luaV_function) &dll_lua_toboolean},
{"lua_tolstring", (luaV_function) &dll_lua_tolstring},
{"lua_touserdata", (luaV_function) &dll_lua_touserdata},
{"lua_pushnil", (luaV_function) &dll_lua_pushnil},
{"lua_pushnumber", (luaV_function) &dll_lua_pushnumber},
{"lua_pushinteger", (luaV_function) &dll_lua_pushinteger},
{"lua_pushlstring", (luaV_function) &dll_lua_pushlstring},
{"lua_pushstring", (luaV_function) &dll_lua_pushstring},
{"lua_pushfstring", (luaV_function) &dll_lua_pushfstring},
{"lua_pushcclosure", (luaV_function) &dll_lua_pushcclosure},
{"lua_pushboolean", (luaV_function) &dll_lua_pushboolean},
{"lua_pushlightuserdata", (luaV_function) &dll_lua_pushlightuserdata},
{"lua_getfield", (luaV_function) &dll_lua_getfield},
{"lua_rawget", (luaV_function) &dll_lua_rawget},
{"lua_rawgeti", (luaV_function) &dll_lua_rawgeti},
{"lua_createtable", (luaV_function) &dll_lua_createtable},
{"lua_newuserdata", (luaV_function) &dll_lua_newuserdata},
{"lua_getmetatable", (luaV_function) &dll_lua_getmetatable},
{"lua_setfield", (luaV_function) &dll_lua_setfield},
{"lua_rawset", (luaV_function) &dll_lua_rawset},
{"lua_rawseti", (luaV_function) &dll_lua_rawseti},
{"lua_setmetatable", (luaV_function) &dll_lua_setmetatable},
{"lua_next", (luaV_function) &dll_lua_next},
/* libs */
{"luaopen_base", (luaV_function) &dll_luaopen_base},
{"luaopen_table", (luaV_function) &dll_luaopen_table},
{"luaopen_string", (luaV_function) &dll_luaopen_string},
{"luaopen_math", (luaV_function) &dll_luaopen_math},
{"luaopen_io", (luaV_function) &dll_luaopen_io},
{"luaopen_os", (luaV_function) &dll_luaopen_os},
{"luaopen_package", (luaV_function) &dll_luaopen_package},
{"luaopen_debug", (luaV_function) &dll_luaopen_debug},
{"luaL_openlibs", (luaV_function) &dll_luaL_openlibs},
{NULL, NULL}
};
static HANDLE hinstLua = NULL;
static void
end_dynamic_lua(void)
{
if (hinstLua)
{
close_dll(hinstLua);
hinstLua = 0;
}
}
static int
lua_link_init(char *libname, int verbose)
{
const luaV_Reg *reg;
if (hinstLua) return OK;
hinstLua = load_dll(libname);
if (!hinstLua)
{
if (verbose)
EMSG2(_(e_loadlib), libname);
return FAIL;
}
for (reg = luaV_dll; reg->func; reg++)
{
if ((*reg->func = symbol_from_dll(hinstLua, reg->name)) == NULL)
{
close_dll(hinstLua);
hinstLua = 0;
if (verbose)
EMSG2(_(e_loadfunc), reg->name);
return FAIL;
}
}
return OK;
}
int
lua_enabled(int verbose)
{
return lua_link_init(DYNAMIC_LUA_DLL, verbose) == OK;
}
#endif /* DYNAMIC_LUA */
#if LUA_VERSION_NUM > 501
static int
luaL_typeerror (lua_State *L, int narg, const char *tname)
{
const char *msg = lua_pushfstring(L, "%s expected, got %s",
tname, luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
}
#endif
/* ======= Internal ======= */
static void
luaV_newmetatable(lua_State *L, const char *tname)
{
lua_newtable(L);
lua_pushlightuserdata(L, (void *) tname);
lua_pushvalue(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
}
static void *
luaV_toudata(lua_State *L, int ud, const char *tname)
{
void *p = lua_touserdata(L, ud);
if (p != NULL) /* value is userdata? */
{
if (lua_getmetatable(L, ud)) /* does it have a metatable? */
{
luaV_getfield(L, tname); /* get metatable */
if (lua_rawequal(L, -1, -2)) /* MTs match? */
{
lua_pop(L, 2); /* MTs */
return p;
}
}
}
return NULL;
}
static void *
luaV_checkcache(lua_State *L, void *p)
{
luaV_getudata(L, p);
if (lua_isnil(L, -1)) luaL_error(L, "invalid object");
lua_pop(L, 1);
return p;
}
#define luaV_unbox(L,luatyp,ud) (*((luatyp *) lua_touserdata((L),(ud))))
#define luaV_checkvalid(L,luatyp,ud) \
luaV_checkcache((L), (void *) luaV_unbox((L),luatyp,(ud)))
static void *
luaV_checkudata(lua_State *L, int ud, const char *tname)
{
void *p = luaV_toudata(L, ud, tname);
if (p == NULL) luaL_typeerror(L, ud, tname);
return p;
}
static void
luaV_pushtypval(lua_State *L, typval_T *tv)
{
if (tv == NULL)
{
lua_pushnil(L);
return;
}
switch (tv->v_type)
{
case VAR_STRING:
lua_pushstring(L, (char *) tv->vval.v_string);
break;
case VAR_NUMBER:
lua_pushinteger(L, (int) tv->vval.v_number);
break;
#ifdef FEAT_FLOAT
case VAR_FLOAT:
lua_pushnumber(L, (lua_Number) tv->vval.v_float);
break;
#endif
case VAR_LIST:
luaV_pushlist(L, tv->vval.v_list);
break;
case VAR_DICT:
luaV_pushdict(L, tv->vval.v_dict);
break;
default:
lua_pushnil(L);
}
}
/* converts lua value at 'pos' to typval 'tv' */
static void
luaV_totypval (lua_State *L, int pos, typval_T *tv)
{
switch(lua_type(L, pos)) {
case LUA_TBOOLEAN:
tv->v_type = VAR_NUMBER;
tv->vval.v_number = (varnumber_T) lua_toboolean(L, pos);
break;
case LUA_TSTRING:
tv->v_type = VAR_STRING;
tv->vval.v_string = vim_strsave((char_u *) lua_tostring(L, pos));
break;
case LUA_TNUMBER:
#ifdef FEAT_FLOAT
tv->v_type = VAR_FLOAT;
tv->vval.v_float = (float_T) lua_tonumber(L, pos);
#else
tv->v_type = VAR_NUMBER;
tv->vval.v_number = (varnumber_T) lua_tointeger(L, pos);
#endif
break;
case LUA_TUSERDATA: {
void *p = lua_touserdata(L, pos);
if (lua_getmetatable(L, pos)) /* has metatable? */
{
/* check list */
luaV_getfield(L, LUAVIM_LIST);
if (lua_rawequal(L, -1, -2))
{
tv->v_type = VAR_LIST;
tv->vval.v_list = *((luaV_List *) p);
++tv->vval.v_list->lv_refcount;
lua_pop(L, 2); /* MTs */
return;
}
/* check dict */
luaV_getfield(L, LUAVIM_DICT);
if (lua_rawequal(L, -1, -3))
{
tv->v_type = VAR_DICT;
tv->vval.v_dict = *((luaV_Dict *) p);
++tv->vval.v_dict->dv_refcount;
lua_pop(L, 3); /* MTs */
return;
}
lua_pop(L, 3); /* MTs */
}
break;
}
default:
tv->v_type = VAR_NUMBER;
tv->vval.v_number = 0;
}
}
/* similar to luaL_addlstring, but replaces \0 with \n if toline and
* \n with \0 otherwise */
static void
luaV_addlstring(luaL_Buffer *b, const char *s, size_t l, int toline)
{
while (l--)
{
if (*s == '\0' && toline)
luaL_addchar(b, '\n');
else if (*s == '\n' && !toline)
luaL_addchar(b, '\0');
else
luaL_addchar(b, *s);
s++;
}
}
static void
luaV_pushline(lua_State *L, buf_T *buf, linenr_T n)
{
const char *s = (const char *) ml_get_buf(buf, n, FALSE);
luaL_Buffer b;
luaL_buffinit(L, &b);
luaV_addlstring(&b, s, strlen(s), 0);
luaL_pushresult(&b);
}
static char_u *
luaV_toline(lua_State *L, int pos)
{
size_t l;
const char *s = lua_tolstring(L, pos, &l);
luaL_Buffer b;
luaL_buffinit(L, &b);
luaV_addlstring(&b, s, l, 1);
luaL_pushresult(&b);
return (char_u *) lua_tostring(L, -1);
}
/* pops a string s from the top of the stack and calls mf(t) for pieces t of
* s separated by newlines */
static void
luaV_msgfunc(lua_State *L, msgfunc_T mf)
{
luaL_Buffer b;
size_t l;
const char *p, *s = lua_tolstring(L, -1, &l);
luaL_buffinit(L, &b);
luaV_addlstring(&b, s, l, 0);
luaL_pushresult(&b);
/* break string */
p = s = lua_tolstring(L, -1, &l);
while (l--)
{
if (*p++ == '\0') /* break? */
{
mf((char_u *) s);
s = p;
}
}
mf((char_u *) s);
lua_pop(L, 2); /* original and modified strings */
}
#define luaV_newtype(typ,tname,luatyp,luatname) \
static luatyp * \
luaV_new##tname (lua_State *L, typ *obj) \
{ \
luatyp *o = (luatyp *) lua_newuserdata(L, sizeof(luatyp)); \
*o = obj; \
luaV_setudata(L, obj); /* cache[obj] = udata */ \
luaV_getfield(L, luatname); \
lua_setmetatable(L, -2); \
return o; \
}
#define luaV_pushtype(typ,tname,luatyp) \
static luatyp * \
luaV_push##tname (lua_State *L, typ *obj) \
{ \
luatyp *o = NULL; \
if (obj == NULL) \
lua_pushnil(L); \
else { \
luaV_getudata(L, obj); \
if (lua_isnil(L, -1)) /* not interned? */ \
{ \
lua_pop(L, 1); \
o = luaV_new##tname(L, obj); \
} \
else \
o = (luatyp *) lua_touserdata(L, -1); \
} \
return o; \
}
#define luaV_type_tostring(tname,luatname) \
static int \
luaV_##tname##_tostring (lua_State *L) \
{ \
lua_pushfstring(L, "%s: %p", luatname, lua_touserdata(L, 1)); \
return 1; \
}
/* adapted from eval.c */
#define listitem_alloc() (listitem_T *)alloc(sizeof(listitem_T))
static listitem_T *
list_find (list_T *l, long n)
{
listitem_T *li;
if (l == NULL || n < -l->lv_len || n >= l->lv_len)
return NULL;
if (n < 0) /* search backward? */
for (li = l->lv_last; n < -1; li = li->li_prev)
n++;
else /* search forward */
for (li = l->lv_first; n > 0; li = li->li_next)
n--;
return li;
}
static void
list_remove (list_T *l, listitem_T *li)
{
listwatch_T *lw;
--l->lv_len;
/* fix watchers */
for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
if (lw->lw_item == li)
lw->lw_item = li->li_next;
/* fix list pointers */
if (li->li_next == NULL) /* last? */
l->lv_last = li->li_prev;
else
li->li_next->li_prev = li->li_prev;
if (li->li_prev == NULL) /* first? */
l->lv_first = li->li_next;
else
li->li_prev->li_next = li->li_next;
l->lv_idx_item = NULL;
}
static void
list_append(list_T *l, listitem_T *item)
{
if (l->lv_last == NULL) /* empty list? */
l->lv_first = item;
else
l->lv_last->li_next = item;
item->li_prev = l->lv_last;
item->li_next = NULL;
l->lv_last = item;
++l->lv_len;
}
static int
list_insert_tv(list_T *l, typval_T *tv, listitem_T *item)
{
listitem_T *ni = listitem_alloc();
if (ni == NULL)
return FAIL;
copy_tv(tv, &ni->li_tv);
if (item == NULL)
list_append(l, ni);
else
{
ni->li_prev = item->li_prev;
ni->li_next = item;
if (item->li_prev == NULL)
{
l->lv_first = ni;
++l->lv_idx;
}
else
{
item->li_prev->li_next = ni;
l->lv_idx_item = NULL;
}
item->li_prev = ni;
++l->lv_len;
}
return OK;
}
/* set references */
static void set_ref_in_tv (typval_T *tv, int copyID);
static void
set_ref_in_dict(dict_T *d, int copyID)
{
hashtab_T *ht = &d->dv_hashtab;
int n = ht->ht_used;
hashitem_T *hi;
for (hi = ht->ht_array; n > 0; ++hi)
if (!HASHITEM_EMPTY(hi))
{
dictitem_T *di = dict_lookup(hi);
set_ref_in_tv(&di->di_tv, copyID);
--n;
}
}
static void
set_ref_in_list(list_T *l, int copyID)
{
listitem_T *li;
for (li = l->lv_first; li != NULL; li = li->li_next)
set_ref_in_tv(&li->li_tv, copyID);
}
static void
set_ref_in_tv(typval_T *tv, int copyID)
{
if (tv->v_type == VAR_LIST)
{
list_T *l = tv->vval.v_list;
if (l != NULL && l->lv_copyID != copyID)
{
l->lv_copyID = copyID;
set_ref_in_list(l, copyID);
}
}
else if (tv->v_type == VAR_DICT)
{
dict_T *d = tv->vval.v_dict;
if (d != NULL && d->dv_copyID != copyID)
{
d->dv_copyID = copyID;
set_ref_in_dict(d, copyID);
}
}
}
/* ======= List type ======= */
static luaV_List *
luaV_newlist (lua_State *L, list_T *lis)
{
luaV_List *l = (luaV_List *) lua_newuserdata(L, sizeof(luaV_List));
*l = lis;
lis->lv_refcount++; /* reference in Lua */
luaV_setudata(L, lis); /* cache[lis] = udata */
luaV_getfield(L, LUAVIM_LIST);
lua_setmetatable(L, -2);
return l;
}
luaV_pushtype(list_T, list, luaV_List)
luaV_type_tostring(list, LUAVIM_LIST)
static int
luaV_list_gc (lua_State *L)
{
list_unref(luaV_unbox(L, luaV_List, 1));
return 0;
}
static int
luaV_list_len (lua_State *L)
{
list_T *l = luaV_unbox(L, luaV_List, 1);
lua_pushinteger(L, (l == NULL) ? 0 : (int) l->lv_len);
return 1;
}
static int
luaV_list_iter (lua_State *L)
{
listitem_T *li = (listitem_T *) lua_touserdata(L, lua_upvalueindex(2));
if (li == NULL) return 0;
luaV_pushtypval(L, &li->li_tv);
lua_pushlightuserdata(L, (void *) li->li_next);
lua_replace(L, lua_upvalueindex(2));
return 1;
}
static int
luaV_list_call (lua_State *L)
{
list_T *l = luaV_unbox(L, luaV_List, 1);
lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
lua_pushlightuserdata(L, (void *) l->lv_first);
lua_pushcclosure(L, luaV_list_iter, 2);
return 1;
}
static int
luaV_list_index (lua_State *L)
{
list_T *l = luaV_unbox(L, luaV_List, 1);
if (lua_isnumber(L, 2)) /* list item? */
{
listitem_T *li = list_find(l, (long) luaL_checkinteger(L, 2));
if (li == NULL)
lua_pushnil(L);
else
luaV_pushtypval(L, &li->li_tv);
}
else if (lua_isstring(L, 2)) /* method? */
{
const char *s = lua_tostring(L, 2);
if (strncmp(s, "add", 3) == 0
|| strncmp(s, "insert", 6) == 0
|| strncmp(s, "extend", 6) == 0)
{
lua_getmetatable(L, 1);
lua_getfield(L, -1, s);
}
else
lua_pushnil(L);
}
else
lua_pushnil(L);
return 1;
}
static int
luaV_list_newindex (lua_State *L)
{
list_T *l = luaV_unbox(L, luaV_List, 1);
long n = (long) luaL_checkinteger(L, 2);
listitem_T *li;
if (l->lv_lock)
luaL_error(L, "list is locked");
li = list_find(l, n);
if (li == NULL) return 0;
if (lua_isnil(L, 3)) /* remove? */
{
list_remove(l, li);
clear_tv(&li->li_tv);
vim_free(li);
}
else
{
typval_T v;
luaV_totypval(L, 3, &v);
clear_tv(&li->li_tv);
copy_tv(&v, &li->li_tv);
}
return 0;
}
static int
luaV_list_add (lua_State *L)
{
luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
listitem_T *li;
if (l->lv_lock)
luaL_error(L, "list is locked");
li = listitem_alloc();
if (li != NULL)
{
typval_T v;
lua_settop(L, 2);
luaV_totypval(L, 2, &v);
copy_tv(&v, &li->li_tv);
list_append(l, li);
}
lua_settop(L, 1);
return 1;
}
static int
luaV_list_insert (lua_State *L)
{
luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
long pos = luaL_optlong(L, 3, 0);
listitem_T *li = NULL;
typval_T v;
if (l->lv_lock)
luaL_error(L, "list is locked");
if (pos < l->lv_len)
{
li = list_find(l, pos);
if (li == NULL)
luaL_error(L, "invalid position");
}
lua_settop(L, 2);
luaV_totypval(L, 2, &v);
list_insert_tv(l, &v, li);
lua_settop(L, 1);
return 1;
}
static const luaL_Reg luaV_List_mt[] = {
{"__tostring", luaV_list_tostring},
{"__gc", luaV_list_gc},
{"__len", luaV_list_len},
{"__call", luaV_list_call},
{"__index", luaV_list_index},
{"__newindex", luaV_list_newindex},
{"add", luaV_list_add},
{"insert", luaV_list_insert},
{NULL, NULL}
};
/* ======= Dict type ======= */
static luaV_Dict *
luaV_newdict (lua_State *L, dict_T *dic)
{
luaV_Dict *d = (luaV_Dict *) lua_newuserdata(L, sizeof(luaV_Dict));
*d = dic;
dic->dv_refcount++; /* reference in Lua */
luaV_setudata(L, dic); /* cache[dic] = udata */
luaV_getfield(L, LUAVIM_DICT);
lua_setmetatable(L, -2);
return d;
}
luaV_pushtype(dict_T, dict, luaV_Dict)
luaV_type_tostring(dict, LUAVIM_DICT)
static int
luaV_dict_gc (lua_State *L)
{
dict_unref(luaV_unbox(L, luaV_Dict, 1));
return 0;
}
static int
luaV_dict_len (lua_State *L)
{
dict_T *d = luaV_unbox(L, luaV_Dict, 1);
lua_pushinteger(L, (d == NULL) ? 0 : (int) d->dv_hashtab.ht_used);
return 1;
}
static int
luaV_dict_iter (lua_State *L)
{
hashitem_T *hi = (hashitem_T *) lua_touserdata(L, lua_upvalueindex(2));
int n = lua_tointeger(L, lua_upvalueindex(3));
dictitem_T *di;
if (n <= 0) return 0;
while (HASHITEM_EMPTY(hi)) hi++;
di = dict_lookup(hi);
lua_pushstring(L, (char *) hi->hi_key);
luaV_pushtypval(L, &di->di_tv);
lua_pushlightuserdata(L, (void *) (hi + 1));
lua_replace(L, lua_upvalueindex(2));
lua_pushinteger(L, n - 1);
lua_replace(L, lua_upvalueindex(3));
return 2;
}
static int
luaV_dict_call (lua_State *L)
{
dict_T *d = luaV_unbox(L, luaV_Dict, 1);
hashtab_T *ht = &d->dv_hashtab;
lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
lua_pushlightuserdata(L, (void *) ht->ht_array);
lua_pushinteger(L, ht->ht_used); /* # remaining items */
lua_pushcclosure(L, luaV_dict_iter, 3);
return 1;
}
static int
luaV_dict_index (lua_State *L)
{
dict_T *d = luaV_unbox(L, luaV_Dict, 1);
char_u *key = (char_u *) luaL_checkstring(L, 2);
dictitem_T *di = dict_find(d, key, -1);
if (di == NULL)
lua_pushnil(L);
else
luaV_pushtypval(L, &di->di_tv);
return 1;
}
static int
luaV_dict_newindex (lua_State *L)
{
dict_T *d = luaV_unbox(L, luaV_Dict, 1);
char_u *key = (char_u *) luaL_checkstring(L, 2);
dictitem_T *di;
if (d->dv_lock)
luaL_error(L, "dict is locked");
di = dict_find(d, key, -1);
if (di == NULL) /* non-existing key? */
{
if (lua_isnil(L, 3)) return 0;
di = dictitem_alloc(key);
if (di == NULL) return 0;
if (dict_add(d, di) == FAIL)
{
vim_free(di);
return 0;
}
}
else
clear_tv(&di->di_tv);
if (lua_isnil(L, 3)) /* remove? */
{
hashitem_T *hi = hash_find(&d->dv_hashtab, di->di_key);
hash_remove(&d->dv_hashtab, hi);
dictitem_free(di);
}
else {
typval_T v;
luaV_totypval(L, 3, &v);
copy_tv(&v, &di->di_tv);
}
return 0;
}
static const luaL_Reg luaV_Dict_mt[] = {
{"__tostring", luaV_dict_tostring},
{"__gc", luaV_dict_gc},
{"__len", luaV_dict_len},
{"__call", luaV_dict_call},
{"__index", luaV_dict_index},
{"__newindex", luaV_dict_newindex},
{NULL, NULL}
};
/* ======= Buffer type ======= */
luaV_newtype(buf_T, buffer, luaV_Buffer, LUAVIM_BUFFER)
luaV_pushtype(buf_T, buffer, luaV_Buffer)
luaV_type_tostring(buffer, LUAVIM_BUFFER)
static int
luaV_buffer_len(lua_State *L)
{
buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
lua_pushinteger(L, b->b_ml.ml_line_count);
return 1;
}
static int
luaV_buffer_call(lua_State *L)
{
buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
lua_settop(L, 1);
set_curbuf(b, DOBUF_SPLIT);
return 1;
}
static int
luaV_buffer_index(lua_State *L)
{
buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
linenr_T n = (linenr_T) lua_tointeger(L, 2);
if (n > 0 && n <= b->b_ml.ml_line_count)
luaV_pushline(L, b, n);
else if (lua_isstring(L, 2))
{
const char *s = lua_tostring(L, 2);
if (strncmp(s, "name", 4) == 0)
lua_pushstring(L, (char *) b->b_sfname);
else if (strncmp(s, "fname", 5) == 0)
lua_pushstring(L, (char *) b->b_ffname);
else if (strncmp(s, "number", 6) == 0)
lua_pushinteger(L, b->b_fnum);
/* methods */
else if (strncmp(s, "insert", 6) == 0
|| strncmp(s, "next", 4) == 0
|| strncmp(s, "previous", 8) == 0
|| strncmp(s, "isvalid", 7) == 0)
{
lua_getmetatable(L, 1);
lua_getfield(L, -1, s);
}
else
lua_pushnil(L);
}
else
lua_pushnil(L);
return 1;
}
static int
luaV_buffer_newindex(lua_State *L)
{
buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
linenr_T n = (linenr_T) luaL_checkinteger(L, 2);
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
if (n < 1 || n > b->b_ml.ml_line_count)
luaL_error(L, "invalid line number");
if (lua_isnil(L, 3)) /* delete line */
{
buf_T *buf = curbuf;
curbuf = b;
if (u_savedel(n, 1L) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot save undo information");
}
else if (ml_delete(n, FALSE) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot delete line");
}
else {
deleted_lines_mark(n, 1L);
if (b == curwin->w_buffer) /* fix cursor in current window? */
{
if (curwin->w_cursor.lnum >= n)
{
if (curwin->w_cursor.lnum > n)
{
curwin->w_cursor.lnum -= 1;
check_cursor_col();
}
else check_cursor();
changed_cline_bef_curs();
}
invalidate_botline();
}
}
curbuf = buf;
}
else if (lua_isstring(L, 3)) /* update line */
{
buf_T *buf = curbuf;
curbuf = b;
if (u_savesub(n) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot save undo information");
}
else if (ml_replace(n, luaV_toline(L, 3), TRUE) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot replace line");
}
else changed_bytes(n, 0);
curbuf = buf;
if (b == curwin->w_buffer)
check_cursor_col();
}
else
luaL_error(L, "wrong argument to change line");
return 0;
}
static int
luaV_buffer_insert(lua_State *L)
{
luaV_Buffer *lb = luaV_checkudata(L, 1, LUAVIM_BUFFER);
buf_T *b = (buf_T *) luaV_checkcache(L, (void *) *lb);
linenr_T last = b->b_ml.ml_line_count;
linenr_T n = (linenr_T) luaL_optinteger(L, 3, last);
buf_T *buf;
luaL_checktype(L, 2, LUA_TSTRING);
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
/* fix insertion line */
if (n < 0) n = 0;
if (n > last) n = last;
/* insert */
buf = curbuf;
curbuf = b;
if (u_save(n, n + 1) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot save undo information");
}
else if (ml_append(n, luaV_toline(L, 2), 0, FALSE) == FAIL)
{
curbuf = buf;
luaL_error(L, "cannot insert line");
}
else
appended_lines_mark(n, 1L);
curbuf = buf;
update_screen(VALID);
return 0;
}
static int
luaV_buffer_next(lua_State *L)
{
luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
luaV_pushbuffer(L, buf->b_next);
return 1;
}
static int
luaV_buffer_previous(lua_State *L)
{
luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
luaV_pushbuffer(L, buf->b_prev);
return 1;
}
static int
luaV_buffer_isvalid(lua_State *L)
{
luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
luaV_getudata(L, *b);
lua_pushboolean(L, !lua_isnil(L, -1));
return 1;
}
static const luaL_Reg luaV_Buffer_mt[] = {
{"__tostring", luaV_buffer_tostring},
{"__len", luaV_buffer_len},
{"__call", luaV_buffer_call},
{"__index", luaV_buffer_index},
{"__newindex", luaV_buffer_newindex},
{"insert", luaV_buffer_insert},
{"next", luaV_buffer_next},
{"previous", luaV_buffer_previous},
{"isvalid", luaV_buffer_isvalid},
{NULL, NULL}
};
/* ======= Window type ======= */
luaV_newtype(win_T, window, luaV_Window, LUAVIM_WINDOW)
luaV_pushtype(win_T, window, luaV_Window)
luaV_type_tostring(window, LUAVIM_WINDOW)
static int
luaV_window_call(lua_State *L)
{
win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
lua_settop(L, 1);
win_goto(w);
return 1;
}
static int
luaV_window_index(lua_State *L)
{
win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
const char *s = luaL_checkstring(L, 2);
if (strncmp(s, "buffer", 6) == 0)
luaV_pushbuffer(L, w->w_buffer);
else if (strncmp(s, "line", 4) == 0)
lua_pushinteger(L, w->w_cursor.lnum);
else if (strncmp(s, "col", 3) == 0)
lua_pushinteger(L, w->w_cursor.col + 1);
#ifdef FEAT_VERTSPLIT
else if (strncmp(s, "width", 5) == 0)
lua_pushinteger(L, W_WIDTH(w));
#endif
else if (strncmp(s, "height", 6) == 0)
lua_pushinteger(L, w->w_height);
/* methods */
else if (strncmp(s, "next", 4) == 0
|| strncmp(s, "previous", 8) == 0
|| strncmp(s, "isvalid", 7) == 0)
{
lua_getmetatable(L, 1);
lua_getfield(L, -1, s);
}
else
lua_pushnil(L);
return 1;
}
static int
luaV_window_newindex (lua_State *L)
{
win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
const char *s = luaL_checkstring(L, 2);
int v = luaL_checkinteger(L, 3);
if (strncmp(s, "line", 4) == 0)
{
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
if (v < 1 || v > w->w_buffer->b_ml.ml_line_count)
luaL_error(L, "line out of range");
w->w_cursor.lnum = v;
update_screen(VALID);
}
else if (strncmp(s, "col", 3) == 0)
{
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
w->w_cursor.col = v - 1;
update_screen(VALID);
}
#ifdef FEAT_VERTSPLIT
else if (strncmp(s, "width", 5) == 0)
{
win_T *win = curwin;
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
curwin = w;
win_setwidth(v);
curwin = win;
}
#endif
else if (strncmp(s, "height", 6) == 0)
{
win_T *win = curwin;
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
curwin = w;
win_setheight(v);
curwin = win;
}
else
luaL_error(L, "invalid window property: `%s'", s);
return 0;
}
static int
luaV_window_next(lua_State *L)
{
luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
luaV_pushwindow(L, win->w_next);
return 1;
}
static int
luaV_window_previous(lua_State *L)
{
luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
luaV_pushwindow(L, win->w_prev);
return 1;
}
static int
luaV_window_isvalid(lua_State *L)
{
luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
luaV_getudata(L, *w);
lua_pushboolean(L, !lua_isnil(L, -1));
return 1;
}
static const luaL_Reg luaV_Window_mt[] = {
{"__tostring", luaV_window_tostring},
{"__call", luaV_window_call},
{"__index", luaV_window_index},
{"__newindex", luaV_window_newindex},
{"next", luaV_window_next},
{"previous", luaV_window_previous},
{"isvalid", luaV_window_isvalid},
{NULL, NULL}
};
/* ======= Vim module ======= */
static int
luaV_print(lua_State *L)
{
int i, n = lua_gettop(L); /* nargs */
const char *s;
size_t l;
luaL_Buffer b;
luaL_buffinit(L, &b);
lua_getglobal(L, "tostring");
for (i = 1; i <= n; i++)
{
lua_pushvalue(L, -1); /* tostring */
lua_pushvalue(L, i); /* arg */
lua_call(L, 1, 1);
s = lua_tolstring(L, -1, &l);
if (s == NULL)
return luaL_error(L, "cannot convert to string");
if (i > 1) luaL_addchar(&b, ' '); /* use space instead of tab */
luaV_addlstring(&b, s, l, 0);
lua_pop(L, 1);
}
luaL_pushresult(&b);
luaV_msg(L);
return 0;
}
static int
luaV_debug(lua_State *L)
{
lua_settop(L, 0);
lua_getglobal(L, "vim");
lua_getfield(L, -1, "eval");
lua_remove(L, -2); /* vim.eval at position 1 */
for (;;)
{
const char *input;
size_t l;
lua_pushvalue(L, 1); /* vim.eval */
lua_pushliteral(L, "input('lua_debug> ')");
lua_call(L, 1, 1); /* return string */
input = lua_tolstring(L, -1, &l);
if (l == 0 || strcmp(input, "cont") == 0)
return 0;
msg_putchar('\n'); /* avoid outputting on input line */
if (luaL_loadbuffer(L, input, l, "=(debug command)")
|| lua_pcall(L, 0, 0, 0))
luaV_emsg(L);
lua_settop(L, 1); /* remove eventual returns, but keep vim.eval */
}
}
static int
luaV_command(lua_State *L)
{
do_cmdline_cmd((char_u *) luaL_checkstring(L, 1));
update_screen(VALID);
return 0;
}
static int
luaV_eval(lua_State *L)
{
typval_T *tv = eval_expr((char_u *) luaL_checkstring(L, 1), NULL);
if (tv == NULL) luaL_error(L, "invalid expression");
luaV_pushtypval(L, tv);
return 1;
}
static int
luaV_beep(lua_State *L UNUSED)
{
vim_beep();
return 0;
}
static int
luaV_line(lua_State *L)
{
luaV_pushline(L, curbuf, curwin->w_cursor.lnum);
return 1;
}
static int
luaV_list(lua_State *L)
{
list_T *l = list_alloc();
if (l == NULL)
lua_pushnil(L);
else
luaV_newlist(L, l);
return 1;
}
static int
luaV_dict(lua_State *L)
{
dict_T *d = dict_alloc();
if (d == NULL)
lua_pushnil(L);
else
luaV_newdict(L, d);
return 1;
}
static int
luaV_buffer(lua_State *L)
{
buf_T *buf;
if (lua_isstring(L, 1)) /* get by number or name? */
{
if (lua_isnumber(L, 1)) /* by number? */
{
int n = lua_tointeger(L, 1);
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_fnum == n) break;
}
else { /* by name */
size_t l;
const char *s = lua_tolstring(L, 1, &l);
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
{
if (buf->b_ffname == NULL || buf->b_sfname == NULL)
{
if (l == 0) break;
}
else if (strncmp(s, (char *)buf->b_ffname, l) == 0
|| strncmp(s, (char *)buf->b_sfname, l) == 0)
break;
}
}
}
else
buf = (lua_toboolean(L, 1)) ? firstbuf : curbuf; /* first buffer? */
luaV_pushbuffer(L, buf);
return 1;
}
static int
luaV_window(lua_State *L)
{
win_T *win;
if (lua_isnumber(L, 1)) /* get by number? */
{
int n = lua_tointeger(L, 1);
for (win = firstwin; win != NULL; win = win->w_next, n--)
if (n == 1) break;
}
else
win = (lua_toboolean(L, 1)) ? firstwin : curwin; /* first window? */
luaV_pushwindow(L, win);
return 1;
}
static int
luaV_open(lua_State *L)
{
char_u *s = NULL;
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
if (lua_isstring(L, 1)) s = (char_u *) lua_tostring(L, 1);
luaV_pushbuffer(L, buflist_new(s, NULL, 1L, BLN_LISTED));
return 1;
}
static int
luaV_type(lua_State *L)
{
luaL_checkany(L, 1);
if (lua_type(L, 1) == LUA_TUSERDATA) /* check vim udata? */
{
lua_settop(L, 1);
if (lua_getmetatable(L, 1))
{
luaV_getfield(L, LUAVIM_LIST);
if (lua_rawequal(L, -1, 2))
{
lua_pushstring(L, "list");
return 1;
}
luaV_getfield(L, LUAVIM_DICT);
if (lua_rawequal(L, -1, 2))
{
lua_pushstring(L, "dict");
return 1;
}
luaV_getfield(L, LUAVIM_BUFFER);
if (lua_rawequal(L, -1, 2))
{
lua_pushstring(L, "buffer");
return 1;
}
luaV_getfield(L, LUAVIM_WINDOW);
if (lua_rawequal(L, -1, 2))
{
lua_pushstring(L, "window");
return 1;
}
}
}
lua_pushstring(L, luaL_typename(L, 1)); /* fallback */
return 1;
}
static const luaL_Reg luaV_module[] = {
{"command", luaV_command},
{"eval", luaV_eval},
{"beep", luaV_beep},
{"line", luaV_line},
{"list", luaV_list},
{"dict", luaV_dict},
{"buffer", luaV_buffer},
{"window", luaV_window},
{"open", luaV_open},
{"type", luaV_type},
{NULL, NULL}
};
/* for freeing list, dict, buffer and window objects; lightuserdata as arg */
static int
luaV_free(lua_State *L)
{
lua_pushnil(L);
luaV_setudata(L, lua_touserdata(L, 1));
return 0;
}
static int
luaV_luaeval (lua_State *L)
{
luaL_Buffer b;
size_t l;
const char *str = lua_tolstring(L, 1, &l);
typval_T *arg = (typval_T *) lua_touserdata(L, 2);
typval_T *rettv = (typval_T *) lua_touserdata(L, 3);
luaL_buffinit(L, &b);
luaL_addlstring(&b, LUAVIM_EVALHEADER, sizeof(LUAVIM_EVALHEADER) - 1);
luaL_addlstring(&b, str, l);
luaL_pushresult(&b);
str = lua_tolstring(L, -1, &l);
if (luaL_loadbuffer(L, str, l, LUAVIM_EVALNAME)) /* compile error? */
{
luaV_emsg(L);
return 0;
}
luaV_pushtypval(L, arg);
if (lua_pcall(L, 1, 1, 0)) /* running error? */
{
luaV_emsg(L);
return 0;
}
luaV_totypval(L, -1, rettv);
return 0;
}
static int
luaV_setref (lua_State *L)
{
int copyID = lua_tointeger(L, 1);
typval_T tv;
luaV_getfield(L, LUAVIM_LIST);
luaV_getfield(L, LUAVIM_DICT);
lua_pushnil(L);
while (lua_next(L, lua_upvalueindex(1)) != 0) /* traverse cache table */
{
lua_getmetatable(L, -1);
if (lua_rawequal(L, -1, 2)) /* list? */
{
tv.v_type = VAR_LIST;
tv.vval.v_list = (list_T *) lua_touserdata(L, 4); /* key */
}
else if (lua_rawequal(L, -1, 3)) /* dict? */
{
tv.v_type = VAR_DICT;
tv.vval.v_dict = (dict_T *) lua_touserdata(L, 4); /* key */
}
lua_pop(L, 2); /* metatable and value */
set_ref_in_tv(&tv, copyID);
}
return 0;
}
static int
luaopen_vim(lua_State *L)
{
/* set cache table */
lua_newtable(L);
lua_newtable(L);
lua_pushstring(L, "v");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2); /* cache is weak-valued */
/* print */
lua_pushcfunction(L, luaV_print);
lua_setglobal(L, "print");
/* debug.debug */
lua_getglobal(L, "debug");
lua_pushcfunction(L, luaV_debug);
lua_setfield(L, -2, "debug");
lua_pop(L, 1);
/* free */
lua_pushlightuserdata(L, (void *) LUAVIM_FREE);
lua_pushvalue(L, 1); /* cache table */
lua_pushcclosure(L, luaV_free, 1);
lua_rawset(L, LUA_REGISTRYINDEX);
/* luaeval */
lua_pushlightuserdata(L, (void *) LUAVIM_LUAEVAL);
lua_pushvalue(L, 1); /* cache table */
lua_pushcclosure(L, luaV_luaeval, 1);
lua_rawset(L, LUA_REGISTRYINDEX);
/* setref */
lua_pushlightuserdata(L, (void *) LUAVIM_SETREF);
lua_pushvalue(L, 1); /* cache table */
lua_pushcclosure(L, luaV_setref, 1);
lua_rawset(L, LUA_REGISTRYINDEX);
/* register */
luaV_newmetatable(L, LUAVIM_LIST);
lua_pushvalue(L, 1);
luaV_openlib(L, luaV_List_mt, 1);
luaV_newmetatable(L, LUAVIM_DICT);
lua_pushvalue(L, 1);
luaV_openlib(L, luaV_Dict_mt, 1);
luaV_newmetatable(L, LUAVIM_BUFFER);
lua_pushvalue(L, 1); /* cache table */
luaV_openlib(L, luaV_Buffer_mt, 1);
luaV_newmetatable(L, LUAVIM_WINDOW);
lua_pushvalue(L, 1); /* cache table */
luaV_openlib(L, luaV_Window_mt, 1);
lua_newtable(L); /* vim table */
lua_pushvalue(L, 1); /* cache table */
luaV_openlib(L, luaV_module, 1);
lua_setglobal(L, LUAVIM_NAME);
return 0;
}
static lua_State *
luaV_newstate(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L); /* core libs */
lua_pushcfunction(L, luaopen_vim); /* vim */
lua_call(L, 0, 0);
return L;
}
static void
luaV_setrange(lua_State *L, int line1, int line2)
{
lua_getglobal(L, LUAVIM_NAME);
lua_pushinteger(L, line1);
lua_setfield(L, -2, "firstline");
lua_pushinteger(L, line2);
lua_setfield(L, -2, "lastline");
lua_pop(L, 1); /* vim table */
}
/* ======= Interface ======= */
static lua_State *L = NULL;
static int
lua_isopen(void)
{
return L != NULL;
}
static int
lua_init(void)
{
if (!lua_isopen())
{
#ifdef DYNAMIC_LUA
if (!lua_enabled(TRUE))
{
EMSG(_("Lua library cannot be loaded."));
return FAIL;
}
#endif
L = luaV_newstate();
}
return OK;
}
void
lua_end(void)
{
if (lua_isopen())
{
lua_close(L);
L = NULL;
#ifdef DYNAMIC_LUA
end_dynamic_lua();
#endif
}
}
/* ex commands */
void
ex_lua(exarg_T *eap)
{
char *script;
if (lua_init() == FAIL) return;
script = (char *) script_get(eap, eap->arg);
if (!eap->skip)
{
char *s = (script) ? script : (char *) eap->arg;
luaV_setrange(L, eap->line1, eap->line2);
if (luaL_loadbuffer(L, s, strlen(s), LUAVIM_CHUNKNAME)
|| lua_pcall(L, 0, 0, 0))
luaV_emsg(L);
}
if (script != NULL) vim_free(script);
}
void
ex_luado(exarg_T *eap)
{
linenr_T l;
const char *s = (const char *) eap->arg;
luaL_Buffer b;
size_t len;
if (lua_init() == FAIL) return;
if (u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
{
EMSG(_("cannot save undo information"));
return;
}
luaV_setrange(L, eap->line1, eap->line2);
luaL_buffinit(L, &b);
luaL_addlstring(&b, "return function(line, linenr) ", 30); /* header */
luaL_addlstring(&b, s, strlen(s));
luaL_addlstring(&b, " end", 4); /* footer */
luaL_pushresult(&b);
s = lua_tolstring(L, -1, &len);
if (luaL_loadbuffer(L, s, len, LUAVIM_CHUNKNAME))
{
luaV_emsg(L);
lua_pop(L, 1); /* function body */
return;
}
lua_call(L, 0, 1);
lua_replace(L, -2); /* function -> body */
for (l = eap->line1; l <= eap->line2; l++)
{
lua_pushvalue(L, -1); /* function */
luaV_pushline(L, curbuf, l); /* current line as arg */
lua_pushinteger(L, l); /* current line number as arg */
if (lua_pcall(L, 2, 1, 0))
{
luaV_emsg(L);
break;
}
if (lua_isstring(L, -1)) /* update line? */
{
#ifdef HAVE_SANDBOX
luaV_checksandbox(L);
#endif
ml_replace(l, luaV_toline(L, -1), TRUE);
changed_bytes(l, 0);
lua_pop(L, 1); /* result from luaV_toline */
}
lua_pop(L, 1); /* line */
}
lua_pop(L, 1); /* function */
check_cursor();
update_screen(NOT_VALID);
}
void
ex_luafile(exarg_T *eap)
{
if (lua_init() == FAIL)
return;
if (!eap->skip)
{
luaV_setrange(L, eap->line1, eap->line2);
if (luaL_loadfile(L, (char *) eap->arg) || lua_pcall(L, 0, 0, 0))
luaV_emsg(L);
}
}
#define luaV_freetype(typ,tname) \
void \
lua_##tname##_free(typ *o) \
{ \
if (!lua_isopen()) return; \
luaV_getfield(L, LUAVIM_FREE); \
lua_pushlightuserdata(L, (void *) o); \
lua_call(L, 1, 0); \
}
luaV_freetype(buf_T, buffer)
luaV_freetype(win_T, window)
void
do_luaeval (char_u *str, typval_T *arg, typval_T *rettv)
{
lua_init();
luaV_getfield(L, LUAVIM_LUAEVAL);
lua_pushstring(L, (char *) str);
lua_pushlightuserdata(L, (void *) arg);
lua_pushlightuserdata(L, (void *) rettv);
lua_call(L, 3, 0);
}
void
set_ref_in_lua (int copyID)
{
if (!lua_isopen()) return;
luaV_getfield(L, LUAVIM_SETREF);
lua_pushinteger(L, copyID);
lua_call(L, 1, 0);
}
#endif
| zyz2011-vim | src/if_lua.c | C | gpl2 | 50,336 |
/* 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.
*/
/*
* Enhanced Motif PushButton widget with move over behavior.
*/
#include "vim.h"
#ifdef FEAT_TOOLBAR
#include <Xm/XmP.h>
#include <Xm/DrawP.h>
#if defined(HAVE_XM_TRAITP_H) && defined(HAVE_XM_MANAGER_H) \
&& defined(HAVE_XM_UNHIGHLIGHTT_H) && defined(HAVE_XM_XPMP_H)
# include <Xm/TraitP.h>
# include <Xm/Manager.h>
# include <Xm/UnhighlightT.h>
# include <Xm/XpmP.h>
# define UNHIGHLIGHTT
#else
# include <X11/xpm.h>
#endif
#include <Xm/ManagerP.h>
#include <Xm/Display.h>
#include <Xm/DisplayP.h>
#include <X11/Shell.h>
#include <X11/ShellP.h>
#include "gui_xmebwp.h"
/* Provide some missing wrappers, which are missed from the LessTif
* implementation. Also missing in Motif 1.2 and earlier.
*
* We neither use XmeGetPixmapData or _XmGetPixmapData, since with LessTif the
* pixmap will not appear in it's caches properly. We cache the interesting
* values in XmEnhancedButtonPart instead ourself.
*/
#if defined(LESSTIF_VERSION) || (XmVersion <= 1002)
# ifndef Lab_IsMenupane
# define Lab_IsMenupane(w) (Lab_MenuType(w) == (int)XmMENU_POPUP || \
Lab_MenuType(w) == (int)XmMENU_PULLDOWN)
# endif
# define XmeClearBorder _XmClearBorder
# define XmeDrawShadows _XmDrawShadows
# define XmeDrawHighlight(a, b, c, d, e, f, g, h) \
_XmDrawHighlight(a, b, c, d, e, f, g, h, LineSolid)
#endif
/*
* Motif internals we have to cheat around with.
*/
/* Hopefully this will never change... */
#ifndef XmFOCUS_IGNORE
# define XmFOCUS_IGNORE 1<<1
#endif
extern Boolean _XmGetInDragMode(Widget widget);
extern void _XmPrimitiveEnter(Widget wid,
XEvent * event,
String * params, Cardinal * num_params);
extern void _XmPrimitiveLeave(Widget wid,
XEvent * event,
String * params, Cardinal * num_params);
extern void _XmSetFocusFlag(Widget w, unsigned int mask, Boolean value);
extern void _XmCalcLabelDimensions(Widget wid);
/*
* Declaration of class methods.
*/
static void Destroy(Widget w);
static void Initialize(Widget rq, Widget eb, ArgList args, Cardinal *n);
static Boolean SetValues(Widget current, Widget request, Widget new, ArgList args, Cardinal *n);
static void Redisplay(Widget, XEvent *, Region);
/*
* Declaration of action methods.
*/
static void Enter(Widget, XEvent *, String *, Cardinal *);
static void Leave(Widget, XEvent *, String *, Cardinal *);
static void BorderHighlight(Widget);
static void BorderUnhighlight(Widget);
/*
* 4 x 4 stipple for desensitized widgets
*/
#define stipple_width 4
#define stipple_height 4
static char stipple_bits[] = { 0x0a, 0x05, 0x0a, 0x05 };
#define STIPPLE_BITMAP xmEnhancedButtonClassRec.enhancedbutton_class.stipple_bitmap
/*
* Override actions.
*/
static XtActionsRec actionsList[] =
{
{"Enter", Enter},
{"Leave", Leave},
};
static XtResource resources[] =
{
{
XmNpixmapData, XmCPixmap, XmRString, sizeof(String),
XtOffsetOf(XmEnhancedButtonRec, enhancedbutton.pixmap_data),
XmRImmediate, (XtPointer) NULL
}, {
XmNpixmapFile, XmCPixmap, XmRString, sizeof(String),
XtOffsetOf(XmEnhancedButtonRec, enhancedbutton.pixmap_file),
XmRImmediate, (XtPointer) NULL
}, {
XmNspacing, XmCSpacing, XmRHorizontalDimension, sizeof(Dimension),
XtOffsetOf(XmEnhancedButtonRec, enhancedbutton.spacing),
XmRImmediate, (XtPointer) 2
},
{
XmNlabelLocation, XmCLocation, XmRInt, sizeof(int),
XtOffsetOf(XmEnhancedButtonRec, enhancedbutton.label_location),
XtRImmediate, (XtPointer) XmRIGHT
}
};
/* This is needed to work around a bug in Lesstif 2, leaving the extension
* NULL somehow results in getting it set to an invalid pointer. */
XmPrimitiveClassExtRec xmEnhancedButtonPrimClassExtRec =
{
/* next_extension */ NULL,
/* record_type */ NULLQUARK,
/* version */ XmPrimitiveClassExtVersion,
/* record_size */ sizeof(XmPrimitiveClassExtRec),
/* widget_baseline */ XmInheritBaselineProc,
/* widget_display_rect */ XmInheritDisplayRectProc,
/* widget_margins */ NULL
};
XmEnhancedButtonClassRec xmEnhancedButtonClassRec =
{
{
/* core_class fields */
/* superclass */ (WidgetClass) & xmPushButtonClassRec,
/* class_name */ "XmEnhancedButton",
/* widget_size */ sizeof(XmEnhancedButtonRec),
/* class_initialize */ NULL,
/* class_part_initialize */ NULL,
/* class_inited */ False,
/* initialize */ Initialize,
/* initialize_hook */ NULL,
/* realize */ XtInheritRealize,
/* actions */ actionsList,
/* num_actions */ XtNumber(actionsList),
/* resources */ resources,
/* num_resources */ XtNumber(resources),
/* xrm_class */ NULLQUARK,
/* compress_motion */ True,
/* compress_exposure */ XtExposeCompressMaximal,
/* compress_enterleave */ True,
/* visible_interest */ False,
/* destroy */ Destroy,
/* resize */ XtInheritResize,
/* expose */ Redisplay,
/* set_values */ SetValues,
/* set_values_hook */ NULL,
/* set_values_almost */ XtInheritSetValuesAlmost,
/* get_values_hook */ NULL,
/* accept_focus */ XtInheritAcceptFocus,
/* version */ XtVersion,
/* callback_private */ NULL,
/* tm_table */ NULL,
/* query_geometry */ NULL,
/* display_accelerator */ XtInheritDisplayAccelerator,
/* extension */ NULL
},
/* primitive_class fields */
{
/* border highlight */ BorderHighlight,
/* border_unhighlight */ BorderUnhighlight,
/* translations */ XtInheritTranslations,
/* arm and activate */ XmInheritArmAndActivate,
/* synthetic resources */ NULL,
/* number of syn res */ 0,
/* extension */ (XtPointer)&xmEnhancedButtonPrimClassExtRec,
},
/* label_class fields */
{
/* setOverrideCallback */ XmInheritSetOverrideCallback,
/* menuProcs */ XmInheritMenuProc,
/* translations */ XtInheritTranslations,
/* extension */ NULL,
},
/* pushbutton_class record */
{
/* extension */ (XtPointer) NULL,
},
/* enhancedbutton_class fields */
{
/* stipple_bitmap */ None
}
};
WidgetClass xmEnhancedButtonWidgetClass =
(WidgetClass)&xmEnhancedButtonClassRec;
/*
* Create a slightly fainter pixmap to be shown on button entry.
*/
static unsigned short
bump_color(unsigned short value)
{
int tmp = 2 * (((int) value - 65535) / 3) + 65535;
return tmp;
}
static int
alloc_color(Display *display,
Colormap colormap,
char *colorname,
XColor *xcolor,
void *closure UNUSED)
{
int status;
if (colorname)
if (!XParseColor(display, colormap, colorname, xcolor))
return -1;
xcolor->red = bump_color(xcolor->red);
xcolor->green = bump_color(xcolor->green);
xcolor->blue = bump_color(xcolor->blue);
status = XAllocColor(display, colormap, xcolor);
return status != 0 ? 1 : 0;
}
/* XPM */
static char * blank_xpm[] =
{
/* width height ncolors cpp [x_hot y_hot] */
"12 12 4 1 0 0",
/* colors */
" s iconColor1 m black c #000000",
". s none m none c none",
"X s topShadowColor m none c #DCDEE5",
"o s bottomShadowColor m black c #5D6069",
/* pixels */
" ..",
" XXXXXXXX ..",
" X....... o.",
" X....... o.",
" X....... o.",
" X....... o.",
" X....... o.",
" X....... o.",
" X....... o.",
" o.",
"..ooooooooo.",
"............"};
/*
* Set the pixmap.
*/
static void
set_pixmap(XmEnhancedButtonWidget eb)
{
/* Configure defines XPMATTRIBUTES_TYPE as XpmAttributes or as
* XpmAttributes_21, depending on what is in Xm/XpmP.h. */
XPMATTRIBUTES_TYPE attr;
Pixmap sen_pix;
Window root;
static XpmColorSymbol color[8] = {
{"none", "none", 0},
{"None", "none", 0},
{"background", NULL, 0},
{"foreground", NULL, 0},
{"bottomShadowColor", NULL, 0},
{"topShadowColor", NULL, 0},
{"highlightColor", NULL, 0},
{"armColor", NULL, 0}
};
int scr;
Display *dpy = XtDisplay(eb);
int x;
int y;
unsigned int height, width, border, depth;
int status = 0;
Pixmap mask;
Pixmap pix = None;
Pixmap arm_pix = None;
Pixmap ins_pix = None;
Pixmap high_pix = None;
char **data = (char **) eb->enhancedbutton.pixmap_data;
char *fname = (char *) eb->enhancedbutton.pixmap_file;
int shift;
GC gc;
/* Make sure there is a default value for the pixmap.
*/
if (!data)
return;
gc = XtGetGC((Widget)eb, (XtGCMask)0, NULL);
scr = DefaultScreen(dpy);
root = RootWindow(dpy, scr);
eb->label.pixmap = None;
eb->enhancedbutton.pixmap_depth = 0;
eb->enhancedbutton.pixmap_width = 0;
eb->enhancedbutton.pixmap_height = 0;
eb->enhancedbutton.normal_pixmap = None;
eb->enhancedbutton.armed_pixmap = None;
eb->enhancedbutton.highlight_pixmap = None;
eb->enhancedbutton.insensitive_pixmap = None;
/* We use dynamic colors, get them now. */
motif_get_toolbar_colors(
&eb->core.background_pixel,
&eb->primitive.foreground,
&eb->primitive.bottom_shadow_color,
&eb->primitive.top_shadow_color,
&eb->primitive.highlight_color);
/* Setup color subsititution table. */
color[0].pixel = eb->core.background_pixel;
color[1].pixel = eb->core.background_pixel;
color[2].pixel = eb->core.background_pixel;
color[3].pixel = eb->primitive.foreground;
color[4].pixel = eb->core.background_pixel;
color[5].pixel = eb->primitive.top_shadow_color;
color[6].pixel = eb->primitive.highlight_color;
color[7].pixel = eb->pushbutton.arm_color;
/* Create the "sensitive" pixmap. */
attr.valuemask = XpmColorSymbols | XpmCloseness;
attr.closeness = 65535; /* accuracy isn't crucial */
attr.colorsymbols = color;
attr.numsymbols = XtNumber(color);
if (fname)
status = XpmReadFileToPixmap(dpy, root, fname, &pix, &mask, &attr);
if (!fname || status != XpmSuccess)
status = XpmCreatePixmapFromData(dpy, root, data, &pix, &mask, &attr);
/* If something failed, we will fill in the default pixmap. */
if (status != XpmSuccess)
status = XpmCreatePixmapFromData(dpy, root, blank_xpm, &pix,
&mask, &attr);
XpmFreeAttributes(&attr);
XGetGeometry(dpy, pix, &root, &x, &y, &width, &height, &border, &depth);
if (eb->enhancedbutton.label_location == (int)XmTOP
|| eb->enhancedbutton.label_location == (int)XmBOTTOM)
shift = eb->primitive.shadow_thickness / 2;
else
shift = eb->primitive.shadow_thickness / 2;
if (shift < 1)
shift = 1;
sen_pix = XCreatePixmap(dpy, root, width + shift, height + shift, depth);
XSetForeground(dpy, gc, eb->core.background_pixel);
XFillRectangle(dpy, sen_pix, gc, 0, 0, width + shift, height + shift);
XSetClipMask(dpy, gc, mask);
XSetClipOrigin(dpy, gc, shift, shift);
XCopyArea(dpy, pix, sen_pix, gc, 0, 0, width, height, shift, shift);
/* Create the "highlight" pixmap. */
color[4].pixel = eb->primitive.bottom_shadow_color;
#ifdef XpmAllocColor /* SGI doesn't have it */
attr.valuemask = XpmColorSymbols | XpmCloseness | XpmAllocColor;
attr.alloc_color = alloc_color;
#else
attr.valuemask = XpmColorSymbols | XpmCloseness;
#endif
attr.closeness = 65535; /* accuracy isn't crucial */
attr.colorsymbols = color;
attr.numsymbols = XtNumber(color);
status = XpmCreatePixmapFromData(dpy, root, data, &pix, NULL, &attr);
XpmFreeAttributes(&attr);
high_pix = XCreatePixmap(dpy, root, width + shift, height + shift, depth);
#if 1
XSetForeground(dpy, gc, eb->core.background_pixel);
#else
XSetForeground(dpy, gc, eb->primitive.top_shadow_color);
#endif
XSetClipMask(dpy, gc, None);
XFillRectangle(dpy, high_pix, gc, 0, 0, width + shift, height + shift);
XSetClipMask(dpy, gc, mask);
XSetClipOrigin(dpy, gc, 0, 0);
XCopyArea(dpy, pix, high_pix, gc, 0, 0, width, height, 0, 0);
arm_pix = XCreatePixmap(dpy, pix, width + shift, height + shift, depth);
if (eb->pushbutton.fill_on_arm)
XSetForeground(dpy, gc, eb->pushbutton.arm_color);
else
XSetForeground(dpy, gc, eb->core.background_pixel);
XSetClipOrigin(dpy, gc, shift, shift);
XSetClipMask(dpy, gc, None);
XFillRectangle(dpy, arm_pix, gc, 0, 0, width + shift, height + shift);
XSetClipMask(dpy, gc, mask);
XSetClipOrigin(dpy, gc, 2 * shift, 2 * shift);
XCopyArea(dpy, pix, arm_pix, gc, 0, 0, width, height, 2 * shift, 2 * shift);
XFreePixmap(dpy, pix);
XFreePixmap(dpy, mask);
/* Create the "insensitive" pixmap. */
attr.valuemask = XpmColorSymbols | XpmCloseness | XpmColorKey;
attr.closeness = 65535; /* accuracy isn't crucial */
attr.colorsymbols = color;
attr.numsymbols = sizeof(color) / sizeof(color[0]);
attr.color_key = XPM_MONO;
status = XpmCreatePixmapFromData(dpy, root, data, &pix, &mask, &attr);
/* Need to create new Pixmaps with the mask applied. */
ins_pix = XCreatePixmap(dpy, root, width + shift, height + shift, depth);
XSetForeground(dpy, gc, eb->core.background_pixel);
XSetClipOrigin(dpy, gc, 0, 0);
XSetClipMask(dpy, gc, None);
XFillRectangle(dpy, ins_pix, gc, 0, 0, width + shift, height + shift);
XSetClipMask(dpy, gc, mask);
XSetForeground(dpy, gc, eb->primitive.top_shadow_color);
XSetClipOrigin(dpy, gc, 2 * shift, 2 * shift);
XFillRectangle(dpy, ins_pix, gc, 2 * shift, 2 * shift, width, height);
XSetForeground(dpy, gc, eb->primitive.bottom_shadow_color);
XSetClipOrigin(dpy, gc, shift, shift);
XFillRectangle(dpy, ins_pix, gc, 0, 0, width + shift, height + shift);
XtReleaseGC((Widget) eb, gc);
XpmFreeAttributes(&attr);
eb->enhancedbutton.pixmap_depth = depth;
eb->enhancedbutton.pixmap_width = width;
eb->enhancedbutton.pixmap_height = height;
eb->enhancedbutton.normal_pixmap = sen_pix;
eb->enhancedbutton.highlight_pixmap = high_pix;
eb->enhancedbutton.insensitive_pixmap = ins_pix;
eb->enhancedbutton.armed_pixmap = arm_pix;
eb->enhancedbutton.doing_setvalues = True;
eb->enhancedbutton.doing_setvalues = False;
XFreePixmap(dpy, pix);
XFreePixmap(dpy, mask);
}
#define BUTTON_MASK ( \
Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask \
)
static void
draw_shadows(XmEnhancedButtonWidget eb)
{
GC top_gc;
GC bottom_gc;
Boolean etched_in;
if (!eb->primitive.shadow_thickness)
return;
if ((eb->core.width <= 2 * eb->primitive.highlight_thickness)
|| (eb->core.height <= 2 * eb->primitive.highlight_thickness))
return;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
{
XmDisplay dpy;
dpy = (XmDisplay) XmGetXmDisplay(XtDisplay(eb));
etched_in = dpy->display.enable_etched_in_menu;
}
#else
etched_in = False;
#endif
if (!etched_in ^ eb->pushbutton.armed)
{
top_gc = eb->primitive.top_shadow_GC;
bottom_gc = eb->primitive.bottom_shadow_GC;
}
else
{
top_gc = eb->primitive.bottom_shadow_GC;
bottom_gc = eb->primitive.top_shadow_GC;
}
XmeDrawShadows(XtDisplay(eb), XtWindow(eb),
top_gc,
bottom_gc,
eb->primitive.highlight_thickness,
eb->primitive.highlight_thickness,
eb->core.width - 2 * eb->primitive.highlight_thickness,
eb->core.height - 2 * eb->primitive.highlight_thickness,
eb->primitive.shadow_thickness,
(unsigned)(etched_in ? XmSHADOW_IN : XmSHADOW_OUT));
}
static void
draw_highlight(XmEnhancedButtonWidget eb)
{
eb->primitive.highlighted = True;
eb->primitive.highlight_drawn = True;
if (!XtWidth(eb) || !XtHeight(eb) || !eb->primitive.highlight_thickness)
return;
XmeDrawHighlight(XtDisplay(eb), XtWindow(eb),
eb->primitive.highlight_GC, 0, 0,
XtWidth(eb), XtHeight(eb),
eb->primitive.highlight_thickness);
}
static void
draw_unhighlight(XmEnhancedButtonWidget eb)
{
GC manager_background_GC;
eb->primitive.highlighted = False;
eb->primitive.highlight_drawn = False;
if (!XtWidth(eb) || !XtHeight(eb) || !eb->primitive.highlight_thickness)
return;
if (XmIsManager(eb->core.parent))
{
#ifdef UNHIGHLIGHTT
XmSpecifyUnhighlightTrait UnhighlightT;
if (((UnhighlightT = (XmSpecifyUnhighlightTrait) XmeTraitGet((XtPointer)
XtClass(eb->core.parent), XmQTspecifyUnhighlight))
!= NULL) && (UnhighlightT->getUnhighlightGC != NULL))
{
/* if unhighlight trait in parent use specified GC... */
manager_background_GC =
UnhighlightT->getUnhighlightGC(eb->core.parent, (Widget) eb);
}
else
{
/* ...otherwise, use parent's background GC */
manager_background_GC = ((XmManagerWidget)
(eb->core.parent))->manager.background_GC;
}
#else
manager_background_GC = ((XmManagerWidget)
(eb->core.parent))->manager.background_GC;
#endif
XmeDrawHighlight(XtDisplay(eb), XtWindow(eb),
manager_background_GC,
0, 0, XtWidth(eb), XtHeight(eb),
eb->primitive.highlight_thickness);
if (!eb->pushbutton.armed && eb->primitive.shadow_thickness)
XmeClearBorder(XtDisplay(eb), XtWindow(eb),
eb->primitive.highlight_thickness,
eb->primitive.highlight_thickness,
eb->core.width - 2 * eb->primitive.highlight_thickness,
eb->core.height - 2 * eb->primitive.highlight_thickness,
eb->primitive.shadow_thickness);
}
else
XmeClearBorder(XtDisplay(eb), XtWindow(eb), 0, 0, XtWidth(eb),
XtHeight(eb), eb->primitive.highlight_thickness);
}
static void
draw_pixmap(XmEnhancedButtonWidget eb,
XEvent *event UNUSED,
Region region UNUSED)
{
Pixmap pix;
GC gc = eb->label.normal_GC;
int depth;
Cardinal width;
Cardinal height;
Cardinal w;
Cardinal h;
int x;
int y;
if (!XtIsSensitive((Widget) eb))
pix = eb->enhancedbutton.insensitive_pixmap;
else
{
if (eb->primitive.highlighted && !eb->pushbutton.armed)
pix = eb->enhancedbutton.highlight_pixmap;
else if (eb->pushbutton.armed)
pix = eb->enhancedbutton.armed_pixmap;
else
pix = eb->enhancedbutton.normal_pixmap;
}
if (pix == None || !eb->enhancedbutton.pixmap_data)
return;
depth = eb->enhancedbutton.pixmap_depth;
w = eb->enhancedbutton.pixmap_width;
h = eb->enhancedbutton.pixmap_height;
gc = eb->label.normal_GC;
x = eb->primitive.highlight_thickness
+ eb->primitive.shadow_thickness
+ eb->label.margin_width;
y = eb->primitive.highlight_thickness
+ eb->primitive.shadow_thickness
+ eb->label.margin_height;
width = eb->core.width - 2 * x;
if (w < width)
width = w;
height = eb->core.height - 2 * y;
if (h < height)
height = h;
if (depth == (int)eb->core.depth)
XCopyArea(XtDisplay(eb), pix, XtWindow(eb), gc, 0, 0,
width, height, x, y);
else if (depth == 1)
XCopyPlane(XtDisplay(eb), pix, XtWindow(eb), gc, 0, 0,
width, height, x, y, (unsigned long)1);
}
/*
* Draw the label contained in the pushbutton.
*/
static void
draw_label(XmEnhancedButtonWidget eb, XEvent *event, Region region)
{
GC tmp_gc = NULL;
Boolean replaceGC = False;
Boolean deadjusted = False;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
XmDisplay dpy = (XmDisplay)XmGetXmDisplay(XtDisplay(eb));
Boolean etched_in = dpy->display.enable_etched_in_menu;
#else
Boolean etched_in = False;
#endif
if (eb->pushbutton.armed
&& ((!Lab_IsMenupane(eb) && eb->pushbutton.fill_on_arm)
|| (Lab_IsMenupane(eb) && etched_in)))
{
if (eb->label.label_type == (int)XmSTRING
&& eb->pushbutton.arm_color == eb->primitive.foreground)
{
tmp_gc = eb->label.normal_GC;
eb->label.normal_GC = eb->pushbutton.background_gc;
replaceGC = True;
}
}
/*
* If the button contains a labeled pixmap, we will take it instead of our
* own pixmap.
*/
if (eb->label.label_type == (int)XmPIXMAP)
{
if (eb->pushbutton.armed)
{
if (eb->pushbutton.arm_pixmap != XmUNSPECIFIED_PIXMAP)
eb->label.pixmap = eb->pushbutton.arm_pixmap;
else
eb->label.pixmap = eb->pushbutton.unarm_pixmap;
}
else
/* pushbutton is not armed */
eb->label.pixmap = eb->pushbutton.unarm_pixmap;
}
/*
* Temporarily remove the Xm3D_ENHANCE_PIXEL hack ("adjustment") from the
* margin values, so we don't confuse Label.
*/
if (eb->pushbutton.default_button_shadow_thickness > 0)
{
deadjusted = True;
Lab_MarginLeft(eb) -= Xm3D_ENHANCE_PIXEL;
Lab_MarginRight(eb) -= Xm3D_ENHANCE_PIXEL;
Lab_MarginTop(eb) -= Xm3D_ENHANCE_PIXEL;
Lab_MarginBottom(eb) -= Xm3D_ENHANCE_PIXEL;
}
{
XtExposeProc expose;
XtProcessLock();
expose = xmLabelClassRec.core_class.expose;
XtProcessUnlock();
(*expose)((Widget) eb, event, region);
}
if (deadjusted)
{
Lab_MarginLeft(eb) += Xm3D_ENHANCE_PIXEL;
Lab_MarginRight(eb) += Xm3D_ENHANCE_PIXEL;
Lab_MarginTop(eb) += Xm3D_ENHANCE_PIXEL;
Lab_MarginBottom(eb) += Xm3D_ENHANCE_PIXEL;
}
if (replaceGC)
eb->label.normal_GC = tmp_gc;
}
static void
Enter(Widget wid,
XEvent *event,
String *params UNUSED,
Cardinal *num_params UNUSED)
{
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget) wid;
XmPushButtonCallbackStruct call_value;
if (Lab_IsMenupane(eb))
{
if ((((ShellWidget) XtParent(XtParent(eb)))->shell.popped_up)
&& _XmGetInDragMode((Widget) eb))
{
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
XmDisplay dpy = (XmDisplay) XmGetXmDisplay(XtDisplay(wid));
Boolean etched_in = dpy->display.enable_etched_in_menu;
#else
Boolean etched_in = False;
#endif
if (eb->pushbutton.armed)
return;
/* ...so KHelp event is delivered correctly. */
_XmSetFocusFlag(XtParent(XtParent(eb)), XmFOCUS_IGNORE, TRUE);
XtSetKeyboardFocus(XtParent(XtParent(eb)), (Widget) eb);
_XmSetFocusFlag(XtParent(XtParent(eb)), XmFOCUS_IGNORE, FALSE);
eb->pushbutton.armed = TRUE;
((XmManagerWidget) XtParent(wid))->manager.active_child = wid;
/* etched in menu button */
if (etched_in && !XmIsTearOffButton(eb))
{
XFillRectangle(XtDisplay(eb), XtWindow(eb),
eb->pushbutton.fill_gc,
0, 0, eb->core.width, eb->core.height);
draw_label(eb, event, NULL);
draw_pixmap(eb, event, NULL);
}
if ((eb->core.width > 2 * eb->primitive.highlight_thickness)
&& (eb->core.height >
2 * eb->primitive.highlight_thickness))
{
XmeDrawShadows(XtDisplay(eb), XtWindow(eb),
eb->primitive.top_shadow_GC,
eb->primitive.bottom_shadow_GC,
eb->primitive.highlight_thickness,
eb->primitive.highlight_thickness,
eb->core.width - 2 * eb->primitive.highlight_thickness,
eb->core.height - 2 * eb->primitive.highlight_thickness,
eb->primitive.shadow_thickness,
(unsigned)(etched_in ? XmSHADOW_IN : XmSHADOW_OUT));
}
if (eb->pushbutton.arm_callback)
{
XFlush(XtDisplay(eb));
call_value.reason = (int)XmCR_ARM;
call_value.event = event;
XtCallCallbackList((Widget) eb,
eb->pushbutton.arm_callback,
&call_value);
}
}
}
else
{
XtExposeProc expose;
_XmPrimitiveEnter((Widget) eb, event, NULL, NULL);
if (eb->pushbutton.armed == TRUE)
{
XtProcessLock();
expose = XtClass(eb)->core_class.expose;
XtProcessUnlock();
(*expose) (wid, event, (Region) NULL);
}
draw_highlight(eb);
draw_shadows(eb);
draw_pixmap(eb, event, NULL);
}
}
static void
Leave(Widget wid,
XEvent *event,
String *params UNUSED,
Cardinal *num_params UNUSED)
{
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget)wid;
XmPushButtonCallbackStruct call_value;
if (Lab_IsMenupane(eb))
{
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
XmDisplay dpy = (XmDisplay) XmGetXmDisplay(XtDisplay(wid));
Boolean etched_in = dpy->display.enable_etched_in_menu;
#else
Boolean etched_in = False;
#endif
if (_XmGetInDragMode((Widget)eb)
&& eb->pushbutton.armed
&& ( /* !ActiveTearOff || */
event->xcrossing.mode == NotifyNormal))
{
eb->pushbutton.armed = FALSE;
((XmManagerWidget) XtParent(wid))->manager.active_child = NULL;
if (etched_in && !XmIsTearOffButton(eb))
{
XFillRectangle(XtDisplay(eb), XtWindow(eb),
eb->pushbutton.background_gc,
0, 0, eb->core.width, eb->core.height);
draw_label(eb, event, NULL);
draw_pixmap(eb, event, NULL);
}
else
XmeClearBorder
(XtDisplay(eb), XtWindow(eb),
eb->primitive.highlight_thickness,
eb->primitive.highlight_thickness,
eb->core.width -
2 * eb->primitive.highlight_thickness,
eb->core.height -
2 * eb->primitive.highlight_thickness,
eb->primitive.shadow_thickness);
if (eb->pushbutton.disarm_callback)
{
XFlush(XtDisplay(eb));
call_value.reason = (int)XmCR_DISARM;
call_value.event = event;
XtCallCallbackList((Widget) eb,
eb->pushbutton.disarm_callback,
&call_value);
}
}
}
else
{
_XmPrimitiveLeave((Widget) eb, event, NULL, NULL);
if (eb->pushbutton.armed == TRUE)
{
XtExposeProc expose;
eb->pushbutton.armed = FALSE;
XtProcessLock();
expose = XtClass(eb)->core_class.expose;
XtProcessUnlock();
(*expose) (wid, event, (Region)NULL);
draw_unhighlight(eb);
draw_pixmap(eb, event, NULL);
eb->pushbutton.armed = TRUE;
}
else
{
draw_unhighlight(eb);
draw_pixmap(eb, event, NULL);
}
}
}
#define IsNull(p) ((p) == XmUNSPECIFIED_PIXMAP)
static void
set_size(XmEnhancedButtonWidget newtb)
{
unsigned int w = 0;
unsigned int h = 0;
_XmCalcLabelDimensions((Widget) newtb);
/* Find out how big the pixmap is */
if (newtb->enhancedbutton.pixmap_data
&& !IsNull(newtb->label.pixmap)
&& !IsNull(newtb->enhancedbutton.normal_pixmap))
{
w = newtb->enhancedbutton.pixmap_width;
h = newtb->enhancedbutton.pixmap_height;
}
/*
* Plase note that we manipulate the width only in case of push buttons not
* used in the context of a menu pane.
*/
if (Lab_IsMenupane(newtb))
{
newtb->label.margin_left = w + 2 * (newtb->primitive.shadow_thickness
+ newtb->primitive.highlight_thickness)
+ newtb->label.margin_width;
}
else
{
newtb->label.margin_left = w;
newtb->core.width = w + 2 * (newtb->primitive.shadow_thickness
+ newtb->primitive.highlight_thickness
+ newtb->label.margin_width)
+ newtb->label.TextRect.width;
if (newtb->label.TextRect.width > 0)
{
newtb->label.margin_left += newtb->label.margin_width
+ newtb->primitive.shadow_thickness;
newtb->core.width += newtb->label.margin_width
+ newtb->primitive.shadow_thickness;
}
}
if (newtb->label.TextRect.height < h)
{
newtb->core.height = h + 2 * (newtb->primitive.shadow_thickness
+ newtb->primitive.highlight_thickness
+ newtb->label.margin_height);
}
else
{
/* FIXME: We should calculate an drawing offset for the pixmap here to
* adjust it. */
}
#if 0
printf("%d %d %d %d %d %d - %d %d\n", newtb->enhancedbutton.normal_pixmap,
h, newtb->core.height,
newtb->primitive.shadow_thickness,
newtb->primitive.highlight_thickness,
newtb->label.margin_height,
newtb->core.width,
newtb->core.height);
#endif
/* Invoke Label's Resize procedure. */
{
XtWidgetProc resize;
XtProcessLock();
resize = xmLabelClassRec.core_class.resize;
XtProcessUnlock();
(* resize) ((Widget) newtb);
}
}
static void
Initialize(Widget rq, Widget ebw, ArgList args UNUSED, Cardinal *n UNUSED)
{
XmEnhancedButtonWidget request = (XmEnhancedButtonWidget)rq;
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget)ebw;
XtWidgetProc resize;
XtProcessLock();
resize = xmLabelClassRec.core_class.resize;
XtProcessUnlock();
/* Create a bitmap for stippling (Drawable resources are cheap). */
if (STIPPLE_BITMAP == None)
{
Display *dpy = XtDisplay((Widget) request);
Window rootW = DefaultRootWindow(dpy);
STIPPLE_BITMAP = XCreateBitmapFromData(dpy, rootW, stipple_bits,
stipple_width, stipple_height);
}
eb->enhancedbutton.doing_setvalues = False;
/* First see what type of extended label this is.
*/
if (eb->enhancedbutton.pixmap_data)
{
XmString str;
set_pixmap(eb);
/* FIXME: this is not the perfect way to deal with menues, which do not
* have any string set right now. */
str = XmStringCreateLocalized("");
XtVaSetValues((Widget) eb, XmNlabelString, str, NULL);
XmStringFree(str);
}
eb->label.pixmap = eb->enhancedbutton.normal_pixmap;
if (request->core.width == 0)
eb->core.width = 0;
if (request->core.height == 0)
eb->core.height = 0;
set_size(eb);
(* resize)((Widget)eb);
}
static void
free_pixmaps(XmEnhancedButtonWidget eb)
{
/*
* Clear the old pixmaps.
*/
Pixmap norm_pix = eb->enhancedbutton.normal_pixmap;
Pixmap arm_pix = eb->enhancedbutton.armed_pixmap;
Pixmap insen_pix = eb->enhancedbutton.insensitive_pixmap;
Pixmap high_pix = eb->enhancedbutton.highlight_pixmap;
if (norm_pix != None && norm_pix != XmUNSPECIFIED_PIXMAP)
XFreePixmap(XtDisplay(eb), norm_pix);
if (arm_pix != None && arm_pix != XmUNSPECIFIED_PIXMAP)
XFreePixmap(XtDisplay(eb), arm_pix);
if (insen_pix != None && insen_pix != XmUNSPECIFIED_PIXMAP)
XFreePixmap(XtDisplay(eb), insen_pix);
if (high_pix != None && high_pix != XmUNSPECIFIED_PIXMAP)
XFreePixmap(XtDisplay(eb), high_pix);
}
static void
Destroy(Widget w)
{
if (!XmIsEnhancedButton(w))
return;
free_pixmaps((XmEnhancedButtonWidget)w);
}
static Boolean
SetValues(Widget current,
Widget request UNUSED,
Widget new,
ArgList args UNUSED,
Cardinal *n UNUSED)
{
XmEnhancedButtonWidget cur = (XmEnhancedButtonWidget) current;
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget) new;
Boolean redraw = False;
Boolean change = True;
Display *dpy = XtDisplay(current);
#define NOT_EQUAL(field) (cur->field != eb->field)
/*
* Make sure that lost sensitivity is causing the border to vanish as well.
*/
if (NOT_EQUAL(core.sensitive) && !Lab_IsMenupane(current))
{
if (cur->core.sensitive == True)
{
draw_unhighlight(eb);
}
else
{
int r_x;
int r_y;
unsigned int r_height;
unsigned int r_width;
unsigned int r_border;
unsigned int r_depth;
int root_x;
int root_y;
int win_x;
int win_y;
Window root;
Window root_q;
Window child;
unsigned int mask;
/*
* Artificially let the highlight appear if the mouse is over us.
*/
/* Best way to get the root window of object: */
XGetGeometry(dpy, XtWindow(cur), &root, &r_x, &r_y, &r_width,
&r_height, &r_border, &r_depth);
XQueryPointer(XtDisplay(cur), XtWindow(cur), &root_q, &child,
&root_x, &root_y, &win_x, &win_y, &mask);
if (root == root_q)
{
if ((win_x < 0) || (win_y < 0))
return False;
if ((win_x > (int)r_width) || (win_y > (int)r_height))
return False;
draw_highlight(eb);
draw_shadows(eb);
}
}
return True;
}
/*
* Check for changed ExtLabelString.
*/
if (NOT_EQUAL(primitive.shadow_thickness))
{
redraw = True;
/* Don't change the pixmaps */
change = False;
}
if (NOT_EQUAL(primitive.foreground))
redraw = True;
if (NOT_EQUAL(core.background_pixel))
redraw = True;
if (NOT_EQUAL(pushbutton.fill_on_arm))
redraw = True;
if (NOT_EQUAL(enhancedbutton.spacing))
redraw = True;
if (NOT_EQUAL(enhancedbutton.label_location))
{
redraw = True;
change = False;
}
if (NOT_EQUAL(label._label))
{
redraw = True;
set_size(eb);
}
if (redraw == True)
{
if (change)
set_pixmap(eb);
if (eb->primitive.highlighted)
eb->label.pixmap = eb->enhancedbutton.highlight_pixmap;
else
eb->label.pixmap = eb->enhancedbutton.normal_pixmap;
if (change)
set_size(eb);
redraw = False;
}
return redraw;
}
static void
Redisplay(Widget w, XEvent *event, Region region)
{
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget) w;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
XmDisplay dpy;
XtEnum default_button_emphasis;
#endif
XRectangle box;
int dx;
int adjust;
short fill = 0;
if (!XtIsRealized((Widget)eb))
return;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
dpy = (XmDisplay)XmGetXmDisplay(XtDisplay(eb));
default_button_emphasis = dpy->display.default_button_emphasis;
#endif
/*
* Compute the area allocated to the label of the pushbutton; fill in the
* dimensions in the box.
*/
if ((eb->pushbutton.arm_color == eb->primitive.top_shadow_color)
|| (eb->pushbutton.arm_color == eb->primitive.bottom_shadow_color))
fill = 1;
if (eb->pushbutton.compatible)
adjust = eb->pushbutton.show_as_default;
else
adjust = eb->pushbutton.default_button_shadow_thickness;
if (adjust > 0)
{
adjust = adjust + eb->primitive.shadow_thickness;
adjust = (adjust << 1);
dx = eb->primitive.highlight_thickness + adjust + fill;
}
else
dx = (eb->primitive.highlight_thickness
+ eb->primitive.shadow_thickness + fill);
box.x = dx;
box.y = dx;
adjust = (dx << 1);
box.width = eb->core.width - adjust;
box.height = eb->core.height - adjust;
/*
* Redraw the background.
*/
if (!Lab_IsMenupane(eb))
{
GC gc;
/* Don't shade if the button contains a label with a pixmap, since
* there is no variant of the label available with the needed
* background.
*/
if (eb->pushbutton.armed && eb->pushbutton.fill_on_arm)
{
if (eb->label.label_type == (int)XmPIXMAP)
{
if (eb->pushbutton.arm_pixmap != XmUNSPECIFIED_PIXMAP)
gc = eb->pushbutton.fill_gc;
else
gc = eb->pushbutton.background_gc;
}
else
gc = eb->pushbutton.fill_gc;
}
else
gc = eb->pushbutton.background_gc;
/* really need to fill with background if not armed ? */
if (gc)
XFillRectangle(XtDisplay(eb), XtWindow(eb), gc,
box.x, box.y, box.width, box.height);
}
draw_label(eb, event, region);
if (Lab_IsMenupane(eb))
{
if (eb->pushbutton.armed)
(*(((XmPushButtonWidgetClass)XtClass(eb))
->primitive_class.border_highlight))(w);
draw_pixmap(eb, event, region);
}
else
{
adjust = 0;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
/*
* NOTE: PushButton has two types of shadows: primitive-shadow and
* default-button-shadow. If pushbutton is in a menu only primitive
* shadows are drawn.
*/
switch (default_button_emphasis)
{
case XmEXTERNAL_HIGHLIGHT:
adjust = (eb->primitive.highlight_thickness -
(eb->pushbutton.default_button_shadow_thickness
? Xm3D_ENHANCE_PIXEL : 0));
break;
case XmINTERNAL_HIGHLIGHT:
break;
default:
assert(FALSE);
return;
}
#endif
/*
* Clear the area not occupied by label with parents background color.
* Label will invoke BorderUnhighlight() on the highlight_thickness
* area, which is redundant when XmEXTERNAL_HIGHLIGHT default button
* shadow emphasis is used.
*/
if (box.x > adjust)
{
int borderwidth =box.x - adjust;
int rectwidth = eb->core.width - 2 * adjust;
int rectheight = eb->core.height - 2 * adjust;
if (XmIsManager(XtParent(eb)))
{
XmeDrawHighlight(XtDisplay(eb), XtWindow(eb),
XmParentBackgroundGC(eb),
adjust, adjust, rectwidth, rectheight, borderwidth);
}
else
{
XmeClearBorder(XtDisplay(eb), XtWindow(eb),
adjust, adjust, rectwidth, rectheight, borderwidth);
}
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
switch (default_button_emphasis)
{
case XmINTERNAL_HIGHLIGHT:
/* The call above erases the border highlighting. */
if (eb->primitive.highlight_drawn)
(*(((XmPushButtonWidgetClass) XtClass (eb))
->primitive_class.border_highlight)) ((Widget) eb) ;
break;
default:
break;
}
#endif
}
if (eb->pushbutton.default_button_shadow_thickness)
{
if (eb->pushbutton.show_as_default)
{
/*
* - get the topShadowColor and bottomShadowColor from the
* parent; use those colors to construct top and bottom gc;
* use these GCs to draw the shadows of the button.
*
* - Should not be called if pushbutton is in a row column or
* in a menu.
*
* - Should be called only if a defaultbuttonshadow is to be
* drawn.
*/
GC top_gc;
GC bottom_gc;
int default_button_shadow_thickness;
int x, y, width, height, delta;
Widget parent;
if (eb->pushbutton.compatible
&& (eb->pushbutton.show_as_default == 0))
return;
if (!eb->pushbutton.compatible
&& (eb->pushbutton.default_button_shadow_thickness
== 0))
return;
delta = eb->primitive.highlight_thickness;
/*
* May need more complex computation for getting the GCs.
*/
parent = XtParent(eb);
if (XmIsManager(parent))
{
/* Use the parent's GC so monochrome works. */
bottom_gc = XmParentTopShadowGC(eb);
top_gc = XmParentBottomShadowGC(eb);
}
else
{
/* Use your own pixel for drawing. */
bottom_gc = eb->primitive.top_shadow_GC;
top_gc = eb->primitive.bottom_shadow_GC;
}
if ((bottom_gc == None) || (top_gc == None))
return;
if (eb->pushbutton.compatible)
default_button_shadow_thickness =
eb->pushbutton.show_as_default;
else
default_button_shadow_thickness =
eb->pushbutton.default_button_shadow_thickness;
#if !defined(LESSTIF_VERSION) && (XmVersion > 1002)
/*
* Compute location of bounding box to contain the
* defaultButtonShadow.
*/
switch (default_button_emphasis)
{
case XmEXTERNAL_HIGHLIGHT:
delta = eb->primitive.highlight_thickness;
break;
case XmINTERNAL_HIGHLIGHT:
delta = Xm3D_ENHANCE_PIXEL;
break;
default:
assert(FALSE);
return;
}
#endif
x = y = delta;
width = eb->core.width - 2 * delta;
height = eb->core.height - 2 * delta;
if ((width > 0) && (height > 0))
XmeDrawShadows(XtDisplay(eb), XtWindow(eb),
top_gc, bottom_gc, x, y, width, height,
default_button_shadow_thickness,
(unsigned)XmSHADOW_OUT);
}
}
if (eb->primitive.highlight_drawn)
draw_shadows(eb);
draw_pixmap(eb, event, region);
}
}
static void
BorderHighlight(Widget w)
{
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget)w;
(*(xmPushButtonClassRec.primitive_class.border_highlight))(w);
draw_pixmap(eb, NULL, NULL);
}
static void
BorderUnhighlight(Widget w)
{
XmEnhancedButtonWidget eb = (XmEnhancedButtonWidget)w;
(*(xmPushButtonClassRec.primitive_class.border_unhighlight))(w);
draw_pixmap(eb, NULL, NULL);
}
#endif /* FEAT_TOOLBAR */
| zyz2011-vim | src/gui_xmebw.c | C | gpl2 | 39,621 |
/* 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.
*/
/*
* The stuff in this file mostly comes from the "screen" program.
* Included with permission from Juergen Weigert.
* Copied from "pty.c". "putenv.c" was used for putenv() in misc2.c.
*
* It has been modified to work better with Vim.
* The parts that are not used in Vim have been deleted.
* See the "screen" sources for the complete stuff.
*
* This specific version is distibuted under the Vim license (attribution by
* Juergen Weigert), the GPL applies to the original version, see the
* copyright notice below.
*/
/* Copyright (c) 1993
* Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de)
* Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de)
* Copyright (c) 1987 Oliver Laumann
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see the file COPYING); if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "vim.h"
#include <signal.h>
#ifdef __CYGWIN32__
# include <sys/termios.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#if HAVE_STROPTS_H
#include <sys/types.h>
#ifdef sinix
#define buf_T __system_buf_t__
#endif
#include <stropts.h>
#ifdef sinix
#undef buf_T
#endif
# ifdef sun
# include <sys/conf.h>
# endif
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#if HAVE_TERMIO_H
# include <termio.h>
#else
# ifdef HAVE_TERMIOS_H
# include <termios.h>
# endif
#endif
#if HAVE_SYS_STREAM_H
# include <sys/stream.h>
#endif
#if HAVE_SYS_PTEM_H
# include <sys/ptem.h>
#endif
#if !defined(sun) && !defined(VMS) && !defined(MACOS)
# include <sys/ioctl.h>
#endif
#if defined(sun) && defined(LOCKPTY) && !defined(TIOCEXCL)
# include <sys/ttold.h>
#endif
#ifdef ISC
# include <sys/tty.h>
# include <sys/sioctl.h>
# include <sys/pty.h>
#endif
#ifdef sgi
# include <sys/sysmacros.h>
#endif
#if defined(_INCLUDE_HPUX_SOURCE) && !defined(hpux)
# define hpux
#endif
/*
* if no PTYRANGE[01] is in the config file, we pick a default
*/
#ifndef PTYRANGE0
# define PTYRANGE0 "qprs"
#endif
#ifndef PTYRANGE1
# define PTYRANGE1 "0123456789abcdef"
#endif
/* SVR4 pseudo ttys don't seem to work with SCO-5 */
#ifdef M_UNIX
# undef HAVE_SVR4_PTYS
#endif
static void initmaster __ARGS((int));
/*
* Open all ptys with O_NOCTTY, just to be on the safe side.
*/
#ifndef O_NOCTTY
# define O_NOCTTY 0
#endif
static void
initmaster(f)
int f UNUSED;
{
#ifndef VMS
# ifdef POSIX
tcflush(f, TCIOFLUSH);
# else
# ifdef TIOCFLUSH
(void)ioctl(f, TIOCFLUSH, (char *) 0);
# endif
# endif
# ifdef LOCKPTY
(void)ioctl(f, TIOCEXCL, (char *) 0);
# endif
#endif
}
/*
* This causes a hang on some systems, but is required for a properly working
* pty on others. Needs to be tuned...
*/
int
SetupSlavePTY(fd)
int fd;
{
if (fd < 0)
return 0;
#if defined(I_PUSH) && defined(HAVE_SVR4_PTYS) && !defined(sgi) && !defined(linux) && !defined(__osf__) && !defined(M_UNIX)
# if defined(HAVE_SYS_PTEM_H) || defined(hpux)
if (ioctl(fd, I_PUSH, "ptem") != 0)
return -1;
# endif
if (ioctl(fd, I_PUSH, "ldterm") != 0)
return -1;
# ifdef sun
if (ioctl(fd, I_PUSH, "ttcompat") != 0)
return -1;
# endif
#endif
return 0;
}
#if defined(OSX) && !defined(PTY_DONE)
#define PTY_DONE
int
OpenPTY(ttyn)
char **ttyn;
{
int f;
static char TtyName[32];
if ((f = open_controlling_pty(TtyName)) < 0)
return -1;
initmaster(f);
*ttyn = TtyName;
return f;
}
#endif
#if (defined(sequent) || defined(_SEQUENT_)) && defined(HAVE_GETPSEUDOTTY) \
&& !defined(PTY_DONE)
#define PTY_DONE
int
OpenPTY(ttyn)
char **ttyn;
{
char *m, *s;
int f;
/* used for opening a new pty-pair: */
static char PtyName[32];
static char TtyName[32];
if ((f = getpseudotty(&s, &m)) < 0)
return -1;
#ifdef _SEQUENT_
fvhangup(s);
#endif
vim_strncpy((char_u *)PtyName, (char_u *)m, sizeof(PtyName) - 1);
vim_strncpy((char_u *)TtyName, (char_u *)s, sizeof(TtyName) - 1);
initmaster(f);
*ttyn = TtyName;
return f;
}
#endif
#if defined(__sgi) && !defined(PTY_DONE)
#define PTY_DONE
int
OpenPTY(ttyn)
char **ttyn;
{
int f;
char *name;
RETSIGTYPE (*sigcld)__ARGS(SIGPROTOARG);
/*
* SIGCHLD set to SIG_DFL for _getpty() because it may fork() and
* exec() /usr/adm/mkpts
*/
sigcld = signal(SIGCHLD, SIG_DFL);
name = _getpty(&f, O_RDWR | O_NONBLOCK | O_EXTRA, 0600, 0);
signal(SIGCHLD, sigcld);
if (name == 0)
return -1;
initmaster(f);
*ttyn = name;
return f;
}
#endif
#if defined(MIPS) && defined(HAVE_DEV_PTC) && !defined(PTY_DONE)
#define PTY_DONE
int
OpenPTY(ttyn)
char **ttyn;
{
int f;
struct stat buf;
/* used for opening a new pty-pair: */
static char TtyName[32];
if ((f = open("/dev/ptc", O_RDWR | O_NOCTTY | O_NONBLOCK | O_EXTRA, 0)) < 0)
return -1;
if (mch_fstat(f, &buf) < 0)
{
close(f);
return -1;
}
sprintf(TtyName, "/dev/ttyq%d", minor(buf.st_rdev));
initmaster(f);
*ttyn = TtyName;
return f;
}
#endif
#if defined(HAVE_SVR4_PTYS) && !defined(PTY_DONE) && !defined(hpux) && !defined(MACOS_X)
/* NOTE: Even though HPUX can have /dev/ptmx, the code below doesn't work!
* Same for Mac OS X Leopard. */
#define PTY_DONE
int
OpenPTY(ttyn)
char **ttyn;
{
int f;
char *m;
char *(ptsname __ARGS((int)));
int unlockpt __ARGS((int));
int grantpt __ARGS((int));
RETSIGTYPE (*sigcld)__ARGS(SIGPROTOARG);
/* used for opening a new pty-pair: */
static char TtyName[32];
if ((f = open("/dev/ptmx", O_RDWR | O_NOCTTY | O_EXTRA, 0)) == -1)
return -1;
/*
* SIGCHLD set to SIG_DFL for grantpt() because it fork()s and
* exec()s pt_chmod
*/
sigcld = signal(SIGCHLD, SIG_DFL);
if ((m = ptsname(f)) == NULL || grantpt(f) || unlockpt(f))
{
signal(SIGCHLD, sigcld);
close(f);
return -1;
}
signal(SIGCHLD, sigcld);
vim_strncpy((char_u *)TtyName, (char_u *)m, sizeof(TtyName) - 1);
initmaster(f);
*ttyn = TtyName;
return f;
}
#endif
#if defined(_AIX) && defined(HAVE_DEV_PTC) && !defined(PTY_DONE)
#define PTY_DONE
#ifdef _IBMR2
int aixhack = -1;
#endif
int
OpenPTY(ttyn)
char **ttyn;
{
int f;
/* used for opening a new pty-pair: */
static char TtyName[32];
/* a dumb looking loop replaced by mycrofts code: */
if ((f = open("/dev/ptc", O_RDWR | O_NOCTTY | O_EXTRA)) < 0)
return -1;
vim_strncpy((char_u *)TtyName, (char_u *)ttyname(f), sizeof(TtyName) - 1);
if (geteuid() != ROOT_UID && mch_access(TtyName, R_OK | W_OK))
{
close(f);
return -1;
}
initmaster(f);
# ifdef _IBMR2
if (aixhack >= 0)
close(aixhack);
if ((aixhack = open(TtyName, O_RDWR | O_NOCTTY | O_EXTRA, 0)) < 0)
{
close(f);
return -1;
}
# endif
*ttyn = TtyName;
return f;
}
#endif
#ifndef PTY_DONE
# ifdef hpux
static char PtyProto[] = "/dev/ptym/ptyXY";
static char TtyProto[] = "/dev/pty/ttyXY";
# else
# ifdef __BEOS__
static char PtyProto[] = "/dev/pt/XY";
static char TtyProto[] = "/dev/tt/XY";
# else
static char PtyProto[] = "/dev/ptyXY";
static char TtyProto[] = "/dev/ttyXY";
# endif
# endif
int
OpenPTY(ttyn)
char **ttyn;
{
char *p, *q, *l, *d;
int f;
/* used for opening a new pty-pair: */
static char PtyName[32];
static char TtyName[32];
strcpy(PtyName, PtyProto);
strcpy(TtyName, TtyProto);
for (p = PtyName; *p != 'X'; p++)
;
for (q = TtyName; *q != 'X'; q++)
;
for (l = PTYRANGE0; (*p = *l) != '\0'; l++)
{
for (d = PTYRANGE1; (p[1] = *d) != '\0'; d++)
{
#if !defined(MACOS) || defined(USE_CARBONIZED)
if ((f = open(PtyName, O_RDWR | O_NOCTTY | O_EXTRA, 0)) == -1)
#else
if ((f = open(PtyName, O_RDWR | O_NOCTTY | O_EXTRA)) == -1)
#endif
continue;
q[0] = *l;
q[1] = *d;
#ifndef MACOS
if (geteuid() != ROOT_UID && mch_access(TtyName, R_OK | W_OK))
{
close(f);
continue;
}
#endif
#if defined(sun) && defined(TIOCGPGRP) && !defined(SUNOS3)
/* Hack to ensure that the slave side of the pty is
* unused. May not work in anything other than SunOS4.1
*/
{
int pgrp;
/* tcgetpgrp does not work (uses TIOCGETPGRP)! */
if (ioctl(f, TIOCGPGRP, (char *)&pgrp) != -1 || errno != EIO)
{
close(f);
continue;
}
}
#endif
initmaster(f);
*ttyn = TtyName;
return f;
}
}
return -1;
}
#endif
| zyz2011-vim | src/pty.c | C | gpl2 | 9,265 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved by Bram Moolenaar
* GUI/Motif support by Robert Webb
* Macintosh port by Dany St-Amant
* and Axel Kielhorn
* Port to MPW by Bernhard Pruemmer
* Initial Carbon port by Ammon Skidmore
*
* 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.
*/
/*
* NOTES: - Vim 7+ does not support classic MacOS. Please use Vim 6.x
* - Comments mentioning FAQ refer to the book:
* "Macworld Mac Programming FAQs" from "IDG Books"
*/
/*
* TODO: Change still to merge from the macvim's iDisk
*
* error_ga, mch_errmsg, Navigation's changes in gui_mch_browse
* uses of MenuItemIndex, changes in gui_mch_set_shellsize,
* ScrapManager error handling.
* Comments about function remaining to Carbonize.
*
*/
/* TODO (Jussi)
* * Clipboard does not work (at least some cases)
* * ATSU font rendering has some problems
* * Investigate and remove dead code (there is still lots of that)
*/
#include <Devices.h> /* included first to avoid CR problems */
#include "vim.h"
#define USE_CARBONIZED
#define USE_AEVENT /* Enable AEVENT */
#undef USE_OFFSETED_WINDOW /* Debugging feature: start Vim window OFFSETed */
/* Compile as CodeWarior External Editor */
#if defined(FEAT_CW_EDITOR) && !defined(USE_AEVENT)
# define USE_AEVENT /* Need Apple Event Support */
#endif
/* Vim's Scrap flavor. */
#define VIMSCRAPFLAVOR 'VIM!'
#ifdef FEAT_MBYTE
# define SCRAPTEXTFLAVOR kScrapFlavorTypeUnicode
#else
# define SCRAPTEXTFLAVOR kScrapFlavorTypeText
#endif
static EventHandlerUPP mouseWheelHandlerUPP = NULL;
SInt32 gMacSystemVersion;
#ifdef MACOS_CONVERT
# define USE_CARBONKEYHANDLER
static int im_is_active = FALSE;
#if 0
/* TODO: Implement me! */
static int im_start_row = 0;
static int im_start_col = 0;
#endif
#define NR_ELEMS(x) (sizeof(x) / sizeof(x[0]))
static TSMDocumentID gTSMDocument;
static void im_on_window_switch(int active);
static EventHandlerUPP keyEventHandlerUPP = NULL;
static EventHandlerUPP winEventHandlerUPP = NULL;
static pascal OSStatus gui_mac_handle_window_activate(
EventHandlerCallRef nextHandler, EventRef theEvent, void *data);
static pascal OSStatus gui_mac_handle_text_input(
EventHandlerCallRef nextHandler, EventRef theEvent, void *data);
static pascal OSStatus gui_mac_update_input_area(
EventHandlerCallRef nextHandler, EventRef theEvent);
static pascal OSStatus gui_mac_unicode_key_event(
EventHandlerCallRef nextHandler, EventRef theEvent);
#endif
/* Include some file. TODO: move into os_mac.h */
#include <Menus.h>
#include <Resources.h>
#include <Processes.h>
#ifdef USE_AEVENT
# include <AppleEvents.h>
# include <AERegistry.h>
#endif
# include <Gestalt.h>
#if UNIVERSAL_INTERFACES_VERSION >= 0x0330
# include <ControlDefinitions.h>
# include <Navigation.h> /* Navigation only part of ?? */
#endif
/* Help Manager (balloon.h, HM prefixed functions) are not supported
* under Carbon (Jussi) */
# if 0
/* New Help Interface for Mac, not implemented yet.*/
# include <MacHelp.h>
# endif
/*
* These seem to be rectangle options. Why are they not found in
* headers? (Jussi)
*/
#define kNothing 0
#define kCreateEmpty 2 /*1*/
#define kCreateRect 2
#define kDestroy 3
/*
* Dany: Don't like those...
*/
#define topLeft(r) (((Point*)&(r))[0])
#define botRight(r) (((Point*)&(r))[1])
/* Time of last mouse click, to detect double-click */
static long lastMouseTick = 0;
/* ??? */
static RgnHandle cursorRgn;
static RgnHandle dragRgn;
static Rect dragRect;
static short dragRectEnbl;
static short dragRectControl;
/* 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;
/* Last mouse click caused contextual menu, (to provide proper release) */
static short clickIsPopup;
/* Feedback Action for Scrollbar */
ControlActionUPP gScrollAction;
ControlActionUPP gScrollDrag;
/* Keeping track of which scrollbar is being dragged */
static ControlHandle dragged_sb = NULL;
/* Vector of char_u --> control index for hotkeys in dialogs */
static short *gDialogHotKeys;
static struct
{
FMFontFamily family;
FMFontSize size;
FMFontStyle style;
Boolean isPanelVisible;
} gFontPanelInfo = { 0, 0, 0, false };
#ifdef MACOS_CONVERT
# define USE_ATSUI_DRAWING
int p_macatsui_last;
ATSUStyle gFontStyle;
# ifdef FEAT_MBYTE
ATSUStyle gWideFontStyle;
# endif
Boolean gIsFontFallbackSet;
UInt32 useAntialias_cached = 0x0;
#endif
/* Colors Macros */
#define RGB(r,g,b) ((r) << 16) + ((g) << 8) + (b)
#define Red(c) ((c & 0x00FF0000) >> 16)
#define Green(c) ((c & 0x0000FF00) >> 8)
#define Blue(c) ((c & 0x000000FF) >> 0)
/* Key mapping */
#define vk_Esc 0x35 /* -> 1B */
#define vk_F1 0x7A /* -> 10 */
#define vk_F2 0x78 /*0x63*/
#define vk_F3 0x63 /*0x76*/
#define vk_F4 0x76 /*0x60*/
#define vk_F5 0x60 /*0x61*/
#define vk_F6 0x61 /*0x62*/
#define vk_F7 0x62 /*0x63*/ /*?*/
#define vk_F8 0x64
#define vk_F9 0x65
#define vk_F10 0x6D
#define vk_F11 0x67
#define vk_F12 0x6F
#define vk_F13 0x69
#define vk_F14 0x6B
#define vk_F15 0x71
#define vk_Clr 0x47 /* -> 1B (ESC) */
#define vk_Enter 0x4C /* -> 03 */
#define vk_Space 0x31 /* -> 20 */
#define vk_Tab 0x30 /* -> 09 */
#define vk_Return 0x24 /* -> 0D */
/* This is wrong for OSX, what is it for? */
#define vk_Delete 0X08 /* -> 08 BackSpace */
#define vk_Help 0x72 /* -> 05 */
#define vk_Home 0x73 /* -> 01 */
#define vk_PageUp 0x74 /* -> 0D */
#define vk_FwdDelete 0x75 /* -> 7F */
#define vk_End 0x77 /* -> 04 */
#define vk_PageDown 0x79 /* -> 0C */
#define vk_Up 0x7E /* -> 1E */
#define vk_Down 0x7D /* -> 1F */
#define vk_Left 0x7B /* -> 1C */
#define vk_Right 0x7C /* -> 1D */
#define vk_Undo vk_F1
#define vk_Cut vk_F2
#define vk_Copy vk_F3
#define vk_Paste vk_F4
#define vk_PrintScreen vk_F13
#define vk_SCrollLock vk_F14
#define vk_Pause vk_F15
#define vk_NumLock vk_Clr
#define vk_Insert vk_Help
#define KeySym char
static struct
{
KeySym 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'},
/* {XK_Help, '%', '1'}, */
/* {XK_Undo, '&', '8'}, */
/* {XK_BackSpace, 'k', 'b'}, */
#ifndef MACOS_X
{vk_Delete, 'k', 'b'},
#endif
{vk_Insert, 'k', 'I'},
{vk_FwdDelete, 'k', 'D'},
{vk_Home, 'k', 'h'},
{vk_End, '@', '7'},
/* {XK_Prior, 'k', 'P'}, */
/* {XK_Next, 'k', 'N'}, */
/* {XK_Print, '%', '9'}, */
{vk_PageUp, 'k', 'P'},
{vk_PageDown, 'k', 'N'},
/* End of list marker: */
{(KeySym)0, 0, 0}
};
/*
* ------------------------------------------------------------
* Forward declaration (for those needed)
* ------------------------------------------------------------
*/
#ifdef USE_AEVENT
OSErr HandleUnusedParms(const AppleEvent *theAEvent);
#endif
#ifdef FEAT_GUI_TABLINE
static void initialise_tabline(void);
static WindowRef drawer = NULL; // TODO: put into gui.h
#endif
#ifdef USE_ATSUI_DRAWING
static void gui_mac_set_font_attributes(GuiFont font);
static void gui_mac_dispose_atsui_style(void);
#endif
/*
* ------------------------------------------------------------
* Conversion Utility
* ------------------------------------------------------------
*/
/*
* C2Pascal_save
*
* Allocate memory and convert the C-String passed in
* into a pascal string
*
*/
char_u *
C2Pascal_save(char_u *Cstring)
{
char_u *PascalString;
int len;
if (Cstring == NULL)
return NULL;
len = STRLEN(Cstring);
if (len > 255) /* Truncate if necessary */
len = 255;
PascalString = alloc(len + 1);
if (PascalString != NULL)
{
mch_memmove(PascalString + 1, Cstring, len);
PascalString[0] = len;
}
return PascalString;
}
/*
* C2Pascal_save_and_remove_backslash
*
* Allocate memory and convert the C-String passed in
* into a pascal string. Also remove the backslash at the same time
*
*/
char_u *
C2Pascal_save_and_remove_backslash(char_u *Cstring)
{
char_u *PascalString;
int len;
char_u *p, *c;
len = STRLEN(Cstring);
if (len > 255) /* Truncate if necessary */
len = 255;
PascalString = alloc(len + 1);
if (PascalString != NULL)
{
for (c = Cstring, p = PascalString+1, len = 0; (*c != 0) && (len < 255); c++)
{
if ((*c == '\\') && (c[1] != 0))
{
c++;
}
*p = *c;
p++;
len++;
}
PascalString[0] = len;
}
return PascalString;
}
/*
* Convert the modifiers of an Event into vim's modifiers (mouse)
*/
int_u
EventModifiers2VimMouseModifiers(EventModifiers macModifiers)
{
int_u vimModifiers = 0x00;
if (macModifiers & (shiftKey | rightShiftKey))
vimModifiers |= MOUSE_SHIFT;
if (macModifiers & (controlKey | rightControlKey))
vimModifiers |= MOUSE_CTRL;
if (macModifiers & (optionKey | rightOptionKey))
vimModifiers |= MOUSE_ALT;
#if 0
/* Not yet supported */
if (macModifiers & (cmdKey)) /* There's no rightCmdKey */
vimModifiers |= MOUSE_CMD;
#endif
return (vimModifiers);
}
/*
* Convert the modifiers of an Event into vim's modifiers (keys)
*/
static int_u
EventModifiers2VimModifiers(EventModifiers macModifiers)
{
int_u vimModifiers = 0x00;
if (macModifiers & (shiftKey | rightShiftKey))
vimModifiers |= MOD_MASK_SHIFT;
if (macModifiers & (controlKey | rightControlKey))
vimModifiers |= MOD_MASK_CTRL;
if (macModifiers & (optionKey | rightOptionKey))
vimModifiers |= MOD_MASK_ALT;
#ifdef USE_CMD_KEY
if (macModifiers & (cmdKey)) /* There's no rightCmdKey */
vimModifiers |= MOD_MASK_CMD;
#endif
return (vimModifiers);
}
/* 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.
*
* From gui_w48.c
*/
static int
points_to_pixels(char_u *str, char_u **end, int vertical)
{
int pixels;
int points = 0;
int divisor = 0;
while (*str)
{
if (*str == '.' && divisor == 0)
{
/* Start keeping a divisor, for later */
divisor = 1;
continue;
}
if (!isdigit(*str))
break;
points *= 10;
points += *str - '0';
divisor *= 10;
++str;
}
if (divisor == 0)
divisor = 1;
pixels = points/divisor;
*end = str;
return pixels;
}
#ifdef MACOS_CONVERT
/*
* Deletes all traces of any Windows-style mnemonic text (including any
* parentheses) from a menu item and returns the cleaned menu item title.
* The caller is responsible for releasing the returned string.
*/
static CFStringRef
menu_title_removing_mnemonic(vimmenu_T *menu)
{
CFStringRef name;
size_t menuTitleLen;
CFIndex displayLen;
CFRange mnemonicStart;
CFRange mnemonicEnd;
CFMutableStringRef cleanedName;
menuTitleLen = STRLEN(menu->dname);
name = (CFStringRef) mac_enc_to_cfstring(menu->dname, menuTitleLen);
if (name)
{
/* Simple mnemonic-removal algorithm, assumes single parenthesized
* mnemonic character towards the end of the menu text */
mnemonicStart = CFStringFind(name, CFSTR("("), kCFCompareBackwards);
displayLen = CFStringGetLength(name);
if (mnemonicStart.location != kCFNotFound
&& (mnemonicStart.location + 2) < displayLen
&& CFStringGetCharacterAtIndex(name,
mnemonicStart.location + 1) == (UniChar)menu->mnemonic)
{
if (CFStringFindWithOptions(name, CFSTR(")"),
CFRangeMake(mnemonicStart.location + 1,
displayLen - mnemonicStart.location - 1),
kCFCompareBackwards, &mnemonicEnd) &&
(mnemonicStart.location + 2) == mnemonicEnd.location)
{
cleanedName = CFStringCreateMutableCopy(NULL, 0, name);
if (cleanedName)
{
CFStringDelete(cleanedName,
CFRangeMake(mnemonicStart.location,
mnemonicEnd.location + 1 -
mnemonicStart.location));
CFRelease(name);
name = cleanedName;
}
}
}
}
return name;
}
#endif
/*
* Convert a list of FSSpec aliases into a list of fullpathname
* character strings.
*/
char_u **
new_fnames_from_AEDesc(AEDesc *theList, long *numFiles, OSErr *error)
{
char_u **fnames = NULL;
OSErr newError;
long fileCount;
FSSpec fileToOpen;
long actualSize;
AEKeyword dummyKeyword;
DescType dummyType;
/* Get number of files in list */
*error = AECountItems(theList, numFiles);
if (*error)
return fnames;
/* Allocate the pointer list */
fnames = (char_u **) alloc(*numFiles * sizeof(char_u *));
/* Empty out the list */
for (fileCount = 0; fileCount < *numFiles; fileCount++)
fnames[fileCount] = NULL;
/* Scan the list of FSSpec */
for (fileCount = 1; fileCount <= *numFiles; fileCount++)
{
/* Get the alias for the nth file, convert to an FSSpec */
newError = AEGetNthPtr(theList, fileCount, typeFSS,
&dummyKeyword, &dummyType,
(Ptr) &fileToOpen, sizeof(FSSpec), &actualSize);
if (newError)
{
/* Caller is able to clean up */
/* TODO: Should be clean up or not? For safety. */
return fnames;
}
/* Convert the FSSpec to a pathname */
fnames[fileCount - 1] = FullPathFromFSSpec_save(fileToOpen);
}
return (fnames);
}
/*
* ------------------------------------------------------------
* CodeWarrior External Editor Support
* ------------------------------------------------------------
*/
#ifdef FEAT_CW_EDITOR
/*
* Handle the Window Search event from CodeWarrior
*
* Description
* -----------
*
* The IDE sends the Window Search AppleEvent to the editor when it
* needs to know whether a particular file is open in the editor.
*
* Event Reply
* -----------
*
* None. Put data in the location specified in the structure received.
*
* Remarks
* -------
*
* When the editor receives this event, determine whether the specified
* file is open. If it is, return the modification date/time for that file
* in the appropriate location specified in the structure. If the file is
* not opened, put the value fnfErr(file not found) in that location.
*
*/
typedef struct WindowSearch WindowSearch;
struct WindowSearch /* for handling class 'KAHL', event 'SRCH', keyDirectObject typeChar*/
{
FSSpec theFile; // identifies the file
long *theDate; // where to put the modification date/time
};
pascal OSErr
Handle_KAHL_SRCH_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
buf_T *buf;
int foundFile = false;
DescType typeCode;
WindowSearch SearchData;
Size actualSize;
error = AEGetParamPtr(theAEvent, keyDirectObject, typeChar, &typeCode, (Ptr) &SearchData, sizeof(WindowSearch), &actualSize);
if (error)
return error;
error = HandleUnusedParms(theAEvent);
if (error)
return error;
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_ml.ml_mfp != NULL
&& SearchData.theFile.parID == buf->b_FSSpec.parID
&& SearchData.theFile.name[0] == buf->b_FSSpec.name[0]
&& STRNCMP(SearchData.theFile.name, buf->b_FSSpec.name, buf->b_FSSpec.name[0] + 1) == 0)
{
foundFile = true;
break;
}
if (foundFile == false)
*SearchData.theDate = fnfErr;
else
*SearchData.theDate = buf->b_mtime;
return error;
};
/*
* Handle the Modified (from IDE to Editor) event from CodeWarrior
*
* Description
* -----------
*
* The IDE sends this event to the external editor when it wants to
* know which files that are open in the editor have been modified.
*
* Parameters None.
* ----------
*
* Event Reply
* -----------
* The reply for this event is:
*
* keyDirectObject typeAEList required
* each element in the list is a structure of typeChar
*
* Remarks
* -------
*
* When building the reply event, include one element in the list for
* each open file that has been modified.
*
*/
typedef struct ModificationInfo ModificationInfo;
struct ModificationInfo /* for replying to class 'KAHL', event 'MOD ', keyDirectObject typeAEList*/
{
FSSpec theFile; // identifies the file
long theDate; // the date/time the file was last modified
short saved; // set this to zero when replying, unused
};
pascal OSErr
Handle_KAHL_MOD_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
AEDescList replyList;
long numFiles;
ModificationInfo theFile;
buf_T *buf;
theFile.saved = 0;
error = HandleUnusedParms(theAEvent);
if (error)
return error;
/* Send the reply */
/* replyObject.descriptorType = typeNull;
replyObject.dataHandle = nil;*/
/* AECreateDesc(typeChar, (Ptr)&title[1], title[0], &data) */
error = AECreateList(nil, 0, false, &replyList);
if (error)
return error;
#if 0
error = AECountItems(&replyList, &numFiles);
/* AEPutKeyDesc(&replyList, keyAEPnject, &aDesc)
* AEPutKeyPtr(&replyList, keyAEPosition, typeChar, (Ptr)&theType,
* sizeof(DescType))
*/
/* AEPutDesc */
#endif
numFiles = 0;
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_ml.ml_mfp != NULL)
{
/* Add this file to the list */
theFile.theFile = buf->b_FSSpec;
theFile.theDate = buf->b_mtime;
/* theFile.theDate = time(NULL) & (time_t) 0xFFFFFFF0; */
error = AEPutPtr(&replyList, numFiles, typeChar, (Ptr) &theFile, sizeof(theFile));
};
#if 0
error = AECountItems(&replyList, &numFiles);
#endif
/* We can add data only if something to reply */
error = AEPutParamDesc(theReply, keyDirectObject, &replyList);
if (replyList.dataHandle)
AEDisposeDesc(&replyList);
return error;
};
/*
* Handle the Get Text event from CodeWarrior
*
* Description
* -----------
*
* The IDE sends the Get Text AppleEvent to the editor when it needs
* the source code from a file. For example, when the user issues a
* Check Syntax or Compile command, the compiler needs access to
* the source code contained in the file.
*
* Event Reply
* -----------
*
* None. Put data in locations specified in the structure received.
*
* Remarks
* -------
*
* When the editor receives this event, it must set the size of the handle
* in theText to fit the data in the file. It must then copy the entire
* contents of the specified file into the memory location specified in
* theText.
*
*/
typedef struct CW_GetText CW_GetText;
struct CW_GetText /* for handling class 'KAHL', event 'GTTX', keyDirectObject typeChar*/
{
FSSpec theFile; /* identifies the file */
Handle theText; /* the location where you return the text (must be resized properly) */
long *unused; /* 0 (not used) */
long *theDate; /* where to put the modification date/time */
};
pascal OSErr
Handle_KAHL_GTTX_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
buf_T *buf;
int foundFile = false;
DescType typeCode;
CW_GetText GetTextData;
Size actualSize;
char_u *line;
char_u *fullbuffer = NULL;
long linesize;
long lineStart;
long BufferSize;
long lineno;
error = AEGetParamPtr(theAEvent, keyDirectObject, typeChar, &typeCode, (Ptr) &GetTextData, sizeof(GetTextData), &actualSize);
if (error)
return error;
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_ml.ml_mfp != NULL)
if (GetTextData.theFile.parID == buf->b_FSSpec.parID)
{
foundFile = true;
break;
}
if (foundFile)
{
BufferSize = 0; /* GetHandleSize(GetTextData.theText); */
for (lineno = 0; lineno <= buf->b_ml.ml_line_count; lineno++)
{
/* Must use the right buffer */
line = ml_get_buf(buf, (linenr_T) lineno, FALSE);
linesize = STRLEN(line) + 1;
lineStart = BufferSize;
BufferSize += linesize;
/* Resize handle to linesize+1 to include the linefeed */
SetHandleSize(GetTextData.theText, BufferSize);
if (GetHandleSize(GetTextData.theText) != BufferSize)
{
break; /* Simple handling for now */
}
else
{
HLock(GetTextData.theText);
fullbuffer = (char_u *) *GetTextData.theText;
STRCPY((char_u *)(fullbuffer + lineStart), line);
fullbuffer[BufferSize-1] = '\r';
HUnlock(GetTextData.theText);
}
}
if (fullbuffer != NULL)
{
HLock(GetTextData.theText);
fullbuffer[BufferSize-1] = 0;
HUnlock(GetTextData.theText);
}
if (foundFile == false)
*GetTextData.theDate = fnfErr;
else
/* *GetTextData.theDate = time(NULL) & (time_t) 0xFFFFFFF0;*/
*GetTextData.theDate = buf->b_mtime;
}
error = HandleUnusedParms(theAEvent);
return error;
}
/*
*
*/
/* Taken from MoreAppleEvents:ProcessHelpers*/
pascal OSErr
FindProcessBySignature(
const OSType targetType,
const OSType targetCreator,
ProcessSerialNumberPtr psnPtr)
{
OSErr anErr = noErr;
Boolean lookingForProcess = true;
ProcessInfoRec infoRec;
infoRec.processInfoLength = sizeof(ProcessInfoRec);
infoRec.processName = nil;
infoRec.processAppSpec = nil;
psnPtr->lowLongOfPSN = kNoProcess;
psnPtr->highLongOfPSN = kNoProcess;
while (lookingForProcess)
{
anErr = GetNextProcess(psnPtr);
if (anErr != noErr)
lookingForProcess = false;
else
{
anErr = GetProcessInformation(psnPtr, &infoRec);
if ((anErr == noErr)
&& (infoRec.processType == targetType)
&& (infoRec.processSignature == targetCreator))
lookingForProcess = false;
}
}
return anErr;
}//end FindProcessBySignature
void
Send_KAHL_MOD_AE(buf_T *buf)
{
OSErr anErr = noErr;
AEDesc targetAppDesc = { typeNull, nil };
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
AppleEvent theReply = { typeNull, nil };
AESendMode sendMode;
AppleEvent theEvent = {typeNull, nil };
AEIdleUPP idleProcUPP = nil;
ModificationInfo ModData;
anErr = FindProcessBySignature('APPL', 'CWIE', &psn);
if (anErr == noErr)
{
anErr = AECreateDesc(typeProcessSerialNumber, &psn,
sizeof(ProcessSerialNumber), &targetAppDesc);
if (anErr == noErr)
{
anErr = AECreateAppleEvent( 'KAHL', 'MOD ', &targetAppDesc,
kAutoGenerateReturnID, kAnyTransactionID, &theEvent);
}
AEDisposeDesc(&targetAppDesc);
/* Add the parms */
ModData.theFile = buf->b_FSSpec;
ModData.theDate = buf->b_mtime;
if (anErr == noErr)
anErr = AEPutParamPtr(&theEvent, keyDirectObject, typeChar, &ModData, sizeof(ModData));
if (idleProcUPP == nil)
sendMode = kAENoReply;
else
sendMode = kAEWaitReply;
if (anErr == noErr)
anErr = AESend(&theEvent, &theReply, sendMode, kAENormalPriority, kNoTimeOut, idleProcUPP, nil);
if (anErr == noErr && sendMode == kAEWaitReply)
{
/* anErr = AEHGetHandlerError(&theReply);*/
}
(void) AEDisposeDesc(&theReply);
}
}
#endif /* FEAT_CW_EDITOR */
/*
* ------------------------------------------------------------
* Apple Event Handling procedure
* ------------------------------------------------------------
*/
#ifdef USE_AEVENT
/*
* Handle the Unused parms of an AppleEvent
*/
OSErr
HandleUnusedParms(const AppleEvent *theAEvent)
{
OSErr error;
long actualSize;
DescType dummyType;
AEKeyword missedKeyword;
/* Get the "missed keyword" attribute from the AppleEvent. */
error = AEGetAttributePtr(theAEvent, keyMissedKeywordAttr,
typeKeyword, &dummyType,
(Ptr)&missedKeyword, sizeof(missedKeyword),
&actualSize);
/* If the descriptor isn't found, then we got the required parameters. */
if (error == errAEDescNotFound)
{
error = noErr;
}
else
{
#if 0
/* Why is this removed? */
error = errAEEventNotHandled;
#endif
}
return error;
}
/*
* Handle the ODoc AppleEvent
*
* Deals with all files dragged to the application icon.
*
*/
typedef struct SelectionRange SelectionRange;
struct SelectionRange /* for handling kCoreClassEvent:kOpenDocuments:keyAEPosition typeChar */
{
short unused1; // 0 (not used)
short lineNum; // line to select (<0 to specify range)
long startRange; // start of selection range (if line < 0)
long endRange; // end of selection range (if line < 0)
long unused2; // 0 (not used)
long theDate; // modification date/time
};
/* The IDE uses the optional keyAEPosition parameter to tell the ed-
itor the selection range. If lineNum is zero or greater, scroll the text
to the specified line. If lineNum is less than zero, use the values in
startRange and endRange to select the specified characters. Scroll
the text to display the selection. If lineNum, startRange, and
endRange are all negative, there is no selection range specified.
*/
pascal OSErr
HandleODocAE(const AppleEvent *theAEvent, AppleEvent *theReply, long refCon)
{
/*
* TODO: Clean up the code with convert the AppleEvent into
* a ":args"
*/
OSErr error = noErr;
// OSErr firstError = noErr;
// short numErrors = 0;
AEDesc theList;
DescType typeCode;
long numFiles;
// long fileCount;
char_u **fnames;
// char_u fname[256];
Size actualSize;
SelectionRange thePosition;
short gotPosition = false;
long lnum;
/* the direct object parameter is the list of aliases to files (one or more) */
error = AEGetParamDesc(theAEvent, keyDirectObject, typeAEList, &theList);
if (error)
return error;
error = AEGetParamPtr(theAEvent, keyAEPosition, typeChar, &typeCode, (Ptr) &thePosition, sizeof(SelectionRange), &actualSize);
if (error == noErr)
gotPosition = true;
if (error == errAEDescNotFound)
error = noErr;
if (error)
return error;
/*
error = AEGetParamDesc(theAEvent, keyAEPosition, typeChar, &thePosition);
if (^error) then
{
if (thePosition.lineNum >= 0)
{
// Goto this line
}
else
{
// Set the range char wise
}
}
*/
#ifdef FEAT_VISUAL
reset_VIsual();
#endif
fnames = new_fnames_from_AEDesc(&theList, &numFiles, &error);
if (error)
{
/* TODO: empty fnames[] first */
vim_free(fnames);
return (error);
}
if (starting > 0)
{
int i;
char_u *p;
int fnum = -1;
/* these are the initial files dropped on the Vim icon */
for (i = 0 ; i < numFiles; i++)
{
if (ga_grow(&global_alist.al_ga, 1) == FAIL
|| (p = vim_strsave(fnames[i])) == NULL)
mch_exit(2);
else
alist_add(&global_alist, p, 2);
if (fnum == -1)
fnum = GARGLIST[GARGCOUNT - 1].ae_fnum;
}
/* If the file name was already in the buffer list we need to switch
* to it. */
if (curbuf->b_fnum != fnum)
{
char_u cmd[30];
vim_snprintf((char *)cmd, 30, "silent %dbuffer", fnum);
do_cmdline_cmd(cmd);
}
/* Change directory to the location of the first file. */
if (GARGCOUNT > 0 && vim_chdirfile(alist_name(&GARGLIST[0])) == OK)
shorten_fnames(TRUE);
goto finished;
}
/* Handle the drop, :edit to get to the file */
handle_drop(numFiles, fnames, FALSE);
/* TODO: Handle the goto/select line more cleanly */
if ((numFiles == 1) & (gotPosition))
{
if (thePosition.lineNum >= 0)
{
lnum = thePosition.lineNum + 1;
/* oap->motion_type = MLINE;
setpcmark();*/
if (lnum < 1L)
lnum = 1L;
else if (lnum > curbuf->b_ml.ml_line_count)
lnum = curbuf->b_ml.ml_line_count;
curwin->w_cursor.lnum = lnum;
curwin->w_cursor.col = 0;
/* beginline(BL_SOL | BL_FIX);*/
}
else
goto_byte(thePosition.startRange + 1);
}
/* Update the screen display */
update_screen(NOT_VALID);
#ifdef FEAT_VISUAL
/* Select the text if possible */
if (gotPosition)
{
VIsual_active = TRUE;
VIsual_select = FALSE;
VIsual = curwin->w_cursor;
if (thePosition.lineNum < 0)
{
VIsual_mode = 'v';
goto_byte(thePosition.endRange);
}
else
{
VIsual_mode = 'V';
VIsual.col = 0;
}
}
#endif
setcursor();
out_flush();
/* Fake mouse event to wake from stall */
PostEvent(mouseUp, 0);
finished:
AEDisposeDesc(&theList); /* dispose what we allocated */
error = HandleUnusedParms(theAEvent);
return error;
}
/*
*
*/
pascal OSErr
Handle_aevt_oapp_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
error = HandleUnusedParms(theAEvent);
return error;
}
/*
*
*/
pascal OSErr
Handle_aevt_quit_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
error = HandleUnusedParms(theAEvent);
if (error)
return error;
/* Need to fake a :confirm qa */
do_cmdline_cmd((char_u *)"confirm qa");
return error;
}
/*
*
*/
pascal OSErr
Handle_aevt_pdoc_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
error = HandleUnusedParms(theAEvent);
return error;
}
/*
* Handling of unknown AppleEvent
*
* (Just get rid of all the parms)
*/
pascal OSErr
Handle_unknown_AE(
const AppleEvent *theAEvent,
AppleEvent *theReply,
long refCon)
{
OSErr error = noErr;
error = HandleUnusedParms(theAEvent);
return error;
}
/*
* Install the various AppleEvent Handlers
*/
OSErr
InstallAEHandlers(void)
{
OSErr error;
/* install open application handler */
error = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
NewAEEventHandlerUPP(Handle_aevt_oapp_AE), 0, false);
if (error)
{
return error;
}
/* install quit application handler */
error = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
NewAEEventHandlerUPP(Handle_aevt_quit_AE), 0, false);
if (error)
{
return error;
}
/* install open document handler */
error = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
NewAEEventHandlerUPP(HandleODocAE), 0, false);
if (error)
{
return error;
}
/* install print document handler */
error = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
NewAEEventHandlerUPP(Handle_aevt_pdoc_AE), 0, false);
/* Install Core Suite */
/* error = AEInstallEventHandler(kAECoreSuite, kAEClone,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEClose,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAECountElements,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAECreateElement,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEDelete,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEDoObjectsExist,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEGetData,
NewAEEventHandlerUPP(Handle_unknown_AE), kAEGetData, false);
error = AEInstallEventHandler(kAECoreSuite, kAEGetDataSize,
NewAEEventHandlerUPP(Handle_unknown_AE), kAEGetDataSize, false);
error = AEInstallEventHandler(kAECoreSuite, kAEGetClassInfo,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEGetEventInfo,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAEMove,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAESave,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
error = AEInstallEventHandler(kAECoreSuite, kAESetData,
NewAEEventHandlerUPP(Handle_unknown_AE), nil, false);
*/
#ifdef FEAT_CW_EDITOR
/*
* Bind codewarrior support handlers
*/
error = AEInstallEventHandler('KAHL', 'GTTX',
NewAEEventHandlerUPP(Handle_KAHL_GTTX_AE), 0, false);
if (error)
{
return error;
}
error = AEInstallEventHandler('KAHL', 'SRCH',
NewAEEventHandlerUPP(Handle_KAHL_SRCH_AE), 0, false);
if (error)
{
return error;
}
error = AEInstallEventHandler('KAHL', 'MOD ',
NewAEEventHandlerUPP(Handle_KAHL_MOD_AE), 0, false);
if (error)
{
return error;
}
#endif
return error;
}
#endif /* USE_AEVENT */
/*
* Callback function, installed by InstallFontPanelHandler(), below,
* to handle Font Panel events.
*/
static OSStatus
FontPanelHandler(
EventHandlerCallRef inHandlerCallRef,
EventRef inEvent,
void *inUserData)
{
if (GetEventKind(inEvent) == kEventFontPanelClosed)
{
gFontPanelInfo.isPanelVisible = false;
return noErr;
}
if (GetEventKind(inEvent) == kEventFontSelection)
{
OSStatus status;
FMFontFamily newFamily;
FMFontSize newSize;
FMFontStyle newStyle;
/* Retrieve the font family ID number. */
status = GetEventParameter(inEvent, kEventParamFMFontFamily,
/*inDesiredType=*/typeFMFontFamily, /*outActualType=*/NULL,
/*inBufferSize=*/sizeof(FMFontFamily), /*outActualSize=*/NULL,
&newFamily);
if (status == noErr)
gFontPanelInfo.family = newFamily;
/* Retrieve the font size. */
status = GetEventParameter(inEvent, kEventParamFMFontSize,
typeFMFontSize, NULL, sizeof(FMFontSize), NULL, &newSize);
if (status == noErr)
gFontPanelInfo.size = newSize;
/* Retrieve the font style (bold, etc.). Currently unused. */
status = GetEventParameter(inEvent, kEventParamFMFontStyle,
typeFMFontStyle, NULL, sizeof(FMFontStyle), NULL, &newStyle);
if (status == noErr)
gFontPanelInfo.style = newStyle;
}
return noErr;
}
static void
InstallFontPanelHandler(void)
{
EventTypeSpec eventTypes[2];
EventHandlerUPP handlerUPP;
/* EventHandlerRef handlerRef; */
eventTypes[0].eventClass = kEventClassFont;
eventTypes[0].eventKind = kEventFontSelection;
eventTypes[1].eventClass = kEventClassFont;
eventTypes[1].eventKind = kEventFontPanelClosed;
handlerUPP = NewEventHandlerUPP(FontPanelHandler);
InstallApplicationEventHandler(handlerUPP, /*numTypes=*/2, eventTypes,
/*userData=*/NULL, /*handlerRef=*/NULL);
}
/*
* Fill the buffer pointed to by outName with the name and size
* of the font currently selected in the Font Panel.
*/
#define FONT_STYLE_BUFFER_SIZE 32
static void
GetFontPanelSelection(char_u *outName)
{
Str255 buf;
ByteCount fontNameLen = 0;
ATSUFontID fid;
char_u styleString[FONT_STYLE_BUFFER_SIZE];
if (!outName)
return;
if (FMGetFontFamilyName(gFontPanelInfo.family, buf) == noErr)
{
/* Canonicalize localized font names */
if (FMGetFontFromFontFamilyInstance(gFontPanelInfo.family,
gFontPanelInfo.style, &fid, NULL) != noErr)
return;
/* Request font name with Mac encoding (otherwise we could
* get an unwanted utf-16 name) */
if (ATSUFindFontName(fid, kFontFullName, kFontMacintoshPlatform,
kFontNoScriptCode, kFontNoLanguageCode,
255, (char *)outName, &fontNameLen, NULL) != noErr)
return;
/* Only encode font size, because style (bold, italic, etc) is
* already part of the font full name */
vim_snprintf((char *)styleString, FONT_STYLE_BUFFER_SIZE, ":h%d",
gFontPanelInfo.size/*,
((gFontPanelInfo.style & bold)!=0 ? ":b" : ""),
((gFontPanelInfo.style & italic)!=0 ? ":i" : ""),
((gFontPanelInfo.style & underline)!=0 ? ":u" : "")*/);
if ((fontNameLen + STRLEN(styleString)) < 255)
STRCPY(outName + fontNameLen, styleString);
}
else
{
*outName = NUL;
}
}
/*
* ------------------------------------------------------------
* Unfiled yet
* ------------------------------------------------------------
*/
/*
* gui_mac_get_menu_item_index
*
* Returns the index inside the menu wher
*/
short /* Should we return MenuItemIndex? */
gui_mac_get_menu_item_index(vimmenu_T *pMenu)
{
short index;
short itemIndex = -1;
vimmenu_T *pBrother;
/* Only menu without parent are the:
* -menu in the menubar
* -popup menu
* -toolbar (guess)
*
* Which are not items anyway.
*/
if (pMenu->parent)
{
/* Start from the Oldest Brother */
pBrother = pMenu->parent->children;
index = 1;
while ((pBrother) && (itemIndex == -1))
{
if (pBrother == pMenu)
itemIndex = index;
index++;
pBrother = pBrother->next;
}
}
return itemIndex;
}
static vimmenu_T *
gui_mac_get_vim_menu(short menuID, short itemIndex, vimmenu_T *pMenu)
{
short index;
vimmenu_T *pChildMenu;
vimmenu_T *pElder = pMenu->parent;
/* Only menu without parent are the:
* -menu in the menubar
* -popup menu
* -toolbar (guess)
*
* Which are not items anyway.
*/
if ((pElder) && (pElder->submenu_id == menuID))
{
for (index = 1; (index != itemIndex) && (pMenu != NULL); index++)
pMenu = pMenu->next;
}
else
{
for (; pMenu != NULL; pMenu = pMenu->next)
{
if (pMenu->children != NULL)
{
pChildMenu = gui_mac_get_vim_menu
(menuID, itemIndex, pMenu->children);
if (pChildMenu)
{
pMenu = pChildMenu;
break;
}
}
}
}
return pMenu;
}
/*
* ------------------------------------------------------------
* MacOS Feedback procedures
* ------------------------------------------------------------
*/
pascal
void
gui_mac_drag_thumb(ControlHandle theControl, short partCode)
{
scrollbar_T *sb;
int value, dragging;
ControlHandle theControlToUse;
int dont_scroll_save = dont_scroll;
theControlToUse = dragged_sb;
sb = gui_find_scrollbar((long) GetControlReference(theControlToUse));
if (sb == NULL)
return;
/* Need to find value by diff between Old Poss New Pos */
value = GetControl32BitValue(theControlToUse);
dragging = (partCode != 0);
/* 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, value, dragging);
dont_scroll = dont_scroll_save;
}
pascal
void
gui_mac_scroll_action(ControlHandle theControl, short partCode)
{
/* TODO: have live support */
scrollbar_T *sb, *sb_info;
long data;
long value;
int page;
int dragging = FALSE;
int dont_scroll_save = dont_scroll;
sb = gui_find_scrollbar((long)GetControlReference(theControl));
if (sb == NULL)
return;
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];
if (sb_info->size > 5)
page = sb_info->size - 2; /* use two lines of context */
else
page = sb_info->size;
}
else /* Bottom scrollbar */
{
sb_info = sb;
page = W_WIDTH(curwin) - 5;
}
switch (partCode)
{
case kControlUpButtonPart: data = -1; break;
case kControlDownButtonPart: data = 1; break;
case kControlPageDownPart: data = page; break;
case kControlPageUpPart: data = -page; break;
default: data = 0; break;
}
value = sb_info->value + data;
/* if (value > sb_info->max)
value = sb_info->max;
else if (value < 0)
value = 0;*/
/* 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, value, dragging);
dont_scroll = dont_scroll_save;
out_flush();
gui_mch_set_scrollbar_thumb(sb, value, sb_info->size, sb_info->max);
/* if (sb_info->wp != NULL)
{
win_T *wp;
int sb_num;
sb_num = 0;
for (wp = firstwin; wp != sb->wp && wp != NULL; wp = W_NEXT(wp))
sb_num++;
if (wp != NULL)
{
current_scrollbar = sb_num;
scrollbar_value = value;
gui_do_scroll();
gui_mch_set_scrollbar_thumb(sb, value, sb_info->size, sb_info->max);
}
}*/
}
/*
* ------------------------------------------------------------
* MacOS Click Handling procedures
* ------------------------------------------------------------
*/
/*
* Handle a click inside the window, it may happens in the
* scrollbar or the contents.
*
* TODO: Add support for potential TOOLBAR
*/
void
gui_mac_doInContentClick(EventRecord *theEvent, WindowPtr whichWindow)
{
Point thePoint;
int_u vimModifiers;
short thePortion;
ControlHandle theControl;
int vimMouseButton;
short dblClick;
thePoint = theEvent->where;
GlobalToLocal(&thePoint);
SelectWindow(whichWindow);
thePortion = FindControl(thePoint, whichWindow, &theControl);
if (theControl != NUL)
{
/* We hit a scollbar */
if (thePortion != kControlIndicatorPart)
{
dragged_sb = theControl;
TrackControl(theControl, thePoint, gScrollAction);
dragged_sb = NULL;
}
else
{
dragged_sb = theControl;
#if 1
TrackControl(theControl, thePoint, gScrollDrag);
#else
TrackControl(theControl, thePoint, NULL);
#endif
/* pass 0 as the part to tell gui_mac_drag_thumb, that the mouse
* button has been released */
gui_mac_drag_thumb(theControl, 0); /* Should it be thePortion ? (Dany) */
dragged_sb = NULL;
}
}
else
{
/* We are inside the contents */
/* Convert the CTRL, OPTION, SHIFT and CMD key */
vimModifiers = EventModifiers2VimMouseModifiers(theEvent->modifiers);
/* Defaults to MOUSE_LEFT as there's only one mouse button */
vimMouseButton = MOUSE_LEFT;
/* Convert the CTRL_MOUSE_LEFT to MOUSE_RIGHT */
/* TODO: NEEDED? */
clickIsPopup = FALSE;
if (mouse_model_popup() && IsShowContextualMenuClick(theEvent))
{
vimMouseButton = MOUSE_RIGHT;
vimModifiers &= ~MOUSE_CTRL;
clickIsPopup = TRUE;
}
/* Is it a double click ? */
dblClick = ((theEvent->when - lastMouseTick) < GetDblTime());
/* Send the mouse click to Vim */
gui_send_mouse_event(vimMouseButton, thePoint.h,
thePoint.v, dblClick, vimModifiers);
/* Create the rectangle around the cursor to detect
* the mouse dragging
*/
#if 0
/* TODO: Do we need to this even for the contextual menu?
* It may be require for popup_setpos, but for popup?
*/
if (vimMouseButton == MOUSE_LEFT)
#endif
{
SetRect(&dragRect, FILL_X(X_2_COL(thePoint.h)),
FILL_Y(Y_2_ROW(thePoint.v)),
FILL_X(X_2_COL(thePoint.h)+1),
FILL_Y(Y_2_ROW(thePoint.v)+1));
dragRectEnbl = TRUE;
dragRectControl = kCreateRect;
}
}
}
/*
* Handle the click in the titlebar (to move the window)
*/
void
gui_mac_doInDragClick(Point where, WindowPtr whichWindow)
{
Rect movingLimits;
Rect *movingLimitsPtr = &movingLimits;
/* TODO: may try to prevent move outside screen? */
movingLimitsPtr = GetRegionBounds(GetGrayRgn(), &movingLimits);
DragWindow(whichWindow, where, movingLimitsPtr);
}
/*
* Handle the click in the grow box
*/
void
gui_mac_doInGrowClick(Point where, WindowPtr whichWindow)
{
long newSize;
unsigned short newWidth;
unsigned short newHeight;
Rect resizeLimits;
Rect *resizeLimitsPtr = &resizeLimits;
Rect NewContentRect;
resizeLimitsPtr = GetRegionBounds(GetGrayRgn(), &resizeLimits);
/* Set the minimum size */
/* TODO: Should this come from Vim? */
resizeLimits.top = 100;
resizeLimits.left = 100;
newSize = ResizeWindow(whichWindow, where, &resizeLimits, &NewContentRect);
newWidth = NewContentRect.right - NewContentRect.left;
newHeight = NewContentRect.bottom - NewContentRect.top;
gui_resize_shell(newWidth, newHeight);
gui_mch_set_bg_color(gui.back_pixel);
gui_set_shellsize(TRUE, FALSE, RESIZE_BOTH);
}
/*
* Handle the click in the zoom box
*/
static void
gui_mac_doInZoomClick(EventRecord *theEvent, WindowPtr whichWindow)
{
Rect r;
Point p;
short thePart;
/* ideal width is current */
p.h = Columns * gui.char_width + 2 * gui.border_offset;
if (gui.which_scrollbars[SBAR_LEFT])
p.h += gui.scrollbar_width;
if (gui.which_scrollbars[SBAR_RIGHT])
p.h += gui.scrollbar_width;
/* ideal height is as high as we can get */
p.v = 15 * 1024;
thePart = IsWindowInStandardState(whichWindow, &p, &r)
? inZoomIn : inZoomOut;
if (!TrackBox(whichWindow, theEvent->where, thePart))
return;
/* use returned width */
p.h = r.right - r.left;
/* adjust returned height */
p.v = r.bottom - r.top - 2 * gui.border_offset;
if (gui.which_scrollbars[SBAR_BOTTOM])
p.v -= gui.scrollbar_height;
p.v -= p.v % gui.char_height;
p.v += 2 * gui.border_width;
if (gui.which_scrollbars[SBAR_BOTTOM])
p.v += gui.scrollbar_height;
ZoomWindowIdeal(whichWindow, thePart, &p);
GetWindowBounds(whichWindow, kWindowContentRgn, &r);
gui_resize_shell(r.right - r.left, r.bottom - r.top);
gui_mch_set_bg_color(gui.back_pixel);
gui_set_shellsize(TRUE, FALSE, RESIZE_BOTH);
}
/*
* ------------------------------------------------------------
* MacOS Event Handling procedure
* ------------------------------------------------------------
*/
/*
* Handle the Update Event
*/
void
gui_mac_doUpdateEvent(EventRecord *event)
{
WindowPtr whichWindow;
GrafPtr savePort;
RgnHandle updateRgn;
Rect updateRect;
Rect *updateRectPtr;
Rect rc;
Rect growRect;
RgnHandle saveRgn;
updateRgn = NewRgn();
if (updateRgn == NULL)
return;
/* This could be done by the caller as we
* don't require anything else out of the event
*/
whichWindow = (WindowPtr) event->message;
/* Save Current Port */
GetPort(&savePort);
/* Select the Window's Port */
SetPortWindowPort(whichWindow);
/* Let's update the window */
BeginUpdate(whichWindow);
/* Redraw the biggest rectangle covering the area
* to be updated.
*/
GetPortVisibleRegion(GetWindowPort(whichWindow), updateRgn);
# if 0
/* Would be more appropriate to use the following but doesn't
* seem to work under MacOS X (Dany)
*/
GetWindowRegion(whichWindow, kWindowUpdateRgn, updateRgn);
# endif
/* Use the HLock useless in Carbon? Is it harmful?*/
HLock((Handle) updateRgn);
updateRectPtr = GetRegionBounds(updateRgn, &updateRect);
# if 0
/* Code from original Carbon Port (using GetWindowRegion.
* I believe the UpdateRgn is already in local (Dany)
*/
GlobalToLocal(&topLeft(updateRect)); /* preCarbon? */
GlobalToLocal(&botRight(updateRect));
# endif
/* Update the content (i.e. the text) */
gui_redraw(updateRectPtr->left, updateRectPtr->top,
updateRectPtr->right - updateRectPtr->left,
updateRectPtr->bottom - updateRectPtr->top);
/* Clear the border areas if needed */
gui_mch_set_bg_color(gui.back_pixel);
if (updateRectPtr->left < FILL_X(0))
{
SetRect(&rc, 0, 0, FILL_X(0), FILL_Y(Rows));
EraseRect(&rc);
}
if (updateRectPtr->top < FILL_Y(0))
{
SetRect(&rc, 0, 0, FILL_X(Columns), FILL_Y(0));
EraseRect(&rc);
}
if (updateRectPtr->right > FILL_X(Columns))
{
SetRect(&rc, FILL_X(Columns), 0,
FILL_X(Columns) + gui.border_offset, FILL_Y(Rows));
EraseRect(&rc);
}
if (updateRectPtr->bottom > FILL_Y(Rows))
{
SetRect(&rc, 0, FILL_Y(Rows), FILL_X(Columns) + gui.border_offset,
FILL_Y(Rows) + gui.border_offset);
EraseRect(&rc);
}
HUnlock((Handle) updateRgn);
DisposeRgn(updateRgn);
/* Update scrollbars */
DrawControls(whichWindow);
/* Update the GrowBox */
/* Taken from FAQ 33-27 */
saveRgn = NewRgn();
GetWindowBounds(whichWindow, kWindowGrowRgn, &growRect);
GetClip(saveRgn);
ClipRect(&growRect);
DrawGrowIcon(whichWindow);
SetClip(saveRgn);
DisposeRgn(saveRgn);
EndUpdate(whichWindow);
/* Restore original Port */
SetPort(savePort);
}
/*
* Handle the activate/deactivate event
* (apply to a window)
*/
void
gui_mac_doActivateEvent(EventRecord *event)
{
WindowPtr whichWindow;
whichWindow = (WindowPtr) event->message;
/* Dim scrollbars */
if (whichWindow == gui.VimWindow)
{
ControlRef rootControl;
GetRootControl(gui.VimWindow, &rootControl);
if ((event->modifiers) & activeFlag)
ActivateControl(rootControl);
else
DeactivateControl(rootControl);
}
/* Activate */
gui_focus_change((event->modifiers) & activeFlag);
}
/*
* Handle the suspend/resume event
* (apply to the application)
*/
void
gui_mac_doSuspendEvent(EventRecord *event)
{
/* The frontmost application just changed */
/* NOTE: the suspend may happen before the deactivate
* seen on MacOS X
*/
/* May not need to change focus as the window will
* get an activate/deactivate event
*/
if (event->message & 1)
/* Resume */
gui_focus_change(TRUE);
else
/* Suspend */
gui_focus_change(FALSE);
}
/*
* Handle the key
*/
#ifdef USE_CARBONKEYHANDLER
static pascal OSStatus
gui_mac_handle_window_activate(
EventHandlerCallRef nextHandler,
EventRef theEvent,
void *data)
{
UInt32 eventClass = GetEventClass(theEvent);
UInt32 eventKind = GetEventKind(theEvent);
if (eventClass == kEventClassWindow)
{
switch (eventKind)
{
case kEventWindowActivated:
#if defined(USE_IM_CONTROL)
im_on_window_switch(TRUE);
#endif
return noErr;
case kEventWindowDeactivated:
#if defined(USE_IM_CONTROL)
im_on_window_switch(FALSE);
#endif
return noErr;
}
}
return eventNotHandledErr;
}
static pascal OSStatus
gui_mac_handle_text_input(
EventHandlerCallRef nextHandler,
EventRef theEvent,
void *data)
{
UInt32 eventClass = GetEventClass(theEvent);
UInt32 eventKind = GetEventKind(theEvent);
if (eventClass != kEventClassTextInput)
return eventNotHandledErr;
if ((kEventTextInputUpdateActiveInputArea != eventKind) &&
(kEventTextInputUnicodeForKeyEvent != eventKind) &&
(kEventTextInputOffsetToPos != eventKind) &&
(kEventTextInputPosToOffset != eventKind) &&
(kEventTextInputGetSelectedText != eventKind))
return eventNotHandledErr;
switch (eventKind)
{
case kEventTextInputUpdateActiveInputArea:
return gui_mac_update_input_area(nextHandler, theEvent);
case kEventTextInputUnicodeForKeyEvent:
return gui_mac_unicode_key_event(nextHandler, theEvent);
case kEventTextInputOffsetToPos:
case kEventTextInputPosToOffset:
case kEventTextInputGetSelectedText:
break;
}
return eventNotHandledErr;
}
static pascal
OSStatus gui_mac_update_input_area(
EventHandlerCallRef nextHandler,
EventRef theEvent)
{
return eventNotHandledErr;
}
static int dialog_busy = FALSE; /* TRUE when gui_mch_dialog() wants the
keys */
# define INLINE_KEY_BUFFER_SIZE 80
static pascal OSStatus
gui_mac_unicode_key_event(
EventHandlerCallRef nextHandler,
EventRef theEvent)
{
/* Multibyte-friendly key event handler */
OSStatus err = -1;
UInt32 actualSize;
UniChar *text;
char_u result[INLINE_KEY_BUFFER_SIZE];
short len = 0;
UInt32 key_sym;
char charcode;
int key_char;
UInt32 modifiers, vimModifiers;
size_t encLen;
char_u *to = NULL;
Boolean isSpecial = FALSE;
int i;
EventRef keyEvent;
/* Mask the mouse (as per user setting) */
if (p_mh)
ObscureCursor();
/* Don't use the keys when the dialog wants them. */
if (dialog_busy)
return eventNotHandledErr;
if (noErr != GetEventParameter(theEvent, kEventParamTextInputSendText,
typeUnicodeText, NULL, 0, &actualSize, NULL))
return eventNotHandledErr;
text = (UniChar *)alloc(actualSize);
if (!text)
return eventNotHandledErr;
err = GetEventParameter(theEvent, kEventParamTextInputSendText,
typeUnicodeText, NULL, actualSize, NULL, text);
require_noerr(err, done);
err = GetEventParameter(theEvent, kEventParamTextInputSendKeyboardEvent,
typeEventRef, NULL, sizeof(EventRef), NULL, &keyEvent);
require_noerr(err, done);
err = GetEventParameter(keyEvent, kEventParamKeyModifiers,
typeUInt32, NULL, sizeof(UInt32), NULL, &modifiers);
require_noerr(err, done);
err = GetEventParameter(keyEvent, kEventParamKeyCode,
typeUInt32, NULL, sizeof(UInt32), NULL, &key_sym);
require_noerr(err, done);
err = GetEventParameter(keyEvent, kEventParamKeyMacCharCodes,
typeChar, NULL, sizeof(char), NULL, &charcode);
require_noerr(err, done);
#ifndef USE_CMD_KEY
if (modifiers & cmdKey)
goto done; /* Let system handle Cmd+... */
#endif
key_char = charcode;
vimModifiers = EventModifiers2VimModifiers(modifiers);
/* Find the special key (eg., for cursor keys) */
if (actualSize <= sizeof(UniChar) &&
((text[0] < 0x20) || (text[0] == 0x7f)))
{
for (i = 0; special_keys[i].key_sym != (KeySym)0; ++i)
if (special_keys[i].key_sym == key_sym)
{
key_char = TO_SPECIAL(special_keys[i].vim_code0,
special_keys[i].vim_code1);
key_char = simplify_key(key_char,
(int *)&vimModifiers);
isSpecial = TRUE;
break;
}
}
/* Intercept CMD-. and CTRL-c */
if (((modifiers & controlKey) && key_char == 'c') ||
((modifiers & cmdKey) && key_char == '.'))
got_int = TRUE;
if (!isSpecial)
{
/* remove SHIFT for keys that are already shifted, e.g.,
* '(' and '*' */
if (key_char < 0x100 && !isalpha(key_char) && isprint(key_char))
vimModifiers &= ~MOD_MASK_SHIFT;
/* remove CTRL from keys that already have it */
if (key_char < 0x20)
vimModifiers &= ~MOD_MASK_CTRL;
/* don't process unicode characters here */
if (!IS_SPECIAL(key_char))
{
/* Following code to simplify and consolidate vimModifiers
* taken liberally from gui_w48.c */
key_char = simplify_key(key_char, (int *)&vimModifiers);
/* Interpret META, include SHIFT, etc. */
key_char = extract_modifiers(key_char, (int *)&vimModifiers);
if (key_char == CSI)
key_char = K_CSI;
if (IS_SPECIAL(key_char))
isSpecial = TRUE;
}
}
if (vimModifiers)
{
result[len++] = CSI;
result[len++] = KS_MODIFIER;
result[len++] = vimModifiers;
}
if (isSpecial && IS_SPECIAL(key_char))
{
result[len++] = CSI;
result[len++] = K_SECOND(key_char);
result[len++] = K_THIRD(key_char);
}
else
{
encLen = actualSize;
to = mac_utf16_to_enc(text, actualSize, &encLen);
if (to)
{
/* This is basically add_to_input_buf_csi() */
for (i = 0; i < encLen && len < (INLINE_KEY_BUFFER_SIZE-1); ++i)
{
result[len++] = to[i];
if (to[i] == CSI)
{
result[len++] = KS_EXTRA;
result[len++] = (int)KE_CSI;
}
}
vim_free(to);
}
}
add_to_input_buf(result, len);
err = noErr;
done:
vim_free(text);
if (err == noErr)
{
/* Fake event to wake up WNE (required to get
* key repeat working */
PostEvent(keyUp, 0);
return noErr;
}
return eventNotHandledErr;
}
#else
void
gui_mac_doKeyEvent(EventRecord *theEvent)
{
/* TODO: add support for COMMAND KEY */
long menu;
unsigned char string[20];
short num, i;
short len = 0;
KeySym key_sym;
int key_char;
int modifiers;
int simplify = FALSE;
/* Mask the mouse (as per user setting) */
if (p_mh)
ObscureCursor();
/* Get the key code and it's ASCII representation */
key_sym = ((theEvent->message & keyCodeMask) >> 8);
key_char = theEvent->message & charCodeMask;
num = 1;
/* Intercept CTRL-C */
if (theEvent->modifiers & controlKey)
{
if (key_char == Ctrl_C && ctrl_c_interrupts)
got_int = TRUE;
else if ((theEvent->modifiers & ~(controlKey|shiftKey)) == 0
&& (key_char == '2' || key_char == '6'))
{
/* CTRL-^ and CTRL-@ don't work in the normal way. */
if (key_char == '2')
key_char = Ctrl_AT;
else
key_char = Ctrl_HAT;
theEvent->modifiers = 0;
}
}
/* Intercept CMD-. */
if (theEvent->modifiers & cmdKey)
if (key_char == '.')
got_int = TRUE;
/* Handle command key as per menu */
/* TODO: should override be allowed? Require YAO or could use 'winaltkey' */
if (theEvent->modifiers & cmdKey)
/* Only accept CMD alone or with CAPLOCKS and the mouse button.
* Why the mouse button? */
if ((theEvent->modifiers & (~(cmdKey | btnState | alphaLock))) == 0)
{
menu = MenuKey(key_char);
if (HiWord(menu))
{
gui_mac_handle_menu(menu);
return;
}
}
/* Convert the modifiers */
modifiers = EventModifiers2VimModifiers(theEvent->modifiers);
/* Handle special keys. */
#if 0
/* Why has this been removed? */
if (!(theEvent->modifiers & (cmdKey | controlKey | rightControlKey)))
#endif
{
/* Find the special key (for non-printable keyt_char) */
if ((key_char < 0x20) || (key_char == 0x7f))
for (i = 0; special_keys[i].key_sym != (KeySym)0; i++)
if (special_keys[i].key_sym == key_sym)
{
# if 0
/* We currently don't have not so special key */
if (special_keys[i].vim_code1 == NUL)
key_char = special_keys[i].vim_code0;
else
# endif
key_char = TO_SPECIAL(special_keys[i].vim_code0,
special_keys[i].vim_code1);
simplify = TRUE;
break;
}
}
/* For some keys the modifier is included in the char itself. */
if (simplify || key_char == TAB || key_char == ' ')
key_char = simplify_key(key_char, &modifiers);
/* Add the modifier to the input bu if needed */
/* Do not want SHIFT-A or CTRL-A with modifier */
if (!IS_SPECIAL(key_char)
&& key_sym != vk_Space
&& key_sym != vk_Tab
&& key_sym != vk_Return
&& key_sym != vk_Enter
&& key_sym != vk_Esc)
{
#if 1
/* Clear modifiers when only one modifier is set */
if ((modifiers == MOD_MASK_SHIFT)
|| (modifiers == MOD_MASK_CTRL)
|| (modifiers == MOD_MASK_ALT))
modifiers = 0;
#else
if (modifiers & MOD_MASK_CTRL)
modifiers = modifiers & ~MOD_MASK_CTRL;
if (modifiers & MOD_MASK_ALT)
modifiers = modifiers & ~MOD_MASK_ALT;
if (modifiers & MOD_MASK_SHIFT)
modifiers = modifiers & ~MOD_MASK_SHIFT;
#endif
}
if (modifiers)
{
string[len++] = CSI;
string[len++] = KS_MODIFIER;
string[len++] = modifiers;
}
if (IS_SPECIAL(key_char))
{
string[len++] = CSI;
string[len++] = K_SECOND(key_char);
string[len++] = K_THIRD(key_char);
}
else
{
#ifdef FEAT_MBYTE
/* Convert characters when needed (e.g., from MacRoman to latin1).
* This doesn't work for the NUL byte. */
if (input_conv.vc_type != CONV_NONE && key_char > 0)
{
char_u from[2], *to;
int l;
from[0] = key_char;
from[1] = NUL;
l = 1;
to = string_convert(&input_conv, from, &l);
if (to != NULL)
{
for (i = 0; i < l && len < 19; i++)
{
if (to[i] == CSI)
{
string[len++] = KS_EXTRA;
string[len++] = KE_CSI;
}
else
string[len++] = to[i];
}
vim_free(to);
}
else
string[len++] = key_char;
}
else
#endif
string[len++] = key_char;
}
if (len == 1 && string[0] == CSI)
{
/* Turn CSI into K_CSI. */
string[ len++ ] = KS_EXTRA;
string[ len++ ] = KE_CSI;
}
add_to_input_buf(string, len);
}
#endif
/*
* Handle MouseClick
*/
void
gui_mac_doMouseDownEvent(EventRecord *theEvent)
{
short thePart;
WindowPtr whichWindow;
thePart = FindWindow(theEvent->where, &whichWindow);
#ifdef FEAT_GUI_TABLINE
/* prevent that the vim window size changes if it's activated by a
click into the tab pane */
if (whichWindow == drawer)
return;
#endif
switch (thePart)
{
case (inDesk):
/* TODO: what to do? */
break;
case (inMenuBar):
gui_mac_handle_menu(MenuSelect(theEvent->where));
break;
case (inContent):
gui_mac_doInContentClick(theEvent, whichWindow);
break;
case (inDrag):
gui_mac_doInDragClick(theEvent->where, whichWindow);
break;
case (inGrow):
gui_mac_doInGrowClick(theEvent->where, whichWindow);
break;
case (inGoAway):
if (TrackGoAway(whichWindow, theEvent->where))
gui_shell_closed();
break;
case (inZoomIn):
case (inZoomOut):
gui_mac_doInZoomClick(theEvent, whichWindow);
break;
}
}
/*
* Handle MouseMoved
* [this event is a moving in and out of a region]
*/
void
gui_mac_doMouseMovedEvent(EventRecord *event)
{
Point thePoint;
int_u vimModifiers;
thePoint = event->where;
GlobalToLocal(&thePoint);
vimModifiers = EventModifiers2VimMouseModifiers(event->modifiers);
if (!Button())
gui_mouse_moved(thePoint.h, thePoint.v);
else
if (!clickIsPopup)
gui_send_mouse_event(MOUSE_DRAG, thePoint.h,
thePoint.v, FALSE, vimModifiers);
/* Reset the region from which we move in and out */
SetRect(&dragRect, FILL_X(X_2_COL(thePoint.h)),
FILL_Y(Y_2_ROW(thePoint.v)),
FILL_X(X_2_COL(thePoint.h)+1),
FILL_Y(Y_2_ROW(thePoint.v)+1));
if (dragRectEnbl)
dragRectControl = kCreateRect;
}
/*
* Handle the mouse release
*/
void
gui_mac_doMouseUpEvent(EventRecord *theEvent)
{
Point thePoint;
int_u vimModifiers;
/* TODO: Properly convert the Contextual menu mouse-up */
/* Potential source of the double menu */
lastMouseTick = theEvent->when;
dragRectEnbl = FALSE;
dragRectControl = kCreateEmpty;
thePoint = theEvent->where;
GlobalToLocal(&thePoint);
vimModifiers = EventModifiers2VimMouseModifiers(theEvent->modifiers);
if (clickIsPopup)
{
vimModifiers &= ~MOUSE_CTRL;
clickIsPopup = FALSE;
}
gui_send_mouse_event(MOUSE_RELEASE, thePoint.h, thePoint.v, FALSE, vimModifiers);
}
static pascal OSStatus
gui_mac_mouse_wheel(EventHandlerCallRef nextHandler, EventRef theEvent,
void *data)
{
Point point;
Rect bounds;
UInt32 mod;
SInt32 delta;
int_u vim_mod;
EventMouseWheelAxis axis;
if (noErr == GetEventParameter(theEvent, kEventParamMouseWheelAxis,
typeMouseWheelAxis, NULL, sizeof(axis), NULL, &axis)
&& axis != kEventMouseWheelAxisY)
goto bail; /* Vim only does up-down scrolling */
if (noErr != GetEventParameter(theEvent, kEventParamMouseWheelDelta,
typeSInt32, NULL, sizeof(SInt32), NULL, &delta))
goto bail;
if (noErr != GetEventParameter(theEvent, kEventParamMouseLocation,
typeQDPoint, NULL, sizeof(Point), NULL, &point))
goto bail;
if (noErr != GetEventParameter(theEvent, kEventParamKeyModifiers,
typeUInt32, NULL, sizeof(UInt32), NULL, &mod))
goto bail;
vim_mod = 0;
if (mod & shiftKey)
vim_mod |= MOUSE_SHIFT;
if (mod & controlKey)
vim_mod |= MOUSE_CTRL;
if (mod & optionKey)
vim_mod |= MOUSE_ALT;
if (noErr == GetWindowBounds(gui.VimWindow, kWindowContentRgn, &bounds))
{
point.h -= bounds.left;
point.v -= bounds.top;
}
gui_send_mouse_event((delta > 0) ? MOUSE_4 : MOUSE_5,
point.h, point.v, FALSE, vim_mod);
/* post a bogus event to wake up WaitNextEvent */
PostEvent(keyUp, 0);
return noErr;
bail:
/*
* when we fail give any additional callback handler a chance to perform
* it's actions
*/
return CallNextEventHandler(nextHandler, theEvent);
}
void
gui_mch_mousehide(int hide)
{
/* TODO */
}
#if 0
/*
* This would be the normal way of invoking the contextual menu
* but the Vim API doesn't seem to a support a request to get
* the menu that we should display
*/
void
gui_mac_handle_contextual_menu(event)
EventRecord *event;
{
/*
* Clone PopUp to use menu
* Create a object descriptor for the current selection
* Call the procedure
*/
// Call to Handle Popup
OSStatus status = ContextualMenuSelect(CntxMenu, event->where, false, kCMHelpItemNoHelp, "", NULL, &CntxType, &CntxMenuID, &CntxMenuItem);
if (status != noErr)
return;
if (CntxType == kCMMenuItemSelected)
{
/* Handle the menu CntxMenuID, CntxMenuItem */
/* The submenu can be handle directly by gui_mac_handle_menu */
/* But what about the current menu, is the meny changed by ContextualMenuSelect */
gui_mac_handle_menu((CntxMenuID << 16) + CntxMenuItem);
}
else if (CntxMenuID == kCMShowHelpSelected)
{
/* Should come up with the help */
}
}
#endif
/*
* Handle menubar selection
*/
void
gui_mac_handle_menu(long menuChoice)
{
short menu = HiWord(menuChoice);
short item = LoWord(menuChoice);
vimmenu_T *theVimMenu = root_menu;
if (menu == 256) /* TODO: use constant or gui.xyz */
{
if (item == 1)
gui_mch_beep(); /* TODO: Popup dialog or do :intro */
}
else if (item != 0)
{
theVimMenu = gui_mac_get_vim_menu(menu, item, root_menu);
if (theVimMenu)
gui_menu_cb(theVimMenu);
}
HiliteMenu(0);
}
/*
* Dispatch the event to proper handler
*/
void
gui_mac_handle_event(EventRecord *event)
{
OSErr error;
/* Handle contextual menu right now (if needed) */
if (IsShowContextualMenuClick(event))
{
# if 0
gui_mac_handle_contextual_menu(event);
# else
gui_mac_doMouseDownEvent(event);
# endif
return;
}
/* Handle normal event */
switch (event->what)
{
#ifndef USE_CARBONKEYHANDLER
case (keyDown):
case (autoKey):
gui_mac_doKeyEvent(event);
break;
#endif
case (keyUp):
/* We don't care about when the key is released */
break;
case (mouseDown):
gui_mac_doMouseDownEvent(event);
break;
case (mouseUp):
gui_mac_doMouseUpEvent(event);
break;
case (updateEvt):
gui_mac_doUpdateEvent(event);
break;
case (diskEvt):
/* We don't need special handling for disk insertion */
break;
case (activateEvt):
gui_mac_doActivateEvent(event);
break;
case (osEvt):
switch ((event->message >> 24) & 0xFF)
{
case (0xFA): /* mouseMovedMessage */
gui_mac_doMouseMovedEvent(event);
break;
case (0x01): /* suspendResumeMessage */
gui_mac_doSuspendEvent(event);
break;
}
break;
#ifdef USE_AEVENT
case (kHighLevelEvent):
/* Someone's talking to us, through AppleEvents */
error = AEProcessAppleEvent(event); /* TODO: Error Handling */
break;
#endif
}
}
/*
* ------------------------------------------------------------
* Unknown Stuff
* ------------------------------------------------------------
*/
GuiFont
gui_mac_find_font(char_u *font_name)
{
char_u c;
char_u *p;
char_u pFontName[256];
Str255 systemFontname;
short font_id;
short size=9;
GuiFont font;
#if 0
char_u *fontNamePtr;
#endif
for (p = font_name; ((*p != 0) && (*p != ':')); p++)
;
c = *p;
*p = 0;
#if 1
STRCPY(&pFontName[1], font_name);
pFontName[0] = STRLEN(font_name);
*p = c;
/* Get the font name, minus the style suffix (:h, etc) */
char_u fontName[256];
char_u *styleStart = vim_strchr(font_name, ':');
size_t fontNameLen = styleStart ? styleStart - font_name : STRLEN(fontName);
vim_strncpy(fontName, font_name, fontNameLen);
ATSUFontID fontRef;
FMFontStyle fontStyle;
font_id = 0;
if (ATSUFindFontFromName(&pFontName[1], pFontName[0], kFontFullName,
kFontMacintoshPlatform, kFontNoScriptCode, kFontNoLanguageCode,
&fontRef) == noErr)
{
if (FMGetFontFamilyInstanceFromFont(fontRef, &font_id, &fontStyle) != noErr)
font_id = 0;
}
if (font_id == 0)
{
/*
* Try again, this time replacing underscores in the font name
* with spaces (:set guifont allows the two to be used
* interchangeably; the Font Manager doesn't).
*/
int i, changed = FALSE;
for (i = pFontName[0]; i > 0; --i)
{
if (pFontName[i] == '_')
{
pFontName[i] = ' ';
changed = TRUE;
}
}
if (changed)
if (ATSUFindFontFromName(&pFontName[1], pFontName[0],
kFontFullName, kFontNoPlatformCode, kFontNoScriptCode,
kFontNoLanguageCode, &fontRef) == noErr)
{
if (FMGetFontFamilyInstanceFromFont(fontRef, &font_id, &fontStyle) != noErr)
font_id = 0;
}
}
#else
/* name = C2Pascal_save(menu->dname); */
fontNamePtr = C2Pascal_save_and_remove_backslash(font_name);
GetFNum(fontNamePtr, &font_id);
#endif
if (font_id == 0)
{
/* Oups, the system font was it the one the user want */
if (FMGetFontFamilyName(systemFont, systemFontname) != noErr)
return NOFONT;
if (!EqualString(pFontName, systemFontname, false, false))
return NOFONT;
}
if (*p == ':')
{
p++;
/* Set the values found after ':' */
while (*p)
{
switch (*p++)
{
case 'h':
size = points_to_pixels(p, &p, TRUE);
break;
/*
* TODO: Maybe accept width and styles
*/
}
while (*p == ':')
p++;
}
}
if (size < 1)
size = 1; /* Avoid having a size of 0 with system font */
font = (size << 16) + ((long) font_id & 0xFFFF);
return font;
}
/*
* ------------------------------------------------------------
* GUI_MCH functionality
* ------------------------------------------------------------
*/
/*
* 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)
{
/* TODO: Move most of this stuff toward gui_mch_init */
#ifdef USE_EXE_NAME
FSSpec applDir;
# ifndef USE_FIND_BUNDLE_PATH
short applVRefNum;
long applDirID;
Str255 volName;
# else
ProcessSerialNumber psn;
FSRef applFSRef;
# endif
#endif
#if 0
InitCursor();
RegisterAppearanceClient();
#ifdef USE_AEVENT
(void) InstallAEHandlers();
#endif
pomme = NewMenu(256, "\p\024"); /* 0x14= = Apple Menu */
AppendMenu(pomme, "\pAbout VIM");
InsertMenu(pomme, 0);
DrawMenuBar();
#ifndef USE_OFFSETED_WINDOW
SetRect(&windRect, 10, 48, 10+80*7 + 16, 48+24*11);
#else
SetRect(&windRect, 300, 40, 300+80*7 + 16, 40+24*11);
#endif
CreateNewWindow(kDocumentWindowClass,
kWindowResizableAttribute | kWindowCollapseBoxAttribute,
&windRect, &gui.VimWindow);
SetPortWindowPort(gui.VimWindow);
gui.char_width = 7;
gui.char_height = 11;
gui.char_ascent = 6;
gui.num_rows = 24;
gui.num_cols = 80;
gui.in_focus = TRUE; /* For the moment -> syn. of front application */
gScrollAction = NewControlActionUPP(gui_mac_scroll_action);
gScrollDrag = NewControlActionUPP(gui_mac_drag_thumb);
dragRectEnbl = FALSE;
dragRgn = NULL;
dragRectControl = kCreateEmpty;
cursorRgn = NewRgn();
#endif
#ifdef USE_EXE_NAME
# ifndef USE_FIND_BUNDLE_PATH
HGetVol(volName, &applVRefNum, &applDirID);
/* TN2015: mention a possible bad VRefNum */
FSMakeFSSpec(applVRefNum, applDirID, "\p", &applDir);
# else
/* OSErr GetApplicationBundleFSSpec(FSSpecPtr theFSSpecPtr)
* of TN2015
*/
(void)GetCurrentProcess(&psn);
/* if (err != noErr) return err; */
(void)GetProcessBundleLocation(&psn, &applFSRef);
/* if (err != noErr) return err; */
(void)FSGetCatalogInfo(&applFSRef, kFSCatInfoNone, NULL, NULL, &applDir, NULL);
/* This technic return NIL when we disallow_gui */
# endif
exe_name = FullPathFromFSSpec_save(applDir);
#endif
}
#ifndef ALWAYS_USE_GUI
/*
* Check if the GUI can be started. Called before gvimrc is sourced.
* Return OK or FAIL.
*/
int
gui_mch_init_check(void)
{
/* TODO: For MacOS X find a way to return FAIL, if the user logged in
* using the >console
*/
if (disallow_gui) /* see main.c for reason to disallow */
return FAIL;
return OK;
}
#endif
static OSErr
receiveHandler(WindowRef theWindow, void *handlerRefCon, DragRef theDrag)
{
int x, y;
int_u modifiers;
char_u **fnames = NULL;
int count;
int i, j;
/* Get drop position, modifiers and count of items */
{
Point point;
SInt16 mouseUpModifiers;
UInt16 countItem;
GetDragMouse(theDrag, &point, NULL);
GlobalToLocal(&point);
x = point.h;
y = point.v;
GetDragModifiers(theDrag, NULL, NULL, &mouseUpModifiers);
modifiers = EventModifiers2VimMouseModifiers(mouseUpModifiers);
CountDragItems(theDrag, &countItem);
count = countItem;
}
fnames = (char_u **)alloc(count * sizeof(char_u *));
if (fnames == NULL)
return dragNotAcceptedErr;
/* Get file names dropped */
for (i = j = 0; i < count; ++i)
{
DragItemRef item;
OSErr err;
Size size;
FlavorType type = flavorTypeHFS;
HFSFlavor hfsFlavor;
fnames[i] = NULL;
GetDragItemReferenceNumber(theDrag, i + 1, &item);
err = GetFlavorDataSize(theDrag, item, type, &size);
if (err != noErr || size > sizeof(hfsFlavor))
continue;
err = GetFlavorData(theDrag, item, type, &hfsFlavor, &size, 0);
if (err != noErr)
continue;
fnames[j++] = FullPathFromFSSpec_save(hfsFlavor.fileSpec);
}
count = j;
gui_handle_drop(x, y, modifiers, fnames, count);
/* Fake mouse event to wake from stall */
PostEvent(mouseUp, 0);
return noErr;
}
/*
* Initialise the GUI. Create all the windows, set up all the call-backs
* etc.
*/
int
gui_mch_init(void)
{
/* TODO: Move most of this stuff toward gui_mch_init */
Rect windRect;
MenuHandle pomme;
EventHandlerRef mouseWheelHandlerRef;
EventTypeSpec eventTypeSpec;
ControlRef rootControl;
if (Gestalt(gestaltSystemVersion, &gMacSystemVersion) != noErr)
gMacSystemVersion = 0x1000; /* TODO: Default to minimum sensible value */
#if 1
InitCursor();
RegisterAppearanceClient();
#ifdef USE_AEVENT
(void) InstallAEHandlers();
#endif
pomme = NewMenu(256, "\p\024"); /* 0x14= = Apple Menu */
AppendMenu(pomme, "\pAbout VIM");
InsertMenu(pomme, 0);
DrawMenuBar();
#ifndef USE_OFFSETED_WINDOW
SetRect(&windRect, 10, 48, 10+80*7 + 16, 48+24*11);
#else
SetRect(&windRect, 300, 40, 300+80*7 + 16, 40+24*11);
#endif
gui.VimWindow = NewCWindow(nil, &windRect, "\pgVim on Macintosh", true,
zoomDocProc,
(WindowPtr)-1L, true, 0);
CreateRootControl(gui.VimWindow, &rootControl);
InstallReceiveHandler((DragReceiveHandlerUPP)receiveHandler,
gui.VimWindow, NULL);
SetPortWindowPort(gui.VimWindow);
gui.char_width = 7;
gui.char_height = 11;
gui.char_ascent = 6;
gui.num_rows = 24;
gui.num_cols = 80;
gui.in_focus = TRUE; /* For the moment -> syn. of front application */
gScrollAction = NewControlActionUPP(gui_mac_scroll_action);
gScrollDrag = NewControlActionUPP(gui_mac_drag_thumb);
/* Install Carbon event callbacks. */
(void)InstallFontPanelHandler();
dragRectEnbl = FALSE;
dragRgn = NULL;
dragRectControl = kCreateEmpty;
cursorRgn = NewRgn();
#endif
/* Display any pending error messages */
display_errors();
/* Get background/foreground colors from system */
/* TODO: do the appropriate call to get real defaults */
gui.norm_pixel = 0x00000000;
gui.back_pixel = 0x00FFFFFF;
/* 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();
/*
* Setting the gui constants
*/
#ifdef FEAT_MENU
gui.menu_height = 0;
#endif
gui.scrollbar_height = gui.scrollbar_width = 15; /* cheat 1 overlap */
gui.border_offset = gui.border_width = 2;
/* If Quartz-style text anti aliasing is available (see
gui_mch_draw_string() below), enable it for all font sizes. */
vim_setenv((char_u *)"QDTEXT_MINSIZE", (char_u *)"1");
eventTypeSpec.eventClass = kEventClassMouse;
eventTypeSpec.eventKind = kEventMouseWheelMoved;
mouseWheelHandlerUPP = NewEventHandlerUPP(gui_mac_mouse_wheel);
if (noErr != InstallApplicationEventHandler(mouseWheelHandlerUPP, 1,
&eventTypeSpec, NULL, &mouseWheelHandlerRef))
{
mouseWheelHandlerRef = NULL;
DisposeEventHandlerUPP(mouseWheelHandlerUPP);
mouseWheelHandlerUPP = NULL;
}
#ifdef USE_CARBONKEYHANDLER
InterfaceTypeList supportedServices = { kUnicodeDocument };
NewTSMDocument(1, supportedServices, &gTSMDocument, 0);
/* We don't support inline input yet, use input window by default */
UseInputWindow(gTSMDocument, TRUE);
/* Should we activate the document by default? */
// ActivateTSMDocument(gTSMDocument);
EventTypeSpec textEventTypes[] = {
{ kEventClassTextInput, kEventTextInputUpdateActiveInputArea },
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
{ kEventClassTextInput, kEventTextInputPosToOffset },
{ kEventClassTextInput, kEventTextInputOffsetToPos },
};
keyEventHandlerUPP = NewEventHandlerUPP(gui_mac_handle_text_input);
if (noErr != InstallApplicationEventHandler(keyEventHandlerUPP,
NR_ELEMS(textEventTypes),
textEventTypes, NULL, NULL))
{
DisposeEventHandlerUPP(keyEventHandlerUPP);
keyEventHandlerUPP = NULL;
}
EventTypeSpec windowEventTypes[] = {
{ kEventClassWindow, kEventWindowActivated },
{ kEventClassWindow, kEventWindowDeactivated },
};
/* Install window event handler to support TSMDocument activate and
* deactivate */
winEventHandlerUPP = NewEventHandlerUPP(gui_mac_handle_window_activate);
if (noErr != InstallWindowEventHandler(gui.VimWindow,
winEventHandlerUPP,
NR_ELEMS(windowEventTypes),
windowEventTypes, NULL, NULL))
{
DisposeEventHandlerUPP(winEventHandlerUPP);
winEventHandlerUPP = NULL;
}
#endif
/*
#ifdef FEAT_MBYTE
set_option_value((char_u *)"encoding", 0L, (char_u *)"utf-8", 0);
#endif
*/
#ifdef FEAT_GUI_TABLINE
/*
* Create the tabline
*/
initialise_tabline();
#endif
/* TODO: Load bitmap if using TOOLBAR */
return OK;
}
/*
* Called when the foreground or background color has been changed.
*/
void
gui_mch_new_colors(void)
{
/* TODO:
* This proc is called when Normal is set to a value
* so what must be done? I don't know
*/
}
/*
* Open the GUI window which was created by a call to gui_mch_init().
*/
int
gui_mch_open(void)
{
ShowWindow(gui.VimWindow);
if (gui_win_x != -1 && gui_win_y != -1)
gui_mch_set_winpos(gui_win_x, gui_win_y);
/*
* Make the GUI the foreground process (in case it was launched
* from the Terminal or via :gui).
*/
{
ProcessSerialNumber psn;
if (GetCurrentProcess(&psn) == noErr)
SetFrontProcess(&psn);
}
return OK;
}
#ifdef USE_ATSUI_DRAWING
static void
gui_mac_dispose_atsui_style(void)
{
if (p_macatsui && gFontStyle)
ATSUDisposeStyle(gFontStyle);
#ifdef FEAT_MBYTE
if (p_macatsui && gWideFontStyle)
ATSUDisposeStyle(gWideFontStyle);
#endif
}
#endif
void
gui_mch_exit(int rc)
{
/* TODO: find out all what is missing here? */
DisposeRgn(cursorRgn);
#ifdef USE_CARBONKEYHANDLER
if (keyEventHandlerUPP)
DisposeEventHandlerUPP(keyEventHandlerUPP);
#endif
if (mouseWheelHandlerUPP != NULL)
DisposeEventHandlerUPP(mouseWheelHandlerUPP);
#ifdef USE_ATSUI_DRAWING
gui_mac_dispose_atsui_style();
#endif
#ifdef USE_CARBONKEYHANDLER
FixTSMDocument(gTSMDocument);
DeactivateTSMDocument(gTSMDocument);
DeleteTSMDocument(gTSMDocument);
#endif
/* Exit to shell? */
exit(rc);
}
/*
* Get the position of the top left corner of the window.
*/
int
gui_mch_get_winpos(int *x, int *y)
{
/* TODO */
Rect bounds;
OSStatus status;
/* Carbon >= 1.0.2, MacOS >= 8.5 */
status = GetWindowBounds(gui.VimWindow, kWindowStructureRgn, &bounds);
if (status != noErr)
return FAIL;
*x = bounds.left;
*y = bounds.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)
{
/* TODO: Should make sure the window is move within range
* e.g.: y > ~16 [Menu bar], x > 0, x < screen width
*/
MoveWindowStructure(gui.VimWindow, x, y);
}
void
gui_mch_set_shellsize(
int width,
int height,
int min_width,
int min_height,
int base_width,
int base_height,
int direction)
{
CGrafPtr VimPort;
Rect VimBound;
if (gui.which_scrollbars[SBAR_LEFT])
{
VimPort = GetWindowPort(gui.VimWindow);
GetPortBounds(VimPort, &VimBound);
VimBound.left = -gui.scrollbar_width; /* + 1;*/
SetPortBounds(VimPort, &VimBound);
/* GetWindowBounds(gui.VimWindow, kWindowGlobalPortRgn, &winPortRect); ??*/
}
else
{
VimPort = GetWindowPort(gui.VimWindow);
GetPortBounds(VimPort, &VimBound);
VimBound.left = 0;
SetPortBounds(VimPort, &VimBound);
}
SizeWindow(gui.VimWindow, width, height, TRUE);
gui_resize_shell(width, height);
}
/*
* Get the screen dimensions.
* Allow 10 pixels for horizontal borders, 40 for vertical borders.
* Is there no way to find out how wide the borders really are?
* TODO: Add live update of those value on suspend/resume.
*/
void
gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
{
GDHandle dominantDevice = GetMainDevice();
Rect screenRect = (**dominantDevice).gdRect;
*screen_w = screenRect.right - 10;
*screen_h = screenRect.bottom - 40;
}
/*
* Open the Font Panel and wait for the user to select a font and
* close the panel. Then fill the buffer pointed to by font_name with
* the name and size of the selected font and return the font's handle,
* or NOFONT in case of an error.
*/
static GuiFont
gui_mac_select_font(char_u *font_name)
{
GuiFont selected_font = NOFONT;
OSStatus status;
FontSelectionQDStyle curr_font;
/* Initialize the Font Panel with the current font. */
curr_font.instance.fontFamily = gui.norm_font & 0xFFFF;
curr_font.size = (gui.norm_font >> 16);
/* TODO: set fontStyle once styles are supported in gui_mac_find_font() */
curr_font.instance.fontStyle = 0;
curr_font.hasColor = false;
curr_font.version = 0; /* version number of the style structure */
status = SetFontInfoForSelection(kFontSelectionQDType,
/*numStyles=*/1, &curr_font, /*eventTarget=*/NULL);
gFontPanelInfo.family = curr_font.instance.fontFamily;
gFontPanelInfo.style = curr_font.instance.fontStyle;
gFontPanelInfo.size = curr_font.size;
/* Pop up the Font Panel. */
status = FPShowHideFontPanel();
if (status == noErr)
{
/*
* The Font Panel is modeless. We really need it to be modal,
* so we spin in an event loop until the panel is closed.
*/
gFontPanelInfo.isPanelVisible = true;
while (gFontPanelInfo.isPanelVisible)
{
EventRecord e;
WaitNextEvent(everyEvent, &e, /*sleep=*/20, /*mouseRgn=*/NULL);
}
GetFontPanelSelection(font_name);
selected_font = gui_mac_find_font(font_name);
}
return selected_font;
}
#ifdef USE_ATSUI_DRAWING
static void
gui_mac_create_atsui_style(void)
{
if (p_macatsui && gFontStyle == NULL)
{
if (ATSUCreateStyle(&gFontStyle) != noErr)
gFontStyle = NULL;
}
#ifdef FEAT_MBYTE
if (p_macatsui && gWideFontStyle == NULL)
{
if (ATSUCreateStyle(&gWideFontStyle) != noErr)
gWideFontStyle = NULL;
}
#endif
p_macatsui_last = p_macatsui;
}
#endif
/*
* Initialise vim to use the font with the given name. Return FAIL if the font
* could not be loaded, OK otherwise.
*/
int
gui_mch_init_font(char_u *font_name, int fontset)
{
/* TODO: Add support for bold italic underline proportional etc... */
Str255 suggestedFont = "\pMonaco";
int suggestedSize = 10;
FontInfo font_info;
short font_id;
GuiFont font;
char_u used_font_name[512];
#ifdef USE_ATSUI_DRAWING
gui_mac_create_atsui_style();
#endif
if (font_name == NULL)
{
/* First try to get the suggested font */
GetFNum(suggestedFont, &font_id);
if (font_id == 0)
{
/* Then pickup the standard application font */
font_id = GetAppFont();
STRCPY(used_font_name, "default");
}
else
STRCPY(used_font_name, "Monaco");
font = (suggestedSize << 16) + ((long) font_id & 0xFFFF);
}
else if (STRCMP(font_name, "*") == 0)
{
char_u *new_p_guifont;
font = gui_mac_select_font(used_font_name);
if (font == NOFONT)
return FAIL;
/* Set guifont to the name of the selected font. */
new_p_guifont = alloc(STRLEN(used_font_name) + 1);
if (new_p_guifont != NULL)
{
STRCPY(new_p_guifont, used_font_name);
vim_free(p_guifont);
p_guifont = new_p_guifont;
/* Replace spaces in the font name with underscores. */
for ( ; *new_p_guifont; ++new_p_guifont)
{
if (*new_p_guifont == ' ')
*new_p_guifont = '_';
}
}
}
else
{
font = gui_mac_find_font(font_name);
vim_strncpy(used_font_name, font_name, sizeof(used_font_name) - 1);
if (font == NOFONT)
return FAIL;
}
gui.norm_font = font;
hl_set_font_name(used_font_name);
TextSize(font >> 16);
TextFont(font & 0xFFFF);
GetFontInfo(&font_info);
gui.char_ascent = font_info.ascent;
gui.char_width = CharWidth('_');
gui.char_height = font_info.ascent + font_info.descent + p_linespace;
#ifdef USE_ATSUI_DRAWING
if (p_macatsui && gFontStyle)
gui_mac_set_font_attributes(font);
#endif
return OK;
}
/*
* Adjust gui.char_height (after 'linespace' was changed).
*/
int
gui_mch_adjust_charheight(void)
{
FontInfo font_info;
GetFontInfo(&font_info);
gui.char_height = font_info.ascent + font_info.descent + p_linespace;
gui.char_ascent = font_info.ascent + p_linespace / 2;
return OK;
}
/*
* Get a font structure for highlighting.
*/
GuiFont
gui_mch_get_font(char_u *name, int giveErrorIfMissing)
{
GuiFont font;
font = gui_mac_find_font(name);
if (font == NOFONT)
{
if (giveErrorIfMissing)
EMSG2(_(e_font), name);
return NOFONT;
}
/*
* TODO : Accept only monospace
*/
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.
*/
char_u *
gui_mch_get_fontname(GuiFont font, char_u *name)
{
if (name == NULL)
return NULL;
return vim_strsave(name);
}
#endif
#ifdef USE_ATSUI_DRAWING
static void
gui_mac_set_font_attributes(GuiFont font)
{
ATSUFontID fontID;
Fixed fontSize;
Fixed fontWidth;
fontID = font & 0xFFFF;
fontSize = Long2Fix(font >> 16);
fontWidth = Long2Fix(gui.char_width);
ATSUAttributeTag attribTags[] =
{
kATSUFontTag, kATSUSizeTag, kATSUImposeWidthTag,
kATSUMaxATSUITagValue + 1
};
ByteCount attribSizes[] =
{
sizeof(ATSUFontID), sizeof(Fixed), sizeof(fontWidth),
sizeof(font)
};
ATSUAttributeValuePtr attribValues[] =
{
&fontID, &fontSize, &fontWidth, &font
};
if (FMGetFontFromFontFamilyInstance(fontID, 0, &fontID, NULL) == noErr)
{
if (ATSUSetAttributes(gFontStyle,
(sizeof attribTags) / sizeof(ATSUAttributeTag),
attribTags, attribSizes, attribValues) != noErr)
{
# ifndef NDEBUG
fprintf(stderr, "couldn't set font style\n");
# endif
ATSUDisposeStyle(gFontStyle);
gFontStyle = NULL;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* FIXME: we should use a more mbyte sensitive way to support
* wide font drawing */
fontWidth = Long2Fix(gui.char_width * 2);
if (ATSUSetAttributes(gWideFontStyle,
(sizeof attribTags) / sizeof(ATSUAttributeTag),
attribTags, attribSizes, attribValues) != noErr)
{
ATSUDisposeStyle(gWideFontStyle);
gWideFontStyle = NULL;
}
}
#endif
}
}
#endif
/*
* Set the current text font.
*/
void
gui_mch_set_font(GuiFont font)
{
#ifdef USE_ATSUI_DRAWING
GuiFont currFont;
ByteCount actualFontByteCount;
if (p_macatsui && gFontStyle)
{
/* Avoid setting same font again */
if (ATSUGetAttribute(gFontStyle, kATSUMaxATSUITagValue + 1,
sizeof(font), &currFont, &actualFontByteCount) == noErr
&& actualFontByteCount == (sizeof font))
{
if (currFont == font)
return;
}
gui_mac_set_font_attributes(font);
}
if (p_macatsui && !gIsFontFallbackSet)
{
/* Setup automatic font substitution. The user's guifontwide
* is tried first, then the system tries other fonts. */
/*
ATSUAttributeTag fallbackTags[] = { kATSULineFontFallbacksTag };
ByteCount fallbackSizes[] = { sizeof(ATSUFontFallbacks) };
ATSUCreateFontFallbacks(&gFontFallbacks);
ATSUSetObjFontFallbacks(gFontFallbacks, );
*/
if (gui.wide_font)
{
ATSUFontID fallbackFonts;
gIsFontFallbackSet = TRUE;
if (FMGetFontFromFontFamilyInstance(
(gui.wide_font & 0xFFFF),
0,
&fallbackFonts,
NULL) == noErr)
{
ATSUSetFontFallbacks((sizeof fallbackFonts)/sizeof(ATSUFontID),
&fallbackFonts,
kATSUSequentialFallbacksPreferred);
}
/*
ATSUAttributeValuePtr fallbackValues[] = { };
*/
}
}
#endif
TextSize(font >> 16);
TextFont(font & 0xFFFF);
}
/*
* If a font is not going to be used, free its structure.
*/
void
gui_mch_free_font(font)
GuiFont font;
{
/*
* Free font when "font" is not 0.
* Nothing to do in the current implementation, since
* nothing is allocated for each font used.
*/
}
static int
hex_digit(int c)
{
if (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. This routine was
* pretty much taken from example code in the Silicon Graphics OSF/Motif
* Programmer's Guide.
* Return INVALCOLOR when failed.
*/
guicolor_T
gui_mch_get_color(char_u *name)
{
/* TODO: Add support for the new named color of MacOS 8
*/
RGBColor MacColor;
// guicolor_T color = 0;
typedef struct guicolor_tTable
{
char *name;
guicolor_T color;
} guicolor_tTable;
/*
* The comment at the end of each line is the source
* (Mac, Window, Unix) and the number is the unix rgb.txt value
*/
static guicolor_tTable table[] =
{
{"Black", RGB(0x00, 0x00, 0x00)},
{"darkgray", RGB(0x80, 0x80, 0x80)}, /*W*/
{"darkgrey", RGB(0x80, 0x80, 0x80)}, /*W*/
{"Gray", RGB(0xC0, 0xC0, 0xC0)}, /*W*/
{"Grey", RGB(0xC0, 0xC0, 0xC0)}, /*W*/
{"lightgray", RGB(0xE0, 0xE0, 0xE0)}, /*W*/
{"lightgrey", RGB(0xE0, 0xE0, 0xE0)}, /*W*/
{"gray10", RGB(0x1A, 0x1A, 0x1A)}, /*W*/
{"grey10", RGB(0x1A, 0x1A, 0x1A)}, /*W*/
{"gray20", RGB(0x33, 0x33, 0x33)}, /*W*/
{"grey20", RGB(0x33, 0x33, 0x33)}, /*W*/
{"gray30", RGB(0x4D, 0x4D, 0x4D)}, /*W*/
{"grey30", RGB(0x4D, 0x4D, 0x4D)}, /*W*/
{"gray40", RGB(0x66, 0x66, 0x66)}, /*W*/
{"grey40", RGB(0x66, 0x66, 0x66)}, /*W*/
{"gray50", RGB(0x7F, 0x7F, 0x7F)}, /*W*/
{"grey50", RGB(0x7F, 0x7F, 0x7F)}, /*W*/
{"gray60", RGB(0x99, 0x99, 0x99)}, /*W*/
{"grey60", RGB(0x99, 0x99, 0x99)}, /*W*/
{"gray70", RGB(0xB3, 0xB3, 0xB3)}, /*W*/
{"grey70", RGB(0xB3, 0xB3, 0xB3)}, /*W*/
{"gray80", RGB(0xCC, 0xCC, 0xCC)}, /*W*/
{"grey80", RGB(0xCC, 0xCC, 0xCC)}, /*W*/
{"gray90", RGB(0xE5, 0xE5, 0xE5)}, /*W*/
{"grey90", RGB(0xE5, 0xE5, 0xE5)}, /*W*/
{"white", RGB(0xFF, 0xFF, 0xFF)},
{"darkred", RGB(0x80, 0x00, 0x00)}, /*W*/
{"red", RGB(0xDD, 0x08, 0x06)}, /*M*/
{"lightred", RGB(0xFF, 0xA0, 0xA0)}, /*W*/
{"DarkBlue", RGB(0x00, 0x00, 0x80)}, /*W*/
{"Blue", RGB(0x00, 0x00, 0xD4)}, /*M*/
{"lightblue", RGB(0xA0, 0xA0, 0xFF)}, /*W*/
{"DarkGreen", RGB(0x00, 0x80, 0x00)}, /*W*/
{"Green", RGB(0x00, 0x64, 0x11)}, /*M*/
{"lightgreen", RGB(0xA0, 0xFF, 0xA0)}, /*W*/
{"DarkCyan", RGB(0x00, 0x80, 0x80)}, /*W ?0x307D7E */
{"cyan", RGB(0x02, 0xAB, 0xEA)}, /*M*/
{"lightcyan", RGB(0xA0, 0xFF, 0xFF)}, /*W*/
{"darkmagenta", RGB(0x80, 0x00, 0x80)}, /*W*/
{"magenta", RGB(0xF2, 0x08, 0x84)}, /*M*/
{"lightmagenta",RGB(0xF0, 0xA0, 0xF0)}, /*W*/
{"brown", RGB(0x80, 0x40, 0x40)}, /*W*/
{"yellow", RGB(0xFC, 0xF3, 0x05)}, /*M*/
{"lightyellow", RGB(0xFF, 0xFF, 0xA0)}, /*M*/
{"darkyellow", RGB(0xBB, 0xBB, 0x00)}, /*U*/
{"SeaGreen", RGB(0x2E, 0x8B, 0x57)}, /*W 0x4E8975 */
{"orange", RGB(0xFC, 0x80, 0x00)}, /*W 0xF87A17 */
{"Purple", RGB(0xA0, 0x20, 0xF0)}, /*W 0x8e35e5 */
{"SlateBlue", RGB(0x6A, 0x5A, 0xCD)}, /*W 0x737CA1 */
{"Violet", RGB(0x8D, 0x38, 0xC9)}, /*U*/
};
int r, g, b;
int i;
if (name[0] == '#' && strlen((char *) 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
{
if (STRICMP(name, "hilite") == 0)
{
LMGetHiliteRGB(&MacColor);
return (RGB(MacColor.red >> 8, MacColor.green >> 8, MacColor.blue >> 8));
}
/* 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;
}
/*
* Last attempt. Look in the file "$VIM/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 = 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 = 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;
}
/*
* Set the current text foreground color.
*/
void
gui_mch_set_fg_color(guicolor_T color)
{
RGBColor TheColor;
TheColor.red = Red(color) * 0x0101;
TheColor.green = Green(color) * 0x0101;
TheColor.blue = Blue(color) * 0x0101;
RGBForeColor(&TheColor);
}
/*
* Set the current text background color.
*/
void
gui_mch_set_bg_color(guicolor_T color)
{
RGBColor TheColor;
TheColor.red = Red(color) * 0x0101;
TheColor.green = Green(color) * 0x0101;
TheColor.blue = Blue(color) * 0x0101;
RGBBackColor(&TheColor);
}
RGBColor specialColor;
/*
* Set the current text special color.
*/
void
gui_mch_set_sp_color(guicolor_T color)
{
specialColor.red = Red(color) * 0x0101;
specialColor.green = Green(color) * 0x0101;
specialColor.blue = Blue(color) * 0x0101;
}
/*
* Draw undercurl at the bottom of the character cell.
*/
static void
draw_undercurl(int flags, int row, int col, int cells)
{
int x;
int offset;
const static int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 };
int y = FILL_Y(row + 1) - 1;
RGBForeColor(&specialColor);
offset = val[FILL_X(col) % 8];
MoveTo(FILL_X(col), y - offset);
for (x = FILL_X(col); x < FILL_X(col + cells); ++x)
{
offset = val[x % 8];
LineTo(x, y - offset);
}
}
static void
draw_string_QD(int row, int col, char_u *s, int len, int flags)
{
#ifdef FEAT_MBYTE
char_u *tofree = NULL;
if (output_conv.vc_type != CONV_NONE)
{
tofree = string_convert(&output_conv, s, &len);
if (tofree != NULL)
s = tofree;
}
#endif
/*
* On OS X, try using Quartz-style text antialiasing.
*/
if (gMacSystemVersion >= 0x1020)
{
/* Quartz antialiasing is available only in OS 10.2 and later. */
UInt32 qd_flags = (p_antialias ?
kQDUseCGTextRendering | kQDUseCGTextMetrics : 0);
QDSwapTextFlags(qd_flags);
}
/*
* When antialiasing we're using srcOr mode, we have to clear the block
* before drawing the text.
* Also needed when 'linespace' is non-zero to remove the cursor and
* underlining.
* But not when drawing transparently.
* The following is like calling gui_mch_clear_block(row, col, row, col +
* len - 1), but without setting the bg color to gui.back_pixel.
*/
if (((gMacSystemVersion >= 0x1020 && p_antialias) || p_linespace != 0)
&& !(flags & DRAW_TRANSP))
{
Rect rc;
rc.left = FILL_X(col);
rc.top = FILL_Y(row);
#ifdef FEAT_MBYTE
/* Multibyte computation taken from gui_w32.c */
if (has_mbyte)
{
/* Compute the length in display cells. */
rc.right = FILL_X(col + mb_string2cells(s, len));
}
else
#endif
rc.right = FILL_X(col + len) + (col + len == Columns);
rc.bottom = FILL_Y(row + 1);
EraseRect(&rc);
}
if (gMacSystemVersion >= 0x1020 && p_antialias)
{
StyleParameter face;
face = normal;
if (flags & DRAW_BOLD)
face |= bold;
if (flags & DRAW_UNDERL)
face |= underline;
TextFace(face);
/* Quartz antialiasing works only in srcOr transfer mode. */
TextMode(srcOr);
MoveTo(TEXT_X(col), TEXT_Y(row));
DrawText((char*)s, 0, len);
}
else
{
/* Use old-style, non-antialiased QuickDraw text rendering. */
TextMode(srcCopy);
TextFace(normal);
/* SelectFont(hdc, gui.currFont); */
if (flags & DRAW_TRANSP)
{
TextMode(srcOr);
}
MoveTo(TEXT_X(col), TEXT_Y(row));
DrawText((char *)s, 0, len);
if (flags & DRAW_BOLD)
{
TextMode(srcOr);
MoveTo(TEXT_X(col) + 1, TEXT_Y(row));
DrawText((char *)s, 0, len);
}
if (flags & DRAW_UNDERL)
{
MoveTo(FILL_X(col), FILL_Y(row + 1) - 1);
LineTo(FILL_X(col + len) - 1, FILL_Y(row + 1) - 1);
}
}
if (flags & DRAW_UNDERC)
draw_undercurl(flags, row, col, len);
#ifdef FEAT_MBYTE
vim_free(tofree);
#endif
}
#ifdef USE_ATSUI_DRAWING
static void
draw_string_ATSUI(int row, int col, char_u *s, int len, int flags)
{
/* ATSUI requires utf-16 strings */
UniCharCount utf16_len;
UniChar *tofree = mac_enc_to_utf16(s, len, (size_t *)&utf16_len);
utf16_len /= sizeof(UniChar);
/* - ATSUI automatically antialiases text (Someone)
* - for some reason it does not work... (Jussi) */
#ifdef MAC_ATSUI_DEBUG
fprintf(stderr, "row = %d, col = %d, len = %d: '%c'\n",
row, col, len, len == 1 ? s[0] : ' ');
#endif
/*
* When antialiasing we're using srcOr mode, we have to clear the block
* before drawing the text.
* Also needed when 'linespace' is non-zero to remove the cursor and
* underlining.
* But not when drawing transparently.
* The following is like calling gui_mch_clear_block(row, col, row, col +
* len - 1), but without setting the bg color to gui.back_pixel.
*/
if ((flags & DRAW_TRANSP) == 0)
{
Rect rc;
rc.left = FILL_X(col);
rc.top = FILL_Y(row);
/* Multibyte computation taken from gui_w32.c */
if (has_mbyte)
{
/* Compute the length in display cells. */
rc.right = FILL_X(col + mb_string2cells(s, len));
}
else
rc.right = FILL_X(col + len) + (col + len == Columns);
rc.bottom = FILL_Y(row + 1);
EraseRect(&rc);
}
{
TextMode(srcCopy);
TextFace(normal);
/* SelectFont(hdc, gui.currFont); */
if (flags & DRAW_TRANSP)
{
TextMode(srcOr);
}
MoveTo(TEXT_X(col), TEXT_Y(row));
if (gFontStyle && flags & DRAW_BOLD)
{
Boolean attValue = true;
ATSUAttributeTag attribTags[] = { kATSUQDBoldfaceTag };
ByteCount attribSizes[] = { sizeof(Boolean) };
ATSUAttributeValuePtr attribValues[] = { &attValue };
ATSUSetAttributes(gFontStyle, 1, attribTags, attribSizes, attribValues);
}
UInt32 useAntialias = p_antialias ? kATSStyleApplyAntiAliasing
: kATSStyleNoAntiAliasing;
if (useAntialias != useAntialias_cached)
{
ATSUAttributeTag attribTags[] = { kATSUStyleRenderingOptionsTag };
ByteCount attribSizes[] = { sizeof(UInt32) };
ATSUAttributeValuePtr attribValues[] = { &useAntialias };
if (gFontStyle)
ATSUSetAttributes(gFontStyle, 1, attribTags,
attribSizes, attribValues);
if (gWideFontStyle)
ATSUSetAttributes(gWideFontStyle, 1, attribTags,
attribSizes, attribValues);
useAntialias_cached = useAntialias;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int n, width_in_cell, last_width_in_cell;
UniCharArrayOffset offset = 0;
UniCharCount yet_to_draw = 0;
ATSUTextLayout textLayout;
ATSUStyle textStyle;
last_width_in_cell = 1;
ATSUCreateTextLayout(&textLayout);
ATSUSetTextPointerLocation(textLayout, tofree,
kATSUFromTextBeginning,
kATSUToTextEnd, utf16_len);
/*
ATSUSetRunStyle(textLayout, gFontStyle,
kATSUFromTextBeginning, kATSUToTextEnd); */
/* Compute the length in display cells. */
for (n = 0; n < len; n += MB_BYTE2LEN(s[n]))
{
width_in_cell = (*mb_ptr2cells)(s + n);
/* probably we are switching from single byte character
* to multibyte characters (which requires more than one
* cell to draw) */
if (width_in_cell != last_width_in_cell)
{
#ifdef MAC_ATSUI_DEBUG
fprintf(stderr, "\tn = %2d, (%d-%d), offset = %d, yet_to_draw = %d\n",
n, last_width_in_cell, width_in_cell, offset, yet_to_draw);
#endif
textStyle = last_width_in_cell > 1 ? gWideFontStyle
: gFontStyle;
ATSUSetRunStyle(textLayout, textStyle, offset, yet_to_draw);
offset += yet_to_draw;
yet_to_draw = 0;
last_width_in_cell = width_in_cell;
}
yet_to_draw++;
}
if (yet_to_draw)
{
#ifdef MAC_ATSUI_DEBUG
fprintf(stderr, "\tn = %2d, (%d-%d), offset = %d, yet_to_draw = %d\n",
n, last_width_in_cell, width_in_cell, offset, yet_to_draw);
#endif
/* finish the rest style */
textStyle = width_in_cell > 1 ? gWideFontStyle : gFontStyle;
ATSUSetRunStyle(textLayout, textStyle, offset, kATSUToTextEnd);
}
ATSUSetTransientFontMatching(textLayout, TRUE);
ATSUDrawText(textLayout,
kATSUFromTextBeginning, kATSUToTextEnd,
kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
ATSUDisposeTextLayout(textLayout);
}
else
#endif
{
ATSUTextLayout textLayout;
if (ATSUCreateTextLayoutWithTextPtr(tofree,
kATSUFromTextBeginning, kATSUToTextEnd,
utf16_len,
(gFontStyle ? 1 : 0), &utf16_len,
(gFontStyle ? &gFontStyle : NULL),
&textLayout) == noErr)
{
ATSUSetTransientFontMatching(textLayout, TRUE);
ATSUDrawText(textLayout,
kATSUFromTextBeginning, kATSUToTextEnd,
kATSUUseGrafPortPenLoc, kATSUUseGrafPortPenLoc);
ATSUDisposeTextLayout(textLayout);
}
}
/* drawing is done, now reset bold to normal */
if (gFontStyle && flags & DRAW_BOLD)
{
Boolean attValue = false;
ATSUAttributeTag attribTags[] = { kATSUQDBoldfaceTag };
ByteCount attribSizes[] = { sizeof(Boolean) };
ATSUAttributeValuePtr attribValues[] = { &attValue };
ATSUSetAttributes(gFontStyle, 1, attribTags, attribSizes,
attribValues);
}
}
if (flags & DRAW_UNDERC)
draw_undercurl(flags, row, col, len);
vim_free(tofree);
}
#endif
void
gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
{
#if defined(USE_ATSUI_DRAWING)
if (p_macatsui == 0 && p_macatsui_last != 0)
/* switch from macatsui to nomacatsui */
gui_mac_dispose_atsui_style();
else if (p_macatsui != 0 && p_macatsui_last == 0)
/* switch from nomacatsui to macatsui */
gui_mac_create_atsui_style();
if (p_macatsui)
draw_string_ATSUI(row, col, s, len, flags);
else
#endif
draw_string_QD(row, col, s, len, flags);
}
/*
* 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].key_sym != (KeySym)0; 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)
{
SysBeep(1); /* Should this be 0? (????) */
}
void
gui_mch_flash(int msec)
{
/* Do a visual beep by reversing the foreground and background colors */
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(&rc);
ui_delay((long)msec, TRUE); /* wait for some msec */
InvertRect(&rc);
}
/*
* 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(&rc);
}
/*
* Iconify the GUI window.
*/
void
gui_mch_iconify(void)
{
/* TODO: find out what could replace iconify
* -window shade?
* -hide application?
*/
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Bring the Vim window to the foreground.
*/
void
gui_mch_set_foreground(void)
{
/* TODO */
}
#endif
/*
* Draw a cursor without focus.
*/
void
gui_mch_draw_hollow_cursor(guicolor_T color)
{
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;
gui_mch_set_fg_color(color);
FrameRect(&rc);
}
/*
* Draw part of a cursor, only w pixels wide, and h pixels high.
*/
void
gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
{
Rect rc;
#ifdef FEAT_RIGHTLEFT
/* vertical line should be on the right of current point */
if (CURSOR_BAR_RIGHT)
rc.left = FILL_X(gui.col + 1) - w;
else
#endif
rc.left = FILL_X(gui.col);
rc.top = FILL_Y(gui.row) + gui.char_height - h;
rc.right = rc.left + w;
rc.bottom = rc.top + h;
gui_mch_set_fg_color(color);
FrameRect(&rc);
// PaintRect(&rc);
}
/*
* 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.
*/
void
gui_mch_update(void)
{
/* TODO: find what to do
* maybe call gui_mch_wait_for_chars (0)
* more like look at EventQueue then
* call heart of gui_mch_wait_for_chars;
*
* if (eventther)
* gui_mac_handle_event(&event);
*/
EventRecord theEvent;
if (EventAvail(everyEvent, &theEvent))
if (theEvent.what != nullEvent)
gui_mch_wait_for_chars(0);
}
/*
* Simple wrapper to neglect more easily the time
* spent inside WaitNextEvent while profiling.
*/
pascal
Boolean
WaitNextEventWrp(EventMask eventMask, EventRecord *theEvent, UInt32 sleep, RgnHandle mouseRgn)
{
if (((long) sleep) < -1)
sleep = 32767;
return WaitNextEvent(eventMask, theEvent, sleep, mouseRgn);
}
/*
* 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)
{
EventMask mask = (everyEvent);
EventRecord event;
long entryTick;
long currentTick;
long sleeppyTick;
/* If we are providing life feedback with the scrollbar,
* we don't want to try to wait for an event, or else
* there won't be any life feedback.
*/
if (dragged_sb != NULL)
return FAIL;
/* TODO: Check if FAIL is the proper return code */
entryTick = TickCount();
allow_scrollbar = TRUE;
do
{
/* if (dragRectControl == kCreateEmpty)
{
dragRgn = NULL;
dragRectControl = kNothing;
}
else*/ if (dragRectControl == kCreateRect)
{
dragRgn = cursorRgn;
RectRgn(dragRgn, &dragRect);
dragRectControl = kNothing;
}
/*
* Don't use gui_mch_update() because then we will spin-lock until a
* char arrives, instead we use WaitNextEventWrp() 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.
*/
/* TODO: reduce wtime accordingly??? */
if (wtime > -1)
sleeppyTick = 60 * wtime / 1000;
else
sleeppyTick = 32767;
if (WaitNextEventWrp(mask, &event, sleeppyTick, dragRgn))
{
gui_mac_handle_event(&event);
if (input_available())
{
allow_scrollbar = FALSE;
return OK;
}
}
currentTick = TickCount();
}
while ((wtime == -1) || ((currentTick - entryTick) < 60*wtime/1000));
allow_scrollbar = FALSE;
return FAIL;
}
/*
* Output routines.
*/
/* Flush any output to the screen */
void
gui_mch_flush(void)
{
/* TODO: Is anything needed here? */
}
/*
* 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 next column.
*/
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);
gui_mch_set_bg_color(gui.back_pixel);
EraseRect(&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;
gui_mch_set_bg_color(gui.back_pixel);
EraseRect(&rc);
/* gui_mch_set_fg_color(gui.norm_pixel);
FrameRect(&rc);
*/
}
/*
* 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;
/* changed without checking! */
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);
gui_mch_set_bg_color(gui.back_pixel);
ScrollRect(&rc, 0, -num_lines * gui.char_height, (RgnHandle) nil);
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);
gui_mch_set_bg_color(gui.back_pixel);
ScrollRect(&rc, 0, gui.char_height * num_lines, (RgnHandle) nil);
/* Update gui.cursor_row if the cursor scrolled or copied over */
if (gui.cursor_row >= gui.row
&& gui.cursor_col >= gui.scroll_region_left
&& gui.cursor_col <= gui.scroll_region_right)
{
if (gui.cursor_row <= gui.scroll_region_bot - num_lines)
gui.cursor_row += num_lines;
else if (gui.cursor_row <= gui.scroll_region_bot)
gui.cursor_is_valid = FALSE;
}
gui_clear_block(row, gui.scroll_region_left,
row + num_lines - 1, gui.scroll_region_right);
}
/*
* TODO: add a vim format to the clipboard which remember
* LINEWISE, CHARWISE, BLOCKWISE
*/
void
clip_mch_request_selection(VimClipboard *cbd)
{
Handle textOfClip;
int flavor = 0;
Size scrapSize;
ScrapFlavorFlags scrapFlags;
ScrapRef scrap = nil;
OSStatus error;
int type;
char *searchCR;
char_u *tempclip;
error = GetCurrentScrap(&scrap);
if (error != noErr)
return;
error = GetScrapFlavorFlags(scrap, VIMSCRAPFLAVOR, &scrapFlags);
if (error == noErr)
{
error = GetScrapFlavorSize(scrap, VIMSCRAPFLAVOR, &scrapSize);
if (error == noErr && scrapSize > 1)
flavor = 1;
}
if (flavor == 0)
{
error = GetScrapFlavorFlags(scrap, SCRAPTEXTFLAVOR, &scrapFlags);
if (error != noErr)
return;
error = GetScrapFlavorSize(scrap, SCRAPTEXTFLAVOR, &scrapSize);
if (error != noErr)
return;
}
ReserveMem(scrapSize);
/* In CARBON we don't need a Handle, a pointer is good */
textOfClip = NewHandle(scrapSize);
/* tempclip = lalloc(scrapSize+1, TRUE); */
HLock(textOfClip);
error = GetScrapFlavorData(scrap,
flavor ? VIMSCRAPFLAVOR : SCRAPTEXTFLAVOR,
&scrapSize, *textOfClip);
scrapSize -= flavor;
if (flavor)
type = **textOfClip;
else
type = MAUTO;
tempclip = lalloc(scrapSize + 1, TRUE);
mch_memmove(tempclip, *textOfClip + flavor, scrapSize);
tempclip[scrapSize] = 0;
#ifdef MACOS_CONVERT
{
/* Convert from utf-16 (clipboard) */
size_t encLen = 0;
char_u *to = mac_utf16_to_enc((UniChar *)tempclip, scrapSize, &encLen);
if (to != NULL)
{
scrapSize = encLen;
vim_free(tempclip);
tempclip = to;
}
}
#endif
searchCR = (char *)tempclip;
while (searchCR != NULL)
{
searchCR = strchr(searchCR, '\r');
if (searchCR != NULL)
*searchCR = '\n';
}
clip_yank_selection(type, tempclip, scrapSize, cbd);
vim_free(tempclip);
HUnlock(textOfClip);
DisposeHandle(textOfClip);
}
void
clip_mch_lose_selection(VimClipboard *cbd)
{
/*
* TODO: Really nothing to do?
*/
}
int
clip_mch_own_selection(VimClipboard *cbd)
{
return OK;
}
/*
* Send the current selection to the clipboard.
*/
void
clip_mch_set_selection(VimClipboard *cbd)
{
Handle textOfClip;
long scrapSize;
int type;
ScrapRef scrap;
char_u *str = NULL;
if (!cbd->owned)
return;
clip_get_selection(cbd);
/*
* Once we set the clipboard, lose ownership. If another application sets
* the clipboard, we don't want to think that we still own it.
*/
cbd->owned = FALSE;
type = clip_convert_selection(&str, (long_u *)&scrapSize, cbd);
#ifdef MACOS_CONVERT
size_t utf16_len = 0;
UniChar *to = mac_enc_to_utf16(str, scrapSize, &utf16_len);
if (to)
{
scrapSize = utf16_len;
vim_free(str);
str = (char_u *)to;
}
#endif
if (type >= 0)
{
ClearCurrentScrap();
textOfClip = NewHandle(scrapSize + 1);
HLock(textOfClip);
**textOfClip = type;
mch_memmove(*textOfClip + 1, str, scrapSize);
GetCurrentScrap(&scrap);
PutScrapFlavor(scrap, SCRAPTEXTFLAVOR, kScrapFlavorMaskNone,
scrapSize, *textOfClip + 1);
PutScrapFlavor(scrap, VIMSCRAPFLAVOR, kScrapFlavorMaskNone,
scrapSize + 1, *textOfClip);
HUnlock(textOfClip);
DisposeHandle(textOfClip);
}
vim_free(str);
}
void
gui_mch_set_text_area_pos(int x, int y, int w, int h)
{
Rect VimBound;
/* HideWindow(gui.VimWindow); */
GetWindowBounds(gui.VimWindow, kWindowGlobalPortRgn, &VimBound);
if (gui.which_scrollbars[SBAR_LEFT])
{
VimBound.left = -gui.scrollbar_width + 1;
}
else
{
VimBound.left = 0;
}
SetWindowBounds(gui.VimWindow, kWindowGlobalPortRgn, &VimBound);
ShowWindow(gui.VimWindow);
}
/*
* Menu stuff.
*/
void
gui_mch_enable_menu(int flag)
{
/*
* Menu is always active.
*/
}
void
gui_mch_set_menu_pos(int x, int y, int w, int h)
{
/*
* The menu is always at the top of the screen.
*/
}
/*
* Add a sub menu to the menu bar.
*/
void
gui_mch_add_menu(vimmenu_T *menu, int idx)
{
/*
* TODO: Try to use only menu_id instead of both menu_id and menu_handle.
* TODO: use menu->mnemonic and menu->actext
* TODO: Try to reuse menu id
* Carbon Help suggest to use only id between 1 and 235
*/
static long next_avail_id = 128;
long menu_after_me = 0; /* Default to the end */
#if defined(FEAT_MBYTE)
CFStringRef name;
#else
char_u *name;
#endif
short index;
vimmenu_T *parent = menu->parent;
vimmenu_T *brother = menu->next;
/* Cannot add a menu if ... */
if ((parent != NULL && parent->submenu_id == 0))
return;
/* menu ID greater than 1024 are reserved for ??? */
if (next_avail_id == 1024)
return;
/* My brother could be the PopUp, find my real brother */
while ((brother != NULL) && (!menu_is_menubar(brother->name)))
brother = brother->next;
/* Find where to insert the menu (for MenuBar) */
if ((parent == NULL) && (brother != NULL))
menu_after_me = brother->submenu_id;
/* If the menu is not part of the menubar (and its submenus), add it 'nowhere' */
if (!menu_is_menubar(menu->name))
menu_after_me = hierMenu;
/* Convert the name */
#ifdef MACOS_CONVERT
name = menu_title_removing_mnemonic(menu);
#else
name = C2Pascal_save(menu->dname);
#endif
if (name == NULL)
return;
/* Create the menu unless it's the help menu */
{
/* Carbon suggest use of
* OSStatus CreateNewMenu(MenuID, MenuAttributes, MenuRef *);
* OSStatus SetMenuTitle(MenuRef, ConstStr255Param title);
*/
menu->submenu_id = next_avail_id;
#if defined(FEAT_MBYTE)
if (CreateNewMenu(menu->submenu_id, 0, (MenuRef *)&menu->submenu_handle) == noErr)
SetMenuTitleWithCFString((MenuRef)menu->submenu_handle, name);
#else
menu->submenu_handle = NewMenu(menu->submenu_id, name);
#endif
next_avail_id++;
}
if (parent == NULL)
{
/* Adding a menu to the menubar, or in the no mans land (for PopUp) */
/* TODO: Verify if we could only Insert Menu if really part of the
* menubar The Inserted menu are scanned or the Command-key combos
*/
/* Insert the menu */
InsertMenu(menu->submenu_handle, menu_after_me); /* insert before */
#if 1
/* Vim should normally update it. TODO: verify */
DrawMenuBar();
#endif
}
else
{
/* Adding as a submenu */
index = gui_mac_get_menu_item_index(menu);
/* Call InsertMenuItem followed by SetMenuItemText
* to avoid special character recognition by InsertMenuItem
*/
InsertMenuItem(parent->submenu_handle, "\p ", idx); /* afterItem */
#if defined(FEAT_MBYTE)
SetMenuItemTextWithCFString(parent->submenu_handle, idx+1, name);
#else
SetMenuItemText(parent->submenu_handle, idx+1, name);
#endif
SetItemCmd(parent->submenu_handle, idx+1, 0x1B);
SetItemMark(parent->submenu_handle, idx+1, menu->submenu_id);
InsertMenu(menu->submenu_handle, hierMenu);
}
#if defined(FEAT_MBYTE)
CFRelease(name);
#else
vim_free(name);
#endif
#if 0
/* Done by Vim later on */
DrawMenuBar();
#endif
}
/*
* Add a menu item to a menu
*/
void
gui_mch_add_menu_item(vimmenu_T *menu, int idx)
{
#if defined(FEAT_MBYTE)
CFStringRef name;
#else
char_u *name;
#endif
vimmenu_T *parent = menu->parent;
int menu_inserted;
/* Cannot add item, if the menu have not been created */
if (parent->submenu_id == 0)
return;
/* Could call SetMenuRefCon [CARBON] to associate with the Menu,
for older OS call GetMenuItemData (menu, item, isCommandID?, data) */
/* Convert the name */
#ifdef MACOS_CONVERT
name = menu_title_removing_mnemonic(menu);
#else
name = C2Pascal_save(menu->dname);
#endif
/* Where are just a menu item, so no handle, no id */
menu->submenu_id = 0;
menu->submenu_handle = NULL;
menu_inserted = 0;
if (menu->actext)
{
/* If the accelerator text for the menu item looks like it describes
* a command key (e.g., "<D-S-t>" or "<C-7>"), display it as the
* item's command equivalent.
*/
int key = 0;
int modifiers = 0;
char_u *p_actext;
p_actext = menu->actext;
key = find_special_key(&p_actext, &modifiers, FALSE, FALSE);
if (*p_actext != 0)
key = 0; /* error: trailing text */
/* find_special_key() returns a keycode with as many of the
* specified modifiers as appropriate already applied (e.g., for
* "<D-C-x>" it returns Ctrl-X as the keycode and MOD_MASK_CMD
* as the only modifier). Since we want to display all of the
* modifiers, we need to convert the keycode back to a printable
* character plus modifiers.
* TODO: Write an alternative find_special_key() that doesn't
* apply modifiers.
*/
if (key > 0 && key < 32)
{
/* Convert a control key to an uppercase letter. Note that
* by this point it is no longer possible to distinguish
* between, e.g., Ctrl-S and Ctrl-Shift-S.
*/
modifiers |= MOD_MASK_CTRL;
key += '@';
}
/* If the keycode is an uppercase letter, set the Shift modifier.
* If it is a lowercase letter, don't set the modifier, but convert
* the letter to uppercase for display in the menu.
*/
else if (key >= 'A' && key <= 'Z')
modifiers |= MOD_MASK_SHIFT;
else if (key >= 'a' && key <= 'z')
key += 'A' - 'a';
/* Note: keycodes below 0x22 are reserved by Apple. */
if (key >= 0x22 && vim_isprintc_strict(key))
{
int valid = 1;
char_u mac_mods = kMenuNoModifiers;
/* Convert Vim modifier codes to Menu Manager equivalents. */
if (modifiers & MOD_MASK_SHIFT)
mac_mods |= kMenuShiftModifier;
if (modifiers & MOD_MASK_CTRL)
mac_mods |= kMenuControlModifier;
if (!(modifiers & MOD_MASK_CMD))
mac_mods |= kMenuNoCommandModifier;
if (modifiers & MOD_MASK_ALT || modifiers & MOD_MASK_MULTI_CLICK)
valid = 0; /* TODO: will Alt someday map to Option? */
if (valid)
{
char_u item_txt[10];
/* Insert the menu item after idx, with its command key. */
item_txt[0] = 3; item_txt[1] = ' '; item_txt[2] = '/';
item_txt[3] = key;
InsertMenuItem(parent->submenu_handle, item_txt, idx);
/* Set the modifier keys. */
SetMenuItemModifiers(parent->submenu_handle, idx+1, mac_mods);
menu_inserted = 1;
}
}
}
/* Call InsertMenuItem followed by SetMenuItemText
* to avoid special character recognition by InsertMenuItem
*/
if (!menu_inserted)
InsertMenuItem(parent->submenu_handle, "\p ", idx); /* afterItem */
/* Set the menu item name. */
#if defined(FEAT_MBYTE)
SetMenuItemTextWithCFString(parent->submenu_handle, idx+1, name);
#else
SetMenuItemText(parent->submenu_handle, idx+1, name);
#endif
#if 0
/* Called by Vim */
DrawMenuBar();
#endif
#if defined(FEAT_MBYTE)
CFRelease(name);
#else
/* TODO: Can name be freed? */
vim_free(name);
#endif
}
void
gui_mch_toggle_tearoffs(int enable)
{
/* no tearoff menus */
}
/*
* Destroy the machine specific menu widget.
*/
void
gui_mch_destroy_menu(vimmenu_T *menu)
{
short index = gui_mac_get_menu_item_index(menu);
if (index > 0)
{
if (menu->parent)
{
{
/* For now just don't delete help menu items. (Huh? Dany) */
DeleteMenuItem(menu->parent->submenu_handle, index);
/* Delete the Menu if it was a hierarchical Menu */
if (menu->submenu_id != 0)
{
DeleteMenu(menu->submenu_id);
DisposeMenu(menu->submenu_handle);
}
}
}
#ifdef DEBUG_MAC_MENU
else
{
printf("gmdm 2\n");
}
#endif
}
else
{
{
DeleteMenu(menu->submenu_id);
DisposeMenu(menu->submenu_handle);
}
}
/* Shouldn't this be already done by Vim. TODO: Check */
DrawMenuBar();
}
/*
* Make a menu either grey or not grey.
*/
void
gui_mch_menu_grey(vimmenu_T *menu, int grey)
{
/* TODO: Check if menu really exists */
short index = gui_mac_get_menu_item_index(menu);
/*
index = menu->index;
*/
if (grey)
{
if (menu->children)
DisableMenuItem(menu->submenu_handle, index);
if (menu->parent)
if (menu->parent->submenu_handle)
DisableMenuItem(menu->parent->submenu_handle, index);
}
else
{
if (menu->children)
EnableMenuItem(menu->submenu_handle, index);
if (menu->parent)
if (menu->parent->submenu_handle)
EnableMenuItem(menu->parent->submenu_handle, index);
}
}
/*
* Make menu item hidden or not hidden
*/
void
gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
{
/* There's no hidden mode on MacOS */
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();
}
/*
* Scrollbar stuff.
*/
void
gui_mch_enable_scrollbar(
scrollbar_T *sb,
int flag)
{
if (flag)
ShowControl(sb->id);
else
HideControl(sb->id);
#ifdef DEBUG_MAC_SB
printf("enb_sb (%x) %x\n",sb->id, flag);
#endif
}
void
gui_mch_set_scrollbar_thumb(
scrollbar_T *sb,
long val,
long size,
long max)
{
SetControl32BitMaximum (sb->id, max);
SetControl32BitMinimum (sb->id, 0);
SetControl32BitValue (sb->id, val);
SetControlViewSize (sb->id, size);
#ifdef DEBUG_MAC_SB
printf("thumb_sb (%x) %x, %x,%x\n",sb->id, val, size, max);
#endif
}
void
gui_mch_set_scrollbar_pos(
scrollbar_T *sb,
int x,
int y,
int w,
int h)
{
gui_mch_set_bg_color(gui.back_pixel);
/* if (gui.which_scrollbars[SBAR_LEFT])
{
MoveControl(sb->id, x-16, y);
SizeControl(sb->id, w + 1, h);
}
else
{
MoveControl(sb->id, x, y);
SizeControl(sb->id, w + 1, h);
}*/
if (sb == &gui.bottom_sbar)
h += 1;
else
w += 1;
if (gui.which_scrollbars[SBAR_LEFT])
x -= 15;
MoveControl(sb->id, x, y);
SizeControl(sb->id, w, h);
#ifdef DEBUG_MAC_SB
printf("size_sb (%x) %x, %x, %x, %x\n",sb->id, x, y, w, h);
#endif
}
void
gui_mch_create_scrollbar(
scrollbar_T *sb,
int orient) /* SBAR_VERT or SBAR_HORIZ */
{
Rect bounds;
bounds.top = -16;
bounds.bottom = -10;
bounds.right = -10;
bounds.left = -16;
sb->id = NewControl(gui.VimWindow,
&bounds,
"\pScrollBar",
TRUE,
0, /* current*/
0, /* top */
0, /* bottom */
kControlScrollBarLiveProc,
(long) sb->ident);
#ifdef DEBUG_MAC_SB
printf("create_sb (%x) %x\n",sb->id, orient);
#endif
}
void
gui_mch_destroy_scrollbar(scrollbar_T *sb)
{
gui_mch_set_bg_color(gui.back_pixel);
DisposeControl(sb->id);
#ifdef DEBUG_MAC_SB
printf("dest_sb (%x) \n",sb->id);
#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
*/
void
gui_mch_set_blinking(long wait, long on, long off)
{
/* TODO: TODO: TODO: TODO: */
/* blink_waittime = wait;
blink_ontime = on;
blink_offtime = off;*/
}
/*
* Stop the cursor blinking. Show the cursor if it wasn't shown.
*/
void
gui_mch_stop_blink(void)
{
gui_update_cursor(TRUE, FALSE);
/* TODO: TODO: TODO: TODO: */
/* gui_w32_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_update_cursor(TRUE, FALSE);
/* TODO: TODO: TODO: TODO: */
/* gui_w32_rm_blink_timer(); */
/* Only switch blinking on if none of the times is zero */
/* if (blink_waittime && blink_ontime && blink_offtime)
{
blink_timer = SetTimer(NULL, 0, (UINT)blink_waittime,
(TIMERPROC)_OnBlinkTimer);
blink_state = BLINK_ON;
gui_update_cursor(TRUE, FALSE);
}*/
}
/*
* Return the RGB value of a pixel as long.
*/
long_u
gui_mch_get_rgb(guicolor_T pixel)
{
return (Red(pixel) << 16) + (Green(pixel) << 8) + Blue(pixel);
}
#ifdef FEAT_BROWSE
/*
* 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.
* Has a format like this:
* "C Files (*.c)\0*.c\0"
* "All Files\0*.*\0\0"
* If these two strings were concatenated, then a choice of two file
* filters will be selectable to the user. Then only matching files will
* be shown in the browser. If NULL, the default allows all files.
*
* *NOTE* - the filter string must be terminated with TWO nulls.
*/
char_u *
gui_mch_browse(
int saving,
char_u *title,
char_u *dflt,
char_u *ext,
char_u *initdir,
char_u *filter)
{
/* TODO: Add Ammon's safety checl (Dany) */
NavReplyRecord reply;
char_u *fname = NULL;
char_u **fnames = NULL;
long numFiles;
NavDialogOptions navOptions;
OSErr error;
/* Get Navigation Service Defaults value */
NavGetDefaultDialogOptions(&navOptions);
/* TODO: If we get a :browse args, set the Multiple bit. */
navOptions.dialogOptionFlags = kNavAllowInvisibleFiles
| kNavDontAutoTranslate
| kNavDontAddTranslateItems
/* | kNavAllowMultipleFiles */
| kNavAllowStationery;
(void) C2PascalString(title, &navOptions.message);
(void) C2PascalString(dflt, &navOptions.savedFileName);
/* Could set clientName?
* windowTitle? (there's no title bar?)
*/
if (saving)
{
/* Change first parm AEDesc (typeFSS) *defaultLocation to match dflt */
NavPutFile(NULL, &reply, &navOptions, NULL, 'TEXT', 'VIM!', NULL);
if (!reply.validRecord)
return NULL;
}
else
{
/* Change first parm AEDesc (typeFSS) *defaultLocation to match dflt */
NavGetFile(NULL, &reply, &navOptions, NULL, NULL, NULL, NULL, NULL);
if (!reply.validRecord)
return NULL;
}
fnames = new_fnames_from_AEDesc(&reply.selection, &numFiles, &error);
NavDisposeReply(&reply);
if (fnames)
{
fname = fnames[0];
vim_free(fnames);
}
/* TODO: Shorten the file name if possible */
return fname;
}
#endif /* FEAT_BROWSE */
#ifdef FEAT_GUI_DIALOG
/*
* Stuff for dialogues
*/
/*
* Create a dialogue dynamically from the parameter strings.
* type = type of dialogue (question, alert, etc.)
* title = dialogue title. may be NULL for default title.
* message = text to display. Dialogue 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.
*/
typedef struct
{
short idx;
short width; /* Size of the text in pixel */
Rect box;
} vgmDlgItm; /* Vim Gui_Mac.c Dialog Item */
#define MoveRectTo(r,x,y) OffsetRect(r,x-r->left,y-r->top)
static void
macMoveDialogItem(
DialogRef theDialog,
short itemNumber,
short X,
short Y,
Rect *inBox)
{
#if 0 /* USE_CARBONIZED */
/* Untested */
MoveDialogItem(theDialog, itemNumber, X, Y);
if (inBox != nil)
GetDialogItem(theDialog, itemNumber, &itemType, &itemHandle, inBox);
#else
short itemType;
Handle itemHandle;
Rect localBox;
Rect *itemBox = &localBox;
if (inBox != nil)
itemBox = inBox;
GetDialogItem(theDialog, itemNumber, &itemType, &itemHandle, itemBox);
OffsetRect(itemBox, -itemBox->left, -itemBox->top);
OffsetRect(itemBox, X, Y);
/* To move a control (like a button) we need to call both
* MoveControl and SetDialogItem. FAQ 6-18 */
if (1) /*(itemType & kControlDialogItem) */
MoveControl((ControlRef) itemHandle, X, Y);
SetDialogItem(theDialog, itemNumber, itemType, itemHandle, itemBox);
#endif
}
static void
macSizeDialogItem(
DialogRef theDialog,
short itemNumber,
short width,
short height)
{
short itemType;
Handle itemHandle;
Rect itemBox;
GetDialogItem(theDialog, itemNumber, &itemType, &itemHandle, &itemBox);
/* When width or height is zero do not change it */
if (width == 0)
width = itemBox.right - itemBox.left;
if (height == 0)
height = itemBox.bottom - itemBox.top;
#if 0 /* USE_CARBONIZED */
SizeDialogItem(theDialog, itemNumber, width, height); /* Untested */
#else
/* Resize the bounding box */
itemBox.right = itemBox.left + width;
itemBox.bottom = itemBox.top + height;
/* To resize a control (like a button) we need to call both
* SizeControl and SetDialogItem. (deducted from FAQ 6-18) */
if (itemType & kControlDialogItem)
SizeControl((ControlRef) itemHandle, width, height);
/* Configure back the item */
SetDialogItem(theDialog, itemNumber, itemType, itemHandle, &itemBox);
#endif
}
static void
macSetDialogItemText(
DialogRef theDialog,
short itemNumber,
Str255 itemName)
{
short itemType;
Handle itemHandle;
Rect itemBox;
GetDialogItem(theDialog, itemNumber, &itemType, &itemHandle, &itemBox);
if (itemType & kControlDialogItem)
SetControlTitle((ControlRef) itemHandle, itemName);
else
SetDialogItemText(itemHandle, itemName);
}
/* ModalDialog() handler for message dialogs that have hotkey accelerators.
* Expects a mapping of hotkey char to control index in gDialogHotKeys;
* setting gDialogHotKeys to NULL disables any hotkey handling.
*/
static pascal Boolean
DialogHotkeyFilterProc (
DialogRef theDialog,
EventRecord *event,
DialogItemIndex *itemHit)
{
char_u keyHit;
if (event->what == keyDown || event->what == autoKey)
{
keyHit = (event->message & charCodeMask);
if (gDialogHotKeys && gDialogHotKeys[keyHit])
{
#ifdef DEBUG_MAC_DIALOG_HOTKEYS
printf("user pressed hotkey '%c' --> item %d\n", keyHit, gDialogHotKeys[keyHit]);
#endif
*itemHit = gDialogHotKeys[keyHit];
/* When handing off to StdFilterProc, pretend that the user
* clicked the control manually. Note that this is also supposed
* to cause the button to hilite briefly (to give some user
* feedback), but this seems not to actually work (or it's too
* fast to be seen).
*/
event->what = kEventControlSimulateHit;
return true; /* we took care of it */
}
/* Defer to the OS's standard behavior for this event.
* This ensures that Enter will still activate the default button. */
return StdFilterProc(theDialog, event, itemHit);
}
return false; /* Let ModalDialog deal with it */
}
/* TODO: There have been some crashes with dialogs, check your inbox
* (Jussi)
*/
int
gui_mch_dialog(
int type,
char_u *title,
char_u *message,
char_u *buttons,
int dfltbutton,
char_u *textfield,
int ex_cmd)
{
Handle buttonDITL;
Handle iconDITL;
Handle inputDITL;
Handle messageDITL;
Handle itemHandle;
Handle iconHandle;
DialogPtr theDialog;
char_u len;
char_u PascalTitle[256]; /* place holder for the title */
char_u name[256];
GrafPtr oldPort;
short itemHit;
char_u *buttonChar;
short hotKeys[256]; /* map of hotkey -> control ID */
char_u aHotKey;
Rect box;
short button;
short lastButton;
short itemType;
short useIcon;
short width;
short totalButtonWidth = 0; /* the width of all buttons together
including spacing */
short widestButton = 0;
short dfltButtonEdge = 20; /* gut feeling */
short dfltElementSpacing = 13; /* from IM:V.2-29 */
short dfltIconSideSpace = 23; /* from IM:V.2-29 */
short maximumWidth = 400; /* gut feeling */
short maxButtonWidth = 175; /* gut feeling */
short vertical;
short dialogHeight;
short messageLines = 3;
FontInfo textFontInfo;
vgmDlgItm iconItm;
vgmDlgItm messageItm;
vgmDlgItm inputItm;
vgmDlgItm buttonItm;
WindowRef theWindow;
ModalFilterUPP dialogUPP;
/* Check 'v' flag in 'guioptions': vertical button placement. */
vertical = (vim_strchr(p_go, GO_VERTICAL) != NULL);
/* Create a new Dialog Box from template. */
theDialog = GetNewDialog(129, nil, (WindowRef) -1);
/* Get the WindowRef */
theWindow = GetDialogWindow(theDialog);
/* Hide the window.
* 1. to avoid seeing slow drawing
* 2. to prevent a problem seen while moving dialog item
* within a visible window. (non-Carbon MacOS 9)
* Could be avoided by changing the resource.
*/
HideWindow(theWindow);
/* Change the graphical port to the dialog,
* so we can measure the text with the proper font */
GetPort(&oldPort);
SetPortDialogPort(theDialog);
/* Get the info about the default text,
* used to calculate the height of the message
* and of the text field */
GetFontInfo(&textFontInfo);
/* Set the dialog title */
if (title != NULL)
{
(void) C2PascalString(title, &PascalTitle);
SetWTitle(theWindow, PascalTitle);
}
/* Creates the buttons and add them to the Dialog Box. */
buttonDITL = GetResource('DITL', 130);
buttonChar = buttons;
button = 0;
/* initialize the hotkey mapping */
vim_memset(hotKeys, 0, sizeof(hotKeys));
for (;*buttonChar != 0;)
{
/* Get the name of the button */
button++;
len = 0;
for (;((*buttonChar != DLG_BUTTON_SEP) && (*buttonChar != 0) && (len < 255)); buttonChar++)
{
if (*buttonChar != DLG_HOTKEY_CHAR)
name[++len] = *buttonChar;
else
{
aHotKey = (char_u)*(buttonChar+1);
if (aHotKey >= 'A' && aHotKey <= 'Z')
aHotKey = (char_u)((int)aHotKey + (int)'a' - (int)'A');
hotKeys[aHotKey] = button;
#ifdef DEBUG_MAC_DIALOG_HOTKEYS
printf("### hotKey for button %d is '%c'\n", button, aHotKey);
#endif
}
}
if (*buttonChar != 0)
buttonChar++;
name[0] = len;
/* Add the button */
AppendDITL(theDialog, buttonDITL, overlayDITL); /* appendDITLRight); */
/* Change the button's name */
macSetDialogItemText(theDialog, button, name);
/* Resize the button to fit its name */
width = StringWidth(name) + 2 * dfltButtonEdge;
/* Limite the size of any button to an acceptable value. */
/* TODO: Should be based on the message width */
if (width > maxButtonWidth)
width = maxButtonWidth;
macSizeDialogItem(theDialog, button, width, 0);
totalButtonWidth += width;
if (width > widestButton)
widestButton = width;
}
ReleaseResource(buttonDITL);
lastButton = button;
/* Add the icon to the Dialog Box. */
iconItm.idx = lastButton + 1;
iconDITL = GetResource('DITL', 131);
switch (type)
{
case VIM_GENERIC:
case VIM_INFO:
case VIM_QUESTION: useIcon = kNoteIcon; break;
case VIM_WARNING: useIcon = kCautionIcon; break;
case VIM_ERROR: useIcon = kStopIcon; break;
default: useIcon = kStopIcon;
}
AppendDITL(theDialog, iconDITL, overlayDITL);
ReleaseResource(iconDITL);
GetDialogItem(theDialog, iconItm.idx, &itemType, &itemHandle, &box);
/* TODO: Should the item be freed? */
iconHandle = GetIcon(useIcon);
SetDialogItem(theDialog, iconItm.idx, itemType, iconHandle, &box);
/* Add the message to the Dialog box. */
messageItm.idx = lastButton + 2;
messageDITL = GetResource('DITL', 132);
AppendDITL(theDialog, messageDITL, overlayDITL);
ReleaseResource(messageDITL);
GetDialogItem(theDialog, messageItm.idx, &itemType, &itemHandle, &box);
(void) C2PascalString(message, &name);
SetDialogItemText(itemHandle, name);
messageItm.width = StringWidth(name);
/* Add the input box if needed */
if (textfield != NULL)
{
/* Cheat for now reuse the message and convert to text edit */
inputItm.idx = lastButton + 3;
inputDITL = GetResource('DITL', 132);
AppendDITL(theDialog, inputDITL, overlayDITL);
ReleaseResource(inputDITL);
GetDialogItem(theDialog, inputItm.idx, &itemType, &itemHandle, &box);
/* SetDialogItem(theDialog, inputItm.idx, kEditTextDialogItem, itemHandle, &box);*/
(void) C2PascalString(textfield, &name);
SetDialogItemText(itemHandle, name);
inputItm.width = StringWidth(name);
/* Hotkeys don't make sense if there's a text field */
gDialogHotKeys = NULL;
}
else
/* Install hotkey table */
gDialogHotKeys = (short *)&hotKeys;
/* Set the <ENTER> and <ESC> button. */
SetDialogDefaultItem(theDialog, dfltbutton);
SetDialogCancelItem(theDialog, 0);
/* Reposition element */
/* Check if we need to force vertical */
if (totalButtonWidth > maximumWidth)
vertical = TRUE;
/* Place icon */
macMoveDialogItem(theDialog, iconItm.idx, dfltIconSideSpace, dfltElementSpacing, &box);
iconItm.box.right = box.right;
iconItm.box.bottom = box.bottom;
/* Place Message */
messageItm.box.left = iconItm.box.right + dfltIconSideSpace;
macSizeDialogItem(theDialog, messageItm.idx, 0, messageLines * (textFontInfo.ascent + textFontInfo.descent));
macMoveDialogItem(theDialog, messageItm.idx, messageItm.box.left, dfltElementSpacing, &messageItm.box);
/* Place Input */
if (textfield != NULL)
{
inputItm.box.left = messageItm.box.left;
inputItm.box.top = messageItm.box.bottom + dfltElementSpacing;
macSizeDialogItem(theDialog, inputItm.idx, 0, textFontInfo.ascent + textFontInfo.descent);
macMoveDialogItem(theDialog, inputItm.idx, inputItm.box.left, inputItm.box.top, &inputItm.box);
/* Convert the static text into a text edit.
* For some reason this change need to be done last (Dany) */
GetDialogItem(theDialog, inputItm.idx, &itemType, &itemHandle, &inputItm.box);
SetDialogItem(theDialog, inputItm.idx, kEditTextDialogItem, itemHandle, &inputItm.box);
SelectDialogItemText(theDialog, inputItm.idx, 0, 32767);
}
/* Place Button */
if (textfield != NULL)
{
buttonItm.box.left = inputItm.box.left;
buttonItm.box.top = inputItm.box.bottom + dfltElementSpacing;
}
else
{
buttonItm.box.left = messageItm.box.left;
buttonItm.box.top = messageItm.box.bottom + dfltElementSpacing;
}
for (button=1; button <= lastButton; button++)
{
macMoveDialogItem(theDialog, button, buttonItm.box.left, buttonItm.box.top, &box);
/* With vertical, it's better to have all buttons the same length */
if (vertical)
{
macSizeDialogItem(theDialog, button, widestButton, 0);
GetDialogItem(theDialog, button, &itemType, &itemHandle, &box);
}
/* Calculate position of next button */
if (vertical)
buttonItm.box.top = box.bottom + dfltElementSpacing;
else
buttonItm.box.left = box.right + dfltElementSpacing;
}
/* Resize the dialog box */
dialogHeight = box.bottom + dfltElementSpacing;
SizeWindow(theWindow, maximumWidth, dialogHeight, TRUE);
/* Magic resize */
AutoSizeDialog(theDialog);
/* Need a horizontal resize anyway so not that useful */
/* Display it */
ShowWindow(theWindow);
/* BringToFront(theWindow); */
SelectWindow(theWindow);
/* DrawDialog(theDialog); */
#if 0
GetPort(&oldPort);
SetPortDialogPort(theDialog);
#endif
#ifdef USE_CARBONKEYHANDLER
/* Avoid that we use key events for the main window. */
dialog_busy = TRUE;
#endif
/* Prepare the shortcut-handling filterProc for handing to the dialog */
dialogUPP = NewModalFilterUPP(DialogHotkeyFilterProc);
/* Hang until one of the button is hit */
do
{
ModalDialog(dialogUPP, &itemHit);
} while ((itemHit < 1) || (itemHit > lastButton));
#ifdef USE_CARBONKEYHANDLER
dialog_busy = FALSE;
#endif
/* Copy back the text entered by the user into the param */
if (textfield != NULL)
{
GetDialogItem(theDialog, inputItm.idx, &itemType, &itemHandle, &box);
GetDialogItemText(itemHandle, (char_u *) &name);
#if IOSIZE < 256
/* Truncate the name to IOSIZE if needed */
if (name[0] > IOSIZE)
name[0] = IOSIZE - 1;
#endif
vim_strncpy(textfield, &name[1], name[0]);
}
/* Restore the original graphical port */
SetPort(oldPort);
/* Free the modal filterProc */
DisposeRoutineDescriptor(dialogUPP);
/* Get ride of th edialog (free memory) */
DisposeDialog(theDialog);
return itemHit;
/*
* Useful thing which could be used
* SetDialogTimeout(): Auto click a button after timeout
* SetDialogTracksCursor() : Get the I-beam cursor over input box
* MoveDialogItem(): Probably better than SetDialogItem
* SizeDialogItem(): (but is it Carbon Only?)
* AutoSizeDialog(): Magic resize of dialog based on text length
*/
}
#endif /* FEAT_DIALOG_GUI */
/*
* Display the saved error message(s).
*/
#ifdef USE_MCH_ERRMSG
void
display_errors(void)
{
char *p;
char_u pError[256];
if (error_ga.ga_data == NULL)
return;
/* avoid putting up a message box with blanks only */
for (p = (char *)error_ga.ga_data; *p; ++p)
if (!isspace(*p))
{
if (STRLEN(p) > 255)
pError[0] = 255;
else
pError[0] = STRLEN(p);
STRNCPY(&pError[1], p, pError[0]);
ParamText(pError, nil, nil, nil);
Alert(128, nil);
break;
/* TODO: handled message longer than 256 chars
* use auto-sizeable alert
* or dialog with scrollbars (TextEdit zone)
*/
}
ga_clear(&error_ga);
}
#endif
/*
* Get current mouse coordinates in text window.
*/
void
gui_mch_getmouse(int *x, int *y)
{
Point where;
GetMouse(&where);
*x = where.h;
*y = where.v;
}
void
gui_mch_setmouse(int x, int y)
{
/* TODO */
#if 0
/* From FAQ 3-11 */
CursorDevicePtr myMouse;
Point where;
if ( NGetTrapAddress(_CursorDeviceDispatch, ToolTrap)
!= NGetTrapAddress(_Unimplemented, ToolTrap))
{
/* New way */
/*
* Get first devoice with one button.
* This will probably be the standad mouse
* startat head of cursor dev list
*
*/
myMouse = nil;
do
{
/* Get the next cursor device */
CursorDeviceNextDevice(&myMouse);
}
while ((myMouse != nil) && (myMouse->cntButtons != 1));
CursorDeviceMoveTo(myMouse, x, y);
}
else
{
/* Old way */
where.h = x;
where.v = y;
*(Point *)RawMouse = where;
*(Point *)MTemp = where;
*(Ptr) CrsrNew = 0xFFFF;
}
#endif
}
void
gui_mch_show_popupmenu(vimmenu_T *menu)
{
/*
* Clone PopUp to use menu
* Create a object descriptor for the current selection
* Call the procedure
*/
MenuHandle CntxMenu;
Point where;
OSStatus status;
UInt32 CntxType;
SInt16 CntxMenuID;
UInt16 CntxMenuItem;
Str255 HelpName = "";
GrafPtr savePort;
/* Save Current Port: On MacOS X we seem to lose the port */
GetPort(&savePort); /*OSX*/
GetMouse(&where);
LocalToGlobal(&where); /*OSX*/
CntxMenu = menu->submenu_handle;
/* TODO: Get the text selection from Vim */
/* Call to Handle Popup */
status = ContextualMenuSelect(CntxMenu, where, false, kCMHelpItemRemoveHelp,
HelpName, NULL, &CntxType, &CntxMenuID, &CntxMenuItem);
if (status == noErr)
{
if (CntxType == kCMMenuItemSelected)
{
/* Handle the menu CntxMenuID, CntxMenuItem */
/* The submenu can be handle directly by gui_mac_handle_menu */
/* But what about the current menu, is the menu changed by
* ContextualMenuSelect */
gui_mac_handle_menu((CntxMenuID << 16) + CntxMenuItem);
}
else if (CntxMenuID == kCMShowHelpSelected)
{
/* Should come up with the help */
}
}
/* Restore original Port */
SetPort(savePort); /*OSX*/
}
#if defined(FEAT_CW_EDITOR) || defined(PROTO)
/* TODO: Is it need for MACOS_X? (Dany) */
void
mch_post_buffer_write(buf_T *buf)
{
GetFSSpecFromPath(buf->b_ffname, &buf->b_FSSpec);
Send_KAHL_MOD_AE(buf);
}
#endif
#ifdef FEAT_TITLE
/*
* Set the window title and icon.
* (The icon is not taken care of).
*/
void
gui_mch_settitle(char_u *title, char_u *icon)
{
/* TODO: Get vim to make sure maxlen (from p_titlelen) is smaller
* that 256. Even better get it to fit nicely in the titlebar.
*/
#ifdef MACOS_CONVERT
CFStringRef windowTitle;
size_t windowTitleLen;
#else
char_u *pascalTitle;
#endif
if (title == NULL) /* nothing to do */
return;
#ifdef MACOS_CONVERT
windowTitleLen = STRLEN(title);
windowTitle = (CFStringRef)mac_enc_to_cfstring(title, windowTitleLen);
if (windowTitle)
{
SetWindowTitleWithCFString(gui.VimWindow, windowTitle);
CFRelease(windowTitle);
}
#else
pascalTitle = C2Pascal_save(title);
if (pascalTitle != NULL)
{
SetWTitle(gui.VimWindow, pascalTitle);
vim_free(pascalTitle);
}
#endif
}
#endif
/*
* Transferred from os_mac.c for MacOS X using os_unix.c prep work
*/
int
C2PascalString(char_u *CString, Str255 *PascalString)
{
char_u *PascalPtr = (char_u *) PascalString;
int len;
int i;
PascalPtr[0] = 0;
if (CString == NULL)
return 0;
len = STRLEN(CString);
if (len > 255)
len = 255;
for (i = 0; i < len; i++)
PascalPtr[i+1] = CString[i];
PascalPtr[0] = len;
return 0;
}
int
GetFSSpecFromPath(char_u *file, FSSpec *fileFSSpec)
{
/* From FAQ 8-12 */
Str255 filePascal;
CInfoPBRec myCPB;
OSErr err;
(void) C2PascalString(file, &filePascal);
myCPB.dirInfo.ioNamePtr = filePascal;
myCPB.dirInfo.ioVRefNum = 0;
myCPB.dirInfo.ioFDirIndex = 0;
myCPB.dirInfo.ioDrDirID = 0;
err= PBGetCatInfo(&myCPB, false);
/* vRefNum, dirID, name */
FSMakeFSSpec(0, 0, filePascal, fileFSSpec);
/* TODO: Use an error code mechanism */
return 0;
}
/*
* Convert a FSSpec to a fuill path
*/
char_u *FullPathFromFSSpec_save(FSSpec file)
{
/*
* TODO: Add protection for 256 char max.
*/
CInfoPBRec theCPB;
char_u fname[256];
char_u *filenamePtr = fname;
OSErr error;
int folder = 1;
#ifdef USE_UNIXFILENAME
SInt16 dfltVol_vRefNum;
SInt32 dfltVol_dirID;
FSRef refFile;
OSStatus status;
UInt32 pathSize = 256;
char_u pathname[256];
char_u *path = pathname;
#else
Str255 directoryName;
char_u temporary[255];
char_u *temporaryPtr = temporary;
#endif
#ifdef USE_UNIXFILENAME
/* Get the default volume */
/* TODO: Remove as this only work if Vim is on the Boot Volume*/
error=HGetVol(NULL, &dfltVol_vRefNum, &dfltVol_dirID);
if (error)
return NULL;
#endif
/* Start filling fname with file.name */
vim_strncpy(filenamePtr, &file.name[1], file.name[0]);
/* Get the info about the file specified in FSSpec */
theCPB.dirInfo.ioFDirIndex = 0;
theCPB.dirInfo.ioNamePtr = file.name;
theCPB.dirInfo.ioVRefNum = file.vRefNum;
/*theCPB.hFileInfo.ioDirID = 0;*/
theCPB.dirInfo.ioDrDirID = file.parID;
/* As ioFDirIndex = 0, get the info of ioNamePtr,
which is relative to ioVrefNum, ioDirID */
error = PBGetCatInfo(&theCPB, false);
/* If we are called for a new file we expect fnfErr */
if ((error) && (error != fnfErr))
return NULL;
/* Check if it's a file or folder */
/* default to file if file don't exist */
if (((theCPB.hFileInfo.ioFlAttrib & ioDirMask) == 0) || (error))
folder = 0; /* It's not a folder */
else
folder = 1;
#ifdef USE_UNIXFILENAME
/*
* The function used here are available in Carbon, but
* do nothing une MacOS 8 and 9
*/
if (error == fnfErr)
{
/* If the file to be saved does not already exist, it isn't possible
to convert its FSSpec into an FSRef. But we can construct an
FSSpec for the file's parent folder (since we have its volume and
directory IDs), and since that folder does exist, we can convert
that FSSpec into an FSRef, convert the FSRef in turn into a path,
and, finally, append the filename. */
FSSpec dirSpec;
FSRef dirRef;
Str255 emptyFilename = "\p";
error = FSMakeFSSpec(theCPB.dirInfo.ioVRefNum,
theCPB.dirInfo.ioDrDirID, emptyFilename, &dirSpec);
if (error)
return NULL;
error = FSpMakeFSRef(&dirSpec, &dirRef);
if (error)
return NULL;
status = FSRefMakePath(&dirRef, (UInt8*)path, pathSize);
if (status)
return NULL;
STRCAT(path, "/");
STRCAT(path, filenamePtr);
}
else
{
/* If the file to be saved already exists, we can get its full path
by converting its FSSpec into an FSRef. */
error=FSpMakeFSRef(&file, &refFile);
if (error)
return NULL;
status=FSRefMakePath(&refFile, (UInt8 *) path, pathSize);
if (status)
return NULL;
}
/* Add a slash at the end if needed */
if (folder)
STRCAT(path, "/");
return (vim_strsave(path));
#else
/* TODO: Get rid of all USE_UNIXFILENAME below */
/* Set ioNamePtr, it's the same area which is always reused. */
theCPB.dirInfo.ioNamePtr = directoryName;
/* Trick for first entry, set ioDrParID to the first value
* we want for ioDrDirID*/
theCPB.dirInfo.ioDrParID = file.parID;
theCPB.dirInfo.ioDrDirID = file.parID;
if ((TRUE) && (file.parID != fsRtDirID /*fsRtParID*/))
do
{
theCPB.dirInfo.ioFDirIndex = -1;
/* theCPB.dirInfo.ioNamePtr = directoryName; Already done above. */
theCPB.dirInfo.ioVRefNum = file.vRefNum;
/* theCPB.dirInfo.ioDirID = irrelevant when ioFDirIndex = -1 */
theCPB.dirInfo.ioDrDirID = theCPB.dirInfo.ioDrParID;
/* As ioFDirIndex = -1, get the info of ioDrDirID, */
/* *ioNamePtr[0 TO 31] will be updated */
error = PBGetCatInfo(&theCPB,false);
if (error)
return NULL;
/* Put the new directoryName in front of the current fname */
STRCPY(temporaryPtr, filenamePtr);
vim_strncpy(filenamePtr, &directoryName[1], directoryName[0]);
STRCAT(filenamePtr, ":");
STRCAT(filenamePtr, temporaryPtr);
}
#if 1 /* def USE_UNIXFILENAME */
while ((theCPB.dirInfo.ioDrParID != fsRtDirID) /* && */
/* (theCPB.dirInfo.ioDrDirID != fsRtDirID)*/);
#else
while (theCPB.dirInfo.ioDrDirID != fsRtDirID);
#endif
/* Get the information about the volume on which the file reside */
theCPB.dirInfo.ioFDirIndex = -1;
/* theCPB.dirInfo.ioNamePtr = directoryName; Already done above. */
theCPB.dirInfo.ioVRefNum = file.vRefNum;
/* theCPB.dirInfo.ioDirID = irrelevant when ioFDirIndex = -1 */
theCPB.dirInfo.ioDrDirID = theCPB.dirInfo.ioDrParID;
/* As ioFDirIndex = -1, get the info of ioDrDirID, */
/* *ioNamePtr[0 TO 31] will be updated */
error = PBGetCatInfo(&theCPB,false);
if (error)
return NULL;
/* For MacOS Classic always add the volume name */
/* For MacOS X add the volume name preceded by "Volumes" */
/* when we are not referring to the boot volume */
#ifdef USE_UNIXFILENAME
if (file.vRefNum != dfltVol_vRefNum)
#endif
{
/* Add the volume name */
STRCPY(temporaryPtr, filenamePtr);
vim_strncpy(filenamePtr, &directoryName[1], directoryName[0]);
STRCAT(filenamePtr, ":");
STRCAT(filenamePtr, temporaryPtr);
#ifdef USE_UNIXFILENAME
STRCPY(temporaryPtr, filenamePtr);
filenamePtr[0] = 0; /* NULL terminate the string */
STRCAT(filenamePtr, "Volumes:");
STRCAT(filenamePtr, temporaryPtr);
#endif
}
/* Append final path separator if it's a folder */
if (folder)
STRCAT(fname, ":");
/* As we use Unix File Name for MacOS X convert it */
#ifdef USE_UNIXFILENAME
/* Need to insert leading / */
/* TODO: get the above code to use directly the / */
STRCPY(&temporaryPtr[1], filenamePtr);
temporaryPtr[0] = '/';
STRCPY(filenamePtr, temporaryPtr);
{
char *p;
for (p = fname; *p; p++)
if (*p == ':')
*p = '/';
}
#endif
return (vim_strsave(fname));
#endif
}
#if (defined(USE_IM_CONTROL) || defined(PROTO)) && defined(USE_CARBONKEYHANDLER)
/*
* Input Method Control functions.
*/
/*
* Notify cursor position to IM.
*/
void
im_set_position(int row, int col)
{
#if 0
/* TODO: Implement me! */
im_start_row = row;
im_start_col = col;
#endif
}
static ScriptLanguageRecord gTSLWindow;
static ScriptLanguageRecord gTSLInsert;
static ScriptLanguageRecord gTSLDefault = { 0, 0 };
static Component gTSCWindow;
static Component gTSCInsert;
static Component gTSCDefault;
static int im_initialized = 0;
static void
im_on_window_switch(int active)
{
ScriptLanguageRecord *slptr = NULL;
OSStatus err;
if (! gui.in_use)
return;
if (im_initialized == 0)
{
im_initialized = 1;
/* save default TSM component (should be U.S.) to default */
GetDefaultInputMethodOfClass(&gTSCDefault, &gTSLDefault,
kKeyboardInputMethodClass);
}
if (active == TRUE)
{
im_is_active = TRUE;
ActivateTSMDocument(gTSMDocument);
slptr = &gTSLWindow;
if (slptr)
{
err = SetDefaultInputMethodOfClass(gTSCWindow, slptr,
kKeyboardInputMethodClass);
if (err == noErr)
err = SetTextServiceLanguage(slptr);
if (err == noErr)
KeyScript(slptr->fScript | smKeyForceKeyScriptMask);
}
}
else
{
err = GetTextServiceLanguage(&gTSLWindow);
if (err == noErr)
slptr = &gTSLWindow;
if (slptr)
GetDefaultInputMethodOfClass(&gTSCWindow, slptr,
kKeyboardInputMethodClass);
im_is_active = FALSE;
DeactivateTSMDocument(gTSMDocument);
}
}
/*
* Set IM status on ("active" is TRUE) or off ("active" is FALSE).
*/
void
im_set_active(int active)
{
ScriptLanguageRecord *slptr = NULL;
OSStatus err;
if (! gui.in_use)
return;
if (im_initialized == 0)
{
im_initialized = 1;
/* save default TSM component (should be U.S.) to default */
GetDefaultInputMethodOfClass(&gTSCDefault, &gTSLDefault,
kKeyboardInputMethodClass);
}
if (active == TRUE)
{
im_is_active = TRUE;
ActivateTSMDocument(gTSMDocument);
slptr = &gTSLInsert;
if (slptr)
{
err = SetDefaultInputMethodOfClass(gTSCInsert, slptr,
kKeyboardInputMethodClass);
if (err == noErr)
err = SetTextServiceLanguage(slptr);
if (err == noErr)
KeyScript(slptr->fScript | smKeyForceKeyScriptMask);
}
}
else
{
err = GetTextServiceLanguage(&gTSLInsert);
if (err == noErr)
slptr = &gTSLInsert;
if (slptr)
GetDefaultInputMethodOfClass(&gTSCInsert, slptr,
kKeyboardInputMethodClass);
/* restore to default when switch to normal mode, so than we could
* enter commands easier */
SetDefaultInputMethodOfClass(gTSCDefault, &gTSLDefault,
kKeyboardInputMethodClass);
SetTextServiceLanguage(&gTSLDefault);
im_is_active = FALSE;
DeactivateTSMDocument(gTSMDocument);
}
}
/*
* Get IM status. When IM is on, return not 0. Else return 0.
*/
int
im_get_status(void)
{
if (! gui.in_use)
return 0;
return im_is_active;
}
#endif /* defined(USE_IM_CONTROL) || defined(PROTO) */
#if defined(FEAT_GUI_TABLINE) || defined(PROTO)
// drawer implementation
static MenuRef contextMenu = NULL;
enum
{
kTabContextMenuId = 42,
};
// the caller has to CFRelease() the returned string
static CFStringRef
getTabLabel(tabpage_T *page)
{
get_tabline_label(page, FALSE);
#ifdef MACOS_CONVERT
return (CFStringRef)mac_enc_to_cfstring(NameBuff, STRLEN(NameBuff));
#else
// TODO: check internal encoding?
return CFStringCreateWithCString(kCFAllocatorDefault, (char *)NameBuff,
kCFStringEncodingMacRoman);
#endif
}
#define DRAWER_SIZE 150
#define DRAWER_INSET 16
static ControlRef dataBrowser = NULL;
// when the tabline is hidden, vim doesn't call update_tabline(). When
// the tabline is shown again, show_tabline() is called before update_tabline(),
// and because of this, the tab labels and vims internal tabs are out of sync
// for a very short time. to prevent inconsistent state, we store the labels
// of the tabs, not pointers to the tabs (which are invalid for a short time).
static CFStringRef *tabLabels = NULL;
static int tabLabelsSize = 0;
enum
{
kTabsColumn = 'Tabs'
};
static int
getTabCount(void)
{
tabpage_T *tp;
int numTabs = 0;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
++numTabs;
return numTabs;
}
// data browser item display callback
static OSStatus
dbItemDataCallback(ControlRef browser,
DataBrowserItemID itemID,
DataBrowserPropertyID property /* column id */,
DataBrowserItemDataRef itemData,
Boolean changeValue)
{
OSStatus status = noErr;
// assert(property == kTabsColumn); // why is this violated??
// changeValue is true if we have a modifieable list and data was changed.
// In our case, it's always false.
// (that is: if (changeValue) updateInternalData(); else return
// internalData();
if (!changeValue)
{
CFStringRef str;
assert(itemID - 1 >= 0 && itemID - 1 < tabLabelsSize);
str = tabLabels[itemID - 1];
status = SetDataBrowserItemDataText(itemData, str);
}
else
status = errDataBrowserPropertyNotSupported;
return status;
}
// data browser action callback
static void
dbItemNotificationCallback(ControlRef browser,
DataBrowserItemID item,
DataBrowserItemNotification message)
{
switch (message)
{
case kDataBrowserItemSelected:
send_tabline_event(item);
break;
}
}
// callbacks needed for contextual menu:
static void
dbGetContextualMenuCallback(ControlRef browser,
MenuRef *menu,
UInt32 *helpType,
CFStringRef *helpItemString,
AEDesc *selection)
{
// on mac os 9: kCMHelpItemNoHelp, but it's not the same
*helpType = kCMHelpItemRemoveHelp; // OS X only ;-)
*helpItemString = NULL;
*menu = contextMenu;
}
static void
dbSelectContextualMenuCallback(ControlRef browser,
MenuRef menu,
UInt32 selectionType,
SInt16 menuID,
MenuItemIndex menuItem)
{
if (selectionType == kCMMenuItemSelected)
{
MenuCommand command;
GetMenuItemCommandID(menu, menuItem, &command);
// get tab that was selected when the context menu appeared
// (there is always one tab selected). TODO: check if the context menu
// isn't opened on an item but on empty space (has to be possible some
// way, the finder does it too ;-) )
Handle items = NewHandle(0);
if (items != NULL)
{
int numItems;
GetDataBrowserItems(browser, kDataBrowserNoItem, false,
kDataBrowserItemIsSelected, items);
numItems = GetHandleSize(items) / sizeof(DataBrowserItemID);
if (numItems > 0)
{
int idx;
DataBrowserItemID *itemsPtr;
HLock(items);
itemsPtr = (DataBrowserItemID *)*items;
idx = itemsPtr[0];
HUnlock(items);
send_tabline_menu_event(idx, command);
}
DisposeHandle(items);
}
}
}
// focus callback of the data browser to always leave focus in vim
static OSStatus
dbFocusCallback(EventHandlerCallRef handler, EventRef event, void *data)
{
assert(GetEventClass(event) == kEventClassControl
&& GetEventKind(event) == kEventControlSetFocusPart);
return paramErr;
}
// drawer callback to resize data browser to drawer size
static OSStatus
drawerCallback(EventHandlerCallRef handler, EventRef event, void *data)
{
switch (GetEventKind(event))
{
case kEventWindowBoundsChanged: // move or resize
{
UInt32 attribs;
GetEventParameter(event, kEventParamAttributes, typeUInt32,
NULL, sizeof(attribs), NULL, &attribs);
if (attribs & kWindowBoundsChangeSizeChanged) // resize
{
Rect r;
GetWindowBounds(drawer, kWindowContentRgn, &r);
SetRect(&r, 0, 0, r.right - r.left, r.bottom - r.top);
SetControlBounds(dataBrowser, &r);
SetDataBrowserTableViewNamedColumnWidth(dataBrowser,
kTabsColumn, r.right);
}
}
break;
}
return eventNotHandledErr;
}
// Load DataBrowserChangeAttributes() dynamically on tiger (and better).
// This way the code works on 10.2 and 10.3 as well (it doesn't have the
// blue highlights in the list view on these systems, though. Oh well.)
#import <mach-o/dyld.h>
enum { kMyDataBrowserAttributeListViewAlternatingRowColors = (1 << 1) };
static OSStatus
myDataBrowserChangeAttributes(ControlRef inDataBrowser,
OptionBits inAttributesToSet,
OptionBits inAttributesToClear)
{
long osVersion;
char *symbolName;
NSSymbol symbol = NULL;
OSStatus (*dataBrowserChangeAttributes)(ControlRef inDataBrowser,
OptionBits inAttributesToSet, OptionBits inAttributesToClear);
Gestalt(gestaltSystemVersion, &osVersion);
if (osVersion < 0x1040) // only supported for 10.4 (and up)
return noErr;
// C name mangling...
symbolName = "_DataBrowserChangeAttributes";
if (!NSIsSymbolNameDefined(symbolName)
|| (symbol = NSLookupAndBindSymbol(symbolName)) == NULL)
return noErr;
dataBrowserChangeAttributes = NSAddressOfSymbol(symbol);
if (dataBrowserChangeAttributes == NULL)
return noErr; // well...
return dataBrowserChangeAttributes(inDataBrowser,
inAttributesToSet, inAttributesToClear);
}
static void
initialise_tabline(void)
{
Rect drawerRect = { 0, 0, 0, DRAWER_SIZE };
DataBrowserCallbacks dbCallbacks;
EventTypeSpec focusEvent = {kEventClassControl, kEventControlSetFocusPart};
EventTypeSpec resizeEvent = {kEventClassWindow, kEventWindowBoundsChanged};
DataBrowserListViewColumnDesc colDesc;
// drawers have to have compositing enabled
CreateNewWindow(kDrawerWindowClass,
kWindowStandardHandlerAttribute
| kWindowCompositingAttribute
| kWindowResizableAttribute
| kWindowLiveResizeAttribute,
&drawerRect, &drawer);
SetThemeWindowBackground(drawer, kThemeBrushDrawerBackground, true);
SetDrawerParent(drawer, gui.VimWindow);
SetDrawerOffsets(drawer, kWindowOffsetUnchanged, DRAWER_INSET);
// create list view embedded in drawer
CreateDataBrowserControl(drawer, &drawerRect, kDataBrowserListView,
&dataBrowser);
dbCallbacks.version = kDataBrowserLatestCallbacks;
InitDataBrowserCallbacks(&dbCallbacks);
dbCallbacks.u.v1.itemDataCallback =
NewDataBrowserItemDataUPP(dbItemDataCallback);
dbCallbacks.u.v1.itemNotificationCallback =
NewDataBrowserItemNotificationUPP(dbItemNotificationCallback);
dbCallbacks.u.v1.getContextualMenuCallback =
NewDataBrowserGetContextualMenuUPP(dbGetContextualMenuCallback);
dbCallbacks.u.v1.selectContextualMenuCallback =
NewDataBrowserSelectContextualMenuUPP(dbSelectContextualMenuCallback);
SetDataBrowserCallbacks(dataBrowser, &dbCallbacks);
SetDataBrowserListViewHeaderBtnHeight(dataBrowser, 0); // no header
SetDataBrowserHasScrollBars(dataBrowser, false, true); // only vertical
SetDataBrowserSelectionFlags(dataBrowser,
kDataBrowserSelectOnlyOne | kDataBrowserNeverEmptySelectionSet);
SetDataBrowserTableViewHiliteStyle(dataBrowser,
kDataBrowserTableViewFillHilite);
Boolean b = false;
SetControlData(dataBrowser, kControlEntireControl,
kControlDataBrowserIncludesFrameAndFocusTag, sizeof(b), &b);
// enable blue background in data browser (this is only in 10.4 and vim
// has to support older osx versions as well, so we have to load this
// function dynamically)
myDataBrowserChangeAttributes(dataBrowser,
kMyDataBrowserAttributeListViewAlternatingRowColors, 0);
// install callback that keeps focus in vim and away from the data browser
InstallControlEventHandler(dataBrowser, dbFocusCallback, 1, &focusEvent,
NULL, NULL);
// install callback that keeps data browser at the size of the drawer
InstallWindowEventHandler(drawer, drawerCallback, 1, &resizeEvent,
NULL, NULL);
// add "tabs" column to data browser
colDesc.propertyDesc.propertyID = kTabsColumn;
colDesc.propertyDesc.propertyType = kDataBrowserTextType;
// add if items can be selected (?): kDataBrowserListViewSelectionColumn
colDesc.propertyDesc.propertyFlags = kDataBrowserDefaultPropertyFlags;
colDesc.headerBtnDesc.version = kDataBrowserListViewLatestHeaderDesc;
colDesc.headerBtnDesc.minimumWidth = 100;
colDesc.headerBtnDesc.maximumWidth = 150;
colDesc.headerBtnDesc.titleOffset = 0;
colDesc.headerBtnDesc.titleString = CFSTR("Tabs");
colDesc.headerBtnDesc.initialOrder = kDataBrowserOrderIncreasing;
colDesc.headerBtnDesc.btnFontStyle.flags = 0; // use default font
colDesc.headerBtnDesc.btnContentInfo.contentType = kControlContentTextOnly;
AddDataBrowserListViewColumn(dataBrowser, &colDesc, 0);
// create tabline popup menu required by vim docs (see :he tabline-menu)
CreateNewMenu(kTabContextMenuId, 0, &contextMenu);
AppendMenuItemTextWithCFString(contextMenu, CFSTR("Close"), 0,
TABLINE_MENU_CLOSE, NULL);
AppendMenuItemTextWithCFString(contextMenu, CFSTR("New Tab"), 0,
TABLINE_MENU_NEW, NULL);
AppendMenuItemTextWithCFString(contextMenu, CFSTR("Open Tab..."), 0,
TABLINE_MENU_OPEN, NULL);
}
/*
* Show or hide the tabline.
*/
void
gui_mch_show_tabline(int showit)
{
if (showit == 0)
CloseDrawer(drawer, true);
else
OpenDrawer(drawer, kWindowEdgeRight, true);
}
/*
* Return TRUE when tabline is displayed.
*/
int
gui_mch_showing_tabline(void)
{
WindowDrawerState state = GetDrawerState(drawer);
return state == kWindowDrawerOpen || state == kWindowDrawerOpening;
}
/*
* Update the labels of the tabline.
*/
void
gui_mch_update_tabline(void)
{
tabpage_T *tp;
int numTabs = getTabCount();
int nr = 1;
int curtabidx = 1;
// adjust data browser
if (tabLabels != NULL)
{
int i;
for (i = 0; i < tabLabelsSize; ++i)
CFRelease(tabLabels[i]);
free(tabLabels);
}
tabLabels = (CFStringRef *)malloc(numTabs * sizeof(CFStringRef));
tabLabelsSize = numTabs;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, ++nr)
{
if (tp == curtab)
curtabidx = nr;
tabLabels[nr-1] = getTabLabel(tp);
}
RemoveDataBrowserItems(dataBrowser, kDataBrowserNoItem, 0, NULL,
kDataBrowserItemNoProperty);
// data browser uses ids 1, 2, 3, ... numTabs per default, so we
// can pass NULL for the id array
AddDataBrowserItems(dataBrowser, kDataBrowserNoItem, numTabs, NULL,
kDataBrowserItemNoProperty);
DataBrowserItemID item = curtabidx;
SetDataBrowserSelectedItems(dataBrowser, 1, &item, kDataBrowserItemsAssign);
}
/*
* Set the current tab to "nr". First tab is 1.
*/
void
gui_mch_set_curtab(nr)
int nr;
{
DataBrowserItemID item = nr;
SetDataBrowserSelectedItems(dataBrowser, 1, &item, kDataBrowserItemsAssign);
// TODO: call something like this?: (or restore scroll position, or...)
RevealDataBrowserItem(dataBrowser, item, kTabsColumn,
kDataBrowserRevealOnly);
}
#endif // FEAT_GUI_TABLINE
| zyz2011-vim | src/gui_mac.c | C | gpl2 | 172,220 |
/* 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.
*/
#if !defined(GUI_BEVAL_H) && (defined(FEAT_BEVAL) || defined(PROTO))
#define GUI_BEVAL_H
#ifdef FEAT_GUI_GTK
# include <gtk/gtkwidget.h>
#else
# if defined(FEAT_GUI_X11)
# include <X11/Intrinsic.h>
# endif
#endif
typedef enum
{
ShS_NEUTRAL, /* nothing showing or pending */
ShS_PENDING, /* data requested from debugger */
ShS_UPDATE_PENDING, /* switching information displayed */
ShS_SHOWING /* the balloon is being displayed */
} BeState;
typedef struct BalloonEvalStruct
{
#ifdef FEAT_GUI_GTK
GtkWidget *target; /* widget we are monitoring */
GtkWidget *balloonShell;
GtkWidget *balloonLabel;
unsigned int timerID; /* timer for run */
BeState showState; /* tells us whats currently going on */
int x;
int y;
unsigned int state; /* Button/Modifier key state */
#else
# if !defined(FEAT_GUI_W32)
Widget target; /* widget we are monitoring */
Widget balloonShell;
Widget balloonLabel;
XtIntervalId timerID; /* timer for run */
BeState showState; /* tells us whats currently going on */
XtAppContext appContext; /* used in event handler */
Position x;
Position y;
Position x_root;
Position y_root;
int state; /* Button/Modifier key state */
# else
HWND target;
HWND balloon;
int x;
int y;
BeState showState; /* tells us whats currently going on */
# endif
#endif
int ts; /* tabstop setting for this buffer */
char_u *msg;
void (*msgCB)__ARGS((struct BalloonEvalStruct *, int));
void *clientData; /* For callback */
#if !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_W32)
Dimension screen_width; /* screen width in pixels */
Dimension screen_height; /* screen height in pixels */
#endif
} BalloonEval;
#define EVAL_OFFSET_X 15 /* displacement of beval topleft corner from pointer */
#define EVAL_OFFSET_Y 10
#include "gui_beval.pro"
#endif /* GUI_BEVAL_H and FEAT_BEVAL */
| zyz2011-vim | src/gui_beval.h | C | gpl2 | 2,219 |
/* 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.
*/
/* Before Including the MacOS specific files,
* lets set the OPAQUE_TOOLBOX_STRUCTS to 0 so we
* can access the internal structures.
* (Until fully Carbon compliant)
* TODO: Can we remove this? (Dany)
*/
#if 0
# define OPAQUE_TOOLBOX_STRUCTS 0
#endif
/*
* Macintosh machine-dependent things.
*
* Include the Mac header files, unless also compiling with X11 (the header
* files have many conflicts).
*/
#ifdef FEAT_GUI_MAC
# include <Quickdraw.h> /* Apple calls it QuickDraw.h... */
# include <ToolUtils.h>
# include <LowMem.h>
# include <Scrap.h>
# include <Sound.h>
# include <TextUtils.h>
# include <Memory.h>
# include <OSUtils.h>
# include <Files.h>
# ifdef FEAT_MBYTE
# include <Script.h>
# endif
#endif
/*
* Unix interface
*/
#if defined(__APPLE_CC__) /* for Project Builder and ... */
# include <unistd.h>
/* Get stat.h or something similar. Comment: How come some OS get in in vim.h */
# include <sys/stat.h>
/* && defined(HAVE_CURSE) */
/* The curses.h from MacOS X provides by default some BACKWARD compatibilty
* definition which can cause us problem later on. So we undefine a few of them. */
# include <curses.h>
# undef reg
# undef ospeed
/* OK defined to 0 in MacOS X 10.2 curses! Remove it, we define it to be 1. */
# undef OK
#endif
#include <signal.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <dirent.h>
/*
* MacOS specific #define
*/
/* This will go away when CMD_KEY fully tested */
#define USE_CMD_KEY
/* On MacOS X use the / not the : */
/* TODO: Should file such as ~/.vimrc reside instead in
* ~/Library/Vim or ~/Library/Preferences/org.vim.vim/ ? (Dany)
*/
/* When compiled under MacOS X (including CARBON version)
* we use the Unix File path style. Also when UNIX is defined. */
# define USE_UNIXFILENAME
/*
* Generic Vim #define
*/
#define FEAT_SOURCE_FFS
#define FEAT_SOURCE_FF_MAC
#define USE_EXE_NAME /* to find $VIM */
#define CASE_INSENSITIVE_FILENAME /* ignore case when comparing file names */
#define SPACE_IN_FILENAME
#define BREAKCHECK_SKIP 32 /* call mch_breakcheck() each time, it's
quite fast. Did I forgot to update the
comment */
#define USE_FNAME_CASE /* make ":e os_Mac.c" open the file in its
original case, as "os_mac.c" */
#define BINARY_FILE_IO
#define EOL_DEFAULT EOL_MAC
#ifndef MACOS_X_UNIX /* I hope that switching these two lines */
# define USE_CR /* does what I want -- BNF */
# define NO_CONSOLE /* don't include console mode */
#endif
#define HAVE_AVAIL_MEM
#ifndef HAVE_CONFIG_H
/* #define SYNC_DUP_CLOSE sync() a file with dup() and close() */
# define HAVE_STRING_H
# define HAVE_STRCSPN
# define HAVE_MEMSET
# define USE_TMPNAM /* use tmpnam() instead of mktemp() */
# define HAVE_FCNTL_H
# 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 HAVE_STRFTIME
#endif
/*
* Names for the EXRC, HELP and temporary files.
* Some of these may have been defined in the makefile.
*/
#ifndef SYS_VIMRC_FILE
# define SYS_VIMRC_FILE "$VIM/vimrc"
#endif
#ifndef SYS_GVIMRC_FILE
# define SYS_GVIMRC_FILE "$VIM/gvimrc"
#endif
#ifndef SYS_MENU_FILE
# define SYS_MENU_FILE "$VIMRUNTIME/menu.vim"
#endif
#ifndef SYS_OPTWIN_FILE
# define SYS_OPTWIN_FILE "$VIMRUNTIME/optwin.vim"
#endif
#ifndef EVIM_FILE
# define EVIM_FILE "$VIMRUNTIME/evim.vim"
#endif
#ifdef FEAT_GUI
# ifndef USR_GVIMRC_FILE
# define USR_GVIMRC_FILE "~/.gvimrc"
# endif
# ifndef GVIMRC_FILE
# define GVIMRC_FILE "_gvimrc"
# endif
#endif
#ifndef USR_VIMRC_FILE
# define USR_VIMRC_FILE "~/.vimrc"
#endif
#ifndef USR_EXRC_FILE
# define USR_EXRC_FILE "~/.exrc"
#endif
#ifndef VIMRC_FILE
# define VIMRC_FILE "_vimrc"
#endif
#ifndef EXRC_FILE
# define EXRC_FILE "_exrc"
#endif
#ifndef DFLT_HELPFILE
# define DFLT_HELPFILE "$VIMRUNTIME/doc/help.txt"
#endif
#ifndef FILETYPE_FILE
# define FILETYPE_FILE "filetype.vim"
#endif
#ifndef FTPLUGIN_FILE
# define FTPLUGIN_FILE "ftplugin.vim"
#endif
#ifndef INDENT_FILE
# define INDENT_FILE "indent.vim"
#endif
#ifndef FTOFF_FILE
# define FTOFF_FILE "ftoff.vim"
#endif
#ifndef FTPLUGOF_FILE
# define FTPLUGOF_FILE "ftplugof.vim"
#endif
#ifndef INDOFF_FILE
# define INDOFF_FILE "indoff.vim"
#endif
#ifndef SYNTAX_FNAME
# define SYNTAX_FNAME "$VIMRUNTIME/syntax/%s.vim"
#endif
#ifdef FEAT_VIMINFO
# ifndef VIMINFO_FILE
# define VIMINFO_FILE "~/.viminfo"
# endif
#endif /* FEAT_VIMINFO */
#ifndef DFLT_BDIR
# define DFLT_BDIR "." /* default for 'backupdir' */
#endif
#ifndef DFLT_DIR
# define DFLT_DIR "." /* default for 'directory' */
#endif
#ifndef DFLT_VDIR
# define DFLT_VDIR "$VIM/vimfiles/view" /* default for 'viewdir' */
#endif
#define DFLT_ERRORFILE "errors.err"
#ifndef DFLT_RUNTIMEPATH
# define DFLT_RUNTIMEPATH "~/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,~/.vim/after"
#endif
/*
* Macintosh has plenty of memory, use large buffers
*/
#define CMDBUFFSIZE 1024 /* size of the command processing buffer */
#if !defined(MACOS_X_UNIX)
# define MAXPATHL 256 /* Limited by the Pascal Strings */
# define BASENAMELEN (32-5-1) /* length of base of filename */
#endif
#ifndef DFLT_MAXMEM
# define DFLT_MAXMEM 512 /* use up to 512 Kbyte for buffer */
#endif
#ifndef DFLT_MAXMEMTOT
# define DFLT_MAXMEMTOT 2048 /* use up to 2048 Kbyte for Vim */
#endif
#define WILDCHAR_LIST "*?[{`$"
/**************/
#define mch_rename(src, dst) rename(src, dst)
#define mch_remove(x) unlink((char *)(x))
#ifndef mch_getenv
# if defined(__MRC__) || defined(__SC__)
# define mch_getenv(name) ((char_u *)getenv((char *)(name)))
# define mch_setenv(name, val, x) setenv((name), (val))
# elif defined(__APPLE_CC__)
# define mch_getenv(name) ((char_u *)getenv((char *)(name)))
/*# define mch_setenv(name, val, x) setenv((name), (val)) */ /* Obsoleted by Dany on Oct 30, 2001 */
# define mch_setenv(name, val, x) setenv(name, val, x)
# else
/* vim_getenv() is in pty.c */
# define USE_VIMPTY_GETENV
# define mch_getenv(x) vimpty_getenv(x)
# define mch_setenv(name, val, x) setenv(name, val, x)
# endif
#endif
#ifndef HAVE_CONFIG_H
# ifdef __APPLE_CC__
/* Assuming compiling for MacOS X */
/* Trying to take advantage of the prebinding */
# define HAVE_TGETENT
# define OSPEED_EXTERN
# define UP_BC_PC_EXTERN
# endif
#endif
/* Some "prep work" definition to be able to compile the MacOS X
* version with os_unix.x instead of os_mac.c. Based on the result
* of ./configure for console MacOS X.
*/
#ifdef MACOS_X_UNIX
# ifndef SIGPROTOARG
# define SIGPROTOARG (int)
# endif
# ifndef SIGDEFARG
# define SIGDEFARG(s) (s) int s UNUSED;
# endif
# ifndef SIGDUMMYARG
# define SIGDUMMYARG 0
# endif
# undef HAVE_AVAIL_MEM
# ifndef HAVE_CONFIG_H
# define RETSIGTYPE void
# define SIGRETURN return
/*# define USE_SYSTEM */ /* Output ship do debugger :(, but ot compile */
# define HAVE_SYS_WAIT_H 1 /* Attempt */
# define HAVE_TERMIOS_H 1
# define SYS_SELECT_WITH_SYS_TIME 1
# define HAVE_SELECT 1
# define HAVE_SYS_SELECT_H 1
# define HAVE_PUTENV
# define HAVE_SETENV
# define HAVE_RENAME
# endif
#endif
#if defined(MACOS_X) && !defined(HAVE_CONFIG_H)
# define HAVE_PUTENV
#endif
/* A Mac constant causing big problem to syntax highlighting */
#define UNKNOWN_CREATOR '\?\?\?\?'
| zyz2011-vim | src/os_mac.h | C | gpl2 | 7,556 |
/* 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.
*/
/*
* NetBeans 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 nbdebug_wait(). This is very important for
* debugging startup problems because gvim will be started automatically from
* netbeans and cannot be run directly from a debugger. The only way to debug
* a gvim started by netbeans 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 log tool.
*
* This code must have NBDEBUG defined for it to be compiled into vim/gvim.
*/
#ifdef NBDEBUG
#include "vim.h"
FILE *nb_debug = NULL;
u_int nb_dlevel = 0; /* nb_debug verbosity level */
void nbdb(char *, ...);
static int lookup(char *);
#ifdef USE_NB_ERRORHANDLER
static int errorHandler(Display *, XErrorEvent *);
#endif
/*
* nbdebug_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 nbdebug_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 nbdebug_wait */
void
nbdebug_log_init(
char *log_var, /* env var with log file */
char *level_var) /* env var with nb_debug level */
{
char *file; /* possible nb_debug output file */
char *cp; /* nb_dlevel pointer */
if (log_var && (file = getenv(log_var)) != NULL) {
time_t now;
nb_debug = fopen(file, "a");
time(&now);
fprintf(nb_debug, "%s", asctime(localtime(&now)));
if (level_var && (cp = getenv(level_var)) != NULL) {
nb_dlevel = strtoul(cp, NULL, 0);
} else {
nb_dlevel = NB_TRACE; /* default level */
}
#ifdef USE_NB_ERRORHANDLER
XSetErrorHandler(errorHandler);
#endif
}
} /* end nbdebug_log_init */
void
nbdbg(
char *fmt,
...)
{
va_list ap;
if (nb_debug != NULL && nb_dlevel & NB_TRACE) {
va_start(ap, fmt);
vfprintf(nb_debug, fmt, ap);
va_end(ap);
fflush(nb_debug);
}
} /* end nbdbg */
static int
lookup(
char *file)
{
char buf[BUFSIZ];
expand_env((char_u *) file, (char_u *) buf, BUFSIZ);
return
#ifndef FEAT_GUI_W32
(access(buf, F_OK) == 0);
#else
(access(buf, 0) == 0);
#endif
} /* end lookup */
#ifdef USE_NB_ERRORHANDLER
static int
errorHandler(
Display *dpy,
XErrorEvent *err)
{
char msg[256];
char buf[256];
XGetErrorText(dpy, err->error_code, msg, sizeof(msg));
nbdbg("\n\nNBDEBUG Vim: X Error of failed request: %s\n", msg);
sprintf(buf, "%d", err->request_code);
XGetErrorDatabaseText(dpy,
"XRequest", buf, "Unknown", msg, sizeof(msg));
nbdbg("\tMajor opcode of failed request: %d (%s)\n",
err->request_code, msg);
if (err->request_code > 128) {
nbdbg("\tMinor opcode of failed request: %d\n",
err->minor_code);
}
return 0;
}
#endif
#endif /* NBDEBUG */
| zyz2011-vim | src/nbdebug.c | C | gpl2 | 3,955 |
/* 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.
*/
/*
* if_perlsfio.c: Special I/O functions for Perl interface.
*/
#define _memory_h /* avoid memset redeclaration */
#define IN_PERL_FILE /* don't include if_perl.pro from prot.h */
#include "vim.h"
#if defined(USE_SFIO) || defined(PROTO)
#ifndef USE_SFIO /* just generating prototypes */
# define Sfio_t int
# define Sfdisc_t int
#endif
#define NIL(type) ((type)0)
static int
sfvimwrite(f, buf, n, disc)
Sfio_t *f; /* stream involved */
char *buf; /* buffer to read from */
int n; /* number of bytes to write */
Sfdisc_t *disc; /* discipline */
{
char_u *str;
str = vim_strnsave((char_u *)buf, n);
if (str == NULL)
return 0;
msg_split((char *)str);
vim_free(str);
return n;
}
/*
* sfdcnewnvi --
* Create Vim discipline
*/
Sfdisc_t *
sfdcnewvim()
{
Sfdisc_t *disc;
disc = (Sfdisc_t *)alloc((unsigned)sizeof(Sfdisc_t));
if (disc == NULL)
return NULL;
disc->readf = (Sfread_f)NULL;
disc->writef = sfvimwrite;
disc->seekf = (Sfseek_f)NULL;
disc->exceptf = (Sfexcept_f)NULL;
return disc;
}
#endif /* USE_SFIO */
| zyz2011-vim | src/if_perlsfio.c | C | gpl2 | 1,398 |
/* 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.
*/
#include "vim.h"
#ifdef AMIGA
# include <time.h> /* for time() */
#endif
/*
* Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)
* It has been changed beyond recognition since then.
*
* Differences between version 6.x and 7.x can be found with ":help version7".
* Differences between version 5.x and 6.x can be found with ":help version6".
* Differences between version 4.x and 5.x can be found with ":help version5".
* Differences between version 3.0 and 4.x can be found with ":help version4".
* All the remarks about older versions have been removed, they are not very
* interesting.
*/
#include "version.h"
char *Version = VIM_VERSION_SHORT;
static char *mediumVersion = VIM_VERSION_MEDIUM;
#if defined(HAVE_DATE_TIME) || defined(PROTO)
# if (defined(VMS) && defined(VAXC)) || defined(PROTO)
char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)
+ sizeof(__TIME__) + 3];
void
make_version()
{
/*
* Construct the long version string. Necessary because
* VAX C can't catenate strings in the preprocessor.
*/
strcpy(longVersion, VIM_VERSION_LONG_DATE);
strcat(longVersion, __DATE__);
strcat(longVersion, " ");
strcat(longVersion, __TIME__);
strcat(longVersion, ")");
}
# else
char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")";
# endif
#else
char *longVersion = VIM_VERSION_LONG;
#endif
static void version_msg __ARGS((char *s));
static char *(features[]) =
{
#ifdef AMIGA /* only for Amiga systems */
# ifdef FEAT_ARP
"+ARP",
# else
"-ARP",
# endif
#endif
#ifdef FEAT_ARABIC
"+arabic",
#else
"-arabic",
#endif
#ifdef FEAT_AUTOCMD
"+autocmd",
#else
"-autocmd",
#endif
#ifdef FEAT_BEVAL
"+balloon_eval",
#else
"-balloon_eval",
#endif
#ifdef FEAT_BROWSE
"+browse",
#else
"-browse",
#endif
#ifdef NO_BUILTIN_TCAPS
"-builtin_terms",
#endif
#ifdef SOME_BUILTIN_TCAPS
"+builtin_terms",
#endif
#ifdef ALL_BUILTIN_TCAPS
"++builtin_terms",
#endif
#ifdef FEAT_BYTEOFF
"+byte_offset",
#else
"-byte_offset",
#endif
#ifdef FEAT_CINDENT
"+cindent",
#else
"-cindent",
#endif
#ifdef FEAT_CLIENTSERVER
"+clientserver",
#else
"-clientserver",
#endif
#ifdef FEAT_CLIPBOARD
"+clipboard",
#else
"-clipboard",
#endif
#ifdef FEAT_CMDL_COMPL
"+cmdline_compl",
#else
"-cmdline_compl",
#endif
#ifdef FEAT_CMDHIST
"+cmdline_hist",
#else
"-cmdline_hist",
#endif
#ifdef FEAT_CMDL_INFO
"+cmdline_info",
#else
"-cmdline_info",
#endif
#ifdef FEAT_COMMENTS
"+comments",
#else
"-comments",
#endif
#ifdef FEAT_CONCEAL
"+conceal",
#else
"-conceal",
#endif
#ifdef FEAT_CRYPT
"+cryptv",
#else
"-cryptv",
#endif
#ifdef FEAT_CSCOPE
"+cscope",
#else
"-cscope",
#endif
#ifdef FEAT_CURSORBIND
"+cursorbind",
#else
"-cursorbind",
#endif
#ifdef CURSOR_SHAPE
"+cursorshape",
#else
"-cursorshape",
#endif
#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)
"+dialog_con_gui",
#else
# if defined(FEAT_CON_DIALOG)
"+dialog_con",
# else
# if defined(FEAT_GUI_DIALOG)
"+dialog_gui",
# else
"-dialog",
# endif
# endif
#endif
#ifdef FEAT_DIFF
"+diff",
#else
"-diff",
#endif
#ifdef FEAT_DIGRAPHS
"+digraphs",
#else
"-digraphs",
#endif
#ifdef FEAT_DND
"+dnd",
#else
"-dnd",
#endif
#ifdef EBCDIC
"+ebcdic",
#else
"-ebcdic",
#endif
#ifdef FEAT_EMACS_TAGS
"+emacs_tags",
#else
"-emacs_tags",
#endif
#ifdef FEAT_EVAL
"+eval",
#else
"-eval",
#endif
#ifdef FEAT_EX_EXTRA
"+ex_extra",
#else
"-ex_extra",
#endif
#ifdef FEAT_SEARCH_EXTRA
"+extra_search",
#else
"-extra_search",
#endif
#ifdef FEAT_FKMAP
"+farsi",
#else
"-farsi",
#endif
#ifdef FEAT_SEARCHPATH
"+file_in_path",
#else
"-file_in_path",
#endif
#ifdef FEAT_FIND_ID
"+find_in_path",
#else
"-find_in_path",
#endif
#ifdef FEAT_FLOAT
"+float",
#else
"-float",
#endif
#ifdef FEAT_FOLDING
"+folding",
#else
"-folding",
#endif
#ifdef FEAT_FOOTER
"+footer",
#else
"-footer",
#endif
/* only interesting on Unix systems */
#if !defined(USE_SYSTEM) && defined(UNIX)
"+fork()",
#endif
#ifdef FEAT_GETTEXT
# ifdef DYNAMIC_GETTEXT
"+gettext/dyn",
# else
"+gettext",
# endif
#else
"-gettext",
#endif
#ifdef FEAT_HANGULIN
"+hangul_input",
#else
"-hangul_input",
#endif
#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)
# ifdef DYNAMIC_ICONV
"+iconv/dyn",
# else
"+iconv",
# endif
#else
"-iconv",
#endif
#ifdef FEAT_INS_EXPAND
"+insert_expand",
#else
"-insert_expand",
#endif
#ifdef FEAT_JUMPLIST
"+jumplist",
#else
"-jumplist",
#endif
#ifdef FEAT_KEYMAP
"+keymap",
#else
"-keymap",
#endif
#ifdef FEAT_LANGMAP
"+langmap",
#else
"-langmap",
#endif
#ifdef FEAT_LIBCALL
"+libcall",
#else
"-libcall",
#endif
#ifdef FEAT_LINEBREAK
"+linebreak",
#else
"-linebreak",
#endif
#ifdef FEAT_LISP
"+lispindent",
#else
"-lispindent",
#endif
#ifdef FEAT_LISTCMDS
"+listcmds",
#else
"-listcmds",
#endif
#ifdef FEAT_LOCALMAP
"+localmap",
#else
"-localmap",
#endif
#ifdef FEAT_LUA
# ifdef DYNAMIC_LUA
"+lua/dyn",
# else
"+lua",
# endif
#else
"-lua",
#endif
#ifdef FEAT_MENU
"+menu",
#else
"-menu",
#endif
#ifdef FEAT_SESSION
"+mksession",
#else
"-mksession",
#endif
#ifdef FEAT_MODIFY_FNAME
"+modify_fname",
#else
"-modify_fname",
#endif
#ifdef FEAT_MOUSE
"+mouse",
# ifdef FEAT_MOUSESHAPE
"+mouseshape",
# else
"-mouseshape",
# endif
# else
"-mouse",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_DEC
"+mouse_dec",
# else
"-mouse_dec",
# endif
# ifdef FEAT_MOUSE_GPM
"+mouse_gpm",
# else
"-mouse_gpm",
# endif
# ifdef FEAT_MOUSE_JSB
"+mouse_jsbterm",
# else
"-mouse_jsbterm",
# endif
# ifdef FEAT_MOUSE_NET
"+mouse_netterm",
# else
"-mouse_netterm",
# endif
# ifdef FEAT_SYSMOUSE
"+mouse_sysmouse",
# else
"-mouse_sysmouse",
# endif
# ifdef FEAT_MOUSE_XTERM
"+mouse_xterm",
# else
"-mouse_xterm",
# endif
# ifdef FEAT_MOUSE_URXVT
"+mouse_urxvt",
# else
"-mouse_urxvt",
# endif
#endif
#ifdef __QNX__
# ifdef FEAT_MOUSE_PTERM
"+mouse_pterm",
# else
"-mouse_pterm",
# endif
#endif
#ifdef FEAT_MBYTE_IME
# ifdef DYNAMIC_IME
"+multi_byte_ime/dyn",
# else
"+multi_byte_ime",
# endif
#else
# ifdef FEAT_MBYTE
"+multi_byte",
# else
"-multi_byte",
# endif
#endif
#ifdef FEAT_MULTI_LANG
"+multi_lang",
#else
"-multi_lang",
#endif
#ifdef FEAT_MZSCHEME
# ifdef DYNAMIC_MZSCHEME
"+mzscheme/dyn",
# else
"+mzscheme",
# endif
#else
"-mzscheme",
#endif
#ifdef FEAT_NETBEANS_INTG
"+netbeans_intg",
#else
"-netbeans_intg",
#endif
#ifdef FEAT_GUI_W32
# ifdef FEAT_OLE
"+ole",
# else
"-ole",
# endif
#endif
#ifdef FEAT_PATH_EXTRA
"+path_extra",
#else
"-path_extra",
#endif
#ifdef FEAT_PERL
# ifdef DYNAMIC_PERL
"+perl/dyn",
# else
"+perl",
# endif
#else
"-perl",
#endif
#ifdef FEAT_PERSISTENT_UNDO
"+persistent_undo",
#else
"-persistent_undo",
#endif
#ifdef FEAT_PRINTER
# ifdef FEAT_POSTSCRIPT
"+postscript",
# else
"-postscript",
# endif
"+printer",
#else
"-printer",
#endif
#ifdef FEAT_PROFILE
"+profile",
#else
"-profile",
#endif
#ifdef FEAT_PYTHON
# ifdef DYNAMIC_PYTHON
"+python/dyn",
# else
"+python",
# endif
#else
"-python",
#endif
#ifdef FEAT_PYTHON3
# ifdef DYNAMIC_PYTHON3
"+python3/dyn",
# else
"+python3",
# endif
#else
"-python3",
#endif
#ifdef FEAT_QUICKFIX
"+quickfix",
#else
"-quickfix",
#endif
#ifdef FEAT_RELTIME
"+reltime",
#else
"-reltime",
#endif
#ifdef FEAT_RIGHTLEFT
"+rightleft",
#else
"-rightleft",
#endif
#ifdef FEAT_RUBY
# ifdef DYNAMIC_RUBY
"+ruby/dyn",
# else
"+ruby",
# endif
#else
"-ruby",
#endif
#ifdef FEAT_SCROLLBIND
"+scrollbind",
#else
"-scrollbind",
#endif
#ifdef FEAT_SIGNS
"+signs",
#else
"-signs",
#endif
#ifdef FEAT_SMARTINDENT
"+smartindent",
#else
"-smartindent",
#endif
#ifdef FEAT_SNIFF
"+sniff",
#else
"-sniff",
#endif
#ifdef STARTUPTIME
"+startuptime",
#else
"-startuptime",
#endif
#ifdef FEAT_STL_OPT
"+statusline",
#else
"-statusline",
#endif
#ifdef FEAT_SUN_WORKSHOP
"+sun_workshop",
#else
"-sun_workshop",
#endif
#ifdef FEAT_SYN_HL
"+syntax",
#else
"-syntax",
#endif
/* only interesting on Unix systems */
#if defined(USE_SYSTEM) && (defined(UNIX) || defined(__EMX__))
"+system()",
#endif
#ifdef FEAT_TAG_BINS
"+tag_binary",
#else
"-tag_binary",
#endif
#ifdef FEAT_TAG_OLDSTATIC
"+tag_old_static",
#else
"-tag_old_static",
#endif
#ifdef FEAT_TAG_ANYWHITE
"+tag_any_white",
#else
"-tag_any_white",
#endif
#ifdef FEAT_TCL
# ifdef DYNAMIC_TCL
"+tcl/dyn",
# else
"+tcl",
# endif
#else
"-tcl",
#endif
#if defined(UNIX) || defined(__EMX__)
/* only Unix (or OS/2 with EMX!) can have terminfo instead of termcap */
# ifdef TERMINFO
"+terminfo",
# else
"-terminfo",
# endif
#else /* unix always includes termcap support */
# ifdef HAVE_TGETENT
"+tgetent",
# else
"-tgetent",
# endif
#endif
#ifdef FEAT_TERMRESPONSE
"+termresponse",
#else
"-termresponse",
#endif
#ifdef FEAT_TEXTOBJ
"+textobjects",
#else
"-textobjects",
#endif
#ifdef FEAT_TITLE
"+title",
#else
"-title",
#endif
#ifdef FEAT_TOOLBAR
"+toolbar",
#else
"-toolbar",
#endif
#ifdef FEAT_USR_CMDS
"+user_commands",
#else
"-user_commands",
#endif
#ifdef FEAT_VERTSPLIT
"+vertsplit",
#else
"-vertsplit",
#endif
#ifdef FEAT_VIRTUALEDIT
"+virtualedit",
#else
"-virtualedit",
#endif
#ifdef FEAT_VISUAL
"+visual",
# ifdef FEAT_VISUALEXTRA
"+visualextra",
# else
"-visualextra",
# endif
#else
"-visual",
#endif
#ifdef FEAT_VIMINFO
"+viminfo",
#else
"-viminfo",
#endif
#ifdef FEAT_VREPLACE
"+vreplace",
#else
"-vreplace",
#endif
#ifdef FEAT_WILDIGN
"+wildignore",
#else
"-wildignore",
#endif
#ifdef FEAT_WILDMENU
"+wildmenu",
#else
"-wildmenu",
#endif
#ifdef FEAT_WINDOWS
"+windows",
#else
"-windows",
#endif
#ifdef FEAT_WRITEBACKUP
"+writebackup",
#else
"-writebackup",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_X11
"+X11",
# else
"-X11",
# endif
#endif
#ifdef FEAT_XFONTSET
"+xfontset",
#else
"-xfontset",
#endif
#ifdef FEAT_XIM
"+xim",
#else
"-xim",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef USE_XSMP_INTERACT
"+xsmp_interact",
# else
# ifdef USE_XSMP
"+xsmp",
# else
"-xsmp",
# endif
# endif
# ifdef FEAT_XCLIPBOARD
"+xterm_clipboard",
# else
"-xterm_clipboard",
# endif
#endif
#ifdef FEAT_XTERM_SAVE
"+xterm_save",
#else
"-xterm_save",
#endif
#ifdef WIN3264
# ifdef FEAT_XPM_W32
"+xpm_w32",
# else
"-xpm_w32",
# endif
#endif
NULL
};
static int included_patches[] =
{ /* Add new patch number below this line */
/**/
566,
/**/
565,
/**/
564,
/**/
563,
/**/
562,
/**/
561,
/**/
560,
/**/
559,
/**/
558,
/**/
557,
/**/
556,
/**/
555,
/**/
554,
/**/
553,
/**/
552,
/**/
551,
/**/
550,
/**/
549,
/**/
548,
/**/
547,
/**/
546,
/**/
545,
/**/
544,
/**/
543,
/**/
542,
/**/
541,
/**/
540,
/**/
539,
/**/
538,
/**/
537,
/**/
536,
/**/
535,
/**/
534,
/**/
533,
/**/
532,
/**/
531,
/**/
530,
/**/
529,
/**/
528,
/**/
527,
/**/
526,
/**/
525,
/**/
524,
/**/
523,
/**/
522,
/**/
521,
/**/
520,
/**/
519,
/**/
518,
/**/
517,
/**/
516,
/**/
515,
/**/
514,
/**/
513,
/**/
512,
/**/
511,
/**/
510,
/**/
509,
/**/
508,
/**/
507,
/**/
506,
/**/
505,
/**/
504,
/**/
503,
/**/
502,
/**/
501,
/**/
500,
/**/
499,
/**/
498,
/**/
497,
/**/
496,
/**/
495,
/**/
494,
/**/
493,
/**/
492,
/**/
491,
/**/
490,
/**/
489,
/**/
488,
/**/
487,
/**/
486,
/**/
485,
/**/
484,
/**/
483,
/**/
482,
/**/
481,
/**/
480,
/**/
479,
/**/
478,
/**/
477,
/**/
476,
/**/
475,
/**/
474,
/**/
473,
/**/
472,
/**/
471,
/**/
470,
/**/
469,
/**/
468,
/**/
467,
/**/
466,
/**/
465,
/**/
464,
/**/
463,
/**/
462,
/**/
461,
/**/
460,
/**/
459,
/**/
458,
/**/
457,
/**/
456,
/**/
455,
/**/
454,
/**/
453,
/**/
452,
/**/
451,
/**/
450,
/**/
449,
/**/
448,
/**/
447,
/**/
446,
/**/
445,
/**/
444,
/**/
443,
/**/
442,
/**/
441,
/**/
440,
/**/
439,
/**/
438,
/**/
437,
/**/
436,
/**/
435,
/**/
434,
/**/
433,
/**/
432,
/**/
431,
/**/
430,
/**/
429,
/**/
428,
/**/
427,
/**/
426,
/**/
425,
/**/
424,
/**/
423,
/**/
422,
/**/
421,
/**/
420,
/**/
419,
/**/
418,
/**/
417,
/**/
416,
/**/
415,
/**/
414,
/**/
413,
/**/
412,
/**/
411,
/**/
410,
/**/
409,
/**/
408,
/**/
407,
/**/
406,
/**/
405,
/**/
404,
/**/
403,
/**/
402,
/**/
401,
/**/
400,
/**/
399,
/**/
398,
/**/
397,
/**/
396,
/**/
395,
/**/
394,
/**/
393,
/**/
392,
/**/
391,
/**/
390,
/**/
389,
/**/
388,
/**/
387,
/**/
386,
/**/
385,
/**/
384,
/**/
383,
/**/
382,
/**/
381,
/**/
380,
/**/
379,
/**/
378,
/**/
377,
/**/
376,
/**/
375,
/**/
374,
/**/
373,
/**/
372,
/**/
371,
/**/
370,
/**/
369,
/**/
368,
/**/
367,
/**/
366,
/**/
365,
/**/
364,
/**/
363,
/**/
362,
/**/
361,
/**/
360,
/**/
359,
/**/
358,
/**/
357,
/**/
356,
/**/
355,
/**/
354,
/**/
353,
/**/
352,
/**/
351,
/**/
350,
/**/
349,
/**/
348,
/**/
347,
/**/
346,
/**/
345,
/**/
344,
/**/
343,
/**/
342,
/**/
341,
/**/
340,
/**/
339,
/**/
338,
/**/
337,
/**/
336,
/**/
335,
/**/
334,
/**/
333,
/**/
332,
/**/
331,
/**/
330,
/**/
329,
/**/
328,
/**/
327,
/**/
326,
/**/
325,
/**/
324,
/**/
323,
/**/
322,
/**/
321,
/**/
320,
/**/
319,
/**/
318,
/**/
317,
/**/
316,
/**/
315,
/**/
314,
/**/
313,
/**/
312,
/**/
311,
/**/
310,
/**/
309,
/**/
308,
/**/
307,
/**/
306,
/**/
305,
/**/
304,
/**/
303,
/**/
302,
/**/
301,
/**/
300,
/**/
299,
/**/
298,
/**/
297,
/**/
296,
/**/
295,
/**/
294,
/**/
293,
/**/
292,
/**/
291,
/**/
290,
/**/
289,
/**/
288,
/**/
287,
/**/
286,
/**/
285,
/**/
284,
/**/
283,
/**/
282,
/**/
281,
/**/
280,
/**/
279,
/**/
278,
/**/
277,
/**/
276,
/**/
275,
/**/
274,
/**/
273,
/**/
272,
/**/
271,
/**/
270,
/**/
269,
/**/
268,
/**/
267,
/**/
266,
/**/
265,
/**/
264,
/**/
263,
/**/
262,
/**/
261,
/**/
260,
/**/
259,
/**/
258,
/**/
257,
/**/
256,
/**/
255,
/**/
254,
/**/
253,
/**/
252,
/**/
251,
/**/
250,
/**/
249,
/**/
248,
/**/
247,
/**/
246,
/**/
245,
/**/
244,
/**/
243,
/**/
242,
/**/
241,
/**/
240,
/**/
239,
/**/
238,
/**/
237,
/**/
236,
/**/
235,
/**/
234,
/**/
233,
/**/
232,
/**/
231,
/**/
230,
/**/
229,
/**/
228,
/**/
227,
/**/
226,
/**/
225,
/**/
224,
/**/
223,
/**/
222,
/**/
221,
/**/
220,
/**/
219,
/**/
218,
/**/
217,
/**/
216,
/**/
215,
/**/
214,
/**/
213,
/**/
212,
/**/
211,
/**/
210,
/**/
209,
/**/
208,
/**/
207,
/**/
206,
/**/
205,
/**/
204,
/**/
203,
/**/
202,
/**/
201,
/**/
200,
/**/
199,
/**/
198,
/**/
197,
/**/
196,
/**/
195,
/**/
194,
/**/
193,
/**/
192,
/**/
191,
/**/
190,
/**/
189,
/**/
188,
/**/
187,
/**/
186,
/**/
185,
/**/
184,
/**/
183,
/**/
182,
/**/
181,
/**/
180,
/**/
179,
/**/
178,
/**/
177,
/**/
176,
/**/
175,
/**/
174,
/**/
173,
/**/
172,
/**/
171,
/**/
170,
/**/
169,
/**/
168,
/**/
167,
/**/
166,
/**/
165,
/**/
164,
/**/
163,
/**/
162,
/**/
161,
/**/
160,
/**/
159,
/**/
158,
/**/
157,
/**/
156,
/**/
155,
/**/
154,
/**/
153,
/**/
152,
/**/
151,
/**/
150,
/**/
149,
/**/
148,
/**/
147,
/**/
146,
/**/
145,
/**/
144,
/**/
143,
/**/
142,
/**/
141,
/**/
140,
/**/
139,
/**/
138,
/**/
137,
/**/
136,
/**/
135,
/**/
134,
/**/
133,
/**/
132,
/**/
131,
/**/
130,
/**/
129,
/**/
128,
/**/
127,
/**/
126,
/**/
125,
/**/
124,
/**/
123,
/**/
122,
/**/
121,
/**/
120,
/**/
119,
/**/
118,
/**/
117,
/**/
116,
/**/
115,
/**/
114,
/**/
113,
/**/
112,
/**/
111,
/**/
110,
/**/
109,
/**/
108,
/**/
107,
/**/
106,
/**/
105,
/**/
104,
/**/
103,
/**/
102,
/**/
101,
/**/
100,
/**/
99,
/**/
98,
/**/
97,
/**/
96,
/**/
95,
/**/
94,
/**/
93,
/**/
92,
/**/
91,
/**/
90,
/**/
89,
/**/
88,
/**/
87,
/**/
86,
/**/
85,
/**/
84,
/**/
83,
/**/
82,
/**/
81,
/**/
80,
/**/
79,
/**/
78,
/**/
77,
/**/
76,
/**/
75,
/**/
74,
/**/
73,
/**/
72,
/**/
71,
/**/
70,
/**/
69,
/**/
68,
/**/
67,
/**/
66,
/**/
65,
/**/
64,
/**/
63,
/**/
62,
/**/
61,
/**/
60,
/**/
59,
/**/
58,
/**/
57,
/**/
56,
/**/
55,
/**/
54,
/**/
53,
/**/
52,
/**/
51,
/**/
50,
/**/
49,
/**/
48,
/**/
47,
/**/
46,
/**/
45,
/**/
44,
/**/
43,
/**/
42,
/**/
41,
/**/
40,
/**/
39,
/**/
38,
/**/
37,
/**/
36,
/**/
35,
/**/
34,
/**/
33,
/**/
32,
/**/
31,
/**/
30,
/**/
29,
/**/
28,
/**/
27,
/**/
26,
/**/
25,
/**/
24,
/**/
23,
/**/
22,
/**/
21,
/**/
20,
/**/
19,
/**/
18,
/**/
17,
/**/
16,
/**/
15,
/**/
14,
/**/
13,
/**/
12,
/**/
11,
/**/
10,
/**/
9,
/**/
8,
/**/
7,
/**/
6,
/**/
5,
/**/
4,
/**/
3,
/**/
2,
/**/
1,
/**/
0
};
/*
* Place to put a short description when adding a feature with a patch.
* Keep it short, e.g.,: "relative numbers", "persistent undo".
* Also add a comment marker to separate the lines.
* See the official Vim patches for the diff format: It must use a context of
* one line only. Create it by hand or use "diff -C2" and edit the patch.
*/
static char *(extra_patches[]) =
{ /* Add your patch description below this line */
/**/
NULL
};
int
highest_patch()
{
int i;
int h = 0;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] > h)
h = included_patches[i];
return h;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if patch "n" has been included.
*/
int
has_patch(n)
int n;
{
int i;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] == n)
return TRUE;
return FALSE;
}
#endif
void
ex_version(eap)
exarg_T *eap;
{
/*
* Ignore a ":version 9.99" command.
*/
if (*eap->arg == NUL)
{
msg_putchar('\n');
list_version();
}
}
void
list_version()
{
int i;
int first;
char *s = "";
/*
* When adding features here, don't forget to update the list of
* internal variables in eval.c!
*/
MSG(longVersion);
#ifdef WIN3264
# ifdef FEAT_GUI_W32
# if defined(_MSC_VER) && (_MSC_VER <= 1010)
/* Only MS VC 4.1 and earlier can do Win32s */
MSG_PUTS(_("\nMS-Windows 16/32-bit GUI version"));
# else
# ifdef _WIN64
MSG_PUTS(_("\nMS-Windows 64-bit GUI version"));
# else
MSG_PUTS(_("\nMS-Windows 32-bit GUI version"));
# endif
# endif
if (gui_is_win32s())
MSG_PUTS(_(" in Win32s mode"));
# ifdef FEAT_OLE
MSG_PUTS(_(" with OLE support"));
# endif
# else
# ifdef _WIN64
MSG_PUTS(_("\nMS-Windows 64-bit console version"));
# else
MSG_PUTS(_("\nMS-Windows 32-bit console version"));
# endif
# endif
#endif
#ifdef WIN16
MSG_PUTS(_("\nMS-Windows 16-bit version"));
#endif
#ifdef MSDOS
# ifdef DJGPP
MSG_PUTS(_("\n32-bit MS-DOS version"));
# else
MSG_PUTS(_("\n16-bit MS-DOS version"));
# endif
#endif
#ifdef MACOS
# ifdef MACOS_X
# ifdef MACOS_X_UNIX
MSG_PUTS(_("\nMacOS X (unix) version"));
# else
MSG_PUTS(_("\nMacOS X version"));
# endif
#else
MSG_PUTS(_("\nMacOS version"));
# endif
#endif
#ifdef VMS
MSG_PUTS(_("\nOpenVMS version"));
# ifdef HAVE_PATHDEF
if (*compiled_arch != NUL)
{
MSG_PUTS(" - ");
MSG_PUTS(compiled_arch);
}
# endif
#endif
/* Print the list of patch numbers if there is at least one. */
/* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */
if (included_patches[0] != 0)
{
MSG_PUTS(_("\nIncluded patches: "));
first = -1;
/* find last one */
for (i = 0; included_patches[i] != 0; ++i)
;
while (--i >= 0)
{
if (first < 0)
first = included_patches[i];
if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)
{
MSG_PUTS(s);
s = ", ";
msg_outnum((long)first);
if (first != included_patches[i])
{
MSG_PUTS("-");
msg_outnum((long)included_patches[i]);
}
first = -1;
}
}
}
/* Print the list of extra patch descriptions if there is at least one. */
if (extra_patches[0] != NULL)
{
MSG_PUTS(_("\nExtra patches: "));
s = "";
for (i = 0; extra_patches[i] != NULL; ++i)
{
MSG_PUTS(s);
s = ", ";
MSG_PUTS(extra_patches[i]);
}
}
#ifdef MODIFIED_BY
MSG_PUTS("\n");
MSG_PUTS(_("Modified by "));
MSG_PUTS(MODIFIED_BY);
#endif
#ifdef HAVE_PATHDEF
if (*compiled_user != NUL || *compiled_sys != NUL)
{
MSG_PUTS(_("\nCompiled "));
if (*compiled_user != NUL)
{
MSG_PUTS(_("by "));
MSG_PUTS(compiled_user);
}
if (*compiled_sys != NUL)
{
MSG_PUTS("@");
MSG_PUTS(compiled_sys);
}
}
#endif
#ifdef FEAT_HUGE
MSG_PUTS(_("\nHuge version "));
#else
# ifdef FEAT_BIG
MSG_PUTS(_("\nBig version "));
# else
# ifdef FEAT_NORMAL
MSG_PUTS(_("\nNormal version "));
# else
# ifdef FEAT_SMALL
MSG_PUTS(_("\nSmall version "));
# else
MSG_PUTS(_("\nTiny version "));
# endif
# endif
# endif
#endif
#ifndef FEAT_GUI
MSG_PUTS(_("without GUI."));
#else
# ifdef FEAT_GUI_GTK
# ifdef FEAT_GUI_GNOME
MSG_PUTS(_("with GTK2-GNOME GUI."));
# else
MSG_PUTS(_("with GTK2 GUI."));
# endif
# else
# ifdef FEAT_GUI_MOTIF
MSG_PUTS(_("with X11-Motif GUI."));
# else
# ifdef FEAT_GUI_ATHENA
# ifdef FEAT_GUI_NEXTAW
MSG_PUTS(_("with X11-neXtaw GUI."));
# else
MSG_PUTS(_("with X11-Athena GUI."));
# endif
# else
# ifdef FEAT_GUI_PHOTON
MSG_PUTS(_("with Photon GUI."));
# else
# if defined(MSWIN)
MSG_PUTS(_("with GUI."));
# else
# if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON
MSG_PUTS(_("with Carbon GUI."));
# else
# if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX
MSG_PUTS(_("with Cocoa GUI."));
# else
# if defined(MACOS)
MSG_PUTS(_("with (classic) GUI."));
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
version_msg(_(" Features included (+) or not (-):\n"));
/* print all the features */
for (i = 0; features[i] != NULL; ++i)
{
version_msg(features[i]);
if (msg_col > 0)
version_msg(" ");
}
version_msg("\n");
#ifdef SYS_VIMRC_FILE
version_msg(_(" system vimrc file: \""));
version_msg(SYS_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE
version_msg(_(" user vimrc file: \""));
version_msg(USR_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE2
version_msg(_(" 2nd user vimrc file: \""));
version_msg(USR_VIMRC_FILE2);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE3
version_msg(_(" 3rd user vimrc file: \""));
version_msg(USR_VIMRC_FILE3);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE
version_msg(_(" user exrc file: \""));
version_msg(USR_EXRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE2
version_msg(_(" 2nd user exrc file: \""));
version_msg(USR_EXRC_FILE2);
version_msg("\"\n");
#endif
#ifdef FEAT_GUI
# ifdef SYS_GVIMRC_FILE
version_msg(_(" system gvimrc file: \""));
version_msg(SYS_GVIMRC_FILE);
version_msg("\"\n");
# endif
version_msg(_(" user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE);
version_msg("\"\n");
# ifdef USR_GVIMRC_FILE2
version_msg(_("2nd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE2);
version_msg("\"\n");
# endif
# ifdef USR_GVIMRC_FILE3
version_msg(_("3rd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE3);
version_msg("\"\n");
# endif
#endif
#ifdef FEAT_GUI
# ifdef SYS_MENU_FILE
version_msg(_(" system menu file: \""));
version_msg(SYS_MENU_FILE);
version_msg("\"\n");
# endif
#endif
#ifdef HAVE_PATHDEF
if (*default_vim_dir != NUL)
{
version_msg(_(" fall-back for $VIM: \""));
version_msg((char *)default_vim_dir);
version_msg("\"\n");
}
if (*default_vimruntime_dir != NUL)
{
version_msg(_(" f-b for $VIMRUNTIME: \""));
version_msg((char *)default_vimruntime_dir);
version_msg("\"\n");
}
version_msg(_("Compilation: "));
version_msg((char *)all_cflags);
version_msg("\n");
#ifdef VMS
if (*compiler_version != NUL)
{
version_msg(_("Compiler: "));
version_msg((char *)compiler_version);
version_msg("\n");
}
#endif
version_msg(_("Linking: "));
version_msg((char *)all_lflags);
#endif
#ifdef DEBUG
version_msg("\n");
version_msg(_(" DEBUG BUILD"));
#endif
}
/*
* Output a string for the version message. If it's going to wrap, output a
* newline, unless the message is too long to fit on the screen anyway.
*/
static void
version_msg(s)
char *s;
{
int len = (int)STRLEN(s);
if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns
&& *s != '\n')
msg_putchar('\n');
if (!got_int)
MSG_PUTS(s);
}
static void do_intro_line __ARGS((int row, char_u *mesg, int add_version, int attr));
/*
* Give an introductory message about Vim.
* Only used when starting Vim on an empty file, without a file name.
* Or with the ":intro" command (for Sven :-).
*/
void
intro_message(colon)
int colon; /* TRUE for ":intro" */
{
int i;
int row;
int blanklines;
int sponsor;
char *p;
static char *(lines[]) =
{
N_("VIM - Vi IMproved"),
"",
N_("version "),
N_("by Bram Moolenaar et al."),
#ifdef MODIFIED_BY
" ",
#endif
N_("Vim is open source and freely distributable"),
"",
N_("Help poor children in Uganda!"),
N_("type :help iccf<Enter> for information "),
"",
N_("type :q<Enter> to exit "),
N_("type :help<Enter> or <F1> for on-line help"),
N_("type :help version7<Enter> for version info"),
NULL,
"",
N_("Running in Vi compatible mode"),
N_("type :set nocp<Enter> for Vim defaults"),
N_("type :help cp-default<Enter> for info on this"),
};
#ifdef FEAT_GUI
static char *(gui_lines[]) =
{
NULL,
NULL,
NULL,
NULL,
#ifdef MODIFIED_BY
NULL,
#endif
NULL,
NULL,
NULL,
N_("menu Help->Orphans for information "),
NULL,
N_("Running modeless, typed text is inserted"),
N_("menu Edit->Global Settings->Toggle Insert Mode "),
N_(" for two modes "),
NULL,
NULL,
NULL,
N_("menu Edit->Global Settings->Toggle Vi Compatible"),
N_(" for Vim defaults "),
};
#endif
/* blanklines = screen height - # message lines */
blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1);
if (!p_cp)
blanklines += 4; /* add 4 for not showing "Vi compatible" message */
#if defined(WIN3264) && !defined(FEAT_GUI_W32)
if (mch_windows95())
blanklines -= 3; /* subtract 3 for showing "Windows 95" message */
#endif
#ifdef FEAT_WINDOWS
/* Don't overwrite a statusline. Depends on 'cmdheight'. */
if (p_ls > 1)
blanklines -= Rows - topframe->fr_height;
#endif
if (blanklines < 0)
blanklines = 0;
/* Show the sponsor and register message one out of four times, the Uganda
* message two out of four times. */
sponsor = (int)time(NULL);
sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);
/* start displaying the message lines after half of the blank lines */
row = blanklines / 2;
if ((row >= 2 && Columns >= 50) || colon)
{
for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i)
{
p = lines[i];
#ifdef FEAT_GUI
if (p_im && gui.in_use && gui_lines[i] != NULL)
p = gui_lines[i];
#endif
if (p == NULL)
{
if (!p_cp)
break;
continue;
}
if (sponsor != 0)
{
if (strstr(p, "children") != NULL)
p = sponsor < 0
? N_("Sponsor Vim development!")
: N_("Become a registered Vim user!");
else if (strstr(p, "iccf") != NULL)
p = sponsor < 0
? N_("type :help sponsor<Enter> for information ")
: N_("type :help register<Enter> for information ");
else if (strstr(p, "Orphans") != NULL)
p = N_("menu Help->Sponsor/Register for information ");
}
if (*p != NUL)
do_intro_line(row, (char_u *)_(p), i == 2, 0);
++row;
}
#if defined(WIN3264) && !defined(FEAT_GUI_W32)
if (mch_windows95())
{
do_intro_line(++row,
(char_u *)_("WARNING: Windows 95/98/ME detected"),
FALSE, hl_attr(HLF_E));
do_intro_line(++row,
(char_u *)_("type :help windows95<Enter> for info on this"),
FALSE, 0);
}
#endif
}
/* Make the wait-return message appear just below the text. */
if (colon)
msg_row = row;
}
static void
do_intro_line(row, mesg, add_version, attr)
int row;
char_u *mesg;
int add_version;
int attr;
{
char_u vers[20];
int col;
char_u *p;
int l;
int clen;
#ifdef MODIFIED_BY
# define MODBY_LEN 150
char_u modby[MODBY_LEN];
if (*mesg == ' ')
{
vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1);
l = STRLEN(modby);
vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);
mesg = modby;
}
#endif
/* Center the message horizontally. */
col = vim_strsize(mesg);
if (add_version)
{
STRCPY(vers, mediumVersion);
if (highest_patch())
{
/* Check for 9.9x or 9.9xx, alpha/beta version */
if (isalpha((int)vers[3]))
{
int len = (isalpha((int)vers[4])) ? 5 : 4;
sprintf((char *)vers + len, ".%d%s", highest_patch(),
mediumVersion + len);
}
else
sprintf((char *)vers + 3, ".%d", highest_patch());
}
col += (int)STRLEN(vers);
}
col = (Columns - col) / 2;
if (col < 0)
col = 0;
/* Split up in parts to highlight <> items differently. */
for (p = mesg; *p != NUL; p += l)
{
clen = 0;
for (l = 0; p[l] != NUL
&& (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
clen += ptr2cells(p + l);
l += (*mb_ptr2len)(p + l) - 1;
}
else
#endif
clen += byte2cells(p[l]);
}
screen_puts_len(p, l, row, col, *p == '<' ? hl_attr(HLF_8) : attr);
col += clen;
}
/* Add the version number to the version line. */
if (add_version)
screen_puts(vers, row, col, 0);
}
/*
* ":intro": clear screen, display intro screen and wait for return.
*/
void
ex_intro(eap)
exarg_T *eap UNUSED;
{
screenclear();
intro_message(TRUE);
wait_return(TRUE);
}
| zyz2011-vim | src/version.c | C | gpl2 | 31,909 |
/* 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.
*/
/*
* hardcopy.c: printing to paper
*/
#include "vim.h"
#include "version.h"
#if defined(FEAT_PRINTER) || defined(PROTO)
/*
* To implement printing on a platform, the following functions must be
* defined:
*
* int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
* Called once. Code should display printer dialogue (if appropriate) and
* determine printer font and margin settings. Reset has_color if the printer
* doesn't support colors at all.
* Returns FAIL to abort.
*
* int mch_print_begin(prt_settings_T *settings)
* Called to start the print job.
* Return FALSE to abort.
*
* int mch_print_begin_page(char_u *msg)
* Called at the start of each page.
* "msg" indicates the progress of the print job, can be NULL.
* Return FALSE to abort.
*
* int mch_print_end_page()
* Called at the end of each page.
* Return FALSE to abort.
*
* int mch_print_blank_page()
* Called to generate a blank page for collated, duplex, multiple copy
* document. Return FALSE to abort.
*
* void mch_print_end(prt_settings_T *psettings)
* Called at normal end of print job.
*
* void mch_print_cleanup()
* Called if print job ends normally or is abandoned. Free any memory, close
* devices and handles. Also called when mch_print_begin() fails, but not
* when mch_print_init() fails.
*
* void mch_print_set_font(int Bold, int Italic, int Underline);
* Called whenever the font style changes.
*
* void mch_print_set_bg(long_u bgcol);
* Called to set the background color for the following text. Parameter is an
* RGB value.
*
* void mch_print_set_fg(long_u fgcol);
* Called to set the foreground color for the following text. Parameter is an
* RGB value.
*
* mch_print_start_line(int margin, int page_line)
* Sets the current position at the start of line "page_line".
* If margin is TRUE start in the left margin (for header and line number).
*
* int mch_print_text_out(char_u *p, int len);
* Output one character of text p[len] at the current position.
* Return TRUE if there is no room for another character in the same line.
*
* Note that the generic code has no idea of margins. The machine code should
* simply make the page look smaller! The header and the line numbers are
* printed in the margin.
*/
#ifdef FEAT_SYN_HL
static const long_u cterm_color_8[8] =
{
(long_u)0x000000L, (long_u)0xff0000L, (long_u)0x00ff00L, (long_u)0xffff00L,
(long_u)0x0000ffL, (long_u)0xff00ffL, (long_u)0x00ffffL, (long_u)0xffffffL
};
static const long_u cterm_color_16[16] =
{
(long_u)0x000000L, (long_u)0x0000c0L, (long_u)0x008000L, (long_u)0x004080L,
(long_u)0xc00000L, (long_u)0xc000c0L, (long_u)0x808000L, (long_u)0xc0c0c0L,
(long_u)0x808080L, (long_u)0x6060ffL, (long_u)0x00ff00L, (long_u)0x00ffffL,
(long_u)0xff8080L, (long_u)0xff40ffL, (long_u)0xffff00L, (long_u)0xffffffL
};
static int current_syn_id;
#endif
#define PRCOLOR_BLACK (long_u)0
#define PRCOLOR_WHITE (long_u)0xFFFFFFL
static int curr_italic;
static int curr_bold;
static int curr_underline;
static long_u curr_bg;
static long_u curr_fg;
static int page_count;
#if defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)
# define OPT_MBFONT_USECOURIER 0
# define OPT_MBFONT_ASCII 1
# define OPT_MBFONT_REGULAR 2
# define OPT_MBFONT_BOLD 3
# define OPT_MBFONT_OBLIQUE 4
# define OPT_MBFONT_BOLDOBLIQUE 5
# define OPT_MBFONT_NUM_OPTIONS 6
static option_table_T mbfont_opts[OPT_MBFONT_NUM_OPTIONS] =
{
{"c", FALSE, 0, NULL, 0, FALSE},
{"a", FALSE, 0, NULL, 0, FALSE},
{"r", FALSE, 0, NULL, 0, FALSE},
{"b", FALSE, 0, NULL, 0, FALSE},
{"i", FALSE, 0, NULL, 0, FALSE},
{"o", FALSE, 0, NULL, 0, FALSE},
};
#endif
/*
* These values determine the print position on a page.
*/
typedef struct
{
int lead_spaces; /* remaining spaces for a TAB */
int print_pos; /* virtual column for computing TABs */
colnr_T column; /* byte column */
linenr_T file_line; /* line nr in the buffer */
long_u bytes_printed; /* bytes printed so far */
int ff; /* seen form feed character */
} prt_pos_T;
static char_u *parse_list_options __ARGS((char_u *option_str, option_table_T *table, int table_size));
#ifdef FEAT_SYN_HL
static long_u darken_rgb __ARGS((long_u rgb));
static long_u prt_get_term_color __ARGS((int colorindex));
#endif
static void prt_set_fg __ARGS((long_u fg));
static void prt_set_bg __ARGS((long_u bg));
static void prt_set_font __ARGS((int bold, int italic, int underline));
static void prt_line_number __ARGS((prt_settings_T *psettings, int page_line, linenr_T lnum));
static void prt_header __ARGS((prt_settings_T *psettings, int pagenum, linenr_T lnum));
static void prt_message __ARGS((char_u *s));
static colnr_T hardcopy_line __ARGS((prt_settings_T *psettings, int page_line, prt_pos_T *ppos));
#ifdef FEAT_SYN_HL
static void prt_get_attr __ARGS((int hl_id, prt_text_attr_T* pattr, int modec));
#endif
/*
* Parse 'printoptions' and set the flags in "printer_opts".
* Returns an error message or NULL;
*/
char_u *
parse_printoptions()
{
return parse_list_options(p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS);
}
#if (defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)) || defined(PROTO)
/*
* Parse 'printoptions' and set the flags in "printer_opts".
* Returns an error message or NULL;
*/
char_u *
parse_printmbfont()
{
return parse_list_options(p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS);
}
#endif
/*
* Parse a list of options in the form
* option:value,option:value,option:value
*
* "value" can start with a number which is parsed out, e.g. margin:12mm
*
* Returns an error message for an illegal option, NULL otherwise.
* Only used for the printer at the moment...
*/
static char_u *
parse_list_options(option_str, table, table_size)
char_u *option_str;
option_table_T *table;
int table_size;
{
char_u *stringp;
char_u *colonp;
char_u *commap;
char_u *p;
int idx = 0; /* init for GCC */
int len;
for (idx = 0; idx < table_size; ++idx)
table[idx].present = FALSE;
/*
* Repeat for all comma separated parts.
*/
stringp = option_str;
while (*stringp)
{
colonp = vim_strchr(stringp, ':');
if (colonp == NULL)
return (char_u *)N_("E550: Missing colon");
commap = vim_strchr(stringp, ',');
if (commap == NULL)
commap = option_str + STRLEN(option_str);
len = (int)(colonp - stringp);
for (idx = 0; idx < table_size; ++idx)
if (STRNICMP(stringp, table[idx].name, len) == 0)
break;
if (idx == table_size)
return (char_u *)N_("E551: Illegal component");
p = colonp + 1;
table[idx].present = TRUE;
if (table[idx].hasnum)
{
if (!VIM_ISDIGIT(*p))
return (char_u *)N_("E552: digit expected");
table[idx].number = getdigits(&p); /*advances p*/
}
table[idx].string = p;
table[idx].strlen = (int)(commap - p);
stringp = commap;
if (*stringp == ',')
++stringp;
}
return NULL;
}
#ifdef FEAT_SYN_HL
/*
* If using a dark background, the colors will probably be too bright to show
* up well on white paper, so reduce their brightness.
*/
static long_u
darken_rgb(rgb)
long_u rgb;
{
return ((rgb >> 17) << 16)
+ (((rgb & 0xff00) >> 9) << 8)
+ ((rgb & 0xff) >> 1);
}
static long_u
prt_get_term_color(colorindex)
int colorindex;
{
/* TODO: Should check for xterm with 88 or 256 colors. */
if (t_colors > 8)
return cterm_color_16[colorindex % 16];
return cterm_color_8[colorindex % 8];
}
static void
prt_get_attr(hl_id, pattr, modec)
int hl_id;
prt_text_attr_T *pattr;
int modec;
{
int colorindex;
long_u fg_color;
long_u bg_color;
char *color;
pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL);
pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL);
pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL);
pattr->undercurl = (highlight_has_attr(hl_id, HL_UNDERCURL, modec) != NULL);
# ifdef FEAT_GUI
if (gui.in_use)
{
bg_color = highlight_gui_color_rgb(hl_id, FALSE);
if (bg_color == PRCOLOR_BLACK)
bg_color = PRCOLOR_WHITE;
fg_color = highlight_gui_color_rgb(hl_id, TRUE);
}
else
# endif
{
bg_color = PRCOLOR_WHITE;
color = (char *)highlight_color(hl_id, (char_u *)"fg", modec);
if (color == NULL)
colorindex = 0;
else
colorindex = atoi(color);
if (colorindex >= 0 && colorindex < t_colors)
fg_color = prt_get_term_color(colorindex);
else
fg_color = PRCOLOR_BLACK;
}
if (fg_color == PRCOLOR_WHITE)
fg_color = PRCOLOR_BLACK;
else if (*p_bg == 'd')
fg_color = darken_rgb(fg_color);
pattr->fg_color = fg_color;
pattr->bg_color = bg_color;
}
#endif /* FEAT_SYN_HL */
static void
prt_set_fg(fg)
long_u fg;
{
if (fg != curr_fg)
{
curr_fg = fg;
mch_print_set_fg(fg);
}
}
static void
prt_set_bg(bg)
long_u bg;
{
if (bg != curr_bg)
{
curr_bg = bg;
mch_print_set_bg(bg);
}
}
static void
prt_set_font(bold, italic, underline)
int bold;
int italic;
int underline;
{
if (curr_bold != bold
|| curr_italic != italic
|| curr_underline != underline)
{
curr_underline = underline;
curr_italic = italic;
curr_bold = bold;
mch_print_set_font(bold, italic, underline);
}
}
/*
* Print the line number in the left margin.
*/
static void
prt_line_number(psettings, page_line, lnum)
prt_settings_T *psettings;
int page_line;
linenr_T lnum;
{
int i;
char_u tbuf[20];
prt_set_fg(psettings->number.fg_color);
prt_set_bg(psettings->number.bg_color);
prt_set_font(psettings->number.bold, psettings->number.italic, psettings->number.underline);
mch_print_start_line(TRUE, page_line);
/* Leave two spaces between the number and the text; depends on
* PRINT_NUMBER_WIDTH. */
sprintf((char *)tbuf, "%6ld", (long)lnum);
for (i = 0; i < 6; i++)
(void)mch_print_text_out(&tbuf[i], 1);
#ifdef FEAT_SYN_HL
if (psettings->do_syntax)
/* Set colors for next character. */
current_syn_id = -1;
else
#endif
{
/* Set colors and font back to normal. */
prt_set_fg(PRCOLOR_BLACK);
prt_set_bg(PRCOLOR_WHITE);
prt_set_font(FALSE, FALSE, FALSE);
}
}
/*
* Get the currently effective header height.
*/
int
prt_header_height()
{
if (printer_opts[OPT_PRINT_HEADERHEIGHT].present)
return printer_opts[OPT_PRINT_HEADERHEIGHT].number;
return 2;
}
/*
* Return TRUE if using a line number for printing.
*/
int
prt_use_number()
{
return (printer_opts[OPT_PRINT_NUMBER].present
&& TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y');
}
/*
* Return the unit used in a margin item in 'printoptions'.
* Returns PRT_UNIT_NONE if not recognized.
*/
int
prt_get_unit(idx)
int idx;
{
int u = PRT_UNIT_NONE;
int i;
static char *(units[4]) = PRT_UNIT_NAMES;
if (printer_opts[idx].present)
for (i = 0; i < 4; ++i)
if (STRNICMP(printer_opts[idx].string, units[i], 2) == 0)
{
u = i;
break;
}
return u;
}
/*
* Print the page header.
*/
static void
prt_header(psettings, pagenum, lnum)
prt_settings_T *psettings;
int pagenum;
linenr_T lnum UNUSED;
{
int width = psettings->chars_per_line;
int page_line;
char_u *tbuf;
char_u *p;
#ifdef FEAT_MBYTE
int l;
#endif
/* Also use the space for the line number. */
if (prt_use_number())
width += PRINT_NUMBER_WIDTH;
tbuf = alloc(width + IOSIZE);
if (tbuf == NULL)
return;
#ifdef FEAT_STL_OPT
if (*p_header != NUL)
{
linenr_T tmp_lnum, tmp_topline, tmp_botline;
int use_sandbox = FALSE;
/*
* Need to (temporarily) set current line number and first/last line
* number on the 'window'. Since we don't know how long the page is,
* set the first and current line number to the top line, and guess
* that the page length is 64.
*/
tmp_lnum = curwin->w_cursor.lnum;
tmp_topline = curwin->w_topline;
tmp_botline = curwin->w_botline;
curwin->w_cursor.lnum = lnum;
curwin->w_topline = lnum;
curwin->w_botline = lnum + 63;
printer_page_num = pagenum;
# ifdef FEAT_EVAL
use_sandbox = was_set_insecurely((char_u *)"printheader", 0);
# endif
build_stl_str_hl(curwin, tbuf, (size_t)(width + IOSIZE),
p_header, use_sandbox,
' ', width, NULL, NULL);
/* Reset line numbers */
curwin->w_cursor.lnum = tmp_lnum;
curwin->w_topline = tmp_topline;
curwin->w_botline = tmp_botline;
}
else
#endif
sprintf((char *)tbuf, _("Page %d"), pagenum);
prt_set_fg(PRCOLOR_BLACK);
prt_set_bg(PRCOLOR_WHITE);
prt_set_font(TRUE, FALSE, FALSE);
/* Use a negative line number to indicate printing in the top margin. */
page_line = 0 - prt_header_height();
mch_print_start_line(TRUE, page_line);
for (p = tbuf; *p != NUL; )
{
if (mch_print_text_out(p,
#ifdef FEAT_MBYTE
(l = (*mb_ptr2len)(p))
#else
1
#endif
))
{
++page_line;
if (page_line >= 0) /* out of room in header */
break;
mch_print_start_line(TRUE, page_line);
}
#ifdef FEAT_MBYTE
p += l;
#else
p++;
#endif
}
vim_free(tbuf);
#ifdef FEAT_SYN_HL
if (psettings->do_syntax)
/* Set colors for next character. */
current_syn_id = -1;
else
#endif
{
/* Set colors and font back to normal. */
prt_set_fg(PRCOLOR_BLACK);
prt_set_bg(PRCOLOR_WHITE);
prt_set_font(FALSE, FALSE, FALSE);
}
}
/*
* Display a print status message.
*/
static void
prt_message(s)
char_u *s;
{
screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
screen_puts(s, (int)Rows - 1, 0, hl_attr(HLF_R));
out_flush();
}
void
ex_hardcopy(eap)
exarg_T *eap;
{
linenr_T lnum;
int collated_copies, uncollated_copies;
prt_settings_T settings;
long_u bytes_to_print = 0;
int page_line;
int jobsplit;
vim_memset(&settings, 0, sizeof(prt_settings_T));
settings.has_color = TRUE;
# ifdef FEAT_POSTSCRIPT
if (*eap->arg == '>')
{
char_u *errormsg = NULL;
/* Expand things like "%.ps". */
if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL)
{
if (errormsg != NULL)
EMSG(errormsg);
return;
}
settings.outfile = skipwhite(eap->arg + 1);
}
else if (*eap->arg != NUL)
settings.arguments = eap->arg;
# endif
/*
* Initialise for printing. Ask the user for settings, unless forceit is
* set.
* The mch_print_init() code should set up margins if applicable. (It may
* not be a real printer - for example the engine might generate HTML or
* PS.)
*/
if (mch_print_init(&settings,
curbuf->b_fname == NULL
? (char_u *)buf_spname(curbuf)
: curbuf->b_sfname == NULL
? curbuf->b_fname
: curbuf->b_sfname,
eap->forceit) == FAIL)
return;
#ifdef FEAT_SYN_HL
# ifdef FEAT_GUI
if (gui.in_use)
settings.modec = 'g';
else
# endif
if (t_colors > 1)
settings.modec = 'c';
else
settings.modec = 't';
if (!syntax_present(curwin))
settings.do_syntax = FALSE;
else if (printer_opts[OPT_PRINT_SYNTAX].present
&& TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) != 'a')
settings.do_syntax =
(TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) == 'y');
else
settings.do_syntax = settings.has_color;
#endif
/* Set up printing attributes for line numbers */
settings.number.fg_color = PRCOLOR_BLACK;
settings.number.bg_color = PRCOLOR_WHITE;
settings.number.bold = FALSE;
settings.number.italic = TRUE;
settings.number.underline = FALSE;
#ifdef FEAT_SYN_HL
/*
* Syntax highlighting of line numbers.
*/
if (prt_use_number() && settings.do_syntax)
{
int id;
id = syn_name2id((char_u *)"LineNr");
if (id > 0)
id = syn_get_final_id(id);
prt_get_attr(id, &settings.number, settings.modec);
}
#endif
/*
* Estimate the total lines to be printed
*/
for (lnum = eap->line1; lnum <= eap->line2; lnum++)
bytes_to_print += (long_u)STRLEN(skipwhite(ml_get(lnum)));
if (bytes_to_print == 0)
{
MSG(_("No text to be printed"));
goto print_fail_no_begin;
}
/* Set colors and font to normal. */
curr_bg = (long_u)0xffffffffL;
curr_fg = (long_u)0xffffffffL;
curr_italic = MAYBE;
curr_bold = MAYBE;
curr_underline = MAYBE;
prt_set_fg(PRCOLOR_BLACK);
prt_set_bg(PRCOLOR_WHITE);
prt_set_font(FALSE, FALSE, FALSE);
#ifdef FEAT_SYN_HL
current_syn_id = -1;
#endif
jobsplit = (printer_opts[OPT_PRINT_JOBSPLIT].present
&& TOLOWER_ASC(printer_opts[OPT_PRINT_JOBSPLIT].string[0]) == 'y');
if (!mch_print_begin(&settings))
goto print_fail_no_begin;
/*
* Loop over collated copies: 1 2 3, 1 2 3, ...
*/
page_count = 0;
for (collated_copies = 0;
collated_copies < settings.n_collated_copies;
collated_copies++)
{
prt_pos_T prtpos; /* current print position */
prt_pos_T page_prtpos; /* print position at page start */
int side;
vim_memset(&page_prtpos, 0, sizeof(prt_pos_T));
page_prtpos.file_line = eap->line1;
prtpos = page_prtpos;
if (jobsplit && collated_copies > 0)
{
/* Splitting jobs: Stop a previous job and start a new one. */
mch_print_end(&settings);
if (!mch_print_begin(&settings))
goto print_fail_no_begin;
}
/*
* Loop over all pages in the print job: 1 2 3 ...
*/
for (page_count = 0; prtpos.file_line <= eap->line2; ++page_count)
{
/*
* Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ...
* For duplex: 12 12 12 34 34 34, ...
*/
for (uncollated_copies = 0;
uncollated_copies < settings.n_uncollated_copies;
uncollated_copies++)
{
/* Set the print position to the start of this page. */
prtpos = page_prtpos;
/*
* Do front and rear side of a page.
*/
for (side = 0; side <= settings.duplex; ++side)
{
/*
* Print one page.
*/
/* Check for interrupt character every page. */
ui_breakcheck();
if (got_int || settings.user_abort)
goto print_fail;
sprintf((char *)IObuff, _("Printing page %d (%d%%)"),
page_count + 1 + side,
prtpos.bytes_printed > 1000000
? (int)(prtpos.bytes_printed /
(bytes_to_print / 100))
: (int)((prtpos.bytes_printed * 100)
/ bytes_to_print));
if (!mch_print_begin_page(IObuff))
goto print_fail;
if (settings.n_collated_copies > 1)
sprintf((char *)IObuff + STRLEN(IObuff),
_(" Copy %d of %d"),
collated_copies + 1,
settings.n_collated_copies);
prt_message(IObuff);
/*
* Output header if required
*/
if (prt_header_height() > 0)
prt_header(&settings, page_count + 1 + side,
prtpos.file_line);
for (page_line = 0; page_line < settings.lines_per_page;
++page_line)
{
prtpos.column = hardcopy_line(&settings,
page_line, &prtpos);
if (prtpos.column == 0)
{
/* finished a file line */
prtpos.bytes_printed +=
STRLEN(skipwhite(ml_get(prtpos.file_line)));
if (++prtpos.file_line > eap->line2)
break; /* reached the end */
}
else if (prtpos.ff)
{
/* Line had a formfeed in it - start new page but
* stay on the current line */
break;
}
}
if (!mch_print_end_page())
goto print_fail;
if (prtpos.file_line > eap->line2)
break; /* reached the end */
}
/*
* Extra blank page for duplexing with odd number of pages and
* more copies to come.
*/
if (prtpos.file_line > eap->line2 && settings.duplex
&& side == 0
&& uncollated_copies + 1 < settings.n_uncollated_copies)
{
if (!mch_print_blank_page())
goto print_fail;
}
}
if (settings.duplex && prtpos.file_line <= eap->line2)
++page_count;
/* Remember the position where the next page starts. */
page_prtpos = prtpos;
}
vim_snprintf((char *)IObuff, IOSIZE, _("Printed: %s"),
settings.jobname);
prt_message(IObuff);
}
print_fail:
if (got_int || settings.user_abort)
{
sprintf((char *)IObuff, "%s", _("Printing aborted"));
prt_message(IObuff);
}
mch_print_end(&settings);
print_fail_no_begin:
mch_print_cleanup();
}
/*
* Print one page line.
* Return the next column to print, or zero if the line is finished.
*/
static colnr_T
hardcopy_line(psettings, page_line, ppos)
prt_settings_T *psettings;
int page_line;
prt_pos_T *ppos;
{
colnr_T col;
char_u *line;
int need_break = FALSE;
int outputlen;
int tab_spaces;
long_u print_pos;
#ifdef FEAT_SYN_HL
prt_text_attr_T attr;
int id;
#endif
if (ppos->column == 0 || ppos->ff)
{
print_pos = 0;
tab_spaces = 0;
if (!ppos->ff && prt_use_number())
prt_line_number(psettings, page_line, ppos->file_line);
ppos->ff = FALSE;
}
else
{
/* left over from wrap halfway a tab */
print_pos = ppos->print_pos;
tab_spaces = ppos->lead_spaces;
}
mch_print_start_line(0, page_line);
line = ml_get(ppos->file_line);
/*
* Loop over the columns until the end of the file line or right margin.
*/
for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen)
{
outputlen = 1;
#ifdef FEAT_MBYTE
if (has_mbyte && (outputlen = (*mb_ptr2len)(line + col)) < 1)
outputlen = 1;
#endif
#ifdef FEAT_SYN_HL
/*
* syntax highlighting stuff.
*/
if (psettings->do_syntax)
{
id = syn_get_id(curwin, ppos->file_line, col, 1, NULL, FALSE);
if (id > 0)
id = syn_get_final_id(id);
else
id = 0;
/* Get the line again, a multi-line regexp may invalidate it. */
line = ml_get(ppos->file_line);
if (id != current_syn_id)
{
current_syn_id = id;
prt_get_attr(id, &attr, psettings->modec);
prt_set_font(attr.bold, attr.italic, attr.underline);
prt_set_fg(attr.fg_color);
prt_set_bg(attr.bg_color);
}
}
#endif
/*
* Appropriately expand any tabs to spaces.
*/
if (line[col] == TAB || tab_spaces != 0)
{
if (tab_spaces == 0)
tab_spaces = (int)(curbuf->b_p_ts - (print_pos % curbuf->b_p_ts));
while (tab_spaces > 0)
{
need_break = mch_print_text_out((char_u *)" ", 1);
print_pos++;
tab_spaces--;
if (need_break)
break;
}
/* Keep the TAB if we didn't finish it. */
if (need_break && tab_spaces > 0)
break;
}
else if (line[col] == FF
&& printer_opts[OPT_PRINT_FORMFEED].present
&& TOLOWER_ASC(printer_opts[OPT_PRINT_FORMFEED].string[0])
== 'y')
{
ppos->ff = TRUE;
need_break = 1;
}
else
{
need_break = mch_print_text_out(line + col, outputlen);
#ifdef FEAT_MBYTE
if (has_mbyte)
print_pos += (*mb_ptr2cells)(line + col);
else
#endif
print_pos++;
}
}
ppos->lead_spaces = tab_spaces;
ppos->print_pos = (int)print_pos;
/*
* Start next line of file if we clip lines, or have reached end of the
* line, unless we are doing a formfeed.
*/
if (!ppos->ff
&& (line[col] == NUL
|| (printer_opts[OPT_PRINT_WRAP].present
&& TOLOWER_ASC(printer_opts[OPT_PRINT_WRAP].string[0])
== 'n')))
return 0;
return col;
}
# if defined(FEAT_POSTSCRIPT) || defined(PROTO)
/*
* PS printer stuff.
*
* Sources of information to help maintain the PS printing code:
*
* 1. PostScript Language Reference, 3rd Edition,
* Addison-Wesley, 1999, ISBN 0-201-37922-8
* 2. PostScript Language Program Design,
* Addison-Wesley, 1988, ISBN 0-201-14396-8
* 3. PostScript Tutorial and Cookbook,
* Addison Wesley, 1985, ISBN 0-201-10179-3
* 4. PostScript Language Document Structuring Conventions Specification,
* version 3.0,
* Adobe Technote 5001, 25th September 1992
* 5. PostScript Printer Description File Format Specification, Version 4.3,
* Adobe technote 5003, 9th February 1996
* 6. Adobe Font Metrics File Format Specification, Version 4.1,
* Adobe Technote 5007, 7th October 1998
* 7. Adobe CMap and CIDFont Files Specification, Version 1.0,
* Adobe Technote 5014, 8th October 1996
* 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts,
* Adoboe Technote 5094, 8th September, 2001
* 9. CJKV Information Processing, 2nd Edition,
* O'Reilly, 2002, ISBN 1-56592-224-7
*
* Some of these documents can be found in PDF form on Adobe's web site -
* http://www.adobe.com
*/
#define NUM_ELEMENTS(arr) (sizeof(arr)/sizeof((arr)[0]))
#define PRT_PS_DEFAULT_DPI (72) /* Default user space resolution */
#define PRT_PS_DEFAULT_FONTSIZE (10)
#define PRT_PS_DEFAULT_BUFFER_SIZE (80)
struct prt_mediasize_S
{
char *name;
float width; /* width and height in points for portrait */
float height;
};
#define PRT_MEDIASIZE_LEN (sizeof(prt_mediasize) / sizeof(struct prt_mediasize_S))
static struct prt_mediasize_S prt_mediasize[] =
{
{"A4", 595.0, 842.0},
{"letter", 612.0, 792.0},
{"10x14", 720.0, 1008.0},
{"A3", 842.0, 1191.0},
{"A5", 420.0, 595.0},
{"B4", 729.0, 1032.0},
{"B5", 516.0, 729.0},
{"executive", 522.0, 756.0},
{"folio", 595.0, 935.0},
{"ledger", 1224.0, 792.0}, /* Yes, it is wider than taller! */
{"legal", 612.0, 1008.0},
{"quarto", 610.0, 780.0},
{"statement", 396.0, 612.0},
{"tabloid", 792.0, 1224.0}
};
/* PS font names, must be in Roman, Bold, Italic, Bold-Italic order */
struct prt_ps_font_S
{
int wx;
int uline_offset;
int uline_width;
int bbox_min_y;
int bbox_max_y;
char *(ps_fontname[4]);
};
#define PRT_PS_FONT_ROMAN (0)
#define PRT_PS_FONT_BOLD (1)
#define PRT_PS_FONT_OBLIQUE (2)
#define PRT_PS_FONT_BOLDOBLIQUE (3)
/* Standard font metrics for Courier family */
static struct prt_ps_font_S prt_ps_courier_font =
{
600,
-100, 50,
-250, 805,
{"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique"}
};
#ifdef FEAT_MBYTE
/* Generic font metrics for multi-byte fonts */
static struct prt_ps_font_S prt_ps_mb_font =
{
1000,
-100, 50,
-250, 805,
{NULL, NULL, NULL, NULL}
};
#endif
/* Pointer to current font set being used */
static struct prt_ps_font_S* prt_ps_font;
/* Structures to map user named encoding and mapping to PS equivalents for
* building CID font name */
struct prt_ps_encoding_S
{
char *encoding;
char *cmap_encoding;
int needs_charset;
};
struct prt_ps_charset_S
{
char *charset;
char *cmap_charset;
int has_charset;
};
#ifdef FEAT_MBYTE
#define CS_JIS_C_1978 (0x01)
#define CS_JIS_X_1983 (0x02)
#define CS_JIS_X_1990 (0x04)
#define CS_NEC (0x08)
#define CS_MSWINDOWS (0x10)
#define CS_CP932 (0x20)
#define CS_KANJITALK6 (0x40)
#define CS_KANJITALK7 (0x80)
/* Japanese encodings and charsets */
static struct prt_ps_encoding_S j_encodings[] =
{
{"iso-2022-jp", NULL, (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990|
CS_NEC)},
{"euc-jp", "EUC", (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990)},
{"sjis", "RKSJ", (CS_JIS_C_1978|CS_JIS_X_1983|CS_MSWINDOWS|
CS_KANJITALK6|CS_KANJITALK7)},
{"cp932", "RKSJ", CS_JIS_X_1983},
{"ucs-2", "UCS2", CS_JIS_X_1990},
{"utf-8", "UTF8" , CS_JIS_X_1990}
};
static struct prt_ps_charset_S j_charsets[] =
{
{"JIS_C_1978", "78", CS_JIS_C_1978},
{"JIS_X_1983", NULL, CS_JIS_X_1983},
{"JIS_X_1990", "Hojo", CS_JIS_X_1990},
{"NEC", "Ext", CS_NEC},
{"MSWINDOWS", "90ms", CS_MSWINDOWS},
{"CP932", "90ms", CS_JIS_X_1983},
{"KANJITALK6", "83pv", CS_KANJITALK6},
{"KANJITALK7", "90pv", CS_KANJITALK7}
};
#define CS_GB_2312_80 (0x01)
#define CS_GBT_12345_90 (0x02)
#define CS_GBK2K (0x04)
#define CS_SC_MAC (0x08)
#define CS_GBT_90_MAC (0x10)
#define CS_GBK (0x20)
#define CS_SC_ISO10646 (0x40)
/* Simplified Chinese encodings and charsets */
static struct prt_ps_encoding_S sc_encodings[] =
{
{"iso-2022", NULL, (CS_GB_2312_80|CS_GBT_12345_90)},
{"gb18030", NULL, CS_GBK2K},
{"euc-cn", "EUC", (CS_GB_2312_80|CS_GBT_12345_90|CS_SC_MAC|
CS_GBT_90_MAC)},
{"gbk", "EUC", CS_GBK},
{"ucs-2", "UCS2", CS_SC_ISO10646},
{"utf-8", "UTF8", CS_SC_ISO10646}
};
static struct prt_ps_charset_S sc_charsets[] =
{
{"GB_2312-80", "GB", CS_GB_2312_80},
{"GBT_12345-90","GBT", CS_GBT_12345_90},
{"MAC", "GBpc", CS_SC_MAC},
{"GBT-90_MAC", "GBTpc", CS_GBT_90_MAC},
{"GBK", "GBK", CS_GBK},
{"GB18030", "GBK2K", CS_GBK2K},
{"ISO10646", "UniGB", CS_SC_ISO10646}
};
#define CS_CNS_PLANE_1 (0x01)
#define CS_CNS_PLANE_2 (0x02)
#define CS_CNS_PLANE_1_2 (0x04)
#define CS_B5 (0x08)
#define CS_ETEN (0x10)
#define CS_HK_GCCS (0x20)
#define CS_HK_SCS (0x40)
#define CS_HK_SCS_ETEN (0x80)
#define CS_MTHKL (0x100)
#define CS_MTHKS (0x200)
#define CS_DLHKL (0x400)
#define CS_DLHKS (0x800)
#define CS_TC_ISO10646 (0x1000)
/* Traditional Chinese encodings and charsets */
static struct prt_ps_encoding_S tc_encodings[] =
{
{"iso-2022", NULL, (CS_CNS_PLANE_1|CS_CNS_PLANE_2)},
{"euc-tw", "EUC", CS_CNS_PLANE_1_2},
{"big5", "B5", (CS_B5|CS_ETEN|CS_HK_GCCS|CS_HK_SCS|
CS_HK_SCS_ETEN|CS_MTHKL|CS_MTHKS|CS_DLHKL|
CS_DLHKS)},
{"cp950", "B5", CS_B5},
{"ucs-2", "UCS2", CS_TC_ISO10646},
{"utf-8", "UTF8", CS_TC_ISO10646},
{"utf-16", "UTF16", CS_TC_ISO10646},
{"utf-32", "UTF32", CS_TC_ISO10646}
};
static struct prt_ps_charset_S tc_charsets[] =
{
{"CNS_1992_1", "CNS1", CS_CNS_PLANE_1},
{"CNS_1992_2", "CNS2", CS_CNS_PLANE_2},
{"CNS_1993", "CNS", CS_CNS_PLANE_1_2},
{"BIG5", NULL, CS_B5},
{"CP950", NULL, CS_B5},
{"ETEN", "ETen", CS_ETEN},
{"HK_GCCS", "HKgccs", CS_HK_GCCS},
{"SCS", "HKscs", CS_HK_SCS},
{"SCS_ETEN", "ETHK", CS_HK_SCS_ETEN},
{"MTHKL", "HKm471", CS_MTHKL},
{"MTHKS", "HKm314", CS_MTHKS},
{"DLHKL", "HKdla", CS_DLHKL},
{"DLHKS", "HKdlb", CS_DLHKS},
{"ISO10646", "UniCNS", CS_TC_ISO10646}
};
#define CS_KR_X_1992 (0x01)
#define CS_KR_MAC (0x02)
#define CS_KR_X_1992_MS (0x04)
#define CS_KR_ISO10646 (0x08)
/* Korean encodings and charsets */
static struct prt_ps_encoding_S k_encodings[] =
{
{"iso-2022-kr", NULL, CS_KR_X_1992},
{"euc-kr", "EUC", (CS_KR_X_1992|CS_KR_MAC)},
{"johab", "Johab", CS_KR_X_1992},
{"cp1361", "Johab", CS_KR_X_1992},
{"uhc", "UHC", CS_KR_X_1992_MS},
{"cp949", "UHC", CS_KR_X_1992_MS},
{"ucs-2", "UCS2", CS_KR_ISO10646},
{"utf-8", "UTF8", CS_KR_ISO10646}
};
static struct prt_ps_charset_S k_charsets[] =
{
{"KS_X_1992", "KSC", CS_KR_X_1992},
{"CP1361", "KSC", CS_KR_X_1992},
{"MAC", "KSCpc", CS_KR_MAC},
{"MSWINDOWS", "KSCms", CS_KR_X_1992_MS},
{"CP949", "KSCms", CS_KR_X_1992_MS},
{"WANSUNG", "KSCms", CS_KR_X_1992_MS},
{"ISO10646", "UniKS", CS_KR_ISO10646}
};
/* Collections of encodings and charsets for multi-byte printing */
struct prt_ps_mbfont_S
{
int num_encodings;
struct prt_ps_encoding_S *encodings;
int num_charsets;
struct prt_ps_charset_S *charsets;
char *ascii_enc;
char *defcs;
};
static struct prt_ps_mbfont_S prt_ps_mbfonts[] =
{
{
NUM_ELEMENTS(j_encodings),
j_encodings,
NUM_ELEMENTS(j_charsets),
j_charsets,
"jis_roman",
"JIS_X_1983"
},
{
NUM_ELEMENTS(sc_encodings),
sc_encodings,
NUM_ELEMENTS(sc_charsets),
sc_charsets,
"gb_roman",
"GB_2312-80"
},
{
NUM_ELEMENTS(tc_encodings),
tc_encodings,
NUM_ELEMENTS(tc_charsets),
tc_charsets,
"cns_roman",
"BIG5"
},
{
NUM_ELEMENTS(k_encodings),
k_encodings,
NUM_ELEMENTS(k_charsets),
k_charsets,
"ks_roman",
"KS_X_1992"
}
};
#endif /* FEAT_MBYTE */
struct prt_ps_resource_S
{
char_u name[64];
char_u filename[MAXPATHL + 1];
int type;
char_u title[256];
char_u version[256];
};
/* Types of PS resource file currently used */
#define PRT_RESOURCE_TYPE_PROCSET (0)
#define PRT_RESOURCE_TYPE_ENCODING (1)
#define PRT_RESOURCE_TYPE_CMAP (2)
/* The PS prolog file version number has to match - if the prolog file is
* updated, increment the number in the file and here. Version checking was
* added as of VIM 6.2.
* The CID prolog file version number behaves as per PS prolog.
* Table of VIM and prolog versions:
*
* VIM Prolog CIDProlog
* 6.2 1.3
* 7.0 1.4 1.0
*/
#define PRT_PROLOG_VERSION ((char_u *)"1.4")
#define PRT_CID_PROLOG_VERSION ((char_u *)"1.0")
/* String versions of PS resource types - indexed by constants above so don't
* re-order!
*/
static char *prt_resource_types[] =
{
"procset",
"encoding",
"cmap"
};
/* Strings to look for in a PS resource file */
#define PRT_RESOURCE_HEADER "%!PS-Adobe-"
#define PRT_RESOURCE_RESOURCE "Resource-"
#define PRT_RESOURCE_PROCSET "ProcSet"
#define PRT_RESOURCE_ENCODING "Encoding"
#define PRT_RESOURCE_CMAP "CMap"
/* Data for table based DSC comment recognition, easy to extend if VIM needs to
* read more comments. */
#define PRT_DSC_MISC_TYPE (-1)
#define PRT_DSC_TITLE_TYPE (1)
#define PRT_DSC_VERSION_TYPE (2)
#define PRT_DSC_ENDCOMMENTS_TYPE (3)
#define PRT_DSC_TITLE "%%Title:"
#define PRT_DSC_VERSION "%%Version:"
#define PRT_DSC_ENDCOMMENTS "%%EndComments:"
struct prt_dsc_comment_S
{
char *string;
int len;
int type;
};
struct prt_dsc_line_S
{
int type;
char_u *string;
int len;
};
#define SIZEOF_CSTR(s) (sizeof(s) - 1)
static struct prt_dsc_comment_S prt_dsc_table[] =
{
{PRT_DSC_TITLE, SIZEOF_CSTR(PRT_DSC_TITLE), PRT_DSC_TITLE_TYPE},
{PRT_DSC_VERSION, SIZEOF_CSTR(PRT_DSC_VERSION),
PRT_DSC_VERSION_TYPE},
{PRT_DSC_ENDCOMMENTS, SIZEOF_CSTR(PRT_DSC_ENDCOMMENTS),
PRT_DSC_ENDCOMMENTS_TYPE}
};
static void prt_write_file_raw_len __ARGS((char_u *buffer, int bytes));
static void prt_write_file __ARGS((char_u *buffer));
static void prt_write_file_len __ARGS((char_u *buffer, int bytes));
static void prt_write_string __ARGS((char *s));
static void prt_write_int __ARGS((int i));
static void prt_write_boolean __ARGS((int b));
static void prt_def_font __ARGS((char *new_name, char *encoding, int height, char *font));
static void prt_real_bits __ARGS((double real, int precision, int *pinteger, int *pfraction));
static void prt_write_real __ARGS((double val, int prec));
static void prt_def_var __ARGS((char *name, double value, int prec));
static void prt_flush_buffer __ARGS((void));
static void prt_resource_name __ARGS((char_u *filename, void *cookie));
static int prt_find_resource __ARGS((char *name, struct prt_ps_resource_S *resource));
static int prt_open_resource __ARGS((struct prt_ps_resource_S *resource));
static int prt_check_resource __ARGS((struct prt_ps_resource_S *resource, char_u *version));
static void prt_dsc_start __ARGS((void));
static void prt_dsc_noarg __ARGS((char *comment));
static void prt_dsc_textline __ARGS((char *comment, char *text));
static void prt_dsc_text __ARGS((char *comment, char *text));
static void prt_dsc_ints __ARGS((char *comment, int count, int *ints));
static void prt_dsc_requirements __ARGS((int duplex, int tumble, int collate, int color, int num_copies));
static void prt_dsc_docmedia __ARGS((char *paper_name, double width, double height, double weight, char *colour, char *type));
static void prt_dsc_resources __ARGS((char *comment, char *type, char *strings));
static void prt_dsc_font_resource __ARGS((char *resource, struct prt_ps_font_S *ps_font));
static float to_device_units __ARGS((int idx, double physsize, int def_number));
static void prt_page_margins __ARGS((double width, double height, double *left, double *right, double *top, double *bottom));
static void prt_font_metrics __ARGS((int font_scale));
static int prt_get_cpl __ARGS((void));
static int prt_get_lpp __ARGS((void));
static int prt_add_resource __ARGS((struct prt_ps_resource_S *resource));
static int prt_resfile_next_line __ARGS((void));
static int prt_resfile_strncmp __ARGS((int offset, char *string, int len));
static int prt_resfile_skip_nonws __ARGS((int offset));
static int prt_resfile_skip_ws __ARGS((int offset));
static int prt_next_dsc __ARGS((struct prt_dsc_line_S *p_dsc_line));
#ifdef FEAT_MBYTE
static int prt_build_cid_fontname __ARGS((int font, char_u *name, int name_len));
static void prt_def_cidfont __ARGS((char *new_name, int height, char *cidfont));
static void prt_dup_cidfont __ARGS((char *original_name, char *new_name));
static int prt_match_encoding __ARGS((char *p_encoding, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_encoding_S **pp_mbenc));
static int prt_match_charset __ARGS((char *p_charset, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_charset_S **pp_mbchar));
#endif
/*
* Variables for the output PostScript file.
*/
static FILE *prt_ps_fd;
static int prt_file_error;
static char_u *prt_ps_file_name = NULL;
/*
* Various offsets and dimensions in default PostScript user space (points).
* Used for text positioning calculations
*/
static float prt_page_width;
static float prt_page_height;
static float prt_left_margin;
static float prt_right_margin;
static float prt_top_margin;
static float prt_bottom_margin;
static float prt_line_height;
static float prt_first_line_height;
static float prt_char_width;
static float prt_number_width;
static float prt_bgcol_offset;
static float prt_pos_x_moveto = 0.0;
static float prt_pos_y_moveto = 0.0;
/*
* Various control variables used to decide when and how to change the
* PostScript graphics state.
*/
static int prt_need_moveto;
static int prt_do_moveto;
static int prt_need_font;
static int prt_font;
static int prt_need_underline;
static int prt_underline;
static int prt_do_underline;
static int prt_need_fgcol;
static int prt_fgcol;
static int prt_need_bgcol;
static int prt_do_bgcol;
static int prt_bgcol;
static int prt_new_bgcol;
static int prt_attribute_change;
static float prt_text_run;
static int prt_page_num;
static int prt_bufsiz;
/*
* Variables controlling physical printing.
*/
static int prt_media;
static int prt_portrait;
static int prt_num_copies;
static int prt_duplex;
static int prt_tumble;
static int prt_collate;
/*
* Buffers used when generating PostScript output
*/
static char_u prt_line_buffer[257];
static garray_T prt_ps_buffer;
# ifdef FEAT_MBYTE
static int prt_do_conv;
static vimconv_T prt_conv;
static int prt_out_mbyte;
static int prt_custom_cmap;
static char prt_cmap[80];
static int prt_use_courier;
static int prt_in_ascii;
static int prt_half_width;
static char *prt_ascii_encoding;
static char_u prt_hexchar[] = "0123456789abcdef";
# endif
static void
prt_write_file_raw_len(buffer, bytes)
char_u *buffer;
int bytes;
{
if (!prt_file_error
&& fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd)
!= (size_t)bytes)
{
EMSG(_("E455: Error writing to PostScript output file"));
prt_file_error = TRUE;
}
}
static void
prt_write_file(buffer)
char_u *buffer;
{
prt_write_file_len(buffer, (int)STRLEN(buffer));
}
static void
prt_write_file_len(buffer, bytes)
char_u *buffer;
int bytes;
{
#ifdef EBCDIC
ebcdic2ascii(buffer, bytes);
#endif
prt_write_file_raw_len(buffer, bytes);
}
/*
* Write a string.
*/
static void
prt_write_string(s)
char *s;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%s", s);
prt_write_file(prt_line_buffer);
}
/*
* Write an int and a space.
*/
static void
prt_write_int(i)
int i;
{
sprintf((char *)prt_line_buffer, "%d ", i);
prt_write_file(prt_line_buffer);
}
/*
* Write a boolean and a space.
*/
static void
prt_write_boolean(b)
int b;
{
sprintf((char *)prt_line_buffer, "%s ", (b ? "T" : "F"));
prt_write_file(prt_line_buffer);
}
/*
* Write PostScript to re-encode and define the font.
*/
static void
prt_def_font(new_name, encoding, height, font)
char *new_name;
char *encoding;
int height;
char *font;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/_%s /VIM-%s /%s ref\n", new_name, encoding, font);
prt_write_file(prt_line_buffer);
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
sprintf((char *)prt_line_buffer, "/%s %d %f /_%s sffs\n",
new_name, height, 500./prt_ps_courier_font.wx, new_name);
else
#endif
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/%s %d /_%s ffs\n", new_name, height, new_name);
prt_write_file(prt_line_buffer);
}
#ifdef FEAT_MBYTE
/*
* Write a line to define the CID font.
*/
static void
prt_def_cidfont(new_name, height, cidfont)
char *new_name;
int height;
char *cidfont;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/_%s /%s[/%s] vim_composefont\n", new_name, prt_cmap, cidfont);
prt_write_file(prt_line_buffer);
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/%s %d /_%s ffs\n", new_name, height, new_name);
prt_write_file(prt_line_buffer);
}
/*
* Write a line to define a duplicate of a CID font
*/
static void
prt_dup_cidfont(original_name, new_name)
char *original_name;
char *new_name;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/%s %s d\n", new_name, original_name);
prt_write_file(prt_line_buffer);
}
#endif
/*
* Convert a real value into an integer and fractional part as integers, with
* the fractional part being in the range [0,10^precision). The fractional part
* is also rounded based on the precision + 1'th fractional digit.
*/
static void
prt_real_bits(real, precision, pinteger, pfraction)
double real;
int precision;
int *pinteger;
int *pfraction;
{
int i;
int integer;
float fraction;
integer = (int)real;
fraction = (float)(real - integer);
if (real < (double)integer)
fraction = -fraction;
for (i = 0; i < precision; i++)
fraction *= 10.0;
*pinteger = integer;
*pfraction = (int)(fraction + 0.5);
}
/*
* Write a real and a space. Save bytes if real value has no fractional part!
* We use prt_real_bits() as %f in sprintf uses the locale setting to decide
* what decimal point character to use, but PS always requires a '.'.
*/
static void
prt_write_real(val, prec)
double val;
int prec;
{
int integer;
int fraction;
prt_real_bits(val, prec, &integer, &fraction);
/* Emit integer part */
sprintf((char *)prt_line_buffer, "%d", integer);
prt_write_file(prt_line_buffer);
/* Only emit fraction if necessary */
if (fraction != 0)
{
/* Remove any trailing zeros */
while ((fraction % 10) == 0)
{
prec--;
fraction /= 10;
}
/* Emit fraction left padded with zeros */
sprintf((char *)prt_line_buffer, ".%0*d", prec, fraction);
prt_write_file(prt_line_buffer);
}
sprintf((char *)prt_line_buffer, " ");
prt_write_file(prt_line_buffer);
}
/*
* Write a line to define a numeric variable.
*/
static void
prt_def_var(name, value, prec)
char *name;
double value;
int prec;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"/%s ", name);
prt_write_file(prt_line_buffer);
prt_write_real(value, prec);
sprintf((char *)prt_line_buffer, "d\n");
prt_write_file(prt_line_buffer);
}
/* Convert size from font space to user space at current font scale */
#define PRT_PS_FONT_TO_USER(scale, size) ((size) * ((scale)/1000.0))
static void
prt_flush_buffer()
{
if (prt_ps_buffer.ga_len > 0)
{
/* Any background color must be drawn first */
if (prt_do_bgcol && (prt_new_bgcol != PRCOLOR_WHITE))
{
int r, g, b;
if (prt_do_moveto)
{
prt_write_real(prt_pos_x_moveto, 2);
prt_write_real(prt_pos_y_moveto, 2);
prt_write_string("m\n");
prt_do_moveto = FALSE;
}
/* Size of rect of background color on which text is printed */
prt_write_real(prt_text_run, 2);
prt_write_real(prt_line_height, 2);
/* Lastly add the color of the background */
r = ((unsigned)prt_new_bgcol & 0xff0000) >> 16;
g = ((unsigned)prt_new_bgcol & 0xff00) >> 8;
b = prt_new_bgcol & 0xff;
prt_write_real(r / 255.0, 3);
prt_write_real(g / 255.0, 3);
prt_write_real(b / 255.0, 3);
prt_write_string("bg\n");
}
/* Draw underlines before the text as it makes it slightly easier to
* find the starting point.
*/
if (prt_do_underline)
{
if (prt_do_moveto)
{
prt_write_real(prt_pos_x_moveto, 2);
prt_write_real(prt_pos_y_moveto, 2);
prt_write_string("m\n");
prt_do_moveto = FALSE;
}
/* Underline length of text run */
prt_write_real(prt_text_run, 2);
prt_write_string("ul\n");
}
/* Draw the text
* Note: we write text out raw - EBCDIC conversion is handled in the
* PostScript world via the font encoding vector. */
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
prt_write_string("<");
else
#endif
prt_write_string("(");
prt_write_file_raw_len(prt_ps_buffer.ga_data, prt_ps_buffer.ga_len);
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
prt_write_string(">");
else
#endif
prt_write_string(")");
/* Add a moveto if need be and use the appropriate show procedure */
if (prt_do_moveto)
{
prt_write_real(prt_pos_x_moveto, 2);
prt_write_real(prt_pos_y_moveto, 2);
/* moveto and a show */
prt_write_string("ms\n");
prt_do_moveto = FALSE;
}
else /* Simple show */
prt_write_string("s\n");
ga_clear(&prt_ps_buffer);
ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);
}
}
static void
prt_resource_name(filename, cookie)
char_u *filename;
void *cookie;
{
char_u *resource_filename = cookie;
if (STRLEN(filename) >= MAXPATHL)
*resource_filename = NUL;
else
STRCPY(resource_filename, filename);
}
static int
prt_find_resource(name, resource)
char *name;
struct prt_ps_resource_S *resource;
{
char_u *buffer;
int retval;
buffer = alloc(MAXPATHL + 1);
if (buffer == NULL)
return FALSE;
vim_strncpy(resource->name, (char_u *)name, 63);
/* Look for named resource file in runtimepath */
STRCPY(buffer, "print");
add_pathsep(buffer);
vim_strcat(buffer, (char_u *)name, MAXPATHL);
vim_strcat(buffer, (char_u *)".ps", MAXPATHL);
resource->filename[0] = NUL;
retval = (do_in_runtimepath(buffer, FALSE, prt_resource_name,
resource->filename)
&& resource->filename[0] != NUL);
vim_free(buffer);
return retval;
}
/* PS CR and LF characters have platform independent values */
#define PSLF (0x0a)
#define PSCR (0x0d)
/* Static buffer to read initial comments in a resource file, some can have a
* couple of KB of comments! */
#define PRT_FILE_BUFFER_LEN (2048)
struct prt_resfile_buffer_S
{
char_u buffer[PRT_FILE_BUFFER_LEN];
int len;
int line_start;
int line_end;
};
static struct prt_resfile_buffer_S prt_resfile;
static int
prt_resfile_next_line()
{
int idx;
/* Move to start of next line and then find end of line */
idx = prt_resfile.line_end + 1;
while (idx < prt_resfile.len)
{
if (prt_resfile.buffer[idx] != PSLF && prt_resfile.buffer[idx] != PSCR)
break;
idx++;
}
prt_resfile.line_start = idx;
while (idx < prt_resfile.len)
{
if (prt_resfile.buffer[idx] == PSLF || prt_resfile.buffer[idx] == PSCR)
break;
idx++;
}
prt_resfile.line_end = idx;
return (idx < prt_resfile.len);
}
static int
prt_resfile_strncmp(offset, string, len)
int offset;
char *string;
int len;
{
/* Force not equal if string is longer than remainder of line */
if (len > (prt_resfile.line_end - (prt_resfile.line_start + offset)))
return 1;
return STRNCMP(&prt_resfile.buffer[prt_resfile.line_start + offset],
string, len);
}
static int
prt_resfile_skip_nonws(offset)
int offset;
{
int idx;
idx = prt_resfile.line_start + offset;
while (idx < prt_resfile.line_end)
{
if (isspace(prt_resfile.buffer[idx]))
return idx - prt_resfile.line_start;
idx++;
}
return -1;
}
static int
prt_resfile_skip_ws(offset)
int offset;
{
int idx;
idx = prt_resfile.line_start + offset;
while (idx < prt_resfile.line_end)
{
if (!isspace(prt_resfile.buffer[idx]))
return idx - prt_resfile.line_start;
idx++;
}
return -1;
}
/* prt_next_dsc() - returns detail on next DSC comment line found. Returns true
* if a DSC comment is found, else false */
static int
prt_next_dsc(p_dsc_line)
struct prt_dsc_line_S *p_dsc_line;
{
int comment;
int offset;
/* Move to start of next line */
if (!prt_resfile_next_line())
return FALSE;
/* DSC comments always start %% */
if (prt_resfile_strncmp(0, "%%", 2) != 0)
return FALSE;
/* Find type of DSC comment */
for (comment = 0; comment < (int)NUM_ELEMENTS(prt_dsc_table); comment++)
if (prt_resfile_strncmp(0, prt_dsc_table[comment].string,
prt_dsc_table[comment].len) == 0)
break;
if (comment != NUM_ELEMENTS(prt_dsc_table))
{
/* Return type of comment */
p_dsc_line->type = prt_dsc_table[comment].type;
offset = prt_dsc_table[comment].len;
}
else
{
/* Unrecognised DSC comment, skip to ws after comment leader */
p_dsc_line->type = PRT_DSC_MISC_TYPE;
offset = prt_resfile_skip_nonws(0);
if (offset == -1)
return FALSE;
}
/* Skip ws to comment value */
offset = prt_resfile_skip_ws(offset);
if (offset == -1)
return FALSE;
p_dsc_line->string = &prt_resfile.buffer[prt_resfile.line_start + offset];
p_dsc_line->len = prt_resfile.line_end - (prt_resfile.line_start + offset);
return TRUE;
}
/* Improved hand crafted parser to get the type, title, and version number of a
* PS resource file so the file details can be added to the DSC header comments.
*/
static int
prt_open_resource(resource)
struct prt_ps_resource_S *resource;
{
int offset;
int seen_all;
int seen_title;
int seen_version;
FILE *fd_resource;
struct prt_dsc_line_S dsc_line;
fd_resource = mch_fopen((char *)resource->filename, READBIN);
if (fd_resource == NULL)
{
EMSG2(_("E624: Can't open file \"%s\""), resource->filename);
return FALSE;
}
vim_memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN);
/* Parse first line to ensure valid resource file */
prt_resfile.len = (int)fread((char *)prt_resfile.buffer, sizeof(char_u),
PRT_FILE_BUFFER_LEN, fd_resource);
if (ferror(fd_resource))
{
EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
resource->filename);
fclose(fd_resource);
return FALSE;
}
fclose(fd_resource);
prt_resfile.line_end = -1;
prt_resfile.line_start = 0;
if (!prt_resfile_next_line())
return FALSE;
offset = 0;
if (prt_resfile_strncmp(offset, PRT_RESOURCE_HEADER,
(int)STRLEN(PRT_RESOURCE_HEADER)) != 0)
{
EMSG2(_("E618: file \"%s\" is not a PostScript resource file"),
resource->filename);
return FALSE;
}
/* Skip over any version numbers and following ws */
offset += (int)STRLEN(PRT_RESOURCE_HEADER);
offset = prt_resfile_skip_nonws(offset);
if (offset == -1)
return FALSE;
offset = prt_resfile_skip_ws(offset);
if (offset == -1)
return FALSE;
if (prt_resfile_strncmp(offset, PRT_RESOURCE_RESOURCE,
(int)STRLEN(PRT_RESOURCE_RESOURCE)) != 0)
{
EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
resource->filename);
return FALSE;
}
offset += (int)STRLEN(PRT_RESOURCE_RESOURCE);
/* Decide type of resource in the file */
if (prt_resfile_strncmp(offset, PRT_RESOURCE_PROCSET,
(int)STRLEN(PRT_RESOURCE_PROCSET)) == 0)
resource->type = PRT_RESOURCE_TYPE_PROCSET;
else if (prt_resfile_strncmp(offset, PRT_RESOURCE_ENCODING,
(int)STRLEN(PRT_RESOURCE_ENCODING)) == 0)
resource->type = PRT_RESOURCE_TYPE_ENCODING;
else if (prt_resfile_strncmp(offset, PRT_RESOURCE_CMAP,
(int)STRLEN(PRT_RESOURCE_CMAP)) == 0)
resource->type = PRT_RESOURCE_TYPE_CMAP;
else
{
EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
resource->filename);
return FALSE;
}
/* Look for title and version of resource */
resource->title[0] = '\0';
resource->version[0] = '\0';
seen_title = FALSE;
seen_version = FALSE;
seen_all = FALSE;
while (!seen_all && prt_next_dsc(&dsc_line))
{
switch (dsc_line.type)
{
case PRT_DSC_TITLE_TYPE:
vim_strncpy(resource->title, dsc_line.string, dsc_line.len);
seen_title = TRUE;
if (seen_version)
seen_all = TRUE;
break;
case PRT_DSC_VERSION_TYPE:
vim_strncpy(resource->version, dsc_line.string, dsc_line.len);
seen_version = TRUE;
if (seen_title)
seen_all = TRUE;
break;
case PRT_DSC_ENDCOMMENTS_TYPE:
/* Wont find title or resource after this comment, stop searching */
seen_all = TRUE;
break;
case PRT_DSC_MISC_TYPE:
/* Not interested in whatever comment this line had */
break;
}
}
if (!seen_title || !seen_version)
{
EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
resource->filename);
return FALSE;
}
return TRUE;
}
static int
prt_check_resource(resource, version)
struct prt_ps_resource_S *resource;
char_u *version;
{
/* Version number m.n should match, the revision number does not matter */
if (STRNCMP(resource->version, version, STRLEN(version)))
{
EMSG2(_("E621: \"%s\" resource file has wrong version"),
resource->name);
return FALSE;
}
/* Other checks to be added as needed */
return TRUE;
}
static void
prt_dsc_start()
{
prt_write_string("%!PS-Adobe-3.0\n");
}
static void
prt_dsc_noarg(comment)
char *comment;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%%s\n", comment);
prt_write_file(prt_line_buffer);
}
static void
prt_dsc_textline(comment, text)
char *comment;
char *text;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%%s: %s\n", comment, text);
prt_write_file(prt_line_buffer);
}
static void
prt_dsc_text(comment, text)
char *comment;
char *text;
{
/* TODO - should scan 'text' for any chars needing escaping! */
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%%s: (%s)\n", comment, text);
prt_write_file(prt_line_buffer);
}
#define prt_dsc_atend(c) prt_dsc_text((c), "atend")
static void
prt_dsc_ints(comment, count, ints)
char *comment;
int count;
int *ints;
{
int i;
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%%s:", comment);
prt_write_file(prt_line_buffer);
for (i = 0; i < count; i++)
{
sprintf((char *)prt_line_buffer, " %d", ints[i]);
prt_write_file(prt_line_buffer);
}
prt_write_string("\n");
}
static void
prt_dsc_resources(comment, type, string)
char *comment; /* if NULL add to previous */
char *type;
char *string;
{
if (comment != NULL)
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%%s: %s", comment, type);
else
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%+ %s", type);
prt_write_file(prt_line_buffer);
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
" %s\n", string);
prt_write_file(prt_line_buffer);
}
static void
prt_dsc_font_resource(resource, ps_font)
char *resource;
struct prt_ps_font_S *ps_font;
{
int i;
prt_dsc_resources(resource, "font",
ps_font->ps_fontname[PRT_PS_FONT_ROMAN]);
for (i = PRT_PS_FONT_BOLD ; i <= PRT_PS_FONT_BOLDOBLIQUE ; i++)
if (ps_font->ps_fontname[i] != NULL)
prt_dsc_resources(NULL, "font", ps_font->ps_fontname[i]);
}
static void
prt_dsc_requirements(duplex, tumble, collate, color, num_copies)
int duplex;
int tumble;
int collate;
int color;
int num_copies;
{
/* Only output the comment if we need to.
* Note: tumble is ignored if we are not duplexing
*/
if (!(duplex || collate || color || (num_copies > 1)))
return;
sprintf((char *)prt_line_buffer, "%%%%Requirements:");
prt_write_file(prt_line_buffer);
if (duplex)
{
prt_write_string(" duplex");
if (tumble)
prt_write_string("(tumble)");
}
if (collate)
prt_write_string(" collate");
if (color)
prt_write_string(" color");
if (num_copies > 1)
{
prt_write_string(" numcopies(");
/* Note: no space wanted so dont use prt_write_int() */
sprintf((char *)prt_line_buffer, "%d", num_copies);
prt_write_file(prt_line_buffer);
prt_write_string(")");
}
prt_write_string("\n");
}
static void
prt_dsc_docmedia(paper_name, width, height, weight, colour, type)
char *paper_name;
double width;
double height;
double weight;
char *colour;
char *type;
{
vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
"%%%%DocumentMedia: %s ", paper_name);
prt_write_file(prt_line_buffer);
prt_write_real(width, 2);
prt_write_real(height, 2);
prt_write_real(weight, 2);
if (colour == NULL)
prt_write_string("()");
else
prt_write_string(colour);
prt_write_string(" ");
if (type == NULL)
prt_write_string("()");
else
prt_write_string(type);
prt_write_string("\n");
}
void
mch_print_cleanup()
{
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
int i;
/* Free off all CID font names created, but first clear duplicate
* pointers to the same string (when the same font is used for more than
* one style).
*/
for (i = PRT_PS_FONT_ROMAN; i <= PRT_PS_FONT_BOLDOBLIQUE; i++)
{
if (prt_ps_mb_font.ps_fontname[i] != NULL)
vim_free(prt_ps_mb_font.ps_fontname[i]);
prt_ps_mb_font.ps_fontname[i] = NULL;
}
}
if (prt_do_conv)
{
convert_setup(&prt_conv, NULL, NULL);
prt_do_conv = FALSE;
}
#endif
if (prt_ps_fd != NULL)
{
fclose(prt_ps_fd);
prt_ps_fd = NULL;
prt_file_error = FALSE;
}
if (prt_ps_file_name != NULL)
{
vim_free(prt_ps_file_name);
prt_ps_file_name = NULL;
}
}
static float
to_device_units(idx, physsize, def_number)
int idx;
double physsize;
int def_number;
{
float ret;
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_INCH:
ret = (float)(nr * PRT_PS_DEFAULT_DPI);
break;
case PRT_UNIT_MM:
ret = (float)(nr * PRT_PS_DEFAULT_DPI) / (float)25.4;
break;
case PRT_UNIT_POINT:
ret = (float)nr;
break;
case PRT_UNIT_PERC:
default:
ret = (float)(physsize * nr) / 100;
break;
}
return ret;
}
/*
* Calculate margins for given width and height from printoptions settings.
*/
static void
prt_page_margins(width, height, left, right, top, bottom)
double width;
double height;
double *left;
double *right;
double *top;
double *bottom;
{
*left = to_device_units(OPT_PRINT_LEFT, width, 10);
*right = width - to_device_units(OPT_PRINT_RIGHT, width, 5);
*top = height - to_device_units(OPT_PRINT_TOP, height, 5);
*bottom = to_device_units(OPT_PRINT_BOT, height, 5);
}
static void
prt_font_metrics(font_scale)
int font_scale;
{
prt_line_height = (float)font_scale;
prt_char_width = (float)PRT_PS_FONT_TO_USER(font_scale, prt_ps_font->wx);
}
static int
prt_get_cpl()
{
if (prt_use_number())
{
prt_number_width = PRINT_NUMBER_WIDTH * prt_char_width;
#ifdef FEAT_MBYTE
/* If we are outputting multi-byte characters then line numbers will be
* printed with half width characters
*/
if (prt_out_mbyte)
prt_number_width /= 2;
#endif
prt_left_margin += prt_number_width;
}
else
prt_number_width = 0.0;
return (int)((prt_right_margin - prt_left_margin) / prt_char_width);
}
#ifdef FEAT_MBYTE
static int
prt_build_cid_fontname(font, name, name_len)
int font;
char_u *name;
int name_len;
{
char *fontname;
fontname = (char *)alloc(name_len + 1);
if (fontname == NULL)
return FALSE;
vim_strncpy((char_u *)fontname, name, name_len);
prt_ps_mb_font.ps_fontname[font] = fontname;
return TRUE;
}
#endif
/*
* Get number of lines of text that fit on a page (excluding the header).
*/
static int
prt_get_lpp()
{
int lpp;
/*
* Calculate offset to lower left corner of background rect based on actual
* font height (based on its bounding box) and the line height, handling the
* case where the font height can exceed the line height.
*/
prt_bgcol_offset = (float)PRT_PS_FONT_TO_USER(prt_line_height,
prt_ps_font->bbox_min_y);
if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0)
{
prt_bgcol_offset -= (float)PRT_PS_FONT_TO_USER(prt_line_height,
(1000.0 - (prt_ps_font->bbox_max_y -
prt_ps_font->bbox_min_y)) / 2);
}
/* Get height for topmost line based on background rect offset. */
prt_first_line_height = prt_line_height + prt_bgcol_offset;
/* Calculate lpp */
lpp = (int)((prt_top_margin - prt_bottom_margin) / prt_line_height);
/* Adjust top margin if there is a header */
prt_top_margin -= prt_line_height * prt_header_height();
return lpp - prt_header_height();
}
#ifdef FEAT_MBYTE
static int
prt_match_encoding(p_encoding, p_cmap, pp_mbenc)
char *p_encoding;
struct prt_ps_mbfont_S *p_cmap;
struct prt_ps_encoding_S **pp_mbenc;
{
int mbenc;
int enc_len;
struct prt_ps_encoding_S *p_mbenc;
*pp_mbenc = NULL;
/* Look for recognised encoding */
enc_len = (int)STRLEN(p_encoding);
p_mbenc = p_cmap->encodings;
for (mbenc = 0; mbenc < p_cmap->num_encodings; mbenc++)
{
if (STRNICMP(p_mbenc->encoding, p_encoding, enc_len) == 0)
{
*pp_mbenc = p_mbenc;
return TRUE;
}
p_mbenc++;
}
return FALSE;
}
static int
prt_match_charset(p_charset, p_cmap, pp_mbchar)
char *p_charset;
struct prt_ps_mbfont_S *p_cmap;
struct prt_ps_charset_S **pp_mbchar;
{
int mbchar;
int char_len;
struct prt_ps_charset_S *p_mbchar;
/* Look for recognised character set, using default if one is not given */
if (*p_charset == NUL)
p_charset = p_cmap->defcs;
char_len = (int)STRLEN(p_charset);
p_mbchar = p_cmap->charsets;
for (mbchar = 0; mbchar < p_cmap->num_charsets; mbchar++)
{
if (STRNICMP(p_mbchar->charset, p_charset, char_len) == 0)
{
*pp_mbchar = p_mbchar;
return TRUE;
}
p_mbchar++;
}
return FALSE;
}
#endif
int
mch_print_init(psettings, jobname, forceit)
prt_settings_T *psettings;
char_u *jobname;
int forceit UNUSED;
{
int i;
char *paper_name;
int paper_strlen;
int fontsize;
char_u *p;
double left;
double right;
double top;
double bottom;
#ifdef FEAT_MBYTE
int props;
int cmap = 0;
char_u *p_encoding;
struct prt_ps_encoding_S *p_mbenc;
struct prt_ps_encoding_S *p_mbenc_first;
struct prt_ps_charset_S *p_mbchar = NULL;
#endif
#if 0
/*
* TODO:
* If "forceit" is false: pop up a dialog to select:
* - printer name
* - copies
* - collated/uncollated
* - duplex off/long side/short side
* - paper size
* - portrait/landscape
* - font size
*
* If "forceit" is true: use the default printer and settings
*/
if (forceit)
s_pd.Flags |= PD_RETURNDEFAULT;
#endif
/*
* Set up font and encoding.
*/
#ifdef FEAT_MBYTE
p_encoding = enc_skip(p_penc);
if (*p_encoding == NUL)
p_encoding = enc_skip(p_enc);
/* Look for a multi-byte font that matches the encoding and character set.
* Only look if multi-byte character set is defined, or using multi-byte
* encoding other than Unicode. This is because a Unicode encoding does not
* uniquely identify a CJK character set to use. */
p_mbenc = NULL;
props = enc_canon_props(p_encoding);
if (!(props & ENC_8BIT) && ((*p_pmcs != NUL) || !(props & ENC_UNICODE)))
{
p_mbenc_first = NULL;
for (cmap = 0; cmap < (int)NUM_ELEMENTS(prt_ps_mbfonts); cmap++)
if (prt_match_encoding((char *)p_encoding, &prt_ps_mbfonts[cmap],
&p_mbenc))
{
if (p_mbenc_first == NULL)
p_mbenc_first = p_mbenc;
if (prt_match_charset((char *)p_pmcs, &prt_ps_mbfonts[cmap],
&p_mbchar))
break;
}
/* Use first encoding matched if no charset matched */
if (p_mbchar == NULL && p_mbenc_first != NULL)
p_mbenc = p_mbenc_first;
}
prt_out_mbyte = (p_mbenc != NULL);
if (prt_out_mbyte)
{
/* Build CMap name - will be same for all multi-byte fonts used */
prt_cmap[0] = NUL;
prt_custom_cmap = (p_mbchar == NULL);
if (!prt_custom_cmap)
{
/* Check encoding and character set are compatible */
if ((p_mbenc->needs_charset & p_mbchar->has_charset) == 0)
{
EMSG(_("E673: Incompatible multi-byte encoding and character set."));
return FALSE;
}
/* Add charset name if not empty */
if (p_mbchar->cmap_charset != NULL)
{
vim_strncpy((char_u *)prt_cmap,
(char_u *)p_mbchar->cmap_charset, sizeof(prt_cmap) - 3);
STRCAT(prt_cmap, "-");
}
}
else
{
/* Add custom CMap character set name */
if (*p_pmcs == NUL)
{
EMSG(_("E674: printmbcharset cannot be empty with multi-byte encoding."));
return FALSE;
}
vim_strncpy((char_u *)prt_cmap, p_pmcs, sizeof(prt_cmap) - 3);
STRCAT(prt_cmap, "-");
}
/* CMap name ends with (optional) encoding name and -H for horizontal */
if (p_mbenc->cmap_encoding != NULL && STRLEN(prt_cmap)
+ STRLEN(p_mbenc->cmap_encoding) + 3 < sizeof(prt_cmap))
{
STRCAT(prt_cmap, p_mbenc->cmap_encoding);
STRCAT(prt_cmap, "-");
}
STRCAT(prt_cmap, "H");
if (!mbfont_opts[OPT_MBFONT_REGULAR].present)
{
EMSG(_("E675: No default font specified for multi-byte printing."));
return FALSE;
}
/* Derive CID font names with fallbacks if not defined */
if (!prt_build_cid_fontname(PRT_PS_FONT_ROMAN,
mbfont_opts[OPT_MBFONT_REGULAR].string,
mbfont_opts[OPT_MBFONT_REGULAR].strlen))
return FALSE;
if (mbfont_opts[OPT_MBFONT_BOLD].present)
if (!prt_build_cid_fontname(PRT_PS_FONT_BOLD,
mbfont_opts[OPT_MBFONT_BOLD].string,
mbfont_opts[OPT_MBFONT_BOLD].strlen))
return FALSE;
if (mbfont_opts[OPT_MBFONT_OBLIQUE].present)
if (!prt_build_cid_fontname(PRT_PS_FONT_OBLIQUE,
mbfont_opts[OPT_MBFONT_OBLIQUE].string,
mbfont_opts[OPT_MBFONT_OBLIQUE].strlen))
return FALSE;
if (mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].present)
if (!prt_build_cid_fontname(PRT_PS_FONT_BOLDOBLIQUE,
mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].string,
mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].strlen))
return FALSE;
/* Check if need to use Courier for ASCII code range, and if so pick up
* the encoding to use */
prt_use_courier = mbfont_opts[OPT_MBFONT_USECOURIER].present &&
(TOLOWER_ASC(mbfont_opts[OPT_MBFONT_USECOURIER].string[0]) == 'y');
if (prt_use_courier)
{
/* Use national ASCII variant unless ASCII wanted */
if (mbfont_opts[OPT_MBFONT_ASCII].present &&
(TOLOWER_ASC(mbfont_opts[OPT_MBFONT_ASCII].string[0]) == 'y'))
prt_ascii_encoding = "ascii";
else
prt_ascii_encoding = prt_ps_mbfonts[cmap].ascii_enc;
}
prt_ps_font = &prt_ps_mb_font;
}
else
#endif
{
#ifdef FEAT_MBYTE
prt_use_courier = FALSE;
#endif
prt_ps_font = &prt_ps_courier_font;
}
/*
* Find the size of the paper and set the margins.
*/
prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present
|| TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y');
if (printer_opts[OPT_PRINT_PAPER].present)
{
paper_name = (char *)printer_opts[OPT_PRINT_PAPER].string;
paper_strlen = printer_opts[OPT_PRINT_PAPER].strlen;
}
else
{
paper_name = "A4";
paper_strlen = 2;
}
for (i = 0; i < (int)PRT_MEDIASIZE_LEN; ++i)
if (STRLEN(prt_mediasize[i].name) == (unsigned)paper_strlen
&& STRNICMP(prt_mediasize[i].name, paper_name,
paper_strlen) == 0)
break;
if (i == PRT_MEDIASIZE_LEN)
i = 0;
prt_media = i;
/*
* Set PS pagesize based on media dimensions and print orientation.
* Note: Media and page sizes have defined meanings in PostScript and should
* be kept distinct. Media is the paper (or transparency, or ...) that is
* printed on, whereas the page size is the area that the PostScript
* interpreter renders into.
*/
if (prt_portrait)
{
prt_page_width = prt_mediasize[i].width;
prt_page_height = prt_mediasize[i].height;
}
else
{
prt_page_width = prt_mediasize[i].height;
prt_page_height = prt_mediasize[i].width;
}
/*
* Set PS page margins based on the PS pagesize, not the mediasize - this
* needs to be done before the cpl and lpp are calculated.
*/
prt_page_margins(prt_page_width, prt_page_height, &left, &right, &top,
&bottom);
prt_left_margin = (float)left;
prt_right_margin = (float)right;
prt_top_margin = (float)top;
prt_bottom_margin = (float)bottom;
/*
* Set up the font size.
*/
fontsize = PRT_PS_DEFAULT_FONTSIZE;
for (p = p_pfn; (p = vim_strchr(p, ':')) != NULL; ++p)
if (p[1] == 'h' && VIM_ISDIGIT(p[2]))
fontsize = atoi((char *)p + 2);
prt_font_metrics(fontsize);
/*
* Return the number of characters per line, and lines per page for the
* generic print code.
*/
psettings->chars_per_line = prt_get_cpl();
psettings->lines_per_page = prt_get_lpp();
/* Catch margin settings that leave no space for output! */
if (psettings->chars_per_line <= 0 || psettings->lines_per_page <= 0)
return FAIL;
/*
* Sort out the number of copies to be printed. PS by default will do
* uncollated copies for you, so once we know how many uncollated copies are
* wanted cache it away and lie to the generic code that we only want one
* uncollated copy.
*/
psettings->n_collated_copies = 1;
psettings->n_uncollated_copies = 1;
prt_num_copies = 1;
prt_collate = (!printer_opts[OPT_PRINT_COLLATE].present
|| TOLOWER_ASC(printer_opts[OPT_PRINT_COLLATE].string[0]) == 'y');
if (prt_collate)
{
/* TODO: Get number of collated copies wanted. */
psettings->n_collated_copies = 1;
}
else
{
/* TODO: Get number of uncollated copies wanted and update the cached
* count.
*/
prt_num_copies = 1;
}
psettings->jobname = jobname;
/*
* Set up printer duplex and tumble based on Duplex option setting - default
* is long sided duplex printing (i.e. no tumble).
*/
prt_duplex = TRUE;
prt_tumble = FALSE;
psettings->duplex = 1;
if (printer_opts[OPT_PRINT_DUPLEX].present)
{
if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "off", 3) == 0)
{
prt_duplex = FALSE;
psettings->duplex = 0;
}
else if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "short", 5)
== 0)
prt_tumble = TRUE;
}
/* For now user abort not supported */
psettings->user_abort = 0;
/* If the user didn't specify a file name, use a temp file. */
if (psettings->outfile == NULL)
{
prt_ps_file_name = vim_tempname('p');
if (prt_ps_file_name == NULL)
{
EMSG(_(e_notmp));
return FAIL;
}
prt_ps_fd = mch_fopen((char *)prt_ps_file_name, WRITEBIN);
}
else
{
p = expand_env_save(psettings->outfile);
if (p != NULL)
{
prt_ps_fd = mch_fopen((char *)p, WRITEBIN);
vim_free(p);
}
}
if (prt_ps_fd == NULL)
{
EMSG(_("E324: Can't open PostScript output file"));
mch_print_cleanup();
return FAIL;
}
prt_bufsiz = psettings->chars_per_line;
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
prt_bufsiz *= 2;
#endif
ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);
prt_page_num = 0;
prt_attribute_change = FALSE;
prt_need_moveto = FALSE;
prt_need_font = FALSE;
prt_need_fgcol = FALSE;
prt_need_bgcol = FALSE;
prt_need_underline = FALSE;
prt_file_error = FALSE;
return OK;
}
static int
prt_add_resource(resource)
struct prt_ps_resource_S *resource;
{
FILE* fd_resource;
char_u resource_buffer[512];
size_t bytes_read;
fd_resource = mch_fopen((char *)resource->filename, READBIN);
if (fd_resource == NULL)
{
EMSG2(_("E456: Can't open file \"%s\""), resource->filename);
return FALSE;
}
prt_dsc_resources("BeginResource", prt_resource_types[resource->type],
(char *)resource->title);
prt_dsc_textline("BeginDocument", (char *)resource->filename);
for (;;)
{
bytes_read = fread((char *)resource_buffer, sizeof(char_u),
sizeof(resource_buffer), fd_resource);
if (ferror(fd_resource))
{
EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
resource->filename);
fclose(fd_resource);
return FALSE;
}
if (bytes_read == 0)
break;
prt_write_file_raw_len(resource_buffer, (int)bytes_read);
if (prt_file_error)
{
fclose(fd_resource);
return FALSE;
}
}
fclose(fd_resource);
prt_dsc_noarg("EndDocument");
prt_dsc_noarg("EndResource");
return TRUE;
}
int
mch_print_begin(psettings)
prt_settings_T *psettings;
{
time_t now;
int bbox[4];
char *p_time;
double left;
double right;
double top;
double bottom;
struct prt_ps_resource_S *res_prolog;
struct prt_ps_resource_S *res_encoding;
char buffer[256];
char_u *p_encoding;
char_u *p;
#ifdef FEAT_MBYTE
struct prt_ps_resource_S *res_cidfont;
struct prt_ps_resource_S *res_cmap;
#endif
int retval = FALSE;
res_prolog = (struct prt_ps_resource_S *)
alloc(sizeof(struct prt_ps_resource_S));
res_encoding = (struct prt_ps_resource_S *)
alloc(sizeof(struct prt_ps_resource_S));
#ifdef FEAT_MBYTE
res_cidfont = (struct prt_ps_resource_S *)
alloc(sizeof(struct prt_ps_resource_S));
res_cmap = (struct prt_ps_resource_S *)
alloc(sizeof(struct prt_ps_resource_S));
#endif
if (res_prolog == NULL || res_encoding == NULL
#ifdef FEAT_MBYTE
|| res_cidfont == NULL || res_cmap == NULL
#endif
)
goto theend;
/*
* PS DSC Header comments - no PS code!
*/
prt_dsc_start();
prt_dsc_textline("Title", (char *)psettings->jobname);
if (!get_user_name((char_u *)buffer, 256))
STRCPY(buffer, "Unknown");
prt_dsc_textline("For", buffer);
prt_dsc_textline("Creator", VIM_VERSION_LONG);
/* Note: to ensure Clean8bit I don't think we can use LC_TIME */
now = time(NULL);
p_time = ctime(&now);
/* Note: ctime() adds a \n so we have to remove it :-( */
p = vim_strchr((char_u *)p_time, '\n');
if (p != NULL)
*p = NUL;
prt_dsc_textline("CreationDate", p_time);
prt_dsc_textline("DocumentData", "Clean8Bit");
prt_dsc_textline("Orientation", "Portrait");
prt_dsc_atend("Pages");
prt_dsc_textline("PageOrder", "Ascend");
/* The bbox does not change with orientation - it is always in the default
* user coordinate system! We have to recalculate right and bottom
* coordinates based on the font metrics for the bbox to be accurate. */
prt_page_margins(prt_mediasize[prt_media].width,
prt_mediasize[prt_media].height,
&left, &right, &top, &bottom);
bbox[0] = (int)left;
if (prt_portrait)
{
/* In portrait printing the fixed point is the top left corner so we
* derive the bbox from that point. We have the expected cpl chars
* across the media and lpp lines down the media.
*/
bbox[1] = (int)(top - (psettings->lines_per_page + prt_header_height())
* prt_line_height);
bbox[2] = (int)(left + psettings->chars_per_line * prt_char_width
+ 0.5);
bbox[3] = (int)(top + 0.5);
}
else
{
/* In landscape printing the fixed point is the bottom left corner so we
* derive the bbox from that point. We have lpp chars across the media
* and cpl lines up the media.
*/
bbox[1] = (int)bottom;
bbox[2] = (int)(left + ((psettings->lines_per_page
+ prt_header_height()) * prt_line_height) + 0.5);
bbox[3] = (int)(bottom + psettings->chars_per_line * prt_char_width
+ 0.5);
}
prt_dsc_ints("BoundingBox", 4, bbox);
/* The media width and height does not change with landscape printing! */
prt_dsc_docmedia(prt_mediasize[prt_media].name,
prt_mediasize[prt_media].width,
prt_mediasize[prt_media].height,
(double)0, NULL, NULL);
/* Define fonts needed */
#ifdef FEAT_MBYTE
if (!prt_out_mbyte || prt_use_courier)
#endif
prt_dsc_font_resource("DocumentNeededResources", &prt_ps_courier_font);
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
prt_dsc_font_resource((prt_use_courier ? NULL
: "DocumentNeededResources"), &prt_ps_mb_font);
if (!prt_custom_cmap)
prt_dsc_resources(NULL, "cmap", prt_cmap);
}
#endif
/* Search for external resources VIM supplies */
if (!prt_find_resource("prolog", res_prolog))
{
EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\""));
return FALSE;
}
if (!prt_open_resource(res_prolog))
return FALSE;
if (!prt_check_resource(res_prolog, PRT_PROLOG_VERSION))
return FALSE;
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
/* Look for required version of multi-byte printing procset */
if (!prt_find_resource("cidfont", res_cidfont))
{
EMSG(_("E456: Can't find PostScript resource file \"cidfont.ps\""));
return FALSE;
}
if (!prt_open_resource(res_cidfont))
return FALSE;
if (!prt_check_resource(res_cidfont, PRT_CID_PROLOG_VERSION))
return FALSE;
}
#endif
/* Find an encoding to use for printing.
* Check 'printencoding'. If not set or not found, then use 'encoding'. If
* that cannot be found then default to "latin1".
* Note: VIM specific encoding header is always skipped.
*/
#ifdef FEAT_MBYTE
if (!prt_out_mbyte)
{
#endif
p_encoding = enc_skip(p_penc);
if (*p_encoding == NUL
|| !prt_find_resource((char *)p_encoding, res_encoding))
{
/* 'printencoding' not set or not supported - find alternate */
#ifdef FEAT_MBYTE
int props;
p_encoding = enc_skip(p_enc);
props = enc_canon_props(p_encoding);
if (!(props & ENC_8BIT)
|| !prt_find_resource((char *)p_encoding, res_encoding))
/* 8-bit 'encoding' is not supported */
#endif
{
/* Use latin1 as default printing encoding */
p_encoding = (char_u *)"latin1";
if (!prt_find_resource((char *)p_encoding, res_encoding))
{
EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
p_encoding);
return FALSE;
}
}
}
if (!prt_open_resource(res_encoding))
return FALSE;
/* For the moment there are no checks on encoding resource files to
* perform */
#ifdef FEAT_MBYTE
}
else
{
p_encoding = enc_skip(p_penc);
if (*p_encoding == NUL)
p_encoding = enc_skip(p_enc);
if (prt_use_courier)
{
/* Include ASCII range encoding vector */
if (!prt_find_resource(prt_ascii_encoding, res_encoding))
{
EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
prt_ascii_encoding);
return FALSE;
}
if (!prt_open_resource(res_encoding))
return FALSE;
/* For the moment there are no checks on encoding resource files to
* perform */
}
}
prt_conv.vc_type = CONV_NONE;
if (!(enc_canon_props(p_enc) & enc_canon_props(p_encoding) & ENC_8BIT)) {
/* Set up encoding conversion if required */
if (FAIL == convert_setup(&prt_conv, p_enc, p_encoding))
{
EMSG2(_("E620: Unable to convert to print encoding \"%s\""),
p_encoding);
return FALSE;
}
prt_do_conv = TRUE;
}
prt_do_conv = prt_conv.vc_type != CONV_NONE;
if (prt_out_mbyte && prt_custom_cmap)
{
/* Find user supplied CMap */
if (!prt_find_resource(prt_cmap, res_cmap))
{
EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
prt_cmap);
return FALSE;
}
if (!prt_open_resource(res_cmap))
return FALSE;
}
#endif
/* List resources supplied */
STRCPY(buffer, res_prolog->title);
STRCAT(buffer, " ");
STRCAT(buffer, res_prolog->version);
prt_dsc_resources("DocumentSuppliedResources", "procset", buffer);
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
STRCPY(buffer, res_cidfont->title);
STRCAT(buffer, " ");
STRCAT(buffer, res_cidfont->version);
prt_dsc_resources(NULL, "procset", buffer);
if (prt_custom_cmap)
{
STRCPY(buffer, res_cmap->title);
STRCAT(buffer, " ");
STRCAT(buffer, res_cmap->version);
prt_dsc_resources(NULL, "cmap", buffer);
}
}
if (!prt_out_mbyte || prt_use_courier)
#endif
{
STRCPY(buffer, res_encoding->title);
STRCAT(buffer, " ");
STRCAT(buffer, res_encoding->version);
prt_dsc_resources(NULL, "encoding", buffer);
}
prt_dsc_requirements(prt_duplex, prt_tumble, prt_collate,
#ifdef FEAT_SYN_HL
psettings->do_syntax
#else
0
#endif
, prt_num_copies);
prt_dsc_noarg("EndComments");
/*
* PS Document page defaults
*/
prt_dsc_noarg("BeginDefaults");
/* List font resources most likely common to all pages */
#ifdef FEAT_MBYTE
if (!prt_out_mbyte || prt_use_courier)
#endif
prt_dsc_font_resource("PageResources", &prt_ps_courier_font);
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
prt_dsc_font_resource((prt_use_courier ? NULL : "PageResources"),
&prt_ps_mb_font);
if (!prt_custom_cmap)
prt_dsc_resources(NULL, "cmap", prt_cmap);
}
#endif
/* Paper will be used for all pages */
prt_dsc_textline("PageMedia", prt_mediasize[prt_media].name);
prt_dsc_noarg("EndDefaults");
/*
* PS Document prolog inclusion - all required procsets.
*/
prt_dsc_noarg("BeginProlog");
/* Add required procsets - NOTE: order is important! */
if (!prt_add_resource(res_prolog))
return FALSE;
#ifdef FEAT_MBYTE
if (prt_out_mbyte)
{
/* Add CID font procset, and any user supplied CMap */
if (!prt_add_resource(res_cidfont))
return FALSE;
if (prt_custom_cmap && !prt_add_resource(res_cmap))
return FALSE;
}
#endif
#ifdef FEAT_MBYTE
if (!prt_out_mbyte || prt_use_courier)
#endif
/* There will be only one Roman font encoding to be included in the PS
* file. */
if (!prt_add_resource(res_encoding))
return FALSE;
prt_dsc_noarg("EndProlog");
/*
* PS Document setup - must appear after the prolog
*/
prt_dsc_noarg("BeginSetup");
/* Device setup - page size and number of uncollated copies */
prt_write_int((int)prt_mediasize[prt_media].width);
prt_write_int((int)prt_mediasize[prt_media].height);
prt_write_int(0);
prt_write_string("sps\n");
prt_write_int(prt_num_copies);
prt_write_string("nc\n");
prt_write_boolean(prt_duplex);
prt_write_boolean(prt_tumble);
prt_write_string("dt\n");
prt_write_boolean(prt_collate);
prt_write_string("c\n");
/* Font resource inclusion and definition */
#ifdef FEAT_MBYTE
if (!prt_out_mbyte || prt_use_courier)
{
/* When using Courier for ASCII range when printing multi-byte, need to
* pick up ASCII encoding to use with it. */
if (prt_use_courier)
p_encoding = (char_u *)prt_ascii_encoding;
#endif
prt_dsc_resources("IncludeResource", "font",
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
prt_def_font("F0", (char *)p_encoding, (int)prt_line_height,
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
prt_dsc_resources("IncludeResource", "font",
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
prt_def_font("F1", (char *)p_encoding, (int)prt_line_height,
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
prt_dsc_resources("IncludeResource", "font",
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
prt_def_font("F2", (char *)p_encoding, (int)prt_line_height,
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
prt_dsc_resources("IncludeResource", "font",
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
prt_def_font("F3", (char *)p_encoding, (int)prt_line_height,
prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
#ifdef FEAT_MBYTE
}
if (prt_out_mbyte)
{
/* Define the CID fonts to be used in the job. Typically CJKV fonts do
* not have an italic form being a western style, so where no font is
* defined for these faces VIM falls back to an existing face.
* Note: if using Courier for the ASCII range then the printout will
* have bold/italic/bolditalic regardless of the setting of printmbfont.
*/
prt_dsc_resources("IncludeResource", "font",
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);
if (!prt_custom_cmap)
prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
prt_def_cidfont("CF0", (int)prt_line_height,
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);
if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD] != NULL)
{
prt_dsc_resources("IncludeResource", "font",
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
if (!prt_custom_cmap)
prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
prt_def_cidfont("CF1", (int)prt_line_height,
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
}
else
/* Use ROMAN for BOLD */
prt_dup_cidfont("CF0", "CF1");
if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE] != NULL)
{
prt_dsc_resources("IncludeResource", "font",
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
if (!prt_custom_cmap)
prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
prt_def_cidfont("CF2", (int)prt_line_height,
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
}
else
/* Use ROMAN for OBLIQUE */
prt_dup_cidfont("CF0", "CF2");
if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE] != NULL)
{
prt_dsc_resources("IncludeResource", "font",
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
if (!prt_custom_cmap)
prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
prt_def_cidfont("CF3", (int)prt_line_height,
prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
}
else
/* Use BOLD for BOLDOBLIQUE */
prt_dup_cidfont("CF1", "CF3");
}
#endif
/* Misc constant vars used for underlining and background rects */
prt_def_var("UO", PRT_PS_FONT_TO_USER(prt_line_height,
prt_ps_font->uline_offset), 2);
prt_def_var("UW", PRT_PS_FONT_TO_USER(prt_line_height,
prt_ps_font->uline_width), 2);
prt_def_var("BO", prt_bgcol_offset, 2);
prt_dsc_noarg("EndSetup");
/* Fail if any problems writing out to the PS file */
retval = !prt_file_error;
theend:
vim_free(res_prolog);
vim_free(res_encoding);
#ifdef FEAT_MBYTE
vim_free(res_cidfont);
vim_free(res_cmap);
#endif
return retval;
}
void
mch_print_end(psettings)
prt_settings_T *psettings;
{
prt_dsc_noarg("Trailer");
/*
* Output any info we don't know in toto until we finish
*/
prt_dsc_ints("Pages", 1, &prt_page_num);
prt_dsc_noarg("EOF");
/* Write CTRL-D to close serial communication link if used.
* NOTHING MUST BE WRITTEN AFTER THIS! */
prt_write_file((char_u *)IF_EB("\004", "\067"));
if (!prt_file_error && psettings->outfile == NULL
&& !got_int && !psettings->user_abort)
{
/* Close the file first. */
if (prt_ps_fd != NULL)
{
fclose(prt_ps_fd);
prt_ps_fd = NULL;
}
prt_message((char_u *)_("Sending to printer..."));
/* Not printing to a file: use 'printexpr' to print the file. */
if (eval_printexpr(prt_ps_file_name, psettings->arguments) == FAIL)
EMSG(_("E365: Failed to print PostScript file"));
else
prt_message((char_u *)_("Print job sent."));
}
mch_print_cleanup();
}
int
mch_print_end_page()
{
prt_flush_buffer();
prt_write_string("re sp\n");
prt_dsc_noarg("PageTrailer");
return !prt_file_error;
}
int
mch_print_begin_page(str)
char_u *str UNUSED;
{
int page_num[2];
prt_page_num++;
page_num[0] = page_num[1] = prt_page_num;
prt_dsc_ints("Page", 2, page_num);
prt_dsc_noarg("BeginPageSetup");
prt_write_string("sv\n0 g\n");
#ifdef FEAT_MBYTE
prt_in_ascii = !prt_out_mbyte;
if (prt_out_mbyte)
prt_write_string("CF0 sf\n");
else
#endif
prt_write_string("F0 sf\n");
prt_fgcol = PRCOLOR_BLACK;
prt_bgcol = PRCOLOR_WHITE;
prt_font = PRT_PS_FONT_ROMAN;
/* Set up page transformation for landscape printing. */
if (!prt_portrait)
{
prt_write_int(-((int)prt_mediasize[prt_media].width));
prt_write_string("sl\n");
}
prt_dsc_noarg("EndPageSetup");
/* We have reset the font attributes, force setting them again. */
curr_bg = (long_u)0xffffffff;
curr_fg = (long_u)0xffffffff;
curr_bold = MAYBE;
return !prt_file_error;
}
int
mch_print_blank_page()
{
return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
}
static float prt_pos_x = 0;
static float prt_pos_y = 0;
void
mch_print_start_line(margin, page_line)
int margin;
int page_line;
{
prt_pos_x = prt_left_margin;
if (margin)
prt_pos_x -= prt_number_width;
prt_pos_y = prt_top_margin - prt_first_line_height -
page_line * prt_line_height;
prt_attribute_change = TRUE;
prt_need_moveto = TRUE;
#ifdef FEAT_MBYTE
prt_half_width = FALSE;
#endif
}
int
mch_print_text_out(p, len)
char_u *p;
int len UNUSED;
{
int need_break;
char_u ch;
char_u ch_buff[8];
float char_width;
float next_pos;
#ifdef FEAT_MBYTE
int in_ascii;
int half_width;
#endif
char_width = prt_char_width;
#ifdef FEAT_MBYTE
/* Ideally VIM would create a rearranged CID font to combine a Roman and
* CJKV font to do what VIM is doing here - use a Roman font for characters
* in the ASCII range, and the original CID font for everything else.
* The problem is that GhostScript still (as of 8.13) does not support
* rearranged fonts even though they have been documented by Adobe for 7
* years! If they ever do, a lot of this code will disappear.
*/
if (prt_use_courier)
{
in_ascii = (len == 1 && *p < 0x80);
if (prt_in_ascii)
{
if (!in_ascii)
{
/* No longer in ASCII range - need to switch font */
prt_in_ascii = FALSE;
prt_need_font = TRUE;
prt_attribute_change = TRUE;
}
}
else if (in_ascii)
{
/* Now in ASCII range - need to switch font */
prt_in_ascii = TRUE;
prt_need_font = TRUE;
prt_attribute_change = TRUE;
}
}
if (prt_out_mbyte)
{
half_width = ((*mb_ptr2cells)(p) == 1);
if (half_width)
char_width /= 2;
if (prt_half_width)
{
if (!half_width)
{
prt_half_width = FALSE;
prt_pos_x += prt_char_width/4;
prt_need_moveto = TRUE;
prt_attribute_change = TRUE;
}
}
else if (half_width)
{
prt_half_width = TRUE;
prt_pos_x += prt_char_width/4;
prt_need_moveto = TRUE;
prt_attribute_change = TRUE;
}
}
#endif
/* Output any required changes to the graphics state, after flushing any
* text buffered so far.
*/
if (prt_attribute_change)
{
prt_flush_buffer();
/* Reset count of number of chars that will be printed */
prt_text_run = 0;
if (prt_need_moveto)
{
prt_pos_x_moveto = prt_pos_x;
prt_pos_y_moveto = prt_pos_y;
prt_do_moveto = TRUE;
prt_need_moveto = FALSE;
}
if (prt_need_font)
{
#ifdef FEAT_MBYTE
if (!prt_in_ascii)
prt_write_string("CF");
else
#endif
prt_write_string("F");
prt_write_int(prt_font);
prt_write_string("sf\n");
prt_need_font = FALSE;
}
if (prt_need_fgcol)
{
int r, g, b;
r = ((unsigned)prt_fgcol & 0xff0000) >> 16;
g = ((unsigned)prt_fgcol & 0xff00) >> 8;
b = prt_fgcol & 0xff;
prt_write_real(r / 255.0, 3);
if (r == g && g == b)
prt_write_string("g\n");
else
{
prt_write_real(g / 255.0, 3);
prt_write_real(b / 255.0, 3);
prt_write_string("r\n");
}
prt_need_fgcol = FALSE;
}
if (prt_bgcol != PRCOLOR_WHITE)
{
prt_new_bgcol = prt_bgcol;
if (prt_need_bgcol)
prt_do_bgcol = TRUE;
}
else
prt_do_bgcol = FALSE;
prt_need_bgcol = FALSE;
if (prt_need_underline)
prt_do_underline = prt_underline;
prt_need_underline = FALSE;
prt_attribute_change = FALSE;
}
#ifdef FEAT_MBYTE
if (prt_do_conv)
{
/* Convert from multi-byte to 8-bit encoding */
p = string_convert(&prt_conv, p, &len);
if (p == NULL)
p = (char_u *)"";
}
if (prt_out_mbyte)
{
/* Multi-byte character strings are represented more efficiently as hex
* strings when outputting clean 8 bit PS.
*/
do
{
ch = prt_hexchar[(unsigned)(*p) >> 4];
ga_append(&prt_ps_buffer, ch);
ch = prt_hexchar[(*p) & 0xf];
ga_append(&prt_ps_buffer, ch);
p++;
}
while (--len);
}
else
#endif
{
/* Add next character to buffer of characters to output.
* Note: One printed character may require several PS characters to
* represent it, but we only count them as one printed character.
*/
ch = *p;
if (ch < 32 || ch == '(' || ch == ')' || ch == '\\')
{
/* Convert non-printing characters to either their escape or octal
* sequence, ensures PS sent over a serial line does not interfere
* with the comms protocol. Note: For EBCDIC we need to write out
* the escape sequences as ASCII codes!
* Note 2: Char codes < 32 are identical in EBCDIC and ASCII AFAIK!
*/
ga_append(&prt_ps_buffer, IF_EB('\\', 0134));
switch (ch)
{
case BS: ga_append(&prt_ps_buffer, IF_EB('b', 0142)); break;
case TAB: ga_append(&prt_ps_buffer, IF_EB('t', 0164)); break;
case NL: ga_append(&prt_ps_buffer, IF_EB('n', 0156)); break;
case FF: ga_append(&prt_ps_buffer, IF_EB('f', 0146)); break;
case CAR: ga_append(&prt_ps_buffer, IF_EB('r', 0162)); break;
case '(': ga_append(&prt_ps_buffer, IF_EB('(', 0050)); break;
case ')': ga_append(&prt_ps_buffer, IF_EB(')', 0051)); break;
case '\\': ga_append(&prt_ps_buffer, IF_EB('\\', 0134)); break;
default:
sprintf((char *)ch_buff, "%03o", (unsigned int)ch);
#ifdef EBCDIC
ebcdic2ascii(ch_buff, 3);
#endif
ga_append(&prt_ps_buffer, ch_buff[0]);
ga_append(&prt_ps_buffer, ch_buff[1]);
ga_append(&prt_ps_buffer, ch_buff[2]);
break;
}
}
else
ga_append(&prt_ps_buffer, ch);
}
#ifdef FEAT_MBYTE
/* Need to free any translated characters */
if (prt_do_conv && (*p != NUL))
vim_free(p);
#endif
prt_text_run += char_width;
prt_pos_x += char_width;
/* The downside of fp - use relative error on right margin check */
next_pos = prt_pos_x + prt_char_width;
need_break = (next_pos > prt_right_margin) &&
((next_pos - prt_right_margin) > (prt_right_margin*1e-5));
if (need_break)
prt_flush_buffer();
return need_break;
}
void
mch_print_set_font(iBold, iItalic, iUnderline)
int iBold;
int iItalic;
int iUnderline;
{
int font = 0;
if (iBold)
font |= 0x01;
if (iItalic)
font |= 0x02;
if (font != prt_font)
{
prt_font = font;
prt_attribute_change = TRUE;
prt_need_font = TRUE;
}
if (prt_underline != iUnderline)
{
prt_underline = iUnderline;
prt_attribute_change = TRUE;
prt_need_underline = TRUE;
}
}
void
mch_print_set_bg(bgcol)
long_u bgcol;
{
prt_bgcol = (int)bgcol;
prt_attribute_change = TRUE;
prt_need_bgcol = TRUE;
}
void
mch_print_set_fg(fgcol)
long_u fgcol;
{
if (fgcol != (long_u)prt_fgcol)
{
prt_fgcol = (int)fgcol;
prt_attribute_change = TRUE;
prt_need_fgcol = TRUE;
}
}
# endif /*FEAT_POSTSCRIPT*/
#endif /*FEAT_PRINTER*/
| zyz2011-vim | src/hardcopy.c | C | gpl2 | 97,381 |
#! /bin/sh
# installman.sh --- install or uninstall manpages for Vim
#
# arguments:
# 1 what: "install", "uninstall" or "xxd"
# 2 target directory e.g., "/usr/local/man/it/man1"
# 3 language addition e.g., "" or "-it"
# 4 vim location as used in manual pages e.g., "/usr/local/share/vim"
# 5 runtime dir for menu.vim et al. e.g., "/usr/local/share/vim/vim70"
# 6 runtime dir for global vimrc file e.g., "/usr/local/share/vim"
# 7 source dir for help files e.g., "../runtime/doc"
# 8 mode bits for manpages e.g., "644"
# 9 vim exe name e.g., "vim"
# 10 name of vimdiff exe e.g., "vimdiff"
# 11 name of evim exe e.g., "evim"
errstatus=0
what=$1
destdir=$2
langadd=$3
vimloc=$4
scriptloc=$5
vimrcloc=$6
helpsource=$7
manmod=$8
exename=$9
# older shells don't support ${10}
shift
vimdiffname=$9
shift
evimname=$9
helpsubloc=$scriptloc/doc
printsubloc=$scriptloc/print
synsubloc=$scriptloc/syntax
tutorsubloc=$scriptloc/tutor
if test $what = "install" -o $what = "xxd"; then
if test ! -d $destdir; then
echo creating $destdir
./mkinstalldirs $destdir
fi
fi
if test $what = "install"; then
# vim.1
echo installing $destdir/$exename.1
sed -e s+/usr/local/lib/vim+$vimloc+ \
-e s+$vimloc/doc+$helpsubloc+ \
-e s+$vimloc/print+$printsubloc+ \
-e s+$vimloc/syntax+$synsubloc+ \
-e s+$vimloc/tutor+$tutorsubloc+ \
-e s+$vimloc/vimrc+$vimrcloc/vimrc+ \
-e s+$vimloc/gvimrc+$vimrcloc/gvimrc+ \
-e s+$vimloc/menu.vim+$scriptloc/menu.vim+ \
-e s+$vimloc/bugreport.vim+$scriptloc/bugreport.vim+ \
-e s+$vimloc/filetype.vim+$scriptloc/filetype.vim+ \
-e s+$vimloc/scripts.vim+$scriptloc/scripts.vim+ \
-e s+$vimloc/optwin.vim+$scriptloc/optwin.vim+ \
-e 's+$vimloc/\*.ps+$scriptloc/\*.ps+' \
$helpsource/vim$langadd.1 > $destdir/$exename.1
chmod $manmod $destdir/$exename.1
# vimtutor.1
echo installing $destdir/$exename""tutor.1
sed -e s+/usr/local/lib/vim+$vimloc+ \
-e s+$vimloc/tutor+$tutorsubloc+ \
$helpsource/vimtutor$langadd.1 > $destdir/$exename""tutor.1
chmod $manmod $destdir/$exename""tutor.1
# vimdiff.1
echo installing $destdir/$vimdiffname.1
cp $helpsource/vimdiff$langadd.1 $destdir/$vimdiffname.1
chmod $manmod $destdir/$vimdiffname.1
# evim.1
echo installing $destdir/$evimname.1
sed -e s+/usr/local/lib/vim+$vimloc+ \
-e s+$vimloc/evim.vim+$scriptloc/evim.vim+ \
$helpsource/evim$langadd.1 > $destdir/$evimname.1
chmod $manmod $destdir/$evimname.1
fi
if test $what = "uninstall"; then
echo Checking for Vim manual pages in $destdir...
if test -r $destdir/$exename.1; then
echo deleting $destdir/$exename.1
rm -f $destdir/$exename.1
fi
if test -r $destdir/$exename""tutor.1; then
echo deleting $destdir/$exename""tutor.1
rm -f $destdir/$exename""tutor.1
fi
if test -r $destdir/$vimdiffname.1; then
echo deleting $destdir/$vimdiffname.1
rm -f $destdir/$vimdiffname.1
fi
if test -r $destdir/$evimname.1; then
echo deleting $destdir/$evimname.1
rm -f $destdir/$evimname.1
fi
fi
if test $what = "xxd"; then
echo installing $destdir/xxd.1
cp $helpsource/xxd$langadd.1 $destdir/xxd.1
chmod $manmod $destdir/xxd.1
fi
exit $errstatus
# vim: set sw=3 sts=3 :
| zyz2011-vim | src/installman.sh | Shell | gpl2 | 3,329 |
/* 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.
*/
#if !defined(WORKSHOP_H) && defined(FEAT_SUN_WORKSHOP)
#define WORKSHOP_H
#include <X11/Intrinsic.h>
#include <Xm/Xm.h>
#include "integration.h"
#ifdef WSDEBUG
# include "wsdebug.h"
#else
# ifndef ASSERT
# define ASSERT(c)
# endif
#endif
extern int usingSunWorkShop; /* set if -ws flag is used */
#endif
| zyz2011-vim | src/workshop.h | C | gpl2 | 575 |
/* 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.
*/
#ifndef VIM__H
# define VIM__H
/* use fastcall for Borland, when compiling for Win32 (not for DOS16) */
#if defined(__BORLANDC__) && defined(WIN32) && !defined(DEBUG)
#if defined(FEAT_PERL) || \
defined(FEAT_PYTHON) || \
defined(FEAT_PYTHON3) || \
defined(FEAT_RUBY) || \
defined(FEAT_TCL) || \
defined(FEAT_MZSCHEME) || \
defined(DYNAMIC_GETTEXT) || \
defined(DYNAMIC_ICONV) || \
defined(DYNAMIC_IME) || \
defined(XPM)
#pragma option -pc
# else
#pragma option -pr
# endif
#endif
#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64) \
|| defined(__EMX__)
# include "vimio.h"
#endif
/* ============ the header file puzzle (ca. 50-100 pieces) ========= */
#ifdef HAVE_CONFIG_H /* GNU autoconf (or something else) was here */
# include "auto/config.h"
# define HAVE_PATHDEF
/*
* Check if configure correctly managed to find sizeof(int). If this failed,
* it becomes zero. This is likely a problem of not being able to run the
* test program. Other items from configure may also be wrong then!
*/
# if (SIZEOF_INT == 0)
Error: configure did not run properly. Check auto/config.log.
# endif
/*
* Cygwin may have fchdir() in a newer release, but in most versions it
* doesn't work well and avoiding it keeps the binary backward compatible.
*/
# if defined(__CYGWIN32__) && defined(HAVE_FCHDIR)
# undef HAVE_FCHDIR
# endif
/* We may need to define the uint32_t on non-Unix system, but using the same
* identifier causes conflicts. Therefore use UINT32_T. */
# define UINT32_TYPEDEF uint32_t
#endif
#if !defined(UINT32_TYPEDEF)
# if defined(uint32_t) /* this doesn't catch typedefs, unfortunately */
# define UINT32_TYPEDEF uint32_t
# else
/* Fall back to assuming unsigned int is 32 bit. If this is wrong then the
* test in blowfish.c will fail. */
# define UINT32_TYPEDEF unsigned int
# endif
#endif
/* user ID of root is usually zero, but not for everybody */
#ifdef __TANDEM
# ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE
# endif
# include <floss.h>
# define ROOT_UID 65535
#else
# define ROOT_UID 0
#endif
#ifdef __EMX__ /* hand-edited config.h for OS/2 with EMX */
# include "os_os2_cfg.h"
#endif
/*
* MACOS_CLASSIC compiling for MacOS prior to MacOS X
* MACOS_X_UNIX compiling for MacOS X (using os_unix.c)
* MACOS_X compiling for MacOS X (using os_unix.c)
* MACOS compiling for either one
*/
#if defined(macintosh) && !defined(MACOS_CLASSIC)
# define MACOS_CLASSIC
#endif
#if defined(MACOS_X_UNIX)
# define MACOS_X
# ifndef HAVE_CONFIG_H
# define UNIX
# endif
# ifndef FEAT_CLIPBOARD
# define FEAT_CLIPBOARD
# endif
#endif
#if defined(MACOS_X) || defined(MACOS_CLASSIC)
# define MACOS
#endif
#if defined(MACOS_X) && defined(MACOS_CLASSIC)
Error: To compile for both MACOS X and Classic use a Classic Carbon
#endif
/* Unless made through the Makefile enforce GUI on Mac */
#if defined(MACOS) && !defined(HAVE_CONFIG_H)
# define FEAT_GUI_MAC
#endif
#if defined(FEAT_GUI_MOTIF) \
|| defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_ATHENA) \
|| defined(FEAT_GUI_MAC) \
|| defined(FEAT_GUI_W32) \
|| defined(FEAT_GUI_W16) \
|| defined(FEAT_GUI_PHOTON)
# define FEAT_GUI_ENABLED /* also defined with NO_X11_INCLUDES */
# if !defined(FEAT_GUI) && !defined(NO_X11_INCLUDES)
# define FEAT_GUI
# endif
#endif
/* Visual Studio 2005 has 'deprecated' many of the standard CRT functions */
#if _MSC_VER >= 1400
# define _CRT_SECURE_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
#endif
#if defined(FEAT_GUI_W32) || defined(FEAT_GUI_W16)
# define FEAT_GUI_MSWIN
#endif
#if defined(WIN16) || defined(WIN32) || defined(_WIN64)
# define MSWIN
#endif
/* Practically everything is common to both Win32 and Win64 */
#if defined(WIN32) || defined(_WIN64)
# define WIN3264
#endif
/*
* SIZEOF_INT is used in feature.h, and the system-specific included files
* need items from feature.h. Therefore define SIZEOF_INT here.
*/
#ifdef WIN3264
# define SIZEOF_INT 4
#endif
#ifdef MSDOS
# ifdef DJGPP
# ifndef FEAT_GUI_GTK /* avoid problems when generating prototypes */
# define SIZEOF_INT 4 /* 32 bit ints */
# endif
# define DOS32
# define FEAT_CLIPBOARD
# else
# ifndef FEAT_GUI_GTK /* avoid problems when generating prototypes */
# define SIZEOF_INT 2 /* 16 bit ints */
# endif
# define SMALL_MALLOC /* 16 bit storage allocation */
# define DOS16
# endif
#endif
#ifdef AMIGA
/* Be conservative about sizeof(int). It could be 4 too. */
# ifndef FEAT_GUI_GTK /* avoid problems when generating prototypes */
# ifdef __GNUC__
# define SIZEOF_INT 4
# else
# define SIZEOF_INT 2
# endif
# endif
#endif
#ifdef MACOS
# if defined(__POWERPC__) || defined(MACOS_X) || defined(__fourbyteints__) \
|| defined(__MRC__) || defined(__SC__) || defined(__APPLE_CC__)/* MPW Compilers */
# define SIZEOF_INT 4
# else
# define SIZEOF_INT 2
# endif
#endif
#include "feature.h" /* #defines for optionals and features */
/* +x11 is only enabled when it's both available and wanted. */
#if defined(HAVE_X11) && defined(WANT_X11)
# define FEAT_X11
#endif
#ifdef NO_X11_INCLUDES
/* In os_mac_conv.c and os_macosx.m NO_X11_INCLUDES is defined to avoid
* X11 headers. Disable all X11 related things to avoid conflicts. */
# ifdef FEAT_X11
# undef FEAT_X11
# endif
# ifdef FEAT_GUI_X11
# undef FEAT_GUI_X11
# endif
# ifdef FEAT_XCLIPBOARD
# undef FEAT_XCLIPBOARD
# endif
# ifdef FEAT_GUI_MOTIF
# undef FEAT_GUI_MOTIF
# endif
# ifdef FEAT_GUI_ATHENA
# undef FEAT_GUI_ATHENA
# endif
# ifdef FEAT_GUI_GTK
# undef FEAT_GUI_GTK
# endif
# ifdef FEAT_BEVAL_TIP
# undef FEAT_BEVAL_TIP
# endif
# ifdef FEAT_XIM
# undef FEAT_XIM
# endif
# ifdef FEAT_CLIENTSERVER
# undef FEAT_CLIENTSERVER
# endif
#endif
/* The Mac conversion stuff doesn't work under X11. */
#if defined(FEAT_MBYTE) && defined(MACOS_X)
# define MACOS_CONVERT
#endif
/* Can't use "PACKAGE" here, conflicts with a Perl include file. */
#ifndef VIMPACKAGE
# define VIMPACKAGE "vim"
#endif
/*
* Find out if function definitions should include argument types
*/
#ifdef AZTEC_C
# include <functions.h>
# define __ARGS(x) x
#endif
#ifdef SASC
# include <clib/exec_protos.h>
# define __ARGS(x) x
#endif
#ifdef _DCC
# include <clib/exec_protos.h>
# define __ARGS(x) x
#endif
#ifdef __TURBOC__
# define __ARGS(x) x
#endif
#ifdef __BEOS__
# include "os_beos.h"
# define __ARGS(x) x
#endif
#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) \
&& (!defined(MACOS_X) || defined(HAVE_CONFIG_H))
# include "os_unix.h" /* bring lots of system header files */
#endif
#if defined(MACOS) && (defined(__MRC__) || defined(__SC__))
/* Apple's Compilers support prototypes */
# define __ARGS(x) x
#endif
#ifndef __ARGS
# if defined(__STDC__) || defined(__GNUC__) || defined(WIN3264)
# define __ARGS(x) x
# else
# define __ARGS(x) ()
# endif
#endif
/* __ARGS and __PARMS are the same thing. */
#ifndef __PARMS
# define __PARMS(x) __ARGS(x)
#endif
/* Mark unused function arguments with UNUSED, so that gcc -Wunused-parameter
* can be used to check for mistakes. */
#ifdef HAVE_ATTRIBUTE_UNUSED
# define UNUSED __attribute__((unused))
#else
# define UNUSED
#endif
/* if we're compiling in C++ (currently only KVim), the system
* headers must have the correct prototypes or nothing will build.
* conversely, our prototypes might clash due to throw() specifiers and
* cause compilation failures even though the headers are correct. For
* a concrete example, gcc-3.2 enforces exception specifications, and
* glibc-2.2.5 has them in their system headers.
*/
#if !defined(__cplusplus) && defined(UNIX) \
&& !defined(MACOS_X) /* MACOS_X doesn't yet support osdef.h */
# include "auto/osdef.h" /* bring missing declarations in */
#endif
#ifdef __EMX__
# define getcwd _getcwd2
# define chdir _chdir2
# undef CHECK_INODE
#endif
#ifdef AMIGA
# include "os_amiga.h"
#endif
#ifdef MSDOS
# include "os_msdos.h"
#endif
#ifdef WIN16
# include "os_win16.h"
#endif
#ifdef WIN3264
# include "os_win32.h"
#endif
#ifdef __MINT__
# include "os_mint.h"
#endif
#if defined(MACOS)
# if defined(__MRC__) || defined(__SC__) /* MPW Compilers */
# define HAVE_SETENV
# endif
# include "os_mac.h"
#endif
#ifdef __QNX__
# include "os_qnx.h"
#endif
#ifdef FEAT_SUN_WORKSHOP
# include "workshop.h"
#endif
#ifdef X_LOCALE
# include <X11/Xlocale.h>
#else
# ifdef HAVE_LOCALE_H
# include <locale.h>
# endif
#endif
/*
* Maximum length of a path (for non-unix systems) Make it a bit long, to stay
* on the safe side. But not too long to put on the stack.
*/
#ifndef MAXPATHL
# ifdef MAXPATHLEN
# define MAXPATHL MAXPATHLEN
# else
# define MAXPATHL 256
# endif
#endif
#ifdef BACKSLASH_IN_FILENAME
# define PATH_ESC_CHARS ((char_u *)" \t\n*?[{`%#'\"|!<")
#else
# ifdef VMS
/* VMS allows a lot of characters in the file name */
# define PATH_ESC_CHARS ((char_u *)" \t\n*?{`\\%#'\"|!")
# define SHELL_ESC_CHARS ((char_u *)" \t\n*?{`\\%#'|!()&")
# else
# define PATH_ESC_CHARS ((char_u *)" \t\n*?[{`$\\%#'\"|!<")
# define SHELL_ESC_CHARS ((char_u *)" \t\n*?[{`$\\%#'\"|!<>();&")
# endif
#endif
#define NUMBUFLEN 30 /* length of a buffer to store a number in ASCII */
/*
* Shorthand for unsigned variables. Many systems, but not all, have u_char
* already defined, so we use char_u to avoid trouble.
*/
typedef unsigned char char_u;
typedef unsigned short short_u;
typedef unsigned int int_u;
/* Make sure long_u is big enough to hold a pointer.
* On Win64, longs are 32 bits and pointers are 64 bits.
* For printf() and scanf(), we need to take care of long_u specifically. */
#ifdef _WIN64
typedef unsigned __int64 long_u;
typedef __int64 long_i;
# define SCANF_HEX_LONG_U "%Ix"
# define SCANF_DECIMAL_LONG_U "%Iu"
# define PRINTF_HEX_LONG_U "0x%Ix"
#else
/* Microsoft-specific. The __w64 keyword should be specified on any typedefs
* that change size between 32-bit and 64-bit platforms. For any such type,
* __w64 should appear only on the 32-bit definition of the typedef.
* Define __w64 as an empty token for everything but MSVC 7.x or later.
*/
# if !defined(_MSC_VER) || (_MSC_VER < 1300)
# define __w64
# endif
typedef unsigned long __w64 long_u;
typedef long __w64 long_i;
# define SCANF_HEX_LONG_U "%lx"
# define SCANF_DECIMAL_LONG_U "%lu"
# define PRINTF_HEX_LONG_U "0x%lx"
#endif
#define PRINTF_DECIMAL_LONG_U SCANF_DECIMAL_LONG_U
/*
* Only systems which use configure will have SIZEOF_OFF_T and SIZEOF_LONG
* defined, which is ok since those are the same systems which can have
* varying sizes for off_t. The other systems will continue to use "%ld" to
* print off_t since off_t is simply a typedef to long for them.
*/
#if defined(SIZEOF_OFF_T) && (SIZEOF_OFF_T > SIZEOF_LONG)
# define LONG_LONG_OFF_T
#endif
/*
* The characters and attributes cached for the screen.
*/
typedef char_u schar_T;
#ifdef FEAT_SYN_HL
typedef unsigned short sattr_T;
# define MAX_TYPENR 65535
#else
typedef unsigned char sattr_T;
# define MAX_TYPENR 255
#endif
/*
* The u8char_T can hold one decoded UTF-8 character.
* We normally use 32 bits now, since some Asian characters don't fit in 16
* bits. u8char_T is only used for displaying, it could be 16 bits to save
* memory.
*/
#ifdef FEAT_MBYTE
# ifdef UNICODE16
typedef unsigned short u8char_T; /* short should be 16 bits */
# else
# if SIZEOF_INT >= 4
typedef unsigned int u8char_T; /* int is 32 bits */
# else
typedef unsigned long u8char_T; /* long should be 32 bits or more */
# endif
# endif
#endif
#ifndef UNIX /* For Unix this is included in os_unix.h */
# include <stdio.h>
# include <ctype.h>
#endif
#include "ascii.h"
#include "keymap.h"
#include "term.h"
#include "macros.h"
#ifdef LATTICE
# include <sys/types.h>
# include <sys/stat.h>
#endif
#ifdef _DCC
# include <sys/stat.h>
#endif
#if defined(MSDOS) || defined(MSWIN)
# include <sys/stat.h>
#endif
#if defined(HAVE_ERRNO_H) || defined(DJGPP) || defined(WIN16) \
|| defined(WIN32) || defined(_WIN64) || defined(__EMX__)
# include <errno.h>
#endif
/*
* Allow other (non-unix) systems to configure themselves now
* These are also in os_unix.h, because osdef.sh needs them there.
*/
#ifndef UNIX
/* Note: Some systems need both string.h and strings.h (Savage). If the
* system can't handle this, define NO_STRINGS_WITH_STRING_H. */
# ifdef HAVE_STRING_H
# include <string.h>
# endif
# if defined(HAVE_STRINGS_H) && !defined(NO_STRINGS_WITH_STRING_H)
# include <strings.h>
# endif
# ifdef HAVE_STAT_H
# include <stat.h>
# endif
# ifdef HAVE_STDLIB_H
# include <stdlib.h>
# endif
#endif /* NON-UNIX */
#include <assert.h>
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#ifdef HAVE_WCTYPE_H
# include <wctype.h>
#endif
#ifdef HAVE_STDARG_H
# include <stdarg.h>
#endif
# if defined(HAVE_SYS_SELECT_H) && \
(!defined(HAVE_SYS_TIME_H) || defined(SYS_SELECT_WITH_SYS_TIME))
# include <sys/select.h>
# endif
# ifndef HAVE_SELECT
# ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
# define HAVE_POLL
# else
# ifdef HAVE_POLL_H
# include <poll.h>
# define HAVE_POLL
# endif
# endif
# endif
/* ================ end of the header file puzzle =============== */
/*
* For dynamically loaded imm library. Currently, only for Win32.
*/
#ifdef DYNAMIC_IME
# ifndef FEAT_MBYTE_IME
# define FEAT_MBYTE_IME
# endif
#endif
/*
* Check input method control.
*/
#if defined(FEAT_XIM) \
|| (defined(FEAT_GUI) && (defined(FEAT_MBYTE_IME) || defined(GLOBAL_IME))) \
|| (defined(FEAT_GUI_MAC) && defined(FEAT_MBYTE))
# define USE_IM_CONTROL
#endif
/*
* For dynamically loaded gettext library. Currently, only for Win32.
*/
#ifdef DYNAMIC_GETTEXT
# ifndef FEAT_GETTEXT
# define FEAT_GETTEXT
# endif
/* These are in os_win32.c */
extern char *(*dyn_libintl_gettext)(const char *msgid);
extern char *(*dyn_libintl_bindtextdomain)(const char *domainname, const char *dirname);
extern char *(*dyn_libintl_bind_textdomain_codeset)(const char *domainname, const char *codeset);
extern char *(*dyn_libintl_textdomain)(const char *domainname);
#endif
/*
* The _() stuff is for using gettext(). It is a no-op when libintl.h is not
* found or the +multilang feature is disabled.
*/
#ifdef FEAT_GETTEXT
# ifdef DYNAMIC_GETTEXT
# define _(x) (*dyn_libintl_gettext)((char *)(x))
# define N_(x) x
# define bindtextdomain(domain, dir) (*dyn_libintl_bindtextdomain)((domain), (dir))
# define bind_textdomain_codeset(domain, codeset) (*dyn_libintl_bind_textdomain_codeset)((domain), (codeset))
# if !defined(HAVE_BIND_TEXTDOMAIN_CODESET)
# define HAVE_BIND_TEXTDOMAIN_CODESET 1
# endif
# define textdomain(domain) (*dyn_libintl_textdomain)(domain)
# else
# include <libintl.h>
# define _(x) gettext((char *)(x))
# ifdef gettext_noop
# define N_(x) gettext_noop(x)
# else
# define N_(x) x
# endif
# endif
#else
# define _(x) ((char *)(x))
# define N_(x) x
# ifdef bindtextdomain
# undef bindtextdomain
# endif
# define bindtextdomain(x, y) /* empty */
# ifdef bind_textdomain_codeset
# undef bind_textdomain_codeset
# endif
# define bind_textdomain_codeset(x, y) /* empty */
# ifdef textdomain
# undef textdomain
# endif
# define textdomain(x) /* empty */
#endif
/*
* flags for update_screen()
* The higher the value, the higher the priority
*/
#define VALID 10 /* buffer not changed, or changes marked
with b_mod_* */
#define INVERTED 20 /* redisplay inverted part that changed */
#define INVERTED_ALL 25 /* redisplay whole inverted part */
#define REDRAW_TOP 30 /* display first w_upd_rows screen lines */
#define SOME_VALID 35 /* like NOT_VALID but may scroll */
#define NOT_VALID 40 /* buffer needs complete redraw */
#define CLEAR 50 /* screen messed up, clear it */
/*
* Flags for w_valid.
* These are set when something in a window structure becomes invalid, except
* when the cursor is moved. Call check_cursor_moved() before testing one of
* the flags.
* These are reset when that thing has been updated and is valid again.
*
* Every function that invalidates one of these must call one of the
* invalidate_* functions.
*
* w_valid is supposed to be used only in screen.c. From other files, use the
* functions that set or reset the flags.
*
* VALID_BOTLINE VALID_BOTLINE_AP
* on on w_botline valid
* off on w_botline approximated
* off off w_botline not valid
* on off not possible
*/
#define VALID_WROW 0x01 /* w_wrow (window row) is valid */
#define VALID_WCOL 0x02 /* w_wcol (window col) is valid */
#define VALID_VIRTCOL 0x04 /* w_virtcol (file col) is valid */
#define VALID_CHEIGHT 0x08 /* w_cline_height and w_cline_folded valid */
#define VALID_CROW 0x10 /* w_cline_row is valid */
#define VALID_BOTLINE 0x20 /* w_botine and w_empty_rows are valid */
#define VALID_BOTLINE_AP 0x40 /* w_botine is approximated */
#define VALID_TOPLINE 0x80 /* w_topline is valid (for cursor position) */
/*
* Terminal highlighting attribute bits.
* Attributes above HL_ALL are used for syntax highlighting.
*/
#define HL_NORMAL 0x00
#define HL_INVERSE 0x01
#define HL_BOLD 0x02
#define HL_ITALIC 0x04
#define HL_UNDERLINE 0x08
#define HL_UNDERCURL 0x10
#define HL_STANDOUT 0x20
#define HL_ALL 0x3f
/* special attribute addition: Put message in history */
#define MSG_HIST 0x1000
/*
* values for State
*
* The lower bits up to 0x20 are used to distinguish normal/visual/op_pending
* and cmdline/insert+replace mode. This is used for mapping. If none of
* these bits are set, no mapping is done.
* The upper bits are used to distinguish between other states.
*/
#define NORMAL 0x01 /* Normal mode, command expected */
#define VISUAL 0x02 /* Visual mode - use get_real_state() */
#define OP_PENDING 0x04 /* Normal mode, operator is pending - use
get_real_state() */
#define CMDLINE 0x08 /* Editing command line */
#define INSERT 0x10 /* Insert mode */
#define LANGMAP 0x20 /* Language mapping, can be combined with
INSERT and CMDLINE */
#define REPLACE_FLAG 0x40 /* Replace mode flag */
#define REPLACE (REPLACE_FLAG + INSERT)
#ifdef FEAT_VREPLACE
# define VREPLACE_FLAG 0x80 /* Virtual-replace mode flag */
# define VREPLACE (REPLACE_FLAG + VREPLACE_FLAG + INSERT)
#endif
#define LREPLACE (REPLACE_FLAG + LANGMAP)
#define NORMAL_BUSY (0x100 + NORMAL) /* Normal mode, busy with a command */
#define HITRETURN (0x200 + NORMAL) /* waiting for return or command */
#define ASKMORE 0x300 /* Asking if you want --more-- */
#define SETWSIZE 0x400 /* window size has changed */
#define ABBREV 0x500 /* abbreviation instead of mapping */
#define EXTERNCMD 0x600 /* executing an external command */
#define SHOWMATCH (0x700 + INSERT) /* show matching paren */
#define CONFIRM 0x800 /* ":confirm" prompt */
#define SELECTMODE 0x1000 /* Select mode, only for mappings */
#define MAP_ALL_MODES (0x3f | SELECTMODE) /* all mode bits used for
* mapping */
/* directions */
#define FORWARD 1
#define BACKWARD (-1)
#define FORWARD_FILE 3
#define BACKWARD_FILE (-3)
/* return values for functions */
#if !(defined(OK) && (OK == 1))
/* OK already defined to 1 in MacOS X curses, skip this */
# define OK 1
#endif
#define FAIL 0
#define NOTDONE 2 /* not OK or FAIL but skipped */
/* flags for b_flags */
#define BF_RECOVERED 0x01 /* buffer has been recovered */
#define BF_CHECK_RO 0x02 /* need to check readonly when loading file
into buffer (set by ":e", may be reset by
":buf" */
#define BF_NEVERLOADED 0x04 /* file has never been loaded into buffer,
many variables still need to be set */
#define BF_NOTEDITED 0x08 /* Set when file name is changed after
starting to edit, reset when file is
written out. */
#define BF_NEW 0x10 /* file didn't exist when editing started */
#define BF_NEW_W 0x20 /* Warned for BF_NEW and file created */
#define BF_READERR 0x40 /* got errors while reading the file */
#define BF_DUMMY 0x80 /* dummy buffer, only used internally */
#define BF_PRESERVED 0x100 /* ":preserve" was used */
/* Mask to check for flags that prevent normal writing */
#define BF_WRITE_MASK (BF_NOTEDITED + BF_NEW + BF_READERR)
/*
* values for xp_context when doing command line completion
*/
#define EXPAND_UNSUCCESSFUL (-2)
#define EXPAND_OK (-1)
#define EXPAND_NOTHING 0
#define EXPAND_COMMANDS 1
#define EXPAND_FILES 2
#define EXPAND_DIRECTORIES 3
#define EXPAND_SETTINGS 4
#define EXPAND_BOOL_SETTINGS 5
#define EXPAND_TAGS 6
#define EXPAND_OLD_SETTING 7
#define EXPAND_HELP 8
#define EXPAND_BUFFERS 9
#define EXPAND_EVENTS 10
#define EXPAND_MENUS 11
#define EXPAND_SYNTAX 12
#define EXPAND_HIGHLIGHT 13
#define EXPAND_AUGROUP 14
#define EXPAND_USER_VARS 15
#define EXPAND_MAPPINGS 16
#define EXPAND_TAGS_LISTFILES 17
#define EXPAND_FUNCTIONS 18
#define EXPAND_USER_FUNC 19
#define EXPAND_EXPRESSION 20
#define EXPAND_MENUNAMES 21
#define EXPAND_USER_COMMANDS 22
#define EXPAND_USER_CMD_FLAGS 23
#define EXPAND_USER_NARGS 24
#define EXPAND_USER_COMPLETE 25
#define EXPAND_ENV_VARS 26
#define EXPAND_LANGUAGE 27
#define EXPAND_COLORS 28
#define EXPAND_COMPILER 29
#define EXPAND_USER_DEFINED 30
#define EXPAND_USER_LIST 31
#define EXPAND_SHELLCMD 32
#define EXPAND_CSCOPE 33
#define EXPAND_SIGN 34
#define EXPAND_PROFILE 35
#define EXPAND_BEHAVE 36
#define EXPAND_FILETYPE 37
#define EXPAND_FILES_IN_PATH 38
#define EXPAND_OWNSYNTAX 39
#define EXPAND_LOCALES 40
#define EXPAND_HISTORY 41
/* Values for exmode_active (0 is no exmode) */
#define EXMODE_NORMAL 1
#define EXMODE_VIM 2
/* Values for nextwild() and ExpandOne(). See ExpandOne() for meaning. */
#define WILD_FREE 1
#define WILD_EXPAND_FREE 2
#define WILD_EXPAND_KEEP 3
#define WILD_NEXT 4
#define WILD_PREV 5
#define WILD_ALL 6
#define WILD_LONGEST 7
#define WILD_ALL_KEEP 8
#define WILD_LIST_NOTFOUND 1
#define WILD_HOME_REPLACE 2
#define WILD_USE_NL 4
#define WILD_NO_BEEP 8
#define WILD_ADD_SLASH 16
#define WILD_KEEP_ALL 32
#define WILD_SILENT 64
#define WILD_ESCAPE 128
#define WILD_ICASE 256
/* Flags for expand_wildcards() */
#define EW_DIR 0x01 /* include directory names */
#define EW_FILE 0x02 /* include file names */
#define EW_NOTFOUND 0x04 /* include not found names */
#define EW_ADDSLASH 0x08 /* append slash to directory name */
#define EW_KEEPALL 0x10 /* keep all matches */
#define EW_SILENT 0x20 /* don't print "1 returned" from shell */
#define EW_EXEC 0x40 /* executable files */
#define EW_PATH 0x80 /* search in 'path' too */
#define EW_ICASE 0x100 /* ignore case */
#define EW_NOERROR 0x200 /* no error for bad regexp */
#define EW_NOTWILD 0x400 /* add match with literal name if exists */
/* Note: mostly EW_NOTFOUND and EW_SILENT are mutually exclusive: EW_NOTFOUND
* is used when executing commands and EW_SILENT for interactive expanding. */
/* Flags for find_file_*() functions. */
#define FINDFILE_FILE 0 /* only files */
#define FINDFILE_DIR 1 /* only directories */
#define FINDFILE_BOTH 2 /* files and directories */
#ifdef FEAT_VERTSPLIT
# define W_WINCOL(wp) (wp->w_wincol)
# define W_WIDTH(wp) (wp->w_width)
# define W_ENDCOL(wp) (wp->w_wincol + wp->w_width)
# define W_VSEP_WIDTH(wp) (wp->w_vsep_width)
#else
# define W_WINCOL(wp) 0
# define W_WIDTH(wp) Columns
# define W_ENDCOL(wp) Columns
# define W_VSEP_WIDTH(wp) 0
#endif
#ifdef FEAT_WINDOWS
# define W_STATUS_HEIGHT(wp) (wp->w_status_height)
# define W_WINROW(wp) (wp->w_winrow)
#else
# define W_STATUS_HEIGHT(wp) 0
# define W_WINROW(wp) 0
#endif
#ifdef NO_EXPANDPATH
# define gen_expand_wildcards mch_expand_wildcards
#endif
/* Values for the find_pattern_in_path() function args 'type' and 'action': */
#define FIND_ANY 1
#define FIND_DEFINE 2
#define CHECK_PATH 3
#define ACTION_SHOW 1
#define ACTION_GOTO 2
#define ACTION_SPLIT 3
#define ACTION_SHOW_ALL 4
#ifdef FEAT_INS_EXPAND
# define ACTION_EXPAND 5
#endif
#ifdef FEAT_SYN_HL
# define SST_MIN_ENTRIES 150 /* minimal size for state stack array */
# ifdef FEAT_GUI_W16
# define SST_MAX_ENTRIES 500 /* (only up to 64K blocks) */
# else
# define SST_MAX_ENTRIES 1000 /* maximal size for state stack array */
# endif
# define SST_FIX_STATES 7 /* size of sst_stack[]. */
# define SST_DIST 16 /* normal distance between entries */
# define SST_INVALID (synstate_T *)-1 /* invalid syn_state pointer */
# define HL_CONTAINED 0x01 /* not used on toplevel */
# define HL_TRANSP 0x02 /* has no highlighting */
# define HL_ONELINE 0x04 /* match within one line only */
# define HL_HAS_EOL 0x08 /* end pattern that matches with $ */
# define HL_SYNC_HERE 0x10 /* sync point after this item (syncing only) */
# define HL_SYNC_THERE 0x20 /* sync point at current line (syncing only) */
# define HL_MATCH 0x40 /* use match ID instead of item ID */
# define HL_SKIPNL 0x80 /* nextgroup can skip newlines */
# define HL_SKIPWHITE 0x100 /* nextgroup can skip white space */
# define HL_SKIPEMPTY 0x200 /* nextgroup can skip empty lines */
# define HL_KEEPEND 0x400 /* end match always kept */
# define HL_EXCLUDENL 0x800 /* exclude NL from match */
# define HL_DISPLAY 0x1000 /* only used for displaying, not syncing */
# define HL_FOLD 0x2000 /* define fold */
# define HL_EXTEND 0x4000 /* ignore a keepend */
# define HL_MATCHCONT 0x8000 /* match continued from previous line */
# define HL_TRANS_CONT 0x10000 /* transparent item without contains arg */
# define HL_CONCEAL 0x20000 /* can be concealed */
# define HL_CONCEALENDS 0x40000 /* can be concealed */
#endif
/* Values for 'options' argument in do_search() and searchit() */
#define SEARCH_REV 0x01 /* go in reverse of previous dir. */
#define SEARCH_ECHO 0x02 /* echo the search command and handle options */
#define SEARCH_MSG 0x0c /* give messages (yes, it's not 0x04) */
#define SEARCH_NFMSG 0x08 /* give all messages except not found */
#define SEARCH_OPT 0x10 /* interpret optional flags */
#define SEARCH_HIS 0x20 /* put search pattern in history */
#define SEARCH_END 0x40 /* put cursor at end of match */
#define SEARCH_NOOF 0x80 /* don't add offset to position */
#define SEARCH_START 0x100 /* start search without col offset */
#define SEARCH_MARK 0x200 /* set previous context mark */
#define SEARCH_KEEP 0x400 /* keep previous search pattern */
#define SEARCH_PEEK 0x800 /* peek for typed char, cancel search */
/* Values for find_ident_under_cursor() */
#define FIND_IDENT 1 /* find identifier (word) */
#define FIND_STRING 2 /* find any string (WORD) */
#define FIND_EVAL 4 /* include "->", "[]" and "." */
/* Values for file_name_in_line() */
#define FNAME_MESS 1 /* give error message */
#define FNAME_EXP 2 /* expand to path */
#define FNAME_HYP 4 /* check for hypertext link */
#define FNAME_INCL 8 /* apply 'includeexpr' */
#define FNAME_REL 16 /* ".." and "./" are relative to the (current)
file instead of the current directory */
/* Values for buflist_getfile() */
#define GETF_SETMARK 0x01 /* set pcmark before jumping */
#define GETF_ALT 0x02 /* jumping to alternate file (not buf num) */
#define GETF_SWITCH 0x04 /* respect 'switchbuf' settings when jumping */
/* Values for buflist_new() flags */
#define BLN_CURBUF 1 /* May re-use curbuf for new buffer */
#define BLN_LISTED 2 /* Put new buffer in buffer list */
#define BLN_DUMMY 4 /* Allocating dummy buffer */
/* Values for in_cinkeys() */
#define KEY_OPEN_FORW 0x101
#define KEY_OPEN_BACK 0x102
#define KEY_COMPLETE 0x103 /* end of completion */
/* Values for "noremap" argument of ins_typebuf(). Also used for
* map->m_noremap and menu->noremap[]. */
#define REMAP_YES 0 /* allow remapping */
#define REMAP_NONE -1 /* no remapping */
#define REMAP_SCRIPT -2 /* remap script-local mappings only */
#define REMAP_SKIP -3 /* no remapping for first char */
/* Values for mch_call_shell() second argument */
#define SHELL_FILTER 1 /* filtering text */
#define SHELL_EXPAND 2 /* expanding wildcards */
#define SHELL_COOKED 4 /* set term to cooked mode */
#define SHELL_DOOUT 8 /* redirecting output */
#define SHELL_SILENT 16 /* don't print error returned by command */
#define SHELL_READ 32 /* read lines and insert into buffer */
#define SHELL_WRITE 64 /* write lines from buffer */
/* Values returned by mch_nodetype() */
#define NODE_NORMAL 0 /* file or directory, check with mch_isdir()*/
#define NODE_WRITABLE 1 /* something we can write to (character
device, fifo, socket, ..) */
#define NODE_OTHER 2 /* non-writable thing (e.g., block device) */
/* Values for readfile() flags */
#define READ_NEW 0x01 /* read a file into a new buffer */
#define READ_FILTER 0x02 /* read filter output */
#define READ_STDIN 0x04 /* read from stdin */
#define READ_BUFFER 0x08 /* read from curbuf (converting stdin) */
#define READ_DUMMY 0x10 /* reading into a dummy buffer */
#define READ_KEEP_UNDO 0x20 /* keep undo info*/
/* Values for change_indent() */
#define INDENT_SET 1 /* set indent */
#define INDENT_INC 2 /* increase indent */
#define INDENT_DEC 3 /* decrease indent */
/* Values for flags argument for findmatchlimit() */
#define FM_BACKWARD 0x01 /* search backwards */
#define FM_FORWARD 0x02 /* search forwards */
#define FM_BLOCKSTOP 0x04 /* stop at start/end of block */
#define FM_SKIPCOMM 0x08 /* skip comments */
/* Values for action argument for do_buffer() */
#define DOBUF_GOTO 0 /* go to specified buffer */
#define DOBUF_SPLIT 1 /* split window and go to specified buffer */
#define DOBUF_UNLOAD 2 /* unload specified buffer(s) */
#define DOBUF_DEL 3 /* delete specified buffer(s) from buflist */
#define DOBUF_WIPE 4 /* delete specified buffer(s) really */
/* Values for start argument for do_buffer() */
#define DOBUF_CURRENT 0 /* "count" buffer from current buffer */
#define DOBUF_FIRST 1 /* "count" buffer from first buffer */
#define DOBUF_LAST 2 /* "count" buffer from last buffer */
#define DOBUF_MOD 3 /* "count" mod. buffer from current buffer */
/* Values for sub_cmd and which_pat argument for search_regcomp() */
/* Also used for which_pat argument for searchit() */
#define RE_SEARCH 0 /* save/use pat in/from search_pattern */
#define RE_SUBST 1 /* save/use pat in/from subst_pattern */
#define RE_BOTH 2 /* save pat in both patterns */
#define RE_LAST 2 /* use last used pattern if "pat" is NULL */
/* Second argument for vim_regcomp(). */
#define RE_MAGIC 1 /* 'magic' option */
#define RE_STRING 2 /* match in string instead of buffer text */
#define RE_STRICT 4 /* don't allow [abc] without ] */
#ifdef FEAT_SYN_HL
/* values for reg_do_extmatch */
# define REX_SET 1 /* to allow \z\(...\), */
# define REX_USE 2 /* to allow \z\1 et al. */
#endif
/* Return values for fullpathcmp() */
/* Note: can use (fullpathcmp() & FPC_SAME) to check for equal files */
#define FPC_SAME 1 /* both exist and are the same file. */
#define FPC_DIFF 2 /* both exist and are different files. */
#define FPC_NOTX 4 /* both don't exist. */
#define FPC_DIFFX 6 /* one of them doesn't exist. */
#define FPC_SAMEX 7 /* both don't exist and file names are same. */
/* flags for do_ecmd() */
#define ECMD_HIDE 0x01 /* don't free the current buffer */
#define ECMD_SET_HELP 0x02 /* set b_help flag of (new) buffer before
opening file */
#define ECMD_OLDBUF 0x04 /* use existing buffer if it exists */
#define ECMD_FORCEIT 0x08 /* ! used in Ex command */
#define ECMD_ADDBUF 0x10 /* don't edit, just add to buffer list */
/* for lnum argument in do_ecmd() */
#define ECMD_LASTL (linenr_T)0 /* use last position in loaded file */
#define ECMD_LAST (linenr_T)-1 /* use last position in all files */
#define ECMD_ONE (linenr_T)1 /* use first line */
/* flags for do_cmdline() */
#define DOCMD_VERBOSE 0x01 /* included command in error message */
#define DOCMD_NOWAIT 0x02 /* don't call wait_return() and friends */
#define DOCMD_REPEAT 0x04 /* repeat exec. until getline() returns NULL */
#define DOCMD_KEYTYPED 0x08 /* don't reset KeyTyped */
#define DOCMD_EXCRESET 0x10 /* reset exception environment (for debugging)*/
#define DOCMD_KEEPLINE 0x20 /* keep typed line for repeating with "." */
/* flags for beginline() */
#define BL_WHITE 1 /* cursor on first non-white in the line */
#define BL_SOL 2 /* use 'sol' option */
#define BL_FIX 4 /* don't leave cursor on a NUL */
/* flags for mf_sync() */
#define MFS_ALL 1 /* also sync blocks with negative numbers */
#define MFS_STOP 2 /* stop syncing when a character is available */
#define MFS_FLUSH 4 /* flushed file to disk */
#define MFS_ZERO 8 /* only write block 0 */
/* flags for buf_copy_options() */
#define BCO_ENTER 1 /* going to enter the buffer */
#define BCO_ALWAYS 2 /* always copy the options */
#define BCO_NOHELP 4 /* don't touch the help related options */
/* flags for do_put() */
#define PUT_FIXINDENT 1 /* make indent look nice */
#define PUT_CURSEND 2 /* leave cursor after end of new text */
#define PUT_CURSLINE 4 /* leave cursor on last line of new text */
#define PUT_LINE 8 /* put register as lines */
#define PUT_LINE_SPLIT 16 /* split line for linewise register */
#define PUT_LINE_FORWARD 32 /* put linewise register below Visual sel. */
/* flags for set_indent() */
#define SIN_CHANGED 1 /* call changed_bytes() when line changed */
#define SIN_INSERT 2 /* insert indent before existing text */
#define SIN_UNDO 4 /* save line for undo before changing it */
/* flags for insertchar() */
#define INSCHAR_FORMAT 1 /* force formatting */
#define INSCHAR_DO_COM 2 /* format comments */
#define INSCHAR_CTRLV 4 /* char typed just after CTRL-V */
#define INSCHAR_NO_FEX 8 /* don't use 'formatexpr' */
#define INSCHAR_COM_LIST 16 /* format comments with list/2nd line indent */
/* flags for open_line() */
#define OPENLINE_DELSPACES 1 /* delete spaces after cursor */
#define OPENLINE_DO_COM 2 /* format comments */
#define OPENLINE_KEEPTRAIL 4 /* keep trailing spaces */
#define OPENLINE_MARKFIX 8 /* fix mark positions */
#define OPENLINE_COM_LIST 16 /* format comments with list/2nd line indent */
/*
* There are four history tables:
*/
#define HIST_CMD 0 /* colon commands */
#define HIST_SEARCH 1 /* search commands */
#define HIST_EXPR 2 /* expressions (from entering = register) */
#define HIST_INPUT 3 /* input() lines */
#define HIST_DEBUG 4 /* debug commands */
#define HIST_COUNT 5 /* number of history tables */
/*
* Flags for chartab[].
*/
#define CT_CELL_MASK 0x07 /* mask: nr of display cells (1, 2 or 4) */
#define CT_PRINT_CHAR 0x10 /* flag: set for printable chars */
#define CT_ID_CHAR 0x20 /* flag: set for ID chars */
#define CT_FNAME_CHAR 0x40 /* flag: set for file name chars */
/*
* Values for do_tag().
*/
#define DT_TAG 1 /* jump to newer position or same tag again */
#define DT_POP 2 /* jump to older position */
#define DT_NEXT 3 /* jump to next match of same tag */
#define DT_PREV 4 /* jump to previous match of same tag */
#define DT_FIRST 5 /* jump to first match of same tag */
#define DT_LAST 6 /* jump to first match of same tag */
#define DT_SELECT 7 /* jump to selection from list */
#define DT_HELP 8 /* like DT_TAG, but no wildcards */
#define DT_JUMP 9 /* jump to new tag or selection from list */
#define DT_CSCOPE 10 /* cscope find command (like tjump) */
#define DT_LTAG 11 /* tag using location list */
#define DT_FREE 99 /* free cached matches */
/*
* flags for find_tags().
*/
#define TAG_HELP 1 /* only search for help tags */
#define TAG_NAMES 2 /* only return name of tag */
#define TAG_REGEXP 4 /* use tag pattern as regexp */
#define TAG_NOIC 8 /* don't always ignore case */
#ifdef FEAT_CSCOPE
# define TAG_CSCOPE 16 /* cscope tag */
#endif
#define TAG_VERBOSE 32 /* message verbosity */
#define TAG_INS_COMP 64 /* Currently doing insert completion */
#define TAG_KEEP_LANG 128 /* keep current language */
#define TAG_MANY 300 /* When finding many tags (for completion),
find up to this many tags */
/*
* Types of dialogs passed to do_vim_dialog().
*/
#define VIM_GENERIC 0
#define VIM_ERROR 1
#define VIM_WARNING 2
#define VIM_INFO 3
#define VIM_QUESTION 4
#define VIM_LAST_TYPE 4 /* sentinel value */
/*
* Return values for functions like gui_yesnocancel()
*/
#define VIM_YES 2
#define VIM_NO 3
#define VIM_CANCEL 4
#define VIM_ALL 5
#define VIM_DISCARDALL 6
/*
* arguments for win_split()
*/
#define WSP_ROOM 1 /* require enough room */
#define WSP_VERT 2 /* split vertically */
#define WSP_TOP 4 /* window at top-left of shell */
#define WSP_BOT 8 /* window at bottom-right of shell */
#define WSP_HELP 16 /* creating the help window */
#define WSP_BELOW 32 /* put new window below/right */
#define WSP_ABOVE 64 /* put new window above/left */
#define WSP_NEWLOC 128 /* don't copy location list */
/*
* arguments for gui_set_shellsize()
*/
#define RESIZE_VERT 1 /* resize vertically */
#define RESIZE_HOR 2 /* resize horizontally */
#define RESIZE_BOTH 15 /* resize in both directions */
/*
* "flags" values for option-setting functions.
* When OPT_GLOBAL and OPT_LOCAL are both missing, set both local and global
* values, get local value.
*/
#define OPT_FREE 1 /* free old value if it was allocated */
#define OPT_GLOBAL 2 /* use global value */
#define OPT_LOCAL 4 /* use local value */
#define OPT_MODELINE 8 /* option in modeline */
#define OPT_WINONLY 16 /* only set window-local options */
#define OPT_NOWIN 32 /* don't set window-local options */
/* Magic chars used in confirm dialog strings */
#define DLG_BUTTON_SEP '\n'
#define DLG_HOTKEY_CHAR '&'
/* Values for "starting" */
#define NO_SCREEN 2 /* no screen updating yet */
#define NO_BUFFERS 1 /* not all buffers loaded yet */
/* 0 not starting anymore */
/* Values for swap_exists_action: what to do when swap file already exists */
#define SEA_NONE 0 /* don't use dialog */
#define SEA_DIALOG 1 /* use dialog when possible */
#define SEA_QUIT 2 /* quit editing the file */
#define SEA_RECOVER 3 /* recover the file */
/*
* Minimal size for block 0 of a swap file.
* NOTE: This depends on size of struct block0! It's not done with a sizeof(),
* because struct block0 is defined in memline.c (Sorry).
* The maximal block size is arbitrary.
*/
#define MIN_SWAP_PAGE_SIZE 1048
#define MAX_SWAP_PAGE_SIZE 50000
/* Special values for current_SID. */
#define SID_MODELINE -1 /* when using a modeline */
#define SID_CMDARG -2 /* for "--cmd" argument */
#define SID_CARG -3 /* for "-c" argument */
#define SID_ENV -4 /* for sourcing environment variable */
#define SID_ERROR -5 /* option was reset because of an error */
#define SID_NONE -6 /* don't set scriptID */
/*
* Events for autocommands.
*/
enum auto_event
{
EVENT_BUFADD = 0, /* after adding a buffer to the buffer list */
EVENT_BUFNEW, /* after creating any buffer */
EVENT_BUFDELETE, /* deleting a buffer from the buffer list */
EVENT_BUFWIPEOUT, /* just before really deleting a buffer */
EVENT_BUFENTER, /* after entering a buffer */
EVENT_BUFFILEPOST, /* after renaming a buffer */
EVENT_BUFFILEPRE, /* before renaming a buffer */
EVENT_BUFLEAVE, /* before leaving a buffer */
EVENT_BUFNEWFILE, /* when creating a buffer for a new file */
EVENT_BUFREADPOST, /* after reading a buffer */
EVENT_BUFREADPRE, /* before reading a buffer */
EVENT_BUFREADCMD, /* read buffer using command */
EVENT_BUFUNLOAD, /* just before unloading a buffer */
EVENT_BUFHIDDEN, /* just after buffer becomes hidden */
EVENT_BUFWINENTER, /* after showing a buffer in a window */
EVENT_BUFWINLEAVE, /* just after buffer removed from window */
EVENT_BUFWRITEPOST, /* after writing a buffer */
EVENT_BUFWRITEPRE, /* before writing a buffer */
EVENT_BUFWRITECMD, /* write buffer using command */
EVENT_CMDWINENTER, /* after entering the cmdline window */
EVENT_CMDWINLEAVE, /* before leaving the cmdline window */
EVENT_COLORSCHEME, /* after loading a colorscheme */
EVENT_FILEAPPENDPOST, /* after appending to a file */
EVENT_FILEAPPENDPRE, /* before appending to a file */
EVENT_FILEAPPENDCMD, /* append to a file using command */
EVENT_FILECHANGEDSHELL, /* after shell command that changed file */
EVENT_FILECHANGEDSHELLPOST, /* after (not) reloading changed file */
EVENT_FILECHANGEDRO, /* before first change to read-only file */
EVENT_FILEREADPOST, /* after reading a file */
EVENT_FILEREADPRE, /* before reading a file */
EVENT_FILEREADCMD, /* read from a file using command */
EVENT_FILETYPE, /* new file type detected (user defined) */
EVENT_FILEWRITEPOST, /* after writing a file */
EVENT_FILEWRITEPRE, /* before writing a file */
EVENT_FILEWRITECMD, /* write to a file using command */
EVENT_FILTERREADPOST, /* after reading from a filter */
EVENT_FILTERREADPRE, /* before reading from a filter */
EVENT_FILTERWRITEPOST, /* after writing to a filter */
EVENT_FILTERWRITEPRE, /* before writing to a filter */
EVENT_FOCUSGAINED, /* got the focus */
EVENT_FOCUSLOST, /* lost the focus to another app */
EVENT_GUIENTER, /* after starting the GUI */
EVENT_GUIFAILED, /* after starting the GUI failed */
EVENT_INSERTCHANGE, /* when changing Insert/Replace mode */
EVENT_INSERTENTER, /* when entering Insert mode */
EVENT_INSERTLEAVE, /* when leaving Insert mode */
EVENT_MENUPOPUP, /* just before popup menu is displayed */
EVENT_QUICKFIXCMDPOST, /* after :make, :grep etc. */
EVENT_QUICKFIXCMDPRE, /* before :make, :grep etc. */
EVENT_QUITPRE, /* before :quit */
EVENT_SESSIONLOADPOST, /* after loading a session file */
EVENT_STDINREADPOST, /* after reading from stdin */
EVENT_STDINREADPRE, /* before reading from stdin */
EVENT_SYNTAX, /* syntax selected */
EVENT_TERMCHANGED, /* after changing 'term' */
EVENT_TERMRESPONSE, /* after setting "v:termresponse" */
EVENT_USER, /* user defined autocommand */
EVENT_VIMENTER, /* after starting Vim */
EVENT_VIMLEAVE, /* before exiting Vim */
EVENT_VIMLEAVEPRE, /* before exiting Vim and writing .viminfo */
EVENT_VIMRESIZED, /* after Vim window was resized */
EVENT_WINENTER, /* after entering a window */
EVENT_WINLEAVE, /* before leaving a window */
EVENT_ENCODINGCHANGED, /* after changing the 'encoding' option */
EVENT_INSERTCHARPRE, /* before inserting a char */
EVENT_CURSORHOLD, /* cursor in same position for a while */
EVENT_CURSORHOLDI, /* idem, in Insert mode */
EVENT_FUNCUNDEFINED, /* if calling a function which doesn't exist */
EVENT_REMOTEREPLY, /* upon string reception from a remote vim */
EVENT_SWAPEXISTS, /* found existing swap file */
EVENT_SOURCEPRE, /* before sourcing a Vim script */
EVENT_SOURCECMD, /* sourcing a Vim script using command */
EVENT_SPELLFILEMISSING, /* spell file missing */
EVENT_CURSORMOVED, /* cursor was moved */
EVENT_CURSORMOVEDI, /* cursor was moved in Insert mode */
EVENT_TABLEAVE, /* before leaving a tab page */
EVENT_TABENTER, /* after entering a tab page */
EVENT_SHELLCMDPOST, /* after ":!cmd" */
EVENT_SHELLFILTERPOST, /* after ":1,2!cmd", ":w !cmd", ":r !cmd". */
NUM_EVENTS /* MUST be the last one */
};
typedef enum auto_event event_T;
/*
* Values for index in highlight_attr[].
* When making changes, also update HL_FLAGS below! And update the default
* value of 'highlight' in option.c.
*/
typedef enum
{
HLF_8 = 0 /* Meta & special keys listed with ":map", text that is
displayed different from what it is */
, HLF_AT /* @ and ~ characters at end of screen, characters that
don't really exist in the text */
, HLF_D /* directories in CTRL-D listing */
, HLF_E /* error messages */
, HLF_H /* obsolete, ignored */
, HLF_I /* incremental search */
, HLF_L /* last search string */
, HLF_M /* "--More--" message */
, HLF_CM /* Mode (e.g., "-- INSERT --") */
, HLF_N /* line number for ":number" and ":#" commands */
, HLF_CLN /* current line number */
, HLF_R /* return to continue message and yes/no questions */
, HLF_S /* status lines */
, HLF_SNC /* status lines of not-current windows */
, HLF_C /* column to separate vertically split windows */
, HLF_T /* Titles for output from ":set all", ":autocmd" etc. */
, HLF_V /* Visual mode */
, HLF_VNC /* Visual mode, autoselecting and not clipboard owner */
, HLF_W /* warning messages */
, HLF_WM /* Wildmenu highlight */
, HLF_FL /* Folded line */
, HLF_FC /* Fold column */
, HLF_ADD /* Added diff line */
, HLF_CHD /* Changed diff line */
, HLF_DED /* Deleted diff line */
, HLF_TXD /* Text Changed in diff line */
, HLF_CONCEAL /* Concealed text */
, HLF_SC /* Sign column */
, HLF_SPB /* SpellBad */
, HLF_SPC /* SpellCap */
, HLF_SPR /* SpellRare */
, HLF_SPL /* SpellLocal */
, HLF_PNI /* popup menu normal item */
, HLF_PSI /* popup menu selected item */
, HLF_PSB /* popup menu scrollbar */
, HLF_PST /* popup menu scrollbar thumb */
, HLF_TP /* tabpage line */
, HLF_TPS /* tabpage line selected */
, HLF_TPF /* tabpage line filler */
, HLF_CUC /* 'cursurcolumn' */
, HLF_CUL /* 'cursurline' */
, HLF_MC /* 'colorcolumn' */
, HLF_COUNT /* MUST be the last one */
} hlf_T;
/* The HL_FLAGS must be in the same order as the HLF_ enums!
* When changing this also adjust the default for 'highlight'. */
#define HL_FLAGS {'8', '@', 'd', 'e', 'h', 'i', 'l', 'm', 'M', \
'n', 'N', 'r', 's', 'S', 'c', 't', 'v', 'V', 'w', 'W', \
'f', 'F', 'A', 'C', 'D', 'T', '-', '>', \
'B', 'P', 'R', 'L', \
'+', '=', 'x', 'X', '*', '#', '_', '!', '.', 'o'}
/*
* Boolean constants
*/
#ifndef TRUE
# define FALSE 0 /* note: this is an int, not a long! */
# define TRUE 1
#endif
#define MAYBE 2 /* sometimes used for a variant on TRUE */
#ifndef UINT32_T
typedef UINT32_TYPEDEF UINT32_T;
#endif
/*
* Operator IDs; The order must correspond to opchars[] in ops.c!
*/
#define OP_NOP 0 /* no pending operation */
#define OP_DELETE 1 /* "d" delete operator */
#define OP_YANK 2 /* "y" yank operator */
#define OP_CHANGE 3 /* "c" change operator */
#define OP_LSHIFT 4 /* "<" left shift operator */
#define OP_RSHIFT 5 /* ">" right shift operator */
#define OP_FILTER 6 /* "!" filter operator */
#define OP_TILDE 7 /* "g~" switch case operator */
#define OP_INDENT 8 /* "=" indent operator */
#define OP_FORMAT 9 /* "gq" format operator */
#define OP_COLON 10 /* ":" colon operator */
#define OP_UPPER 11 /* "gU" make upper case operator */
#define OP_LOWER 12 /* "gu" make lower case operator */
#define OP_JOIN 13 /* "J" join operator, only for Visual mode */
#define OP_JOIN_NS 14 /* "gJ" join operator, only for Visual mode */
#define OP_ROT13 15 /* "g?" rot-13 encoding */
#define OP_REPLACE 16 /* "r" replace chars, only for Visual mode */
#define OP_INSERT 17 /* "I" Insert column, only for Visual mode */
#define OP_APPEND 18 /* "A" Append column, only for Visual mode */
#define OP_FOLD 19 /* "zf" define a fold */
#define OP_FOLDOPEN 20 /* "zo" open folds */
#define OP_FOLDOPENREC 21 /* "zO" open folds recursively */
#define OP_FOLDCLOSE 22 /* "zc" close folds */
#define OP_FOLDCLOSEREC 23 /* "zC" close folds recursively */
#define OP_FOLDDEL 24 /* "zd" delete folds */
#define OP_FOLDDELREC 25 /* "zD" delete folds recursively */
#define OP_FORMAT2 26 /* "gw" format operator, keeps cursor pos */
#define OP_FUNCTION 27 /* "g@" call 'operatorfunc' */
/*
* Motion types, used for operators and for yank/delete registers.
*/
#define MCHAR 0 /* character-wise movement/register */
#define MLINE 1 /* line-wise movement/register */
#define MBLOCK 2 /* block-wise register */
#define MAUTO 0xff /* Decide between MLINE/MCHAR */
/*
* Minimum screen size
*/
#define MIN_COLUMNS 12 /* minimal columns for screen */
#define MIN_LINES 2 /* minimal lines for screen */
#define STATUS_HEIGHT 1 /* height of a status line under a window */
#define QF_WINHEIGHT 10 /* default height for quickfix window */
/*
* Buffer sizes
*/
#ifndef CMDBUFFSIZE
# define CMDBUFFSIZE 256 /* size of the command processing buffer */
#endif
#define LSIZE 512 /* max. size of a line in the tags file */
#define IOSIZE (1024+1) /* file i/o and sprintf buffer size */
#define DIALOG_MSG_SIZE 1000 /* buffer size for dialog_msg() */
#ifdef FEAT_MBYTE
# define MSG_BUF_LEN 480 /* length of buffer for small messages */
# define MSG_BUF_CLEN (MSG_BUF_LEN / 6) /* cell length (worst case: utf-8
takes 6 bytes for one cell) */
#else
# define MSG_BUF_LEN 80 /* length of buffer for small messages */
# define MSG_BUF_CLEN MSG_BUF_LEN /* cell length */
#endif
/* Size of the buffer used for tgetent(). Unfortunately this is largely
* undocumented, some systems use 1024. Using a buffer that is too small
* causes a buffer overrun and a crash. Use the maximum known value to stay
* on the safe side. */
#define TBUFSZ 2048 /* buffer size for termcap entry */
/*
* Maximum length of key sequence to be mapped.
* Must be able to hold an Amiga resize report.
*/
#define MAXMAPLEN 50
/* Size in bytes of the hash used in the undo file. */
#define UNDO_HASH_SIZE 32
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef BINARY_FILE_IO
# define WRITEBIN "wb" /* no CR-LF translation */
# define READBIN "rb"
# define APPENDBIN "ab"
#else
# define WRITEBIN "w"
# define READBIN "r"
# define APPENDBIN "a"
#endif
/*
* EMX doesn't have a global way of making open() use binary I/O.
* Use O_BINARY for all open() calls.
*/
#if defined(__EMX__) || defined(__CYGWIN32__)
# define O_EXTRA O_BINARY
#else
# define O_EXTRA 0
#endif
#ifndef O_NOFOLLOW
# define O_NOFOLLOW 0
#endif
#ifndef W_OK
# define W_OK 2 /* for systems that don't have W_OK in unistd.h */
#endif
#ifndef R_OK
# define R_OK 4 /* for systems that don't have R_OK in unistd.h */
#endif
/*
* defines to avoid typecasts from (char_u *) to (char *) and back
* (vim_strchr() and vim_strrchr() are now in alloc.c)
*/
#define STRLEN(s) strlen((char *)(s))
#define STRCPY(d, s) strcpy((char *)(d), (char *)(s))
#define STRNCPY(d, s, n) strncpy((char *)(d), (char *)(s), (size_t)(n))
#define STRCMP(d, s) strcmp((char *)(d), (char *)(s))
#define STRNCMP(d, s, n) strncmp((char *)(d), (char *)(s), (size_t)(n))
#ifdef HAVE_STRCASECMP
# define STRICMP(d, s) strcasecmp((char *)(d), (char *)(s))
#else
# ifdef HAVE_STRICMP
# define STRICMP(d, s) stricmp((char *)(d), (char *)(s))
# else
# define STRICMP(d, s) vim_stricmp((char *)(d), (char *)(s))
# endif
#endif
/* Like strcpy() but allows overlapped source and destination. */
#define STRMOVE(d, s) mch_memmove((d), (s), STRLEN(s) + 1)
#ifdef HAVE_STRNCASECMP
# define STRNICMP(d, s, n) strncasecmp((char *)(d), (char *)(s), (size_t)(n))
#else
# ifdef HAVE_STRNICMP
# define STRNICMP(d, s, n) strnicmp((char *)(d), (char *)(s), (size_t)(n))
# else
# define STRNICMP(d, s, n) vim_strnicmp((char *)(d), (char *)(s), (size_t)(n))
# endif
#endif
#ifdef FEAT_MBYTE
/* We need to call mb_stricmp() even when we aren't dealing with a multi-byte
* encoding because mb_stricmp() takes care of all ascii and non-ascii
* encodings, including characters with umlauts in latin1, etc., while
* STRICMP() only handles the system locale version, which often does not
* handle non-ascii properly. */
# define MB_STRICMP(d, s) mb_strnicmp((char_u *)(d), (char_u *)(s), (int)MAXCOL)
# define MB_STRNICMP(d, s, n) mb_strnicmp((char_u *)(d), (char_u *)(s), (int)(n))
#else
# define MB_STRICMP(d, s) STRICMP((d), (s))
# define MB_STRNICMP(d, s, n) STRNICMP((d), (s), (n))
#endif
#define STRCAT(d, s) strcat((char *)(d), (char *)(s))
#define STRNCAT(d, s, n) strncat((char *)(d), (char *)(s), (size_t)(n))
#ifdef HAVE_STRPBRK
# define vim_strpbrk(s, cs) (char_u *)strpbrk((char *)(s), (char *)(cs))
#endif
#define MSG(s) msg((char_u *)(s))
#define MSG_ATTR(s, attr) msg_attr((char_u *)(s), (attr))
#define EMSG(s) emsg((char_u *)(s))
#define EMSG2(s, p) emsg2((char_u *)(s), (char_u *)(p))
#define EMSG3(s, p, q) emsg3((char_u *)(s), (char_u *)(p), (char_u *)(q))
#define EMSGN(s, n) emsgn((char_u *)(s), (long)(n))
#define EMSGU(s, n) emsgu((char_u *)(s), (long_u)(n))
#define OUT_STR(s) out_str((char_u *)(s))
#define OUT_STR_NF(s) out_str_nf((char_u *)(s))
#define MSG_PUTS(s) msg_puts((char_u *)(s))
#define MSG_PUTS_ATTR(s, a) msg_puts_attr((char_u *)(s), (a))
#define MSG_PUTS_TITLE(s) msg_puts_title((char_u *)(s))
#define MSG_PUTS_LONG(s) msg_puts_long_attr((char_u *)(s), 0)
#define MSG_PUTS_LONG_ATTR(s, a) msg_puts_long_attr((char_u *)(s), (a))
/* Prefer using emsg3(), because perror() may send the output to the wrong
* destination and mess up the screen. */
#ifdef HAVE_STRERROR
# define PERROR(msg) (void)emsg3((char_u *)"%s: %s", (char_u *)msg, (char_u *)strerror(errno))
#else
# define PERROR(msg) perror(msg)
#endif
typedef long linenr_T; /* line number type */
typedef int colnr_T; /* column number type */
typedef unsigned short disptick_T; /* display tick type */
#define MAXLNUM (0x7fffffffL) /* maximum (invalid) line number */
/*
* Well, you won't believe it, but some S/390 machines ("host", now also known
* as zServer) use 31 bit pointers. There are also some newer machines, that
* use 64 bit pointers. I don't know how to distinguish between 31 and 64 bit
* machines, so the best way is to assume 31 bits whenever we detect OS/390
* Unix.
* With this we restrict the maximum line length to 1073741823. I guess this is
* not a real problem. BTW: Longer lines are split.
*/
#if SIZEOF_INT >= 4
# ifdef __MVS__
# define MAXCOL (0x3fffffffL) /* maximum column number, 30 bits */
# else
# define MAXCOL (0x7fffffffL) /* maximum column number, 31 bits */
# endif
#else
# define MAXCOL (0x7fff) /* maximum column number, 15 bits */
#endif
#define SHOWCMD_COLS 10 /* columns needed by shown command */
#define STL_MAX_ITEM 80 /* max nr of %<flag> in statusline */
typedef void *vim_acl_T; /* dummy to pass an ACL to a function */
/*
* Include a prototype for mch_memmove(), it may not be in alloc.pro.
*/
#ifdef VIM_MEMMOVE
void mch_memmove __ARGS((void *, void *, size_t));
#else
# ifndef mch_memmove
# define mch_memmove(to, from, len) memmove(to, from, len)
# endif
#endif
/*
* fnamecmp() is used to compare file names.
* On some systems case in a file name does not matter, on others it does.
* (this does not account for maximum name lengths and things like "../dir",
* thus it is not 100% accurate!)
*/
#ifdef CASE_INSENSITIVE_FILENAME
# ifdef BACKSLASH_IN_FILENAME
# define fnamecmp(x, y) vim_fnamecmp((x), (y))
# define fnamencmp(x, y, n) vim_fnamencmp((x), (y), (size_t)(n))
# else
# define fnamecmp(x, y) MB_STRICMP((x), (y))
# define fnamencmp(x, y, n) MB_STRNICMP((x), (y), (n))
# endif
#else
# define fnamecmp(x, y) strcmp((char *)(x), (char *)(y))
# define fnamencmp(x, y, n) strncmp((char *)(x), (char *)(y), (size_t)(n))
#endif
#ifdef HAVE_MEMSET
# define vim_memset(ptr, c, size) memset((ptr), (c), (size))
#else
void *vim_memset __ARGS((void *, int, size_t));
#endif
#ifdef HAVE_MEMCMP
# define vim_memcmp(p1, p2, len) memcmp((p1), (p2), (len))
#else
# ifdef HAVE_BCMP
# define vim_memcmp(p1, p2, len) bcmp((p1), (p2), (len))
# else
int vim_memcmp __ARGS((void *, void *, size_t));
# define VIM_MEMCMP
# endif
#endif
#if defined(UNIX) || defined(FEAT_GUI) || defined(OS2) || defined(VMS) \
|| defined(FEAT_CLIENTSERVER)
# define USE_INPUT_BUF
#endif
#ifndef EINTR
# define read_eintr(fd, buf, count) vim_read((fd), (buf), (count))
# define write_eintr(fd, buf, count) vim_write((fd), (buf), (count))
#endif
#ifdef MSWIN
/* On MS-Windows the third argument isn't size_t. This matters for Win64,
* where sizeof(size_t)==8, not 4 */
# define vim_read(fd, buf, count) read((fd), (char *)(buf), (unsigned int)(count))
# define vim_write(fd, buf, count) write((fd), (char *)(buf), (unsigned int)(count))
#else
# define vim_read(fd, buf, count) read((fd), (char *)(buf), (size_t) (count))
# define vim_write(fd, buf, count) write((fd), (char *)(buf), (size_t) (count))
#endif
/*
* Enums need a typecast to be used as array index (for Ultrix).
*/
#define hl_attr(n) highlight_attr[(int)(n)]
#define term_str(n) term_strings[(int)(n)]
/*
* vim_iswhite() is used for "^" and the like. It differs from isspace()
* because it doesn't include <CR> and <LF> and the like.
*/
#define vim_iswhite(x) ((x) == ' ' || (x) == '\t')
/*
* EXTERN is only defined in main.c. That's where global variables are
* actually defined and initialized.
*/
#ifndef EXTERN
# define EXTERN extern
# define INIT(x)
#else
# ifndef INIT
# define INIT(x) x
# define DO_INIT
# endif
#endif
#ifdef FEAT_MBYTE
# define MAX_MCO 6 /* maximum value for 'maxcombine' */
/* Maximum number of bytes in a multi-byte character. It can be one 32-bit
* character of up to 6 bytes, or one 16-bit character of up to three bytes
* plus six following composing characters of three bytes each. */
# define MB_MAXBYTES 21
#else
# define MB_MAXBYTES 1
#endif
#if (defined(FEAT_PROFILE) || defined(FEAT_RELTIME)) && !defined(PROTO)
# ifdef WIN3264
typedef LARGE_INTEGER proftime_T;
# else
typedef struct timeval proftime_T;
# endif
#else
typedef int proftime_T; /* dummy for function prototypes */
#endif
/* Include option.h before structs.h, because the number of window-local and
* buffer-local options is used there. */
#include "option.h" /* options and default values */
/* Note that gui.h is included by structs.h */
#include "structs.h" /* file that defines many structures */
/* Values for "do_profiling". */
#define PROF_NONE 0 /* profiling not started */
#define PROF_YES 1 /* profiling busy */
#define PROF_PAUSED 2 /* profiling paused */
#ifdef FEAT_MOUSE
/* Codes for mouse button events in lower three bits: */
# define MOUSE_LEFT 0x00
# define MOUSE_MIDDLE 0x01
# define MOUSE_RIGHT 0x02
# define MOUSE_RELEASE 0x03
/* bit masks for modifiers: */
# define MOUSE_SHIFT 0x04
# define MOUSE_ALT 0x08
# define MOUSE_CTRL 0x10
/* mouse buttons that are handled like a key press (GUI only) */
/* Note that the scroll wheel keys are inverted: MOUSE_5 scrolls lines up but
* the result of this is that the window moves down, similarly MOUSE_6 scrolls
* columns left but the window moves right. */
# define MOUSE_4 0x100 /* scroll wheel down */
# define MOUSE_5 0x200 /* scroll wheel up */
# define MOUSE_X1 0x300 /* Mouse-button X1 (6th) */
# define MOUSE_X2 0x400 /* Mouse-button X2 */
# define MOUSE_6 0x500 /* scroll wheel left */
# define MOUSE_7 0x600 /* scroll wheel right */
/* 0x20 is reserved by xterm */
# define MOUSE_DRAG_XTERM 0x40
# define MOUSE_DRAG (0x40 | MOUSE_RELEASE)
/* Lowest button code for using the mouse wheel (xterm only) */
# define MOUSEWHEEL_LOW 0x60
# define MOUSE_CLICK_MASK 0x03
# define NUM_MOUSE_CLICKS(code) \
(((unsigned)((code) & 0xC0) >> 6) + 1)
# define SET_NUM_MOUSE_CLICKS(code, num) \
(code) = ((code) & 0x3f) | ((((num) - 1) & 3) << 6)
/* Added to mouse column for GUI when 'mousefocus' wants to give focus to a
* window by simulating a click on its status line. We could use up to 128 *
* 128 = 16384 columns, now it's reduced to 10000. */
# define MOUSE_COLOFF 10000
/*
* jump_to_mouse() returns one of first four these values, possibly with
* some of the other three added.
*/
# define IN_UNKNOWN 0
# define IN_BUFFER 1
# define IN_STATUS_LINE 2 /* on status or command line */
# define IN_SEP_LINE 4 /* on vertical separator line */
# define IN_OTHER_WIN 8 /* in other window but can't go there */
# define CURSOR_MOVED 0x100
# define MOUSE_FOLD_CLOSE 0x200 /* clicked on '-' in fold column */
# define MOUSE_FOLD_OPEN 0x400 /* clicked on '+' in fold column */
/* flags for jump_to_mouse() */
# define MOUSE_FOCUS 0x01 /* need to stay in this window */
# define MOUSE_MAY_VIS 0x02 /* may start Visual mode */
# define MOUSE_DID_MOVE 0x04 /* only act when mouse has moved */
# define MOUSE_SETPOS 0x08 /* only set current mouse position */
# define MOUSE_MAY_STOP_VIS 0x10 /* may stop Visual mode */
# define MOUSE_RELEASED 0x20 /* button was released */
# if defined(UNIX) && defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
# define CHECK_DOUBLE_CLICK 1 /* Checking for double clicks ourselves. */
# endif
#endif /* FEAT_MOUSE */
/* defines for eval_vars() */
#define VALID_PATH 1
#define VALID_HEAD 2
/* Defines for Vim variables. These must match vimvars[] in eval.c! */
#define VV_COUNT 0
#define VV_COUNT1 1
#define VV_PREVCOUNT 2
#define VV_ERRMSG 3
#define VV_WARNINGMSG 4
#define VV_STATUSMSG 5
#define VV_SHELL_ERROR 6
#define VV_THIS_SESSION 7
#define VV_VERSION 8
#define VV_LNUM 9
#define VV_TERMRESPONSE 10
#define VV_FNAME 11
#define VV_LANG 12
#define VV_LC_TIME 13
#define VV_CTYPE 14
#define VV_CC_FROM 15
#define VV_CC_TO 16
#define VV_FNAME_IN 17
#define VV_FNAME_OUT 18
#define VV_FNAME_NEW 19
#define VV_FNAME_DIFF 20
#define VV_CMDARG 21
#define VV_FOLDSTART 22
#define VV_FOLDEND 23
#define VV_FOLDDASHES 24
#define VV_FOLDLEVEL 25
#define VV_PROGNAME 26
#define VV_SEND_SERVER 27
#define VV_DYING 28
#define VV_EXCEPTION 29
#define VV_THROWPOINT 30
#define VV_REG 31
#define VV_CMDBANG 32
#define VV_INSERTMODE 33
#define VV_VAL 34
#define VV_KEY 35
#define VV_PROFILING 36
#define VV_FCS_REASON 37
#define VV_FCS_CHOICE 38
#define VV_BEVAL_BUFNR 39
#define VV_BEVAL_WINNR 40
#define VV_BEVAL_LNUM 41
#define VV_BEVAL_COL 42
#define VV_BEVAL_TEXT 43
#define VV_SCROLLSTART 44
#define VV_SWAPNAME 45
#define VV_SWAPCHOICE 46
#define VV_SWAPCOMMAND 47
#define VV_CHAR 48
#define VV_MOUSE_WIN 49
#define VV_MOUSE_LNUM 50
#define VV_MOUSE_COL 51
#define VV_OP 52
#define VV_SEARCHFORWARD 53
#define VV_OLDFILES 54
#define VV_WINDOWID 55
#define VV_LEN 56 /* number of v: vars */
#ifdef FEAT_CLIPBOARD
/* VIM_ATOM_NAME is the older Vim-specific selection type for X11. Still
* supported for when a mix of Vim versions is used. VIMENC_ATOM_NAME includes
* the encoding to support Vims using different 'encoding' values. */
#define VIM_ATOM_NAME "_VIM_TEXT"
#define VIMENC_ATOM_NAME "_VIMENC_TEXT"
/* Selection states for modeless selection */
# define SELECT_CLEARED 0
# define SELECT_IN_PROGRESS 1
# define SELECT_DONE 2
# define SELECT_MODE_CHAR 0
# define SELECT_MODE_WORD 1
# define SELECT_MODE_LINE 2
# ifdef FEAT_GUI_W32
# ifdef FEAT_OLE
# define WM_OLE (WM_APP+0)
# endif
# ifdef FEAT_NETBEANS_INTG
/* message for Netbeans socket event */
# define WM_NETBEANS (WM_APP+1)
# endif
# endif
/* Info about selected text */
typedef struct VimClipboard
{
int available; /* Is clipboard available? */
int owned; /* Flag: do we own the selection? */
pos_T start; /* Start of selected area */
pos_T end; /* End of selected area */
int vmode; /* Visual mode character */
/* Fields for selection that doesn't use Visual mode */
short_u origin_row;
short_u origin_start_col;
short_u origin_end_col;
short_u word_start_col;
short_u word_end_col;
pos_T prev; /* Previous position */
short_u state; /* Current selection state */
short_u mode; /* Select by char, word, or line. */
# if defined(FEAT_GUI_X11) || defined(FEAT_XCLIPBOARD)
Atom sel_atom; /* PRIMARY/CLIPBOARD selection ID */
# endif
# ifdef FEAT_GUI_GTK
GdkAtom gtk_sel_atom; /* PRIMARY/CLIPBOARD selection ID */
# endif
# ifdef MSWIN
int_u format; /* Vim's own special clipboard format */
int_u format_raw; /* Vim's raw text clipboard format */
# endif
} VimClipboard;
#else
typedef int VimClipboard; /* This is required for the prototypes. */
#endif
#ifdef __BORLANDC__
/* work around a bug in the Borland 'stat' function: */
# include <io.h> /* for access() */
# define stat(a,b) (access(a,0) ? -1 : stat(a,b))
#endif
#include "ex_cmds.h" /* Ex command defines */
#include "proto.h" /* function prototypes */
/* This has to go after the include of proto.h, as proto/gui.pro declares
* functions of these names. The declarations would break if the defines had
* been seen at that stage. But it must be before globals.h, where error_ga
* is declared. */
#if !defined(FEAT_GUI_W32) && !defined(FEAT_GUI_X11) \
&& !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MAC)
# define mch_errmsg(str) fprintf(stderr, "%s", (str))
# define display_errors() fflush(stderr)
# define mch_msg(str) printf("%s", (str))
#else
# define USE_MCH_ERRMSG
#endif
#ifndef FEAT_MBYTE
# define after_pathsep(b, p) vim_ispathsep(*((p) - 1))
# define transchar_byte(c) transchar(c)
#endif
#ifndef FEAT_LINEBREAK
/* Without the 'numberwidth' option line numbers are always 7 chars. */
# define number_width(x) 7
#endif
#include "globals.h" /* global variables and messages */
#ifdef FEAT_SNIFF
# include "if_sniff.h"
#endif
#ifndef FEAT_VIRTUALEDIT
# define getvvcol(w, p, s, c, e) getvcol(w, p, s, c, e)
# define virtual_active() 0
# define virtual_op FALSE
#endif
/*
* If console dialog not supported, but GUI dialog is, use the GUI one.
*/
#if defined(FEAT_GUI_DIALOG) && !defined(FEAT_CON_DIALOG)
# define do_dialog gui_mch_dialog
#endif
/*
* Default filters for gui_mch_browse().
* The filters are almost system independent. Except for the difference
* between "*" and "*.*" for MSDOS-like systems.
* NOTE: Motif only uses the very first pattern. Therefore
* BROWSE_FILTER_DEFAULT should start with a "*" pattern.
*/
#ifdef FEAT_BROWSE
# ifdef BACKSLASH_IN_FILENAME
# define BROWSE_FILTER_MACROS \
(char_u *)"Vim macro files (*.vim)\t*.vim\nAll Files (*.*)\t*.*\n"
# define BROWSE_FILTER_ALL_FILES (char_u *)"All Files (*.*)\t*.*\n"
# define BROWSE_FILTER_DEFAULT \
(char_u *)"All Files (*.*)\t*.*\nC source (*.c, *.h)\t*.c;*.h\nC++ source (*.cpp, *.hpp)\t*.cpp;*.hpp\nVB code (*.bas, *.frm)\t*.bas;*.frm\nVim files (*.vim, _vimrc, _gvimrc)\t*.vim;_vimrc;_gvimrc\n"
# else
# define BROWSE_FILTER_MACROS \
(char_u *)"Vim macro files (*.vim)\t*.vim\nAll Files (*)\t*\n"
# define BROWSE_FILTER_ALL_FILES (char_u *)"All Files (*)\t*\n"
# define BROWSE_FILTER_DEFAULT \
(char_u *)"All Files (*)\t*\nC source (*.c, *.h)\t*.c;*.h\nC++ source (*.cpp, *.hpp)\t*.cpp;*.hpp\nVim files (*.vim, _vimrc, _gvimrc)\t*.vim;_vimrc;_gvimrc\n"
# endif
# define BROWSE_SAVE 1 /* flag for do_browse() */
# define BROWSE_DIR 2 /* flag for do_browse() */
#endif
/* stop using fastcall for Borland */
#if defined(__BORLANDC__) && defined(WIN32) && !defined(DEBUG)
#pragma option -p.
#endif
#ifdef _MSC_VER
/* Avoid useless warning "conversion from X to Y of greater size". */
#pragma warning(disable : 4312)
#endif
/* Note: a NULL argument for vim_realloc() is not portable, don't use it. */
#if defined(MEM_PROFILE)
# define vim_realloc(ptr, size) mem_realloc((ptr), (size))
#else
# define vim_realloc(ptr, size) realloc((ptr), (size))
#endif
/*
* The following macros stop display/event loop nesting at the wrong time.
*/
#ifdef ALT_X_INPUT
# define ALT_INPUT_LOCK_OFF suppress_alternate_input = FALSE
# define ALT_INPUT_LOCK_ON suppress_alternate_input = TRUE
#endif
#ifdef FEAT_MBYTE
/*
* Return byte length of character that starts with byte "b".
* Returns 1 for a single-byte character.
* MB_BYTE2LEN_CHECK() can be used to count a special key as one byte.
* Don't call MB_BYTE2LEN(b) with b < 0 or b > 255!
*/
# define MB_BYTE2LEN(b) mb_bytelen_tab[b]
# define MB_BYTE2LEN_CHECK(b) (((b) < 0 || (b) > 255) ? 1 : mb_bytelen_tab[b])
#endif
#if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT)
/* properties used in enc_canon_table[] (first three mutually exclusive) */
# define ENC_8BIT 0x01
# define ENC_DBCS 0x02
# define ENC_UNICODE 0x04
# define ENC_ENDIAN_B 0x10 /* Unicode: Big endian */
# define ENC_ENDIAN_L 0x20 /* Unicode: Little endian */
# define ENC_2BYTE 0x40 /* Unicode: UCS-2 */
# define ENC_4BYTE 0x80 /* Unicode: UCS-4 */
# define ENC_2WORD 0x100 /* Unicode: UTF-16 */
# define ENC_LATIN1 0x200 /* Latin1 */
# define ENC_LATIN9 0x400 /* Latin9 */
# define ENC_MACROMAN 0x800 /* Mac Roman (not Macro Man! :-) */
#endif
#ifdef FEAT_MBYTE
# ifdef USE_ICONV
# ifndef EILSEQ
# define EILSEQ 123
# endif
# ifdef DYNAMIC_ICONV
/* On Win32 iconv.dll is dynamically loaded. */
# define ICONV_ERRNO (*iconv_errno())
# define ICONV_E2BIG 7
# define ICONV_EINVAL 22
# define ICONV_EILSEQ 42
# else
# define ICONV_ERRNO errno
# define ICONV_E2BIG E2BIG
# define ICONV_EINVAL EINVAL
# define ICONV_EILSEQ EILSEQ
# endif
# endif
#endif
/* ISSYMLINK(mode) tests if a file is a symbolic link. */
#if (defined(S_IFMT) && defined(S_IFLNK)) || defined(S_ISLNK)
# define HAVE_ISSYMLINK
# if defined(S_IFMT) && defined(S_IFLNK)
# define ISSYMLINK(mode) (((mode) & S_IFMT) == S_IFLNK)
# else
# define ISSYMLINK(mode) S_ISLNK(mode)
# endif
#endif
#define SIGN_BYTE 1 /* byte value used where sign is displayed;
attribute value is sign type */
#ifdef FEAT_NETBEANS_INTG
# define MULTISIGN_BYTE 2 /* byte value used where sign is displayed if
multiple signs exist on the line */
#endif
#if defined(FEAT_GUI) && defined(FEAT_XCLIPBOARD)
# ifdef FEAT_GUI_GTK
/* Avoid using a global variable for the X display. It's ugly
* and is likely to cause trouble in multihead environments. */
# define X_DISPLAY ((gui.in_use) ? gui_mch_get_display() : xterm_dpy)
# else
# define X_DISPLAY (gui.in_use ? gui.dpy : xterm_dpy)
# endif
#else
# ifdef FEAT_GUI
# ifdef FEAT_GUI_GTK
# define X_DISPLAY ((gui.in_use) ? gui_mch_get_display() : (Display *)NULL)
# else
# define X_DISPLAY gui.dpy
# endif
# else
# define X_DISPLAY xterm_dpy
# endif
#endif
#ifndef FEAT_NETBEANS_INTG
# undef NBDEBUG
#endif
#ifdef NBDEBUG /* Netbeans debugging. */
# include "nbdebug.h"
#else
# define nbdebug(a)
#endif
#ifdef IN_PERL_FILE
/*
* Avoid clashes between Perl and Vim namespace.
*/
# undef NORMAL
# undef STRLEN
# undef FF
# undef OP_DELETE
# undef OP_JOIN
# ifdef __BORLANDC__
# define NOPROTO 1
# endif
/* remove MAX and MIN, included by glib.h, redefined by sys/param.h */
# ifdef MAX
# undef MAX
# endif
# ifdef MIN
# undef MIN
# endif
/* We use _() for gettext(), Perl uses it for function prototypes... */
# ifdef _
# undef _
# endif
# ifdef DEBUG
# undef DEBUG
# endif
# ifdef _DEBUG
# undef _DEBUG
# endif
# ifdef instr
# undef instr
# endif
/* bool may cause trouble on MACOS but is required on a few other systems
* and for Perl */
# if defined(bool) && defined(MACOS) && !defined(FEAT_PERL)
# undef bool
# endif
# ifdef __BORLANDC__
/* Borland has the structure stati64 but not _stati64 */
# define _stati64 stati64
# endif
# include <EXTERN.h>
# include <perl.h>
# include <XSUB.h>
#endif
/* values for vim_handle_signal() that are not a signal */
#define SIGNAL_BLOCK -1
#define SIGNAL_UNBLOCK -2
#if !defined(UNIX) && !defined(VMS) && !defined(OS2)
# define vim_handle_signal(x) 0
#endif
/* flags for skip_vimgrep_pat() */
#define VGR_GLOBAL 1
#define VGR_NOJUMP 2
/* behavior for bad character, "++bad=" argument */
#define BAD_REPLACE '?' /* replace it with '?' (default) */
#define BAD_KEEP -1 /* leave it */
#define BAD_DROP -2 /* erase it */
/* last argument for do_source() */
#define DOSO_NONE 0
#define DOSO_VIMRC 1 /* loading vimrc file */
#define DOSO_GVIMRC 2 /* loading gvimrc file */
/* flags for read_viminfo() and children */
#define VIF_WANT_INFO 1 /* load non-mark info */
#define VIF_WANT_MARKS 2 /* load file marks */
#define VIF_FORCEIT 4 /* overwrite info already read */
#define VIF_GET_OLDFILES 8 /* load v:oldfiles */
/* flags for buf_freeall() */
#define BFA_DEL 1 /* buffer is going to be deleted */
#define BFA_WIPE 2 /* buffer is going to be wiped out */
#define BFA_KEEP_UNDO 4 /* do not free undo information */
/* direction for nv_mousescroll() and ins_mousescroll() */
#define MSCR_DOWN 0 /* DOWN must be FALSE */
#define MSCR_UP 1
#define MSCR_LEFT -1
#define MSCR_RIGHT -2
#define KEYLEN_PART_KEY -1 /* keylen value for incomplete key-code */
#define KEYLEN_PART_MAP -2 /* keylen value for incomplete mapping */
#define KEYLEN_REMOVED 9999 /* keylen value for removed sequence */
/* Return values from win32_fileinfo(). */
#define FILEINFO_OK 0
#define FILEINFO_ENC_FAIL 1 /* enc_to_utf16() failed */
#define FILEINFO_READ_FAIL 2 /* CreateFile() failed */
#define FILEINFO_INFO_FAIL 3 /* GetFileInformationByHandle() failed */
#endif /* VIM__H */
| zyz2011-vim | src/vim.h | C | gpl2 | 73,088 |
# Makefile for Vim on Unix and Unix-like systems vim:ts=8:sw=8:tw=78
#
# This Makefile is loosely based on the GNU Makefile conventions found in
# standards.info.
#
# Compiling Vim, summary:
#
# 3. make
# 5. make install
#
# Compiling Vim, details:
#
# Edit this file for adjusting to your system. You should not need to edit any
# other file for machine specific things!
# The name of this file MUST be Makefile (note the uppercase 'M').
#
# 1. Edit this Makefile {{{1
# The defaults for Vim should work on most machines, but you may want to
# uncomment some lines or make other changes below to tune it to your
# system, compiler or preferences. Uncommenting means that the '#' in
# the first column of a line is removed.
# - If you want a version of Vim that is small and starts up quickly,
# you might want to disable the GUI, X11, Perl, Python and Tcl.
# - Uncomment the line with --disable-gui if you have Motif, GTK and/or
# Athena but don't want to make gvim (the GUI version of Vim with nice
# menus and scrollbars, but makes Vim bigger and startup slower).
# - Uncomment --disable-darwin if on Mac OS X but you want to compile a
# Unix version.
# - Uncomment the line "CONF_OPT_X = --without-x" if you have X11 but
# want to disable using X11 libraries. This speeds up starting Vim,
# but the window title will not be set and the X11 selection can not
# be used.
# - Uncomment the line "CONF_OPT_XSMP = --disable-xsmp" if you have the
# X11 Session Management Protocol (XSMP) library (libSM) but do not
# want to use it.
# This can speedup Vim startup but Vim loses the ability to catch the
# user logging out from session-managers like GNOME and work
# could be lost.
# - Uncomment one or more of these lines to include an interface;
# each makes Vim quite a bit bigger:
# --enable-luainterp for Lua interpreter
# --enable-mzschemeinterp for MzScheme interpreter
# --enable-perlinterp for Perl interpreter
# --enable-python3interp for Python3 interpreter
# --enable-pythoninterp for Python interpreter
# --enable-rubyinterp for Ruby interpreter
# --enable-tclinterp for Tcl interpreter
# --enable-cscope for Cscope interface
# - Uncomment one of the lines with --with-features= to enable a set of
# features (but not the interfaces just mentioned).
# - Uncomment the line with --disable-acl to disable ACL support even
# though your system supports it.
# - Uncomment the line with --disable-gpm to disable gpm support
# even though you have gpm libraries and includes.
# - Uncomment the line with --disable-sysmouse to disable sysmouse
# support even though you have /dev/sysmouse and includes.
# - Uncomment one of the lines with CFLAGS and/or CC if you have
# something very special or want to tune the optimizer.
# - Search for the name of your system to see if it needs anything
# special.
# - A few versions of make use '.include "file"' instead of 'include
# file'. Adjust the include line below if yours does.
#
# 2. Edit feature.h {{{1
# Only if you do not agree with the default compile features, e.g.:
# - you want Vim to be as vi compatible as it can be
# - you want to use Emacs tags files
# - you want right-to-left editing (Hebrew)
# - you want 'langmap' support (Greek)
# - you want to remove features to make Vim smaller
#
# 3. "make" {{{1
# Will first run ./configure with the options in this file. Then it will
# start make again on this Makefile to do the compiling. You can also do
# this in two steps with:
# make config
# make
# The configuration phase creates/overwrites auto/config.h and
# auto/config.mk.
# The configure script is created with "make autoconf". It can detect
# different features of your system and act accordingly. However, it is
# not correct for all systems. Check this:
# - If you have X windows, but configure could not find it or reported
# another include/library directory then you wanted to use, you have
# to set CONF_OPT_X below. You might also check the installation of
# xmkmf.
# - If you have --enable-gui=motif and have Motif on your system, but
# configure reports "checking for location of gui... <not found>", you
# have to set GUI_INC_LOC and GUI_LIB_LOC below.
# If you changed something, do this to run configure again:
# make reconfig
#
# - If you do not trust the automatic configuration code, then inspect
# auto/config.h and auto/config.mk, before starting the actual build
# phase. If possible edit this Makefile, rather than auto/config.mk --
# especially look at the definition of VIMLOC below. Note that the
# configure phase overwrites auto/config.mk and auto/config.h again.
# - If you get error messages, find out what is wrong and try to correct
# it in this Makefile. You may need to do "make reconfig" when you
# change anything that configure uses (e.g. switching from an old C
# compiler to an ANSI C compiler). Only when auto/configure does
# something wrong you may need to change one of the other files. If
# you find a clean way to fix the problem, consider sending a note to
# the author of autoconf (bug-gnu-utils@prep.ai.mit.edu) or Vim
# (Bram@vim.org). Don't bother to do that when you made a hack
# solution for a non-standard system.
#
# 4. "make test" {{{1
# This is optional. This will run Vim scripts on a number of test
# files, and compare the produced output with the expected output.
# If all is well, you will get the "ALL DONE" message in the end. If a
# test fails you get "TEST FAILURE". See below (search for "/^test").
#
# 5. "make install" {{{1
# If the new Vim seems to be working OK you can install it and the
# documentation in the appropriate location. The default is
# "/usr/local". Change "prefix" below to change the location.
# "auto/pathdef.c" will be compiled again after changing this to make
# the executable know where the help files are located.
# Note that any existing executable is removed or overwritten. If you
# want to keep it you will have to make a backup copy first.
# The runtime files are in a different directory for each version. You
# might want to delete an older version.
# If you don't want to install everything, there are other targets:
# make installvim only installs Vim, not the tools
# make installvimbin only installs the Vim executable
# make installruntime installs most of the runtime files
# make installrtbase only installs the Vim help and
# runtime files
# make installlinks only installs the Vim binary links
# make installmanlinks only installs the Vim manpage links
# make installmacros only installs the Vim macros
# make installtutorbin only installs the Vim tutor program
# make installtutor only installs the Vim tutor files
# make installspell only installs the spell files
# make installtools only installs xxd
# If you install Vim, not to install for real but to prepare a package
# or RPM, set DESTDIR to the root of the tree.
#
# 6. Use Vim until a new version comes out. {{{1
#
# 7. "make uninstall_runtime" {{{1
# Will remove the runtime files for the current version. This is safe
# to use while another version is being used, only version-specific
# files will be deleted.
# To remove the runtime files of another version:
# make uninstall_runtime VIMRTDIR=/vim54
# If you want to delete all installed files, use:
# make uninstall
# Note that this will delete files that have the same name for any
# version, thus you might need to do a "make install" soon after this.
# Be careful not to remove a version of Vim that is still being used!
# To find out which files and directories will be deleted, use:
# make -n uninstall
# }}}
#
### This Makefile has been successfully tested on many systems. {{{
### Only the ones that require special options are mentioned here.
### 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:
#------------- ------------------------ ------- - ----------
#AIX 3.2.5 cc (not gcc) - 4.5 (M) Will Fiveash
#AIX 4 cc +X11 -GUI 3.27 (4) Axel Kielhorn
#AIX 4.1.4 cc +X11 +GUI 4.5 (5) Nico Bakker
#AIX 4.2.1 cc 5.2k (C) Will Fiveash
#AIX 4.3.3.12 xic 3.6.6 5.6 (5) David R. Favor
#A/UX 3.1.1 gcc +X11 4.0 (6) Jim Jagielski
#BeOS PR mwcc DR3 5.0n (T) Olaf Seibert
#BSDI 2.1 (x86) shlicc2 gcc-2.6.3 -X11 X11R6 4.5 (1) Jos Backus
#BSD/OS 3.0 (x86) gcc gcc-2.7.2.1 -X11 X11R6 4.6c (1) Jos Backus
#CX/UX 6.2 cc +X11 +GUI_Mofif 5.4 (V) Kipp E. Howard
#DG/UX 5.4* gcc 2.5.8 GUI 5.0e (H) Jonas Schlein
#DG/UX 5.4R4.20 gcc 2.7.2 GUI 5.0s (H) Rocky Olive
#HP-UX (most) c89 cc 5.1 (2) Bram Moolenaar
#HP-UX_9.04 cc +X11 +Motif 5.0 (2) Carton Lao
#Irix 6.3 (O2) cc ? 4.5 (L) Edouard Poor
#Irix 6.4 cc ? 5.0m (S) Rick Sayre
#Irix 6.5 cc ? 6.0 (S) David Harrison
#Irix 64 bit 4.5 (K) Jon Wright
#Linux 2.0 gcc-2.7.2 Infomagic Motif 4.3 (3) Ronald Rietman
#Linux 2.0.31 gcc +X11 +GUI Athena 5.0w (U) Darren Hiebert
#LynxOS 3.0.1 2.9-gnupro-98r2 +X11 +GUI Athena 5.7.1(O) Lorenz Hahn
#LynxOS 3.1.0 2.9-gnupro-98r2 +X11 +GUI Athena 5.7.1(O) Lorenz Hahn
#NEC UP4800 UNIX_SV 4.2MP cc +X11R6 Motif,Athena4.6b (Q) Lennart Schultz
#NetBSD 1.0A gcc-2.4.5 -X11 -GUI 3.21 (X) Juergen Weigert
#QNX 4.2 wcc386-10.6 -X11 4.2 (D) G.F. Desrochers
#QNX 4.23 Watcom -X11 4.2 (F) John Oleynick
#SCO Unix v3.2.5 cc +X11 Motif 3.27 (C) M. Kuperblum
#SCO Open Server 5 gcc 2.7.2.3 +X11 +GUI Motif 5.3 (A) Glauber Ribeiro
#SINIX-N 5.43 RM400 R4000 cc +X11 +GUI 5.0l (I) Martin Furter
#SINIX-Z 5.42 i386 gcc 2.7.2.3 +X11 +GUI Motif 5.1 (I) Joachim Fehn
#SINIX-Y 5.43 RM600 R4000 gcc 2.7.2.3 +X11 +GUI Motif 5.1 (I) Joachim Fehn
#Reliant/SINIX 5.44 cc +X11 +GUI 5.5a (I) B. Pruemmer
#SNI Targon31 TOS 4.1.11 gcc-2.4.5 +X11 -GUI 4.6c (B) Paul Slootman
#Solaris 2.4 (Sparc) cc +X11 +GUI 3.29 (9) Glauber
#Solaris 2.4/2.5 clcc +X11 -GUI openwin 3.20 (7) Robert Colon
#Solaris 2.5 (sun4m) cc (SC4.0) +X11R6 +GUI (CDE) 4.6b (E) Andrew Large
#Solaris 2.5 cc +X11 +GUI Athena 4.2 (9) Sonia Heimann
#Solaris 2.5 gcc 2.5.6 +X11 Motif 5.0m (R) Ant. Colombo
#Solaris 2.6 gcc 2.8.1 ncursus 5.3 (G) Larry W. Virden
#Solaris with -lthread 5.5 (W) K. Nagano
#Solaris gcc (b) Riccardo
#SunOS 4.1.x +X11 -GUI 5.1b (J) Bram Moolenaar
#SunOS 4.1.3_U1 (sun4c) gcc +X11 +GUI Athena 5.0w (J) Darren Hiebert
#SUPER-UX 6.2 (NEC SX-4) cc +X11R6 Motif,Athena4.6b (P) Lennart Schultz
#Tandem/NSK (c) Matthew Woehlke
#Unisys 6035 cc +X11 Motif 5.3 (8) Glauber Ribeiro
#ESIX V4.2 cc +X11 6.0 (a) Reinhard Wobst
#Mac OS X 10.[23] gcc Carbon 6.2 (x) Bram Moolenaar
# }}}
# (*) Remarks: {{{
#
# (1) Uncomment line below for shlicc2
# (2) HPUX with compile problems or wrong digraphs, uncomment line below
# (3) Infomagic Motif needs GUI_LIB_LOC and GUI_INC_LOC set, see below.
# And add "-lXpm" to MOTIF_LIBS2.
# (4) For cc the optimizer must be disabled (use CFLAGS= after running
# configure) (symptom: ":set termcap" output looks weird).
# (5) Compiler may need extra argument, see below.
# (6) See below for a few lines to uncomment
# (7) See below for lines which enable the use of clcc
# (8) Needs some EXTRA_LIBS, search for Unisys below
# (9) Needs an extra compiler flag to compile gui_at_sb.c, see below.
# (A) May need EXTRA_LIBS, see below
# (B) Can't compile GUI because there is no waitpid()... Disable GUI below.
# (C) Force the use of curses instead of termcap, see below.
# (D) Uncomment lines below for QNX
# (E) You might want to use termlib instead of termcap, see below.
# (F) See below for instructions.
# (G) Using ncursus version 4.2 has reported to cause a crash. Use the
# Sun cursus library instead.
# (H) See line for EXTRA_LIBS below.
# (I) SINIX-N 5.42 and 5.43 need some EXTRA_LIBS. Also for Reliant-Unix.
# (J) If you get undefined symbols, see below for a solution.
# (K) See lines to uncomment below for machines with 64 bit pointers.
# (L) For Silicon Graphics O2 workstations remove "-lnsl" from auto/config.mk
# (M) gcc version cygnus-2.0.1 does NOT work (symptom: "dl" deletes two
# characters instead of one).
# (N) SCO with decmouse.
# (O) LynxOS needs EXTRA_LIBS, see below.
# (P) For SuperUX 6.2 on NEC SX-4 see a few lines below to uncomment.
# (Q) For UNIXSVR 4.2MP on NEC UP4800 see below for lines to uncomment.
# (R) For Solaris 2.5 (or 2.5.1) with gcc > 2.5.6, uncomment line below.
# (S) For Irix 6.x with MipsPro compiler, use -OPT:Olimit. See line below.
# (T) See ../doc/os_beos.txt.
# (U) Must uncomment CONF_OPT_PYTHON option below to disable Python
# detection, since the configure script runs into an error when it
# detects Python (probably because of the bash shell).
# (V) See lines to uncomment below.
# (X) Need to use the .include "auto/config.mk" line below
# (Y) See line with c89 below
# (Z) See lines with cc or c89 below
# (a) See line with EXTRA_LIBS below.
# (b) When using gcc with the Solaris linker, make sure you don't use GNU
# strip, otherwise the binary may not run: "Cannot find ELF".
# (c) Add -lfloss to EXTRA_LIBS, see below.
# (x) When you get warnings for precompiled header files, run
# "sudo fixPrecomps". Also see CONF_OPT_DARWIN below.
# }}}
#DO NOT CHANGE the next line, we need it for configure to find the compiler
#instead of using the default from the "make" program.
#Use a line further down to change the value for CC.
CC=
# Change and use these defines if configure cannot find your Motif stuff.
# Unfortunately there is no "standard" location for Motif. {{{
# These defines can contain a single directory (recommended) or a list of
# directories (for when you are working with several systems). The LAST
# directory that exists is used.
# When changed, run "make reconfig" next!
#GUI_INC_LOC = -I/usr/include/Motif2.0 -I/usr/include/Motif1.2
#GUI_LIB_LOC = -L/usr/lib/Motif2.0 -L/usr/lib/Motif1.2
### Use these two lines for Infomagic Motif (3)
#GUI_INC_LOC = -I/usr/X11R6/include
#GUI_LIB_LOC = -L/usr/X11R6/lib
# }}}
######################## auto/config.mk ######################## {{{1
# At this position auto/config.mk is included. When starting from the
# toplevel Makefile it is almost empty. After running auto/configure it
# contains settings that have been discovered for your system. Settings below
# this include override settings in auto/config.mk!
# Note: If make fails because auto/config.mk does not exist (it is not
# included in the repository), do:
# cp config.mk.dist auto/config.mk
# (X) How to include auto/config.mk depends on the version of "make" you have,
# if the current choice doesn't work, try the other one.
include auto/config.mk
#.include "auto/config.mk"
CClink = $(CC)
#}}}
# Include the configuration choices first, so we can override everything
# below. As shipped, this file contains a target that causes to run
# configure. Once configure was run, this file contains a list of
# make variables with predefined values instead. Thus any second invocation
# of make, will build Vim.
# CONFIGURE - configure arguments {{{1
# You can give a lot of options to configure.
# Change this to your desire and do 'make config' afterwards
# examples (can only use one!):
#CONF_ARGS = --exec-prefix=/usr
#CONF_ARGS = --with-vim-name=vim7 --with-ex-name=ex7 --with-view-name=view7
#CONF_ARGS = --with-global-runtime=/etc/vim
#CONF_ARGS = --with-local-dir=/usr/share
#CONF_ARGS = --without-local-dir
# Use this one if you distribute a modified version of Vim.
#CONF_ARGS = --with-modified-by="John Doe"
# GUI - For creating Vim with GUI (gvim) (B)
# Uncomment this line when you don't want to get the GUI version, although you
# have GTK, Motif and/or Athena. Also use --without-x if you don't want X11
# at all.
#CONF_OPT_GUI = --disable-gui
# Uncomment one of these lines if you have that GUI but don't want to use it.
# The automatic check will use another one that can be found.
# Gnome is disabled by default, it may cause trouble.
#CONF_OPT_GUI = --disable-gtk2-check
#CONF_OPT_GUI = --enable-gnome2-check
#CONF_OPT_GUI = --disable-motif-check
#CONF_OPT_GUI = --disable-athena-check
#CONF_OPT_GUI = --disable-nextaw-check
# Uncomment one of these lines to select a specific GUI to use.
# When using "yes" or nothing, configure will use the first one found: GTK+,
# Motif or Athena.
#
# GTK versions that are known not to work 100% are rejected.
# Use "--disable-gtktest" to accept them anyway.
# Only GTK 2 is supported, for GTK 1 use Vim 7.2.
#
# GNOME means GTK with Gnome support. If using GTK and --enable-gnome-check
# is used then GNOME will automatically be used if it is found. If you have
# GNOME, but do not want to use it (e.g., want a GTK-only version), then use
# --enable-gui=gtk or leave out --enable-gnome-check.
#
# If the selected GUI isn't found, the GUI is disabled automatically
#CONF_OPT_GUI = --enable-gui=gtk2
#CONF_OPT_GUI = --enable-gui=gtk2 --disable-gtktest
#CONF_OPT_GUI = --enable-gui=gnome2
#CONF_OPT_GUI = --enable-gui=gnome2 --disable-gtktest
#CONF_OPT_GUI = --enable-gui=motif
#CONF_OPT_GUI = --enable-gui=motif --with-motif-lib="-static -lXm -shared"
#CONF_OPT_GUI = --enable-gui=athena
#CONF_OPT_GUI = --enable-gui=nextaw
# Carbon GUI for Mac OS X
#CONF_OPT_GUI = --enable-gui=carbon
# DARWIN - detecting Mac OS X
# Uncomment this line when you want to compile a Unix version of Vim on
# Darwin. None of the Mac specific options or files will be used.
#CONF_OPT_DARWIN = --disable-darwin
# Select the architecture supported. Default is to build for the current
# platform. Use "both" for a universal binary. That probably doesn't work
# when including Perl, Python, etc.
#CONF_OPT_DARWIN = --with-mac-arch=i386
#CONF_OPT_DARWIN = --with-mac-arch=ppc
#CONF_OPT_DARWIN = --with-mac-arch=both
# LUA
# Uncomment one of these when you want to include the Lua interface.
# First one is for static linking, second one for dynamic loading.
#CONF_OPT_LUA = --enable-luainterp
#CONF_OPT_LUA = --enable-luainterp=dynamic
# Lua installation dir (when not set uses $LUA_PREFIX or defaults to /usr)
#CONF_OPT_LUA_PREFIX = --with-lua-prefix=/usr/local
# MZSCHEME
# Uncomment this when you want to include the MzScheme interface.
#CONF_OPT_MZSCHEME = --enable-mzschemeinterp
# PLT/mrscheme/drscheme Home dir; the PLTHOME environment variable also works
#CONF_OPT_PLTHOME = --with-plthome=/usr/local/plt
#CONF_OPT_PLTHOME = --with-plthome=/usr/local/drscheme
#CONF_OPT_PLTHOME = --with-plthome=/home/me/mz
# Uncomment the next line to fail if one of the requested language interfaces
# cannot be configured. Without this Vim will be build anyway, without
# the failing interfaces.
#CONF_OPT_FAIL = --enable-fail-if-missing
# PERL
# Uncomment one of these when you want to include the Perl interface.
# First one is for static linking, second one for dynamic loading.
# The Perl option sometimes causes problems, because it adds extra flags
#
# to the command line. If you see strange flags during compilation, check in
# auto/config.mk where they come from. If it's PERL_CFLAGS, try commenting
# the next line.
# When you get an error for a missing "perl.exp" file, try creating an emtpy
# one: "touch perl.exp".
# This requires at least "small" features, "tiny" doesn't work.
#CONF_OPT_PERL = --enable-perlinterp
#CONF_OPT_PERL = --enable-perlinterp=dynamic
# PYTHON
# Uncomment this when you want to include the Python interface.
# NOTE: This may cause threading to be enabled, which has side effects (such
# as using different libraries and debugging becomes more difficult).
# NOTE: Using this together with Perl may cause a crash in initialization.
# For Python3 support make a symbolic link in /usr/local/bin:
# ln -s python3 python3.1
# If both python2.x and python3.x are enabled then the linking will be via
# dlopen(), dlsym(), dlclose(), i.e. pythonX.Y.so must be available
# However, this may still cause problems, such as "import termios" failing.
# Build two separate versions of Vim in that case.
#CONF_OPT_PYTHON = --enable-pythoninterp
#CONF_OPT_PYTHON = --enable-pythoninterp=dynamic
#CONF_OPT_PYTHON3 = --enable-python3interp
#CONF_OPT_PYTHON3 = --enable-python3interp=dynamic
# RUBY
# Uncomment this when you want to include the Ruby interface.
# First one for static linking, second one for loading when used.
# Note: you need the development package (e.g., ruby1.9.1-dev on Ubuntu).
#CONF_OPT_RUBY = --enable-rubyinterp
#CONF_OPT_RUBY = --enable-rubyinterp=dynamic
#CONF_OPT_RUBY = --enable-rubyinterp --with-ruby-command=ruby1.9.1
# TCL
# Uncomment this when you want to include the Tcl interface.
#CONF_OPT_TCL = --enable-tclinterp
#CONF_OPT_TCL = --enable-tclinterp --with-tclsh=tclsh8.4
# CSCOPE
# Uncomment this when you want to include the Cscope interface.
#CONF_OPT_CSCOPE = --enable-cscope
# WORKSHOP - Sun Visual Workshop interface. Only works with Motif!
#CONF_OPT_WORKSHOP = --enable-workshop
# NETBEANS - NetBeans interface. Only works with Motif, GTK, and gnome.
# Motif version must have XPM libraries (see |workshop-xpm|).
# Uncomment this when you do not want the netbeans interface.
#CONF_OPT_NETBEANS = --disable-netbeans
# SNIFF - Include support for SNiFF+.
#CONF_OPT_SNIFF = --enable-sniff
# MULTIBYTE - To edit multi-byte characters.
# Uncomment this when you want to edit a multibyte language.
# It's automatically enabled with big features or IME support.
# Note: Compile on a machine where setlocale() actually works, otherwise the
# configure tests may fail.
#CONF_OPT_MULTIBYTE = --enable-multibyte
# NLS - National Language Support
# Uncomment this when you do not want to support translated messages, even
# though configure can find support for it.
#CONF_OPT_NLS = --disable-nls
# XIM - X Input Method. Special character input support for X11 (Chinese,
# Japanese, special symbols, etc). Also needed for dead-key support.
# When omitted it's automatically enabled for the X-windows GUI.
# HANGUL - Input Hangul (Korean) language using internal routines.
# Uncomment one of these when you want to input a multibyte language.
#CONF_OPT_INPUT = --enable-xim
#CONF_OPT_INPUT = --disable-xim
#CONF_OPT_INPUT = --enable-hangulinput
# FONTSET - X fontset support for output of languages with many characters.
# Uncomment this when you want to output a multibyte language.
#CONF_OPT_OUTPUT = --enable-fontset
# ACL - Uncomment this when you do not want to include ACL support, even
# though your system does support it. E.g., when it's buggy.
#CONF_OPT_ACL = --disable-acl
# gpm - For mouse support on Linux console via gpm
# Uncomment this when you do not want to include gpm support, even
# though you have gpm libraries and includes.
#CONF_OPT_GPM = --disable-gpm
# sysmouse - For mouse support on FreeBSD and DragonFly console via sysmouse
# Uncomment this when you do not want do include sysmouse support, even
# though you have /dev/sysmouse and includes.
#CONF_OPT_SYSMOUSE = --disable-sysmouse
# FEATURES - For creating Vim with more or less features
# Uncomment one of these lines when you want to include few to many features.
# The default is "normal".
#CONF_OPT_FEAT = --with-features=tiny
#CONF_OPT_FEAT = --with-features=small
#CONF_OPT_FEAT = --with-features=normal
#CONF_OPT_FEAT = --with-features=big
#CONF_OPT_FEAT = --with-features=huge
# COMPILED BY - For including a specific e-mail address for ":version".
#CONF_OPT_COMPBY = "--with-compiledby=John Doe <JohnDoe@yahoo.com>"
# X WINDOWS DISABLE - For creating a plain Vim without any X11 related fancies
# (otherwise Vim configure will try to include xterm titlebar access)
# Also disable the GUI above, otherwise it will be included anyway.
# When both GUI and X11 have been disabled this may save about 15% of the
# code and make Vim startup quicker.
#CONF_OPT_X = --without-x
# X WINDOWS DIRECTORY - specify X directories
# If configure can't find you X stuff, or if you have multiple X11 derivatives
# installed, you may wish to specify which one to use.
# Select nothing to let configure choose.
# This here selects openwin (as found on sun).
#XROOT = /usr/openwin
#CONF_OPT_X = --x-include=$(XROOT)/include --x-libraries=$(XROOT)/lib
# X11 Session Management Protocol support
# Vim will try to use XSMP to catch the user logging out if there are unsaved
# files. Uncomment this line to disable that (it prevents vim trying to open
# communications with the session manager).
#CONF_OPT_XSMP = --disable-xsmp
# You may wish to include xsmp but use exclude xsmp-interact if the logout
# XSMP functionality does not work well with your session-manager (at time of
# writing, this would be early GNOME-1 gnome-session: it 'freezes' other
# applications after Vim has cancelled a logout (until Vim quits). This
# *might* be the Vim code, but is more likely a bug in early GNOME-1.
# This disables the dialog that asks you if you want to save files or not.
#CONF_OPT_XSMP = --disable-xsmp-interact
# COMPILER - Name of the compiler {{{1
# The default from configure will mostly be fine, no need to change this, just
# an example. If a compiler is defined here, configure will use it rather than
# probing for one. It is dangerous to change this after configure was run.
# Make will use your choice then -- but beware: Many things may change with
# another compiler. It is wise to run 'make reconfig' to start all over
# again.
#CC = cc
#CC = gcc
# COMPILER FLAGS - change as you please. Either before running {{{1
# configure or afterwards. For examples see below.
# When using -g with some older versions of Linux you might get a
# statically linked executable.
# When not defined, configure will try to use -O2 -g for gcc and -O for cc.
#CFLAGS = -g
#CFLAGS = -O
# Optimization limits - depends on the compiler. Automatic check in configure
# doesn't work very well, because many compilers only give a warning for
# unrecognized arguments.
#CFLAGS = -O -OPT:Olimit=2600
#CFLAGS = -O -Olimit 2000
#CFLAGS = -O -FOlimit,2000
# Often used for GCC: mixed optimizing, lot of optimizing, debugging
#CFLAGS = -g -O2 -fno-strength-reduce -Wall -Wshadow -Wmissing-prototypes
#CFLAGS = -g -O2 -fno-strength-reduce -Wall -Wmissing-prototypes
#CFLAGS = -g -Wall -Wmissing-prototypes
#CFLAGS = -O6 -fno-strength-reduce -Wall -Wshadow -Wmissing-prototypes
#CFLAGS = -g -DDEBUG -Wall -Wshadow -Wmissing-prototypes
#CFLAGS = -g -O2 '-DSTARTUPTIME="vimstartup"' -fno-strength-reduce -Wall -Wmissing-prototypes
# Use this with GCC to check for mistakes, unused arguments, etc.
#CFLAGS = -g -Wall -Wextra -Wmissing-prototypes -Wunreachable-code -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
#CFLAGS = -g -O2 -Wall -Wextra -Wmissing-prototypes -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DU_DEBUG
#PYTHON_CFLAGS_EXTRA = -Wno-missing-field-initializers
#MZSCHEME_CFLAGS_EXTRA = -Wno-unreachable-code -Wno-unused-parameter
# EFENCE - Electric-Fence malloc debugging: catches memory accesses beyond
# allocated memory (and makes every malloc()/free() very slow).
# Electric Fence is free (search ftp sites).
# You may want to set the EF_PROTECT_BELOW environment variable to check the
# other side of allocated memory.
# On FreeBSD you might need to enlarge the number of mmaps allowed. Do this
# as root: sysctl -w vm.max_proc_mmap=30000
#EXTRA_LIBS = /usr/local/lib/libefence.a
# PURIFY - remove the # to use the "purify" program (hoi Nia++!)
#PURIFY = purify
# NBDEBUG - debugging the netbeans interface.
#EXTRA_DEFS = -DNBDEBUG
# }}}
# LINT - for running lint
# For standard Unix lint
LINT = lint
LINT_OPTIONS = -beprxzF
# For splint
# It doesn't work well, crashes on include files and non-ascii characters.
#LINT = splint
#LINT_OPTIONS = +unixlib -weak -macrovarprefixexclude -showfunc -linelen 9999
# PROFILING - Uncomment the next two lines to do profiling with gcc and gprof.
# Might not work with GUI or Perl.
# For unknown reasons adding "-lc" fixes a linking problem with some versions
# of GCC. That's probably a bug in the "-pg" implementation.
# After running Vim see the profile result with: gmon vim gmon.out | vim -
# Need to recompile everything after changing this: "make clean" "make".
#PROFILE_CFLAGS = -pg -g -DWE_ARE_PROFILING
#PROFILE_LIBS = -pg
#PROFILE_LIBS = -pg -lc
# MEMORY LEAK DETECTION
# Requires installing the ccmalloc library.
# Configuration is in the .ccmalloc or ~/.ccmalloc file.
# Doesn't work very well, since memory linked to from global variables
# (in libraries) is also marked as leaked memory.
#LEAK_CFLAGS = -DEXITFREE
#LEAK_LIBS = -lccmalloc
#####################################################
### Specific systems, check if yours is listed! ### {{{
#####################################################
### Uncomment things here only if the values chosen by configure are wrong.
### It's better to adjust configure.in and "make autoconf", if you can!
### Then send the required changes to configure.in to the bugs list.
### (1) BSD/OS 2.0.1, 2.1 or 3.0 using shared libraries
###
#CC = shlicc2
#CFLAGS = -O2 -g -m486 -Wall -Wshadow -Wmissing-prototypes -fno-builtin
### (2) HP-UX with a non-ANSI cc, use the c89 ANSI compiler
### The first probably works on all systems
### The second should work a bit better on newer systems
### The third should work a bit better on HPUX 11.11
### Information provided by: Richard Allen <ra@rhi.hi.is>
#CC = c89 -D_HPUX_SOURCE
#CC = c89 -O +Onolimit +ESlit -D_HPUX_SOURCE
#CC = c89 -O +Onolimit +ESlit +e -D_HPUX_SOURCE
### (2) For HP-UX: Enable the use of a different set of digraphs. Use this
### when the default (ISO) digraphs look completely wrong.
### After changing this do "touch digraph.c; make".
#EXTRA_DEFS = -DHPUX_DIGRAPHS
### (2) For HP-UX: 9.04 cpp default macro definition table of 128000 bytes
### is too small to compile many routines. It produces too much defining
### and no space errors.
### Uncomment the following to specify a larger macro definition table.
#CFLAGS = -Wp,-H256000
### (2) For HP-UX 10.20 using the HP cc, with X11R6 and Motif 1.2, with
### libraries in /usr/lib instead of /lib (avoiding transition links).
### Information provided by: David Green
#XROOT = /usr
#CONF_OPT_X = --x-include=$(XROOT)/include/X11R6 --x-libraries=$(XROOT)/lib/X11R6
#GUI_INC_LOC = -I/usr/include/Motif1.2
#GUI_LIB_LOC = -L/usr/lib/Motif1.2_R6
### (5) AIX 4.1.4 with cc
#CFLAGS = -O -qmaxmem=8192
### AIX with c89 (Walter Briscoe)
#CC = c89
#CPPFLAGS = -D_ALL_SOURCE
### AIX 4.3.3.12 with xic 3.6.6 (David R. Favor)
# needed to avoid a problem where strings.h gets included
#CFLAGS = -qsrcmsg -O2 -qmaxmem=8192 -D__STR31__
### (W) Solaris with multi-threaded libraries (-lthread):
### If suspending doesn't work properly, try using this line:
#EXTRA_DEFS = -D_REENTRANT
### (7) Solaris 2.4/2.5 with Centerline compiler
#CC = clcc
#X_LIBS_DIR = -L/usr/openwin/lib -R/usr/openwin/lib
#CFLAGS = -O
### (9) Solaris 2.x with cc (SunPro), using Athena.
### Only required for compiling gui_at_sb.c.
### Symptom: "identifier redeclared: vim_XawScrollbarSetThumb"
### Use one of the lines (either Full ANSI or no ANSI at all)
#CFLAGS = $(CFLAGS) -Xc
#CFLAGS = $(CFLAGS) -Xs
### Solaris 2.3 with X11 and specific cc
#CC=/opt/SUNWspro/bin/cc -O -Xa -v -R/usr/openwin/lib
### Solaris with /usr/ucb/cc (it is rejected by autoconf as "cc")
#CC = /usr/ucb/cc
#EXTRA_LIBS = -R/usr/ucblib
### Solaris with Forte Developer and FEAT_SUN_WORKSHOP
# The Xpm library is available from http://koala.ilog.fr/ftp/pub/xpm.
#CC = cc
#XPM_DIR = /usr/local/xpm/xpm-3.4k-solaris
#XPM_LIB = -L$(XPM_DIR)/lib -R$(XPM_DIR)/lib -lXpm
#XPM_IPATH = -I$(XPM_DIR)/include
#EXTRA_LIBS = $(XPM_LIB)
#EXTRA_IPATHS = $(XPM_IPATH)
#EXTRA_DEFS = -xCC -DHAVE_X11_XPM_H
### Solaris with workshop compilers: Vim is unstable when compiled with
# "-fast". Use this instead. (Shea Martin)
#CFLAGS = -x02 -xtarget=ultra
### (R) for Solaris 2.5 (or 2.5.1) with gcc > 2.5.6 you might need this:
#LDFLAGS = -lw -ldl -lXmu
#GUI_LIB_LOC = -L/usr/local/lib
### (8) Unisys 6035 (Glauber Ribeiro)
#EXTRA_LIBS = -lnsl -lsocket -lgen
### When builtin functions cause problems with gcc (for Sun 4.1.x)
#CFLAGS = -O2 -Wall -traditional -Wno-implicit
### Apollo DOMAIN (with SYSTYPE = bsd4.3) (TESTED for version 3.0)
#EXTRA_DEFS = -DDOMAIN
#CFLAGS= -O -A systype,bsd4.3
### Coherent 4.2.10 on Intel 386 platform
#EXTRA_DEFS = -Dvoid=int
#EXTRA_LIBS = -lterm -lsocket
### SCO 3.2, with different library name for terminfo
#EXTRA_LIBS = -ltinfo
### UTS2 for Amdahl UTS 2.1.x
#EXTRA_DEFS = -DUTS2
#EXTRA_LIBS = -lsocket
### UTS4 for Amdahl UTS 4.x
#EXTRA_DEFS = -DUTS4 -Xa
### USL for Unix Systems Laboratories (SYSV 4.2)
#EXTRA_DEFS = -DUSL
### (6) A/UX 3.1.1 with gcc (Jim Jagielski)
#CC= gcc -D_POSIX_SOURCE
#CFLAGS= -O2
#EXTRA_LIBS = -lposix -lbsd -ltermcap -lX11
### (A) Some versions of SCO Open Server 5 (Jan Christiaan van Winkel)
### Also use the CONF_TERM_LIB below!
#EXTRA_LIBS = -lgen
### (D) QNX (by G.F. Desrochers)
#CFLAGS = -g -O -mf -4
### (F) QNX (by John Oleynick)
# 1. If you don't have an X server: Comment out CONF_OPT_GUI and uncomment
# CONF_OPT_X = --without-x.
# 2. make config
# 3. edit auto/config.mk and remove -ldir and -ltermcap from LIBS. It doesn't
# have -ldir (does config find it somewhere?) and -ltermcap has at
# least one problem so I use termlib.o instead. The problem with
# termcap is that it segfaults if you call it with the name of
# a non-existent terminal type.
# 4. edit auto/config.h and add #define USE_TMPNAM
# 5. add termlib.o to OBJ
# 6. make
### (H) for Data general DG/UX 5.4.2 and 5.4R3.10 (Jonas J. Schlein)
#EXTRA_LIBS = -lgen
### (I) SINIX-N 5.42 or 5.43 RM400 R4000 (also SINIX-Y and SINIX-Z)
#EXTRA_LIBS = -lgen -lnsl
### For SINIX-Y this is needed for the right prototype of gettimeofday()
#EXTRA_DEFS = -D_XPG_IV
### (I) Reliant-Unix (aka SINIX) 5.44 with standard cc
# Use both "-F O3" lines for optimization or the "-g" line for debugging
#EXTRA_LIBS = -lgen -lsocket -lnsl -lSM -lICE
#CFLAGS = -F O3 -DSINIXN
#LDFLAGS = -F O3
#CFLAGS = -g -DSINIXN
### (P) SCO 3.2.42, with different termcap names for some useful keys DJB
#EXTRA_DEFS = -DSCOKEYS -DNETTERM_MOUSE -DDEC_MOUSE -DXTERM_MOUSE -DHAVE_GETTIMEOFDAY
#EXTRA_LIBS = -lsocket -ltermcap -lmalloc -lc_s
### (P) SuperUX 6.2 on NEC SX-4 (Lennart Schultz)
#GUI_INC_LOC = -I/usr/include
#GUI_LIB_LOC = -L/usr/lib
#EXTRA_LIBS = -lgen
### (Q) UNIXSVR 4.2MP on NEC UP4800 (Lennart Schultz)
#GUI_INC_LOC = -I/usr/necccs/include
#GUI_LIB_LOC = -L/usr/necccs/lib/X11R6
#XROOT = /usr/necccs
#CONF_OPT_X = --x-include=$(XROOT)/include --x-libraries=$(XROOT)/lib/X11R6
#EXTRA_LIBS = -lsocket -lgen
### Irix 4.0 & 5.2 (Silicon Graphics Machines, __sgi will be defined)
# Not needed for Irix 5.3, Ives Aerts reported
#EXTRA_LIBS = -lmalloc -lc_s
# Irix 4.0, when regexp and regcmp cannot be found when linking:
#EXTRA_LIBS = -lmalloc -lc_s -lPW
### (S) Irix 6.x (MipsPro compiler): Uses different Olimit flag:
# Note: This newer option style is used with the MipsPro compilers ONLY if
# you are compiling an "n32" or "64" ABI binary (use either a -n32
# flag or a -64 flag for CFLAGS). If you explicitly use a -o32 flag,
# then the CFLAGS option format will be the typical style (i.e.
# -Olimit 3000).
#CFLAGS = -OPT:Olimit=3000 -O
### (S) Irix 6.5 with MipsPro C compiler. Try this as a test to see new
# compiler features! Beware, the optimization is EXTREMELY thorough
# and takes quite a long time.
# Note: See the note above. Here, the -mips3 option automatically
# enables either the "n32" or "64" ABI, depending on what machine you
# are compiling on (n32 is explicitly enabled here, just to make sure).
#CFLAGS = -OPT:Olimit=3500 -O -n32 -mips3 -IPA:aggr_cprop=ON -INLINE:dfe=ON:list=ON:must=screen_char,out_char,ui_write,out_flush
#LDFLAGS= -OPT:Olimit=3500 -O -n32 -mips3 -IPA:aggr_cprop=ON -INLINE:dfe=ON:list=ON:must=screen_char,out_char,ui_write,out_flush
### (K) for SGI Irix machines with 64 bit pointers ("uname -s" says IRIX64)
### Suggested by Jon Wright <jon@gate.sinica.edu.tw>.
### Tested on R8000 IRIX6.1 Power Indigo2.
### Check /etc/compiler.defaults for your compiler settings.
# either (for 64 bit pointers) uncomment the following line
#GUI_LIB_LOC = -L/usr/lib64
# then
# 1) make config
# 2) edit auto/config.mk and delete the -lelf entry in the LIBS line
# 3) make
#
# or (for 32bit pointers) uncomment the following line
#EXTRA_DEFS = -n32
#GUI_LIB_LOC = -L/usr/lib32
# then
# 1) make config
# 2) edit auto/config.mk, add -n32 to LDFLAGS
# 3) make
#
#Alternatively: use -o32 instead of -n32.
###
### (C) On SCO Unix v3.2.5 (and probably other versions) the termcap library,
### which is found by configure, doesn't work correctly. Symptom is the
### error message "Termcap entry too long". Uncomment the next line.
### On AIX 4.2.1 (and other versions probably), libtermcap is reported
### not to display properly.
### after changing this, you need to do "make reconfig".
#CONF_TERM_LIB = --with-tlib=curses
### (E) If you want to use termlib library instead of the automatically found
### one. After changing this, you need to do "make reconfig".
#CONF_TERM_LIB = --with-tlib=termlib
### (a) ESIX V4.2 (Reinhard Wobst)
#EXTRA_LIBS = -lnsl -lsocket -lgen -lXIM -lXmu -lXext
### (c) Tandem/NSK (Matthew Woehlke)
#EXTRA_LIBS = -lfloss
### If you want to use ncurses library instead of the automatically found one
### after changing this, you need to do "make reconfig".
#CONF_TERM_LIB = --with-tlib=ncurses
### For GCC on MSDOS, the ".exe" suffix will be added.
#EXEEXT = .exe
#LNKEXT = .exe
### (O) For LynxOS 2.5.0, tested on PC.
#EXTRA_LIBS = -lXext -lSM -lICE -lbsd
### For LynxOS 3.0.1, tested on PPC
#EXTRA_LIBS= -lXext -lSM -lICE -lnetinet -lXmu -liberty -lX11
### For LynxOS 3.1.0, tested on PC
#EXTRA_LIBS= -lXext -lSM -lICE -lnetinet -lXmu
### (V) For CX/UX 6.2 (on Harris/Concurrent NightHawk 4800, 5800). Remove
### -Qtarget if only in a 5800 environment. (Kipp E. Howard)
#CFLAGS = -O -Qtarget=m88110compat
#EXTRA_LIBS = -lgen
# The value of QUOTESED comes from auto/config.mk.
# Uncomment the next line to use the default value.
# QUOTESED = sed -e 's/[\\"]/\\&/g' -e 's/\\"/"/' -e 's/\\";$$/";/'
##################### end of system specific lines ################### }}}
### Names of the programs and targets {{{1
VIMTARGET = $(VIMNAME)$(EXEEXT)
EXTARGET = $(EXNAME)$(LNKEXT)
VIEWTARGET = $(VIEWNAME)$(LNKEXT)
GVIMNAME = g$(VIMNAME)
GVIMTARGET = $(GVIMNAME)$(LNKEXT)
GVIEWNAME = g$(VIEWNAME)
GVIEWTARGET = $(GVIEWNAME)$(LNKEXT)
RVIMNAME = r$(VIMNAME)
RVIMTARGET = $(RVIMNAME)$(LNKEXT)
RVIEWNAME = r$(VIEWNAME)
RVIEWTARGET = $(RVIEWNAME)$(LNKEXT)
RGVIMNAME = r$(GVIMNAME)
RGVIMTARGET = $(RGVIMNAME)$(LNKEXT)
RGVIEWNAME = r$(GVIEWNAME)
RGVIEWTARGET = $(RGVIEWNAME)$(LNKEXT)
VIMDIFFNAME = $(VIMNAME)diff
GVIMDIFFNAME = g$(VIMDIFFNAME)
VIMDIFFTARGET = $(VIMDIFFNAME)$(LNKEXT)
GVIMDIFFTARGET = $(GVIMDIFFNAME)$(LNKEXT)
EVIMNAME = e$(VIMNAME)
EVIMTARGET = $(EVIMNAME)$(LNKEXT)
EVIEWNAME = e$(VIEWNAME)
EVIEWTARGET = $(EVIEWNAME)$(LNKEXT)
### Names of the tools that are also made {{{1
TOOLS = xxd/xxd$(EXEEXT)
### Installation directories. The defaults come from configure. {{{1
#
### prefix the top directory for the data (default "/usr/local")
#
# Uncomment the next line to install Vim in your home directory.
#prefix = $(HOME)
### exec_prefix is the top directory for the executable (default $(prefix))
#
# Uncomment the next line to install the Vim executable in "/usr/machine/bin"
#exec_prefix = /usr/machine
### BINDIR dir for the executable (default "$(exec_prefix)/bin")
### MANDIR dir for the manual pages (default "$(prefix)/man")
### DATADIR dir for the other files (default "$(prefix)/lib" or
# "$(prefix)/share")
# They may be different when using different architectures for the
# executable and a common directory for the other files.
#
# Uncomment the next line to install Vim in "/usr/bin"
#BINDIR = /usr/bin
# Uncomment the next line to install Vim manuals in "/usr/share/man/man1"
#MANDIR = /usr/share/man
# Uncomment the next line to install Vim help files in "/usr/share/vim"
#DATADIR = /usr/share
### DESTDIR root of the installation tree. This is prepended to the other
# directories. This directory must exist.
#DESTDIR = ~/pkg/vim
### Directory of the man pages
MAN1DIR = /man1
### Vim version (adjusted by a script)
VIMMAJOR = 7
VIMMINOR = 3
### Location of Vim files (should not need to be changed, and {{{1
### some things might not work when they are changed!)
VIMDIR = /vim
VIMRTDIR = /vim$(VIMMAJOR)$(VIMMINOR)
HELPSUBDIR = /doc
COLSUBDIR = /colors
SYNSUBDIR = /syntax
INDSUBDIR = /indent
AUTOSUBDIR = /autoload
PLUGSUBDIR = /plugin
FTPLUGSUBDIR = /ftplugin
LANGSUBDIR = /lang
COMPSUBDIR = /compiler
KMAPSUBDIR = /keymap
MACROSUBDIR = /macros
TOOLSSUBDIR = /tools
TUTORSUBDIR = /tutor
SPELLSUBDIR = /spell
PRINTSUBDIR = /print
PODIR = po
### VIMLOC common root of the Vim files (all versions)
### VIMRTLOC common root of the runtime Vim files (this version)
### VIMRCLOC compiled-in location for global [g]vimrc files (all versions)
### VIMRUNTIMEDIR compiled-in location for runtime files (optional)
### HELPSUBLOC location for help files
### COLSUBLOC location for colorscheme files
### SYNSUBLOC location for syntax files
### INDSUBLOC location for indent files
### AUTOSUBLOC location for standard autoload files
### PLUGSUBLOC location for standard plugin files
### FTPLUGSUBLOC location for ftplugin files
### LANGSUBLOC location for language files
### COMPSUBLOC location for compiler files
### KMAPSUBLOC location for keymap files
### MACROSUBLOC location for macro files
### TOOLSSUBLOC location for tools files
### TUTORSUBLOC location for tutor files
### SPELLSUBLOC location for spell files
### PRINTSUBLOC location for PostScript files (prolog, latin1, ..)
### SCRIPTLOC location for script files (menu.vim, bugreport.vim, ..)
### You can override these if you want to install them somewhere else.
### Edit feature.h for compile-time settings.
VIMLOC = $(DATADIR)$(VIMDIR)
VIMRTLOC = $(DATADIR)$(VIMDIR)$(VIMRTDIR)
VIMRCLOC = $(VIMLOC)
HELPSUBLOC = $(VIMRTLOC)$(HELPSUBDIR)
COLSUBLOC = $(VIMRTLOC)$(COLSUBDIR)
SYNSUBLOC = $(VIMRTLOC)$(SYNSUBDIR)
INDSUBLOC = $(VIMRTLOC)$(INDSUBDIR)
AUTOSUBLOC = $(VIMRTLOC)$(AUTOSUBDIR)
PLUGSUBLOC = $(VIMRTLOC)$(PLUGSUBDIR)
FTPLUGSUBLOC = $(VIMRTLOC)$(FTPLUGSUBDIR)
LANGSUBLOC = $(VIMRTLOC)$(LANGSUBDIR)
COMPSUBLOC = $(VIMRTLOC)$(COMPSUBDIR)
KMAPSUBLOC = $(VIMRTLOC)$(KMAPSUBDIR)
MACROSUBLOC = $(VIMRTLOC)$(MACROSUBDIR)
TOOLSSUBLOC = $(VIMRTLOC)$(TOOLSSUBDIR)
TUTORSUBLOC = $(VIMRTLOC)$(TUTORSUBDIR)
SPELLSUBLOC = $(VIMRTLOC)$(SPELLSUBDIR)
PRINTSUBLOC = $(VIMRTLOC)$(PRINTSUBDIR)
SCRIPTLOC = $(VIMRTLOC)
### Only set VIMRUNTIMEDIR when VIMRTLOC is set to a different location and
### the runtime directory is not below it.
#VIMRUNTIMEDIR = $(VIMRTLOC)
### Name of the evim file target.
EVIM_FILE = $(DESTDIR)$(SCRIPTLOC)/evim.vim
MSWIN_FILE = $(DESTDIR)$(SCRIPTLOC)/mswin.vim
### Name of the menu file target.
SYS_MENU_FILE = $(DESTDIR)$(SCRIPTLOC)/menu.vim
SYS_SYNMENU_FILE = $(DESTDIR)$(SCRIPTLOC)/synmenu.vim
SYS_DELMENU_FILE = $(DESTDIR)$(SCRIPTLOC)/delmenu.vim
### Name of the bugreport file target.
SYS_BUGR_FILE = $(DESTDIR)$(SCRIPTLOC)/bugreport.vim
### Name of the file type detection file target.
SYS_FILETYPE_FILE = $(DESTDIR)$(SCRIPTLOC)/filetype.vim
### Name of the file type detection file target.
SYS_FTOFF_FILE = $(DESTDIR)$(SCRIPTLOC)/ftoff.vim
### Name of the file type detection script file target.
SYS_SCRIPTS_FILE = $(DESTDIR)$(SCRIPTLOC)/scripts.vim
### Name of the ftplugin-on file target.
SYS_FTPLUGIN_FILE = $(DESTDIR)$(SCRIPTLOC)/ftplugin.vim
### Name of the ftplugin-off file target.
SYS_FTPLUGOF_FILE = $(DESTDIR)$(SCRIPTLOC)/ftplugof.vim
### Name of the indent-on file target.
SYS_INDENT_FILE = $(DESTDIR)$(SCRIPTLOC)/indent.vim
### Name of the indent-off file target.
SYS_INDOFF_FILE = $(DESTDIR)$(SCRIPTLOC)/indoff.vim
### Name of the option window script file target.
SYS_OPTWIN_FILE = $(DESTDIR)$(SCRIPTLOC)/optwin.vim
# Program to install the program in the target directory. Could also be "mv".
INSTALL_PROG = cp
# Program to install the data in the target directory. Cannot be "mv"!
INSTALL_DATA = cp
INSTALL_DATA_R = cp -r
### Program to run on installed binary. Use the second one to disable strip.
#STRIP = strip
#STRIP = /bin/true
### Permissions for binaries {{{1
BINMOD = 755
### Permissions for man page
MANMOD = 644
### Permissions for help files
HELPMOD = 644
### Permissions for Perl and shell scripts
SCRIPTMOD = 755
### Permission for Vim script files (menu.vim, bugreport.vim, ..)
VIMSCRIPTMOD = 644
### Permissions for all directories that are created
DIRMOD = 755
### Permissions for all other files that are created
FILEMOD = 644
# Where to copy the man and help files from
HELPSOURCE = ../runtime/doc
# Where to copy the script files from (menu, bugreport)
SCRIPTSOURCE = ../runtime
# Where to copy the colorscheme files from
COLSOURCE = ../runtime/colors
# Where to copy the syntax files from
SYNSOURCE = ../runtime/syntax
# Where to copy the indent files from
INDSOURCE = ../runtime/indent
# Where to copy the standard plugin files from
AUTOSOURCE = ../runtime/autoload
# Where to copy the standard plugin files from
PLUGSOURCE = ../runtime/plugin
# Where to copy the ftplugin files from
FTPLUGSOURCE = ../runtime/ftplugin
# Where to copy the macro files from
MACROSOURCE = ../runtime/macros
# Where to copy the tools files from
TOOLSSOURCE = ../runtime/tools
# Where to copy the tutor files from
TUTORSOURCE = ../runtime/tutor
# Where to copy the spell files from
SPELLSOURCE = ../runtime/spell
# Where to look for language specific files
LANGSOURCE = ../runtime/lang
# Where to look for compiler files
COMPSOURCE = ../runtime/compiler
# Where to look for keymap files
KMAPSOURCE = ../runtime/keymap
# Where to look for print resource files
PRINTSOURCE = ../runtime/print
# If you are using Linux, you might want to use this to make vim the
# default vi editor, it will create a link from vi to Vim when doing
# "make install". An existing file will be overwritten!
# When not using it, some make programs can't handle an undefined $(LINKIT).
#LINKIT = ln -f -s $(DEST_BIN)/$(VIMTARGET) $(DESTDIR)/usr/bin/vi
LINKIT = @echo >/dev/null
###
### GRAPHICAL USER INTERFACE (GUI). {{{1
### 'configure --enable-gui' can enable one of these for you if you did set
### a corresponding CONF_OPT_GUI above and have X11.
### Override configures choice by uncommenting all the following lines.
### As they are, the GUI is disabled. Replace "NONE" with "ATHENA" or "MOTIF"
### for enabling the Athena or Motif GUI.
#GUI_SRC = $(NONE_SRC)
#GUI_OBJ = $(NONE_OBJ)
#GUI_DEFS = $(NONE_DEFS)
#GUI_IPATH = $(NONE_IPATH)
#GUI_LIBS_DIR = $(NONE_LIBS_DIR)
#GUI_LIBS1 = $(NONE_LIBS1)
#GUI_LIBS2 = $(NONE_LIBS2)
#GUI_INSTALL = $(NONE_INSTALL)
#GUI_TARGETS = $(NONE_TARGETS)
#GUI_MAN_TARGETS= $(NONE_MAN_TARGETS)
#GUI_TESTTARGET = $(NONE_TESTTARGET)
#GUI_BUNDLE = $(NONE_BUNDLE)
# Without a GUI install the normal way.
NONE_INSTALL = install_normal
### GTK GUI
GTK_SRC = gui.c gui_gtk.c gui_gtk_x11.c pty.c gui_gtk_f.c \
gui_beval.c
GTK_OBJ = objects/gui.o objects/gui_gtk.o objects/gui_gtk_x11.o \
objects/pty.o objects/gui_gtk_f.o \
objects/gui_beval.o
GTK_DEFS = -DFEAT_GUI_GTK $(NARROW_PROTO)
GTK_IPATH = $(GUI_INC_LOC)
GTK_LIBS_DIR = $(GUI_LIB_LOC)
GTK_LIBS1 =
GTK_LIBS2 = $(GTK_LIBNAME)
GTK_INSTALL = install_normal install_gui_extra
GTK_TARGETS = installglinks
GTK_MAN_TARGETS = yes
GTK_TESTTARGET = gui
GTK_BUNDLE =
### Motif GUI
MOTIF_SRC = gui.c gui_motif.c gui_x11.c pty.c gui_beval.c \
gui_xmdlg.c gui_xmebw.c
MOTIF_OBJ = objects/gui.o objects/gui_motif.o objects/gui_x11.o \
objects/pty.o objects/gui_beval.o \
objects/gui_xmdlg.o objects/gui_xmebw.o
MOTIF_DEFS = -DFEAT_GUI_MOTIF $(NARROW_PROTO)
MOTIF_IPATH = $(GUI_INC_LOC)
MOTIF_LIBS_DIR = $(GUI_LIB_LOC)
MOTIF_LIBS1 =
MOTIF_LIBS2 = $(MOTIF_LIBNAME) -lXt
MOTIF_INSTALL = install_normal install_gui_extra
MOTIF_TARGETS = installglinks
MOTIF_MAN_TARGETS = yes
MOTIF_TESTTARGET = gui
MOTIF_BUNDLE =
### Athena GUI
### Use Xaw3d to make the menus look a little bit nicer
#XAW_LIB = -lXaw3d
XAW_LIB = -lXaw
### When using Xaw3d, uncomment/comment the following lines to also get the
### scrollbars from Xaw3d.
#ATHENA_SRC = gui.c gui_athena.c gui_x11.c pty.c gui_beval.c gui_at_fs.c
#ATHENA_OBJ = objects/gui.o objects/gui_athena.o objects/gui_x11.o \
# objects/pty.o objects/gui_beval.o objects/gui_at_fs.o
#ATHENA_DEFS = -DFEAT_GUI_ATHENA $(NARROW_PROTO) \
# -Dvim_scrollbarWidgetClass=scrollbarWidgetClass \
# -Dvim_XawScrollbarSetThumb=XawScrollbarSetThumb
ATHENA_SRC = gui.c gui_athena.c gui_x11.c pty.c gui_beval.c \
gui_at_sb.c gui_at_fs.c
ATHENA_OBJ = objects/gui.o objects/gui_athena.o objects/gui_x11.o \
objects/pty.o objects/gui_beval.o \
objects/gui_at_sb.o objects/gui_at_fs.o
ATHENA_DEFS = -DFEAT_GUI_ATHENA $(NARROW_PROTO)
ATHENA_IPATH = $(GUI_INC_LOC)
ATHENA_LIBS_DIR = $(GUI_LIB_LOC)
ATHENA_LIBS1 = $(XAW_LIB)
ATHENA_LIBS2 = -lXt
ATHENA_INSTALL = install_normal install_gui_extra
ATHENA_TARGETS = installglinks
ATHENA_MAN_TARGETS = yes
ATHENA_TESTTARGET = gui
ATHENA_BUNDLE =
### neXtaw GUI
NEXTAW_LIB = -lneXtaw
NEXTAW_SRC = gui.c gui_athena.c gui_x11.c pty.c gui_beval.c gui_at_fs.c
NEXTAW_OBJ = objects/gui.o objects/gui_athena.o objects/gui_x11.o \
objects/pty.o objects/gui_beval.o objects/gui_at_fs.o
NEXTAW_DEFS = -DFEAT_GUI_ATHENA -DFEAT_GUI_NEXTAW $(NARROW_PROTO)
NEXTAW_IPATH = $(GUI_INC_LOC)
NEXTAW_LIBS_DIR = $(GUI_LIB_LOC)
NEXTAW_LIBS1 = $(NEXTAW_LIB)
NEXTAW_LIBS2 = -lXt
NEXTAW_INSTALL = install_normal install_gui_extra
NEXTAW_TARGETS = installglinks
NEXTAW_MAN_TARGETS = yes
NEXTAW_TESTTARGET = gui
NEXTAW_BUNDLE =
### (J) Sun OpenWindows 3.2 (SunOS 4.1.x) or earlier that produce these ld
# errors: ld: Undefined symbol
# _get_wmShellWidgetClass
# _get_applicationShellWidgetClass
# then you need to get patches 100512-02 and 100573-03 from Sun. In the
# meantime, uncomment the following GUI_X_LIBS definition as a workaround:
#GUI_X_LIBS = -Bstatic -lXmu -Bdynamic -lXext
# If you also get cos, sin etc. as undefined symbols, try uncommenting this
# too:
#EXTRA_LIBS = /usr/openwin/lib/libXmu.sa -lm
# PHOTON GUI
PHOTONGUI_SRC = gui.c gui_photon.c pty.c
PHOTONGUI_OBJ = objects/gui.o objects/gui_photon.o objects/pty.o
PHOTONGUI_DEFS = -DFEAT_GUI_PHOTON
PHOTONGUI_IPATH =
PHOTONGUI_LIBS_DIR =
PHOTONGUI_LIBS1 = -lph -lphexlib
PHOTONGUI_LIBS2 =
PHOTONGUI_INSTALL = install_normal install_gui_extra
PHOTONGUI_TARGETS = installglinks
PHOTONGUI_MAN_TARGETS = yes
PHOTONGUI_TESTTARGET = gui
PHOTONGUI_BUNDLE =
# CARBON GUI
CARBONGUI_SRC = gui.c gui_mac.c
CARBONGUI_OBJ = objects/gui.o objects/gui_mac.o objects/pty.o
CARBONGUI_DEFS = -DFEAT_GUI_MAC -fno-common -fpascal-strings \
-Wall -Wno-unknown-pragmas \
-mdynamic-no-pic -pipe
CARBONGUI_IPATH = -I. -Iproto
CARBONGUI_LIBS_DIR =
CARBONGUI_LIBS1 = -framework Carbon
CARBONGUI_LIBS2 =
CARBONGUI_INSTALL = install_macosx
CARBONGUI_TARGETS =
CARBONGUI_MAN_TARGETS =
CARBONGUI_TESTTARGET = gui
CARBONGUI_BUNDLE = gui_bundle
APPDIR = $(VIMNAME).app
CARBONGUI_TESTARG = VIMPROG=../$(APPDIR)/Contents/MacOS/$(VIMTARGET)
# All GUI files
ALL_GUI_SRC = gui.c gui_gtk.c gui_gtk_f.c gui_motif.c gui_xmdlg.c gui_xmebw.c gui_athena.c gui_gtk_x11.c gui_x11.c gui_at_sb.c gui_at_fs.c pty.c
ALL_GUI_PRO = gui.pro gui_gtk.pro gui_motif.pro gui_xmdlg.pro gui_athena.pro gui_gtk_x11.pro gui_x11.pro gui_w16.pro gui_w32.pro gui_photon.pro
# }}}
### Command to create dependencies based on #include "..."
### prototype headers are ignored due to -DPROTO, system
### headers #include <...> are ignored if we use the -MM option, as
### e.g. provided by gcc-cpp.
### Include FEAT_GUI to get gependency on gui.h
### Need to change "-I /<path>" to "-isystem /<path>" for GCC 3.x.
CPP_DEPEND = $(CC) -I$(srcdir) -M$(CPP_MM) \
`echo "$(DEPEND_CFLAGS)" $(DEPEND_CFLAGS_FILTER)`
# flags for cproto
# This is for cproto 3 patchlevel 8 or below
# __inline, __attribute__ and __extension__ are not recognized by cproto
# G_IMPLEMENT_INLINES is to avoid functions defined in glib/gutils.h.
#NO_ATTR = -D__inline= -D__inline__= -DG_IMPLEMENT_INLINES \
# -D"__attribute__\\(x\\)=" -D"__asm__\\(x\\)=" \
# -D__extension__= -D__restrict="" \
# -D__gnuc_va_list=char -D__builtin_va_list=char
#
# This is for cproto 3 patchlevel 9 or above (currently 4.6, 4.7g)
# __inline and __attribute__ are now recognized by cproto
# -D"foo()=" is not supported by all compilers so do not use it
NO_ATTR=
#
# Use this for cproto 3 patchlevel 6 or below (use "cproto -V" to check):
# PROTO_FLAGS = -f4 -m__ARGS -d -E"$(CPP)" $(NO_ATTR)
#
# Use this for cproto 3 patchlevel 7 or above (use "cproto -V" to check):
PROTO_FLAGS = -m -M__ARGS -d -E"$(CPP)" $(NO_ATTR)
################################################
## no changes required below this line ##
################################################
SHELL = /bin/sh
.SUFFIXES:
.SUFFIXES: .c .o .pro
PRE_DEFS = -Iproto $(DEFS) $(GUI_DEFS) $(GUI_IPATH) $(CPPFLAGS) $(EXTRA_IPATHS)
POST_DEFS = $(X_CFLAGS) $(MZSCHEME_CFLAGS) $(TCL_CFLAGS) $(EXTRA_DEFS)
ALL_CFLAGS = $(PRE_DEFS) $(CFLAGS) $(PROFILE_CFLAGS) $(LEAK_CFLAGS) $(POST_DEFS)
# Exclude $CFLAGS for osdef.sh, for Mac 10.4 some flags don't work together
# with "-E".
OSDEF_CFLAGS = $(PRE_DEFS) $(POST_DEFS)
LINT_CFLAGS = -DLINT -I. $(PRE_DEFS) $(POST_DEFS) $(RUBY_CFLAGS) $(LUA_CFLAGS) $(PERL_CFLAGS) $(PYTHON_CFLAGS) $(PYTHON3_CFLAGS) -Dinline= -D__extension__= -Dalloca=alloca
LINT_EXTRA = -DUSE_SNIFF -DHANGUL_INPUT -D"__attribute__(x)="
DEPEND_CFLAGS = -DPROTO -DDEPEND -DFEAT_GUI $(LINT_CFLAGS)
ALL_LIB_DIRS = $(GUI_LIBS_DIR) $(X_LIBS_DIR)
ALL_LIBS = \
$(GUI_LIBS1) \
$(GUI_X_LIBS) \
$(GUI_LIBS2) \
$(X_PRE_LIBS) \
$(X_LIBS) \
$(X_EXTRA_LIBS) \
$(LIBS) \
$(EXTRA_LIBS) \
$(LUA_LIBS) \
$(MZSCHEME_LIBS) \
$(PERL_LIBS) \
$(PYTHON_LIBS) \
$(PYTHON3_LIBS) \
$(TCL_LIBS) \
$(RUBY_LIBS) \
$(PROFILE_LIBS) \
$(LEAK_LIBS)
# abbreviations
DEST_BIN = $(DESTDIR)$(BINDIR)
DEST_VIM = $(DESTDIR)$(VIMLOC)
DEST_RT = $(DESTDIR)$(VIMRTLOC)
DEST_HELP = $(DESTDIR)$(HELPSUBLOC)
DEST_COL = $(DESTDIR)$(COLSUBLOC)
DEST_SYN = $(DESTDIR)$(SYNSUBLOC)
DEST_IND = $(DESTDIR)$(INDSUBLOC)
DEST_AUTO = $(DESTDIR)$(AUTOSUBLOC)
DEST_PLUG = $(DESTDIR)$(PLUGSUBLOC)
DEST_FTP = $(DESTDIR)$(FTPLUGSUBLOC)
DEST_LANG = $(DESTDIR)$(LANGSUBLOC)
DEST_COMP = $(DESTDIR)$(COMPSUBLOC)
DEST_KMAP = $(DESTDIR)$(KMAPSUBLOC)
DEST_MACRO = $(DESTDIR)$(MACROSUBLOC)
DEST_TOOLS = $(DESTDIR)$(TOOLSSUBLOC)
DEST_TUTOR = $(DESTDIR)$(TUTORSUBLOC)
DEST_SPELL = $(DESTDIR)$(SPELLSUBLOC)
DEST_SCRIPT = $(DESTDIR)$(SCRIPTLOC)
DEST_PRINT = $(DESTDIR)$(PRINTSUBLOC)
DEST_MAN_TOP = $(DESTDIR)$(MANDIR)
# We assume that the ".../man/xx/man1/" directory is for latin1 manual pages.
# Some systems use UTF-8, but these should find the ".../man/xx.UTF-8/man1/"
# directory first.
# FreeBSD uses ".../man/xx.ISO8859-1/man1" for latin1, use that one too.
DEST_MAN = $(DEST_MAN_TOP)$(MAN1DIR)
DEST_MAN_FR = $(DEST_MAN_TOP)/fr$(MAN1DIR)
DEST_MAN_FR_I = $(DEST_MAN_TOP)/fr.ISO8859-1$(MAN1DIR)
DEST_MAN_FR_U = $(DEST_MAN_TOP)/fr.UTF-8$(MAN1DIR)
DEST_MAN_IT = $(DEST_MAN_TOP)/it$(MAN1DIR)
DEST_MAN_IT_I = $(DEST_MAN_TOP)/it.ISO8859-1$(MAN1DIR)
DEST_MAN_IT_U = $(DEST_MAN_TOP)/it.UTF-8$(MAN1DIR)
DEST_MAN_PL = $(DEST_MAN_TOP)/pl$(MAN1DIR)
DEST_MAN_PL_I = $(DEST_MAN_TOP)/pl.ISO8859-2$(MAN1DIR)
DEST_MAN_PL_U = $(DEST_MAN_TOP)/pl.UTF-8$(MAN1DIR)
DEST_MAN_RU = $(DEST_MAN_TOP)/ru.KOI8-R$(MAN1DIR)
DEST_MAN_RU_U = $(DEST_MAN_TOP)/ru.UTF-8$(MAN1DIR)
# BASIC_SRC: files that are always used
# GUI_SRC: extra GUI files for current configuration
# ALL_GUI_SRC: all GUI files for Unix
#
# SRC: files used for current configuration
# TAGS_SRC: source files used for make tags
# TAGS_INCL: include files used for make tags
# ALL_SRC: source files used for make depend and make lint
TAGS_INCL = *.h
BASIC_SRC = \
blowfish.c \
buffer.c \
charset.c \
diff.c \
digraph.c \
edit.c \
eval.c \
ex_cmds.c \
ex_cmds2.c \
ex_docmd.c \
ex_eval.c \
ex_getln.c \
fileio.c \
fold.c \
getchar.c \
hardcopy.c \
hashtab.c \
if_cscope.c \
if_xcmdsrv.c \
main.c \
mark.c \
memfile.c \
memline.c \
menu.c \
message.c \
misc1.c \
misc2.c \
move.c \
mbyte.c \
normal.c \
ops.c \
option.c \
os_unix.c \
auto/pathdef.c \
popupmnu.c \
quickfix.c \
regexp.c \
screen.c \
search.c \
sha256.c \
spell.c \
syntax.c \
tag.c \
term.c \
ui.c \
undo.c \
version.c \
window.c \
$(OS_EXTRA_SRC)
SRC = $(BASIC_SRC) \
$(GUI_SRC) \
$(HANGULIN_SRC) \
$(LUA_SRC) \
$(MZSCHEME_SRC) \
$(PERL_SRC) \
$(PYTHON_SRC) $(PYTHON3_SRC) \
$(TCL_SRC) \
$(RUBY_SRC) \
$(SNIFF_SRC) \
$(WORKSHOP_SRC) \
$(WSDEBUG_SRC)
TAGS_SRC = *.c *.cpp if_perl.xs
EXTRA_SRC = hangulin.c if_lua.c if_mzsch.c auto/if_perl.c if_perlsfio.c \
if_python.c if_python3.c if_tcl.c if_ruby.c if_sniff.c \
gui_beval.c workshop.c wsdebug.c integration.c netbeans.c
# Unittest files
MEMFILE_TEST_SRC = memfile_test.c
MEMFILE_TEST_TARGET = memfile_test$(EXEEXT)
UNITTEST_SRC = $(MEMFILE_TEST_SRC)
UNITTEST_TARGETS = $(MEMFILE_TEST_TARGET)
# All sources, also the ones that are not configured
ALL_SRC = $(BASIC_SRC) $(ALL_GUI_SRC) $(UNITTEST_SRC) $(EXTRA_SRC)
# Which files to check with lint. Select one of these three lines. ALL_SRC
# checks more, but may not work well for checking a GUI that wasn't configured.
# The perl sources also don't work well with lint.
LINT_SRC = $(BASIC_SRC) $(GUI_SRC) $(HANGULIN_SRC) $(PYTHON_SRC) $(PYTHON3_SRC) $(TCL_SRC) \
$(SNIFF_SRC) $(WORKSHOP_SRC) $(WSDEBUG_SRC) $(NETBEANS_SRC)
#LINT_SRC = $(SRC)
#LINT_SRC = $(ALL_SRC)
#LINT_SRC = $(BASIC_SRC)
OBJ_COMMON = \
objects/buffer.o \
objects/blowfish.o \
objects/charset.o \
objects/diff.o \
objects/digraph.o \
objects/edit.o \
objects/eval.o \
objects/ex_cmds.o \
objects/ex_cmds2.o \
objects/ex_docmd.o \
objects/ex_eval.o \
objects/ex_getln.o \
objects/fileio.o \
objects/fold.o \
objects/getchar.o \
objects/hardcopy.o \
objects/hashtab.o \
$(HANGULIN_OBJ) \
objects/if_cscope.o \
objects/if_xcmdsrv.o \
objects/mark.o \
objects/memline.o \
objects/menu.o \
objects/message.o \
objects/misc1.o \
objects/misc2.o \
objects/move.o \
objects/mbyte.o \
objects/normal.o \
objects/ops.o \
objects/option.o \
objects/os_unix.o \
objects/pathdef.o \
objects/popupmnu.o \
objects/quickfix.o \
objects/regexp.o \
objects/screen.o \
objects/search.o \
objects/sha256.o \
objects/spell.o \
objects/syntax.o \
$(SNIFF_OBJ) \
objects/tag.o \
objects/term.o \
objects/ui.o \
objects/undo.o \
objects/version.o \
objects/window.o \
$(GUI_OBJ) \
$(LUA_OBJ) \
$(MZSCHEME_OBJ) \
$(PERL_OBJ) \
$(PYTHON_OBJ) \
$(PYTHON3_OBJ) \
$(TCL_OBJ) \
$(RUBY_OBJ) \
$(OS_EXTRA_OBJ) \
$(WORKSHOP_OBJ) \
$(NETBEANS_OBJ) \
$(WSDEBUG_OBJ)
OBJ = $(OBJ_COMMON) \
objects/main.o \
objects/memfile.o
MEMFILE_TEST_OBJ = $(OBJ_COMMON) \
objects/memfile_test.o
PRO_AUTO = \
blowfish.pro \
buffer.pro \
charset.pro \
diff.pro \
digraph.pro \
edit.pro \
eval.pro \
ex_cmds.pro \
ex_cmds2.pro \
ex_docmd.pro \
ex_eval.pro \
ex_getln.pro \
fileio.pro \
fold.pro \
getchar.pro \
hardcopy.pro \
hashtab.pro \
hangulin.pro \
if_cscope.pro \
if_xcmdsrv.pro \
if_python.pro \
if_python3.pro \
if_ruby.pro \
main.pro \
mark.pro \
memfile.pro \
memline.pro \
menu.pro \
message.pro \
misc1.pro \
misc2.pro \
move.pro \
mbyte.pro \
normal.pro \
ops.pro \
option.pro \
os_unix.pro \
popupmnu.pro \
quickfix.pro \
regexp.pro \
screen.pro \
search.pro \
sha256.pro \
spell.pro \
syntax.pro \
tag.pro \
term.pro \
termlib.pro \
ui.pro \
undo.pro \
version.pro \
window.pro \
gui_beval.pro \
workshop.pro \
netbeans.pro \
$(ALL_GUI_PRO) \
$(TCL_PRO)
# Resources used for the Mac are in one directory.
RSRC_DIR = os_mac_rsrc
PRO_MANUAL = os_amiga.pro os_msdos.pro os_win16.pro os_win32.pro \
os_mswin.pro os_beos.pro os_vms.pro $(PERL_PRO)
# Default target is making the executable and tools
all: $(VIMTARGET) $(TOOLS) languages $(GUI_BUNDLE)
tools: $(TOOLS)
# Run configure with all the setting from above.
#
# Note: auto/config.h doesn't depend on configure, because running configure
# doesn't always update auto/config.h. The timestamp isn't changed if the
# file contents didn't change (to avoid recompiling everything). Including a
# dependency on auto/config.h would cause running configure each time when
# auto/config.h isn't updated. The dependency on auto/config.mk should make
# sure configure is run when it's needed.
#
config auto/config.mk: auto/configure config.mk.in config.h.in
GUI_INC_LOC="$(GUI_INC_LOC)" GUI_LIB_LOC="$(GUI_LIB_LOC)" \
CC="$(CC)" CPPFLAGS="$(CPPFLAGS)" CFLAGS="$(CFLAGS)" \
LDFLAGS="$(LDFLAGS)" $(CONF_SHELL) srcdir="$(srcdir)" \
./configure $(CONF_OPT_GUI) $(CONF_OPT_X) $(CONF_OPT_XSMP) \
$(CONF_OPT_DARWIN) $(CONF_OPT_FAIL) \
$(CONF_OPT_PERL) $(CONF_OPT_PYTHON) $(CONF_OPT_PYTHON3) \
$(CONF_OPT_TCL) $(CONF_OPT_RUBY) $(CONF_OPT_NLS) \
$(CONF_OPT_CSCOPE) $(CONF_OPT_MULTIBYTE) $(CONF_OPT_INPUT) \
$(CONF_OPT_OUTPUT) $(CONF_OPT_GPM) $(CONF_OPT_WORKSHOP) \
$(CONF_OPT_SNIFF) $(CONF_OPT_FEAT) $(CONF_TERM_LIB) \
$(CONF_OPT_COMPBY) $(CONF_OPT_ACL) $(CONF_OPT_NETBEANS) \
$(CONF_ARGS) $(CONF_OPT_MZSCHEME) $(CONF_OPT_PLTHOME) \
$(CONF_OPT_LUA) $(CONF_OPT_LUA_PREFIX) \
$(CONF_OPT_SYSMOUSE)
# Use "make reconfig" to rerun configure without cached values.
# When config.h changes, most things will be recompiled automatically.
# Invoke $(MAKE) to run config with the empty auto/config.mk.
# Invoke $(MAKE) to build all with the filled auto/config.mk.
reconfig: scratch clean
$(MAKE) -f Makefile config
$(MAKE) -f Makefile all
# Run autoconf to produce auto/configure.
# Note:
# - DO NOT RUN autoconf MANUALLY! It will overwrite ./configure instead of
# producing auto/configure.
# - autoconf is not run automatically, because a patch usually changes both
# configure.in and auto/configure but can't update the timestamps. People
# who do not have (the correct version of) autoconf would run into trouble.
#
# Two tricks are required to make autoconf put its output in the "auto" dir:
# - Temporarily move the ./configure script to ./configure.save. Don't
# overwrite it, it's probably the result of an aborted autoconf.
# - Use sed to change ./config.log to auto/config.log in the configure script.
# Autoconf 2.5x (2.59 at least) produces a few more files that we need to take
# care of:
# - configure.lineno: has the line numbers replaced with $LINENO. That
# improves patches a LOT, thus use it instead (until someone says it doesn't
# work on some system).
# - autom4te.cache directory is created and not cleaned up. Delete it.
# - Uses ">config.log" instead of "./config.log".
autoconf:
if test ! -f configure.save; then mv configure configure.save; fi
autoconf
sed -e 's+>config.log+>auto/config.log+' -e 's+\./config.log+auto/config.log+' configure > auto/configure
chmod 755 auto/configure
mv -f configure.save configure
-rm -rf autom4te.cache
-rm -f auto/config.status auto/config.cache
# Re-execute this Makefile to include the new auto/config.mk produced by
# configure Only used when typing "make" with a fresh auto/config.mk.
myself:
$(MAKE) -f Makefile all
# The normal command to compile a .c file to its .o file.
CCC = $(CC) -c -I$(srcdir) $(ALL_CFLAGS)
# Link the target for normal use or debugging.
# A shell script is used to try linking without unneccesary libraries.
$(VIMTARGET): auto/config.mk objects $(OBJ) version.c version.h
$(CCC) version.c -o objects/version.o
@LINK="$(PURIFY) $(SHRPENV) $(CClink) $(ALL_LIB_DIRS) $(LDFLAGS) \
-o $(VIMTARGET) $(OBJ) $(ALL_LIBS)" \
MAKE="$(MAKE)" LINK_AS_NEEDED=$(LINK_AS_NEEDED) \
sh $(srcdir)/link.sh
xxd/xxd$(EXEEXT): xxd/xxd.c
cd xxd; CC="$(CC)" CFLAGS="$(CPPFLAGS) $(CFLAGS)" LDFLAGS="$(LDFLAGS)" \
$(MAKE) -f Makefile
# Build the language specific files if they were unpacked.
# Generate the converted .mo files separately, it's no problem if this fails.
languages:
@if test -n "$(MAKEMO)" -a -f $(PODIR)/Makefile; then \
cd $(PODIR); \
CC="$(CC)" $(MAKE) prefix=$(DESTDIR)$(prefix); \
fi
-@if test -n "$(MAKEMO)" -a -f $(PODIR)/Makefile; then \
cd $(PODIR); CC="$(CC)" $(MAKE) prefix=$(DESTDIR)$(prefix) converted; \
fi
# Update the *.po files for changes in the sources. Only run manually.
update-po:
cd $(PODIR); CC="$(CC)" $(MAKE) prefix=$(DESTDIR)$(prefix) update-po
# Generate function prototypes. This is not needed to compile vim, but if
# you want to use it, cproto is out there on the net somewhere -- Webb
#
# When generating os_amiga.pro, os_msdos.pro and os_win32.pro there will be a
# few include files that can not be found, that's OK.
proto: $(PRO_AUTO) $(PRO_MANUAL)
# Filter out arguments that cproto doesn't support.
# Don't pass "-pthread" to cproto, it sees it as a list of individual flags.
# Don't pass "-fstack-protector" to cproto, for the same reason.
# The -E"gcc -E" argument must be separate to avoid problems with shell
# quoting.
CPROTO = cproto $(PROTO_FLAGS) -DPROTO \
`echo '$(LINT_CFLAGS)' | sed -e 's/-pthread//g' -e 's/-fstack-protector//g'`
### Would be nice if this would work for "normal" make.
### Currently it only works for (Free)BSD make.
#$(PRO_AUTO): $$(*F).c
# $(CPROTO) -DFEAT_GUI $(*F).c > $@
# Always define FEAT_GUI. This may generate a few warnings if it's also
# defined in auto/config.h, you can ignore that.
.c.pro:
$(CPROTO) -DFEAT_GUI $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_amiga.pro: os_amiga.c
$(CPROTO) -DAMIGA -UHAVE_CONFIG_H -DBPTR=char* $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_msdos.pro: os_msdos.c
$(CPROTO) -DMSDOS -UHAVE_CONFIG_H $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_win16.pro: os_win16.c
$(CPROTO) -DWIN16 -UHAVE_CONFIG_H $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_win32.pro: os_win32.c
$(CPROTO) -DWIN32 -UHAVE_CONFIG_H $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_mswin.pro: os_mswin.c
$(CPROTO) -DWIN16 -DWIN32 -UHAVE_CONFIG_H $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_beos.pro: os_beos.c
$(CPROTO) -D__BEOS__ -UHAVE_CONFIG_H $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
os_vms.pro: os_vms.c
# must use os_vms_conf.h for auto/config.h
mv auto/config.h auto/config.h.save
cp os_vms_conf.h auto/config.h
$(CPROTO) -DVMS -UFEAT_GUI_ATHENA -UFEAT_GUI_NEXTAW -UFEAT_GUI_MOTIF -UFEAT_GUI_GTK $< > proto/$@
echo "/* vim: set ft=c : */" >> proto/$@
rm auto/config.h
mv auto/config.h.save auto/config.h
# if_perl.pro is special: Use the generated if_perl.c for input and remove
# prototypes for local functions.
if_perl.pro: auto/if_perl.c
$(CPROTO) -DFEAT_GUI auto/if_perl.c | sed "/_VI/d" > proto/$@
notags:
-rm -f tags
# Note: tags is made for the currently configured version, can't include both
# Motif and Athena GUI
# You can ignore error messages for missing files.
tags TAGS: notags
$(TAGPRG) $(TAGS_SRC) $(TAGS_INCL)
# Make a highlight file for types. Requires Exuberant ctags and awk
types: types.vim
types.vim: $(TAGS_SRC) $(TAGS_INCL)
ctags --c-kinds=gstu -o- $(TAGS_SRC) $(TAGS_INCL) |\
awk 'BEGIN{printf("syntax keyword Type\t")}\
{printf("%s ", $$1)}END{print ""}' > $@
# Execute the test scripts. Run these after compiling Vim, before installing.
# This doesn't depend on $(VIMTARGET), because that won't work when configure
# wasn't run yet. Restart make to build it instead.
#
# This will produce a lot of garbage on your screen, including a few error
# messages. Don't worry about that.
# If there is a real error, there will be a difference between "test.out" and
# a "test99.ok" file.
# If everything is alright, the final message will be "ALL DONE". If not you
# get "TEST FAILURE".
#
test check:
$(MAKE) -f Makefile $(VIMTARGET)
-if test -n "$(MAKEMO)" -a -f $(PODIR)/Makefile; then \
cd $(PODIR); $(MAKE) -f Makefile check VIM=../$(VIMTARGET); \
fi
-if test $(VIMTARGET) != vim -a ! -r vim; then \
ln -s $(VIMTARGET) vim; \
fi
cd testdir; $(MAKE) -f Makefile $(GUI_TESTTARGET) VIMPROG=../$(VIMTARGET) $(GUI_TESTARG)
$(MAKE) -f Makefile unittest
unittesttargets:
$(MAKE) -f Makefile $(UNITTEST_TARGETS)
unittest unittests: $(UNITTEST_TARGETS)
@for t in $(UNITTEST_TARGETS); do \
./$$t || exit 1; echo $$t passed; \
done
testclean:
cd testdir; $(MAKE) -f Makefile clean
if test -d $(PODIR); then \
cd $(PODIR); $(MAKE) checkclean; \
fi
# Unittests
# It's build just like Vim to satisfy all dependencies.
$(MEMFILE_TEST_TARGET): auto/config.mk objects $(MEMFILE_TEST_OBJ)
$(CCC) version.c -o objects/version.o
@LINK="$(PURIFY) $(SHRPENV) $(CClink) $(ALL_LIB_DIRS) $(LDFLAGS) \
-o $(MEMFILE_TEST_TARGET) $(MEMFILE_TEST_OBJ) $(ALL_LIBS)" \
MAKE="$(MAKE)" LINK_AS_NEEDED=$(LINK_AS_NEEDED) \
sh $(srcdir)/link.sh
# install targets
install: $(GUI_INSTALL)
install_normal: installvim installtools $(INSTALL_LANGS) install-icons
install_gui_extra: installgtutorbin
installvim: installvimbin installtutorbin \
installruntime installlinks installmanlinks
#
# Avoid overwriting an existing executable, somebody might be running it and
# overwriting it could cause it to crash. Deleting it is OK, it won't be
# really deleted until all running processes for it have exited. It is
# renamed first, in case the deleting doesn't work.
#
# If you want to keep an older version, rename it before running "make
# install".
#
installvimbin: $(VIMTARGET) $(DESTDIR)$(exec_prefix) $(DEST_BIN)
-if test -f $(DEST_BIN)/$(VIMTARGET); then \
mv -f $(DEST_BIN)/$(VIMTARGET) $(DEST_BIN)/$(VIMNAME).rm; \
rm -f $(DEST_BIN)/$(VIMNAME).rm; \
fi
$(INSTALL_PROG) $(VIMTARGET) $(DEST_BIN)
$(STRIP) $(DEST_BIN)/$(VIMTARGET)
chmod $(BINMOD) $(DEST_BIN)/$(VIMTARGET)
# may create a link to the new executable from /usr/bin/vi
-$(LINKIT)
# Long list of arguments for the shell script that installs the manual pages
# for one language.
INSTALLMANARGS = $(VIMLOC) $(SCRIPTLOC) $(VIMRCLOC) $(HELPSOURCE) $(MANMOD) \
$(VIMNAME) $(VIMDIFFNAME) $(EVIMNAME)
# Install most of the runtime files
installruntime: installrtbase installmacros installtutor installspell
# install the help files; first adjust the contents for the final location
installrtbase: $(HELPSOURCE)/vim.1 $(DEST_VIM) $(DEST_RT) \
$(DEST_HELP) $(DEST_PRINT) $(DEST_COL) $(DEST_SYN) $(DEST_IND) \
$(DEST_FTP) $(DEST_AUTO) $(DEST_AUTO)/xml $(DEST_PLUG) \
$(DEST_TUTOR) $(DEST_SPELL) $(DEST_COMP)
-$(SHELL) ./installman.sh install $(DEST_MAN) "" $(INSTALLMANARGS)
@echo generating help tags
# Generate the help tags with ":helptags" to handle all languages.
-@cd $(HELPSOURCE); $(MAKE) VIMEXE=$(DEST_BIN)/$(VIMTARGET) vimtags
cd $(HELPSOURCE); \
files=`ls *.txt tags`; \
files="$$files `ls *.??x tags-?? 2>/dev/null || true`"; \
$(INSTALL_DATA) $$files $(DEST_HELP); \
cd $(DEST_HELP); \
chmod $(HELPMOD) $$files
$(INSTALL_DATA) $(HELPSOURCE)/*.pl $(DEST_HELP)
chmod $(SCRIPTMOD) $(DEST_HELP)/*.pl
# install the menu files
$(INSTALL_DATA) $(SCRIPTSOURCE)/menu.vim $(SYS_MENU_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_MENU_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/synmenu.vim $(SYS_SYNMENU_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_SYNMENU_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/delmenu.vim $(SYS_DELMENU_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_DELMENU_FILE)
# install the evim file
$(INSTALL_DATA) $(SCRIPTSOURCE)/mswin.vim $(MSWIN_FILE)
chmod $(VIMSCRIPTMOD) $(MSWIN_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/evim.vim $(EVIM_FILE)
chmod $(VIMSCRIPTMOD) $(EVIM_FILE)
# install the bugreport file
$(INSTALL_DATA) $(SCRIPTSOURCE)/bugreport.vim $(SYS_BUGR_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_BUGR_FILE)
# install the example vimrc files
$(INSTALL_DATA) $(SCRIPTSOURCE)/vimrc_example.vim $(DEST_SCRIPT)
chmod $(VIMSCRIPTMOD) $(DEST_SCRIPT)/vimrc_example.vim
$(INSTALL_DATA) $(SCRIPTSOURCE)/gvimrc_example.vim $(DEST_SCRIPT)
chmod $(VIMSCRIPTMOD) $(DEST_SCRIPT)/gvimrc_example.vim
# install the file type detection files
$(INSTALL_DATA) $(SCRIPTSOURCE)/filetype.vim $(SYS_FILETYPE_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_FILETYPE_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/ftoff.vim $(SYS_FTOFF_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_FTOFF_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/scripts.vim $(SYS_SCRIPTS_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_SCRIPTS_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/ftplugin.vim $(SYS_FTPLUGIN_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_FTPLUGIN_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/ftplugof.vim $(SYS_FTPLUGOF_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_FTPLUGOF_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/indent.vim $(SYS_INDENT_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_INDENT_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/indoff.vim $(SYS_INDOFF_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_INDOFF_FILE)
$(INSTALL_DATA) $(SCRIPTSOURCE)/optwin.vim $(SYS_OPTWIN_FILE)
chmod $(VIMSCRIPTMOD) $(SYS_OPTWIN_FILE)
# install the print resource files
cd $(PRINTSOURCE); $(INSTALL_DATA) *.ps $(DEST_PRINT)
cd $(DEST_PRINT); chmod $(FILEMOD) *.ps
# install the colorscheme files
cd $(COLSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_COL)
cd $(DEST_COL); chmod $(HELPMOD) *.vim README.txt
# install the syntax files
cd $(SYNSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_SYN)
cd $(DEST_SYN); chmod $(HELPMOD) *.vim README.txt
# install the indent files
cd $(INDSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_IND)
cd $(DEST_IND); chmod $(HELPMOD) *.vim README.txt
# install the standard autoload files
cd $(AUTOSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_AUTO)
cd $(DEST_AUTO); chmod $(HELPMOD) *.vim README.txt
cd $(AUTOSOURCE)/xml; $(INSTALL_DATA) *.vim $(DEST_AUTO)/xml
cd $(DEST_AUTO)/xml; chmod $(HELPMOD) *.vim
# install the standard plugin files
cd $(PLUGSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_PLUG)
cd $(DEST_PLUG); chmod $(HELPMOD) *.vim README.txt
# install the ftplugin files
cd $(FTPLUGSOURCE); $(INSTALL_DATA) *.vim README.txt logtalk.dict $(DEST_FTP)
cd $(DEST_FTP); chmod $(HELPMOD) *.vim README.txt
# install the compiler files
cd $(COMPSOURCE); $(INSTALL_DATA) *.vim README.txt $(DEST_COMP)
cd $(DEST_COMP); chmod $(HELPMOD) *.vim README.txt
installmacros: $(DEST_VIM) $(DEST_RT) $(DEST_MACRO)
$(INSTALL_DATA_R) $(MACROSOURCE)/* $(DEST_MACRO)
chmod $(DIRMOD) `find $(DEST_MACRO) -type d -print`
chmod $(FILEMOD) `find $(DEST_MACRO) -type f -print`
chmod $(SCRIPTMOD) $(DEST_MACRO)/less.sh
# When using CVS some CVS directories might have been copied.
# Also delete AAPDIR and *.info files.
cvs=`find $(DEST_MACRO) \( -name CVS -o -name AAPDIR -o -name "*.info" \) -print`; \
if test -n "$$cvs"; then \
rm -rf $$cvs; \
fi
# install the tutor files
installtutorbin: $(DEST_VIM)
$(INSTALL_DATA) vimtutor $(DEST_BIN)/$(VIMNAME)tutor
chmod $(SCRIPTMOD) $(DEST_BIN)/$(VIMNAME)tutor
installgtutorbin: $(DEST_VIM)
$(INSTALL_DATA) gvimtutor $(DEST_BIN)/$(GVIMNAME)tutor
chmod $(SCRIPTMOD) $(DEST_BIN)/$(GVIMNAME)tutor
installtutor: $(DEST_RT) $(DEST_TUTOR)
-$(INSTALL_DATA) $(TUTORSOURCE)/README* $(TUTORSOURCE)/tutor* $(DEST_TUTOR)
-rm -f $(DEST_TUTOR)/*.info
chmod $(HELPMOD) $(DEST_TUTOR)/*
# Install the spell files, if they exist. This assumes at least the English
# spell file is there.
installspell: $(DEST_VIM) $(DEST_RT) $(DEST_SPELL)
if test -f $(SPELLSOURCE)/en.latin1.spl; then \
$(INSTALL_DATA) $(SPELLSOURCE)/*.spl $(SPELLSOURCE)/*.sug $(SPELLSOURCE)/*.vim $(DEST_SPELL); \
chmod $(HELPMOD) $(DEST_SPELL)/*.spl $(DEST_SPELL)/*.sug $(DEST_SPELL)/*.vim; \
fi
# install helper program xxd
installtools: $(TOOLS) $(DESTDIR)$(exec_prefix) $(DEST_BIN) \
$(TOOLSSOURCE) $(DEST_VIM) $(DEST_RT) $(DEST_TOOLS) \
$(INSTALL_TOOL_LANGS)
if test -f $(DEST_BIN)/xxd$(EXEEXT); then \
mv -f $(DEST_BIN)/xxd$(EXEEXT) $(DEST_BIN)/xxd.rm; \
rm -f $(DEST_BIN)/xxd.rm; \
fi
$(INSTALL_PROG) xxd/xxd$(EXEEXT) $(DEST_BIN)
$(STRIP) $(DEST_BIN)/xxd$(EXEEXT)
chmod $(BINMOD) $(DEST_BIN)/xxd$(EXEEXT)
-$(SHELL) ./installman.sh xxd $(DEST_MAN) "" $(INSTALLMANARGS)
# install the runtime tools
$(INSTALL_DATA_R) $(TOOLSSOURCE)/* $(DEST_TOOLS)
# When using CVS some CVS directories might have been copied.
cvs=`find $(DEST_TOOLS) \( -name CVS -o -name AAPDIR \) -print`; \
if test -n "$$cvs"; then \
rm -rf $$cvs; \
fi
-chmod $(FILEMOD) $(DEST_TOOLS)/*
# replace the path in some tools
perlpath=`./which.sh perl` && sed -e "s+/usr/bin/perl+$$perlpath+" $(TOOLSSOURCE)/efm_perl.pl >$(DEST_TOOLS)/efm_perl.pl
awkpath=`./which.sh nawk` && sed -e "s+/usr/bin/nawk+$$awkpath+" $(TOOLSSOURCE)/mve.awk >$(DEST_TOOLS)/mve.awk; if test -z "$$awkpath"; then \
awkpath=`./which.sh gawk` && sed -e "s+/usr/bin/nawk+$$awkpath+" $(TOOLSSOURCE)/mve.awk >$(DEST_TOOLS)/mve.awk; if test -z "$$awkpath"; then \
awkpath=`./which.sh awk` && sed -e "s+/usr/bin/nawk+$$awkpath+" $(TOOLSSOURCE)/mve.awk >$(DEST_TOOLS)/mve.awk; fi; fi
-chmod $(SCRIPTMOD) `grep -l "^#!" $(DEST_TOOLS)/*`
# install the language specific files for tools, if they were unpacked
install-tool-languages:
-$(SHELL) ./installman.sh xxd $(DEST_MAN_FR) "-fr" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_FR_I) "-fr" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_FR_U) "-fr.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_IT) "-it" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_IT_I) "-it" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_IT_U) "-it.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_PL) "-pl" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_PL_I) "-pl" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_PL_U) "-pl.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_RU) "-ru" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh xxd $(DEST_MAN_RU_U) "-ru.UTF-8" $(INSTALLMANARGS)
# install the language specific files, if they were unpacked
install-languages: languages $(DEST_LANG) $(DEST_KMAP)
-$(SHELL) ./installman.sh install $(DEST_MAN_FR) "-fr" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_FR_I) "-fr" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_FR_U) "-fr.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_IT) "-it" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_IT_I) "-it" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_IT_U) "-it.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_PL) "-pl" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_PL_I) "-pl" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_PL_U) "-pl.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_RU) "-ru" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh install $(DEST_MAN_RU_U) "-ru.UTF-8" $(INSTALLMANARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_RU) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_RU_U) $(INSTALLMLARGS)
if test -n "$(MAKEMO)" -a -f $(PODIR)/Makefile; then \
cd $(PODIR); $(MAKE) prefix=$(DESTDIR)$(prefix) LOCALEDIR=$(DEST_LANG) \
INSTALL_DATA=$(INSTALL_DATA) FILEMOD=$(FILEMOD) install; \
fi
if test -d $(LANGSOURCE); then \
$(INSTALL_DATA) $(LANGSOURCE)/README.txt $(LANGSOURCE)/*.vim $(DEST_LANG); \
chmod $(FILEMOD) $(DEST_LANG)/README.txt $(DEST_LANG)/*.vim; \
fi
if test -d $(KMAPSOURCE); then \
$(INSTALL_DATA) $(KMAPSOURCE)/README.txt $(KMAPSOURCE)/*.vim $(DEST_KMAP); \
chmod $(FILEMOD) $(DEST_KMAP)/README.txt $(DEST_KMAP)/*.vim; \
fi
# install the icons for KDE, if the directory exists and the icon doesn't.
ICON48PATH = $(DESTDIR)$(DATADIR)/icons/hicolor/48x48/apps
ICON32PATH = $(DESTDIR)$(DATADIR)/icons/locolor/32x32/apps
ICON16PATH = $(DESTDIR)$(DATADIR)/icons/locolor/16x16/apps
KDEPATH = $(HOME)/.kde/share/icons
install-icons:
if test -d $(ICON48PATH) -a -w $(ICON48PATH) \
-a ! -f $(ICON48PATH)/gvim.png; then \
$(INSTALL_DATA) $(SCRIPTSOURCE)/vim48x48.png $(ICON48PATH)/gvim.png; \
fi
if test -d $(ICON32PATH) -a -w $(ICON32PATH) \
-a ! -f $(ICON32PATH)/gvim.png; then \
$(INSTALL_DATA) $(SCRIPTSOURCE)/vim32x32.png $(ICON32PATH)/gvim.png; \
fi
if test -d $(ICON16PATH) -a -w $(ICON16PATH) \
-a ! -f $(ICON16PATH)/gvim.png; then \
$(INSTALL_DATA) $(SCRIPTSOURCE)/vim16x16.png $(ICON16PATH)/gvim.png; \
fi
$(HELPSOURCE)/vim.1 $(MACROSOURCE) $(TOOLSSOURCE):
@echo Runtime files not found.
@echo You need to unpack the runtime archive before running "make install".
test -f error
$(DESTDIR)$(exec_prefix) $(DEST_BIN) \
$(DEST_VIM) $(DEST_RT) $(DEST_HELP) \
$(DEST_PRINT) $(DEST_COL) $(DEST_SYN) $(DEST_IND) $(DEST_FTP) \
$(DEST_LANG) $(DEST_KMAP) $(DEST_COMP) \
$(DEST_MACRO) $(DEST_TOOLS) $(DEST_TUTOR) $(DEST_SPELL) \
$(DEST_AUTO) $(DEST_AUTO)/xml $(DEST_PLUG):
-$(SHELL) ./mkinstalldirs $@
-chmod $(DIRMOD) $@
# create links from various names to vim. This is only done when the links
# (or executables with the same name) don't exist yet.
installlinks: $(GUI_TARGETS) \
$(DEST_BIN)/$(EXTARGET) \
$(DEST_BIN)/$(VIEWTARGET) \
$(DEST_BIN)/$(RVIMTARGET) \
$(DEST_BIN)/$(RVIEWTARGET) \
$(INSTALLVIMDIFF)
installglinks: $(DEST_BIN)/$(GVIMTARGET) \
$(DEST_BIN)/$(GVIEWTARGET) \
$(DEST_BIN)/$(RGVIMTARGET) \
$(DEST_BIN)/$(RGVIEWTARGET) \
$(DEST_BIN)/$(EVIMTARGET) \
$(DEST_BIN)/$(EVIEWTARGET) \
$(INSTALLGVIMDIFF)
installvimdiff: $(DEST_BIN)/$(VIMDIFFTARGET)
installgvimdiff: $(DEST_BIN)/$(GVIMDIFFTARGET)
$(DEST_BIN)/$(EXTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(EXTARGET)
$(DEST_BIN)/$(VIEWTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(VIEWTARGET)
$(DEST_BIN)/$(GVIMTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(GVIMTARGET)
$(DEST_BIN)/$(GVIEWTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(GVIEWTARGET)
$(DEST_BIN)/$(RVIMTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(RVIMTARGET)
$(DEST_BIN)/$(RVIEWTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(RVIEWTARGET)
$(DEST_BIN)/$(RGVIMTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(RGVIMTARGET)
$(DEST_BIN)/$(RGVIEWTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(RGVIEWTARGET)
$(DEST_BIN)/$(VIMDIFFTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(VIMDIFFTARGET)
$(DEST_BIN)/$(GVIMDIFFTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(GVIMDIFFTARGET)
$(DEST_BIN)/$(EVIMTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(EVIMTARGET)
$(DEST_BIN)/$(EVIEWTARGET):
cd $(DEST_BIN); ln -s $(VIMTARGET) $(EVIEWTARGET)
# Create links for the manual pages with various names to vim. This is only
# done when the links (or manpages with the same name) don't exist yet.
INSTALLMLARGS = $(VIMNAME) $(VIMDIFFNAME) $(EVIMNAME) \
$(EXNAME) $(VIEWNAME) $(RVIMNAME) $(RVIEWNAME) \
$(GVIMNAME) $(GVIEWNAME) $(RGVIMNAME) $(RGVIEWNAME) \
$(GVIMDIFFNAME) $(EVIEWNAME)
installmanlinks:
-$(SHELL) ./installml.sh install "$(GUI_MAN_TARGETS)" \
$(DEST_MAN) $(INSTALLMLARGS)
uninstall: uninstall_runtime
-rm -f $(DEST_BIN)/$(VIMTARGET)
-rm -f $(DEST_BIN)/vimtutor
-rm -f $(DEST_BIN)/gvimtutor
-rm -f $(DEST_BIN)/$(EXTARGET) $(DEST_BIN)/$(VIEWTARGET)
-rm -f $(DEST_BIN)/$(GVIMTARGET) $(DEST_BIN)/$(GVIEWTARGET)
-rm -f $(DEST_BIN)/$(RVIMTARGET) $(DEST_BIN)/$(RVIEWTARGET)
-rm -f $(DEST_BIN)/$(RGVIMTARGET) $(DEST_BIN)/$(RGVIEWTARGET)
-rm -f $(DEST_BIN)/$(VIMDIFFTARGET) $(DEST_BIN)/$(GVIMDIFFTARGET)
-rm -f $(DEST_BIN)/$(EVIMTARGET) $(DEST_BIN)/$(EVIEWTARGET)
-rm -f $(DEST_BIN)/xxd$(EXEEXT)
# Note: the "rmdir" will fail if any files were added after "make install"
uninstall_runtime:
-$(SHELL) ./installman.sh uninstall $(DEST_MAN) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_FR) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_FR_I) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_FR_U) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_IT) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_IT_I) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_IT_U) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_PL) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_PL_I) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_PL_U) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_RU) "" $(INSTALLMANARGS)
-$(SHELL) ./installman.sh uninstall $(DEST_MAN_RU_U) "" $(INSTALLMANARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_FR_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_IT_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL_I) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_PL_U) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_RU) $(INSTALLMLARGS)
-$(SHELL) ./installml.sh uninstall "$(GUI_MAN_TARGETS)" \
$(DEST_MAN_RU_U) $(INSTALLMLARGS)
-rm -f $(DEST_MAN)/xxd.1
-rm -f $(DEST_MAN_FR)/xxd.1 $(DEST_MAN_FR_I)/xxd.1 $(DEST_MAN_FR_U)/xxd.1
-rm -f $(DEST_MAN_IT)/xxd.1 $(DEST_MAN_IT_I)/xxd.1 $(DEST_MAN_IT_U)/xxd.1
-rm -f $(DEST_MAN_PL)/xxd.1 $(DEST_MAN_PL_I)/xxd.1 $(DEST_MAN_PL_U)/xxd.1
-rm -f $(DEST_MAN_RU)/xxd.1 $(DEST_MAN_RU_U)/xxd.1
-rm -f $(DEST_HELP)/*.txt $(DEST_HELP)/tags $(DEST_HELP)/*.pl
-rm -f $(DEST_HELP)/*.??x $(DEST_HELP)/tags-??
-rm -f $(SYS_MENU_FILE) $(SYS_SYNMENU_FILE) $(SYS_DELMENU_FILE)
-rm -f $(SYS_BUGR_FILE) $(EVIM_FILE) $(MSWIN_FILE)
-rm -f $(DEST_SCRIPT)/gvimrc_example.vim $(DEST_SCRIPT)/vimrc_example.vim
-rm -f $(SYS_FILETYPE_FILE) $(SYS_FTOFF_FILE) $(SYS_SCRIPTS_FILE)
-rm -f $(SYS_INDOFF_FILE) $(SYS_INDENT_FILE)
-rm -f $(SYS_FTPLUGOF_FILE) $(SYS_FTPLUGIN_FILE)
-rm -f $(SYS_OPTWIN_FILE)
-rm -f $(DEST_COL)/*.vim $(DEST_COL)/README.txt
-rm -f $(DEST_SYN)/*.vim $(DEST_SYN)/README.txt
-rm -f $(DEST_IND)/*.vim $(DEST_IND)/README.txt
-rm -rf $(DEST_MACRO)
-rm -rf $(DEST_TUTOR)
-rm -rf $(DEST_SPELL)
-rm -rf $(DEST_TOOLS)
-rm -rf $(DEST_LANG)
-rm -rf $(DEST_KMAP)
-rm -rf $(DEST_COMP)
-rm -f $(DEST_PRINT)/*.ps
-rmdir $(DEST_HELP) $(DEST_PRINT) $(DEST_COL) $(DEST_SYN) $(DEST_IND)
-rm -rf $(DEST_FTP)/*.vim $(DEST_FTP)/README.txt
-rm -f $(DEST_AUTO)/*.vim $(DEST_AUTO)/README.txt $(DEST_AUTO)/xml/*.vim
-rm -f $(DEST_PLUG)/*.vim $(DEST_PLUG)/README.txt
-rmdir $(DEST_FTP) $(DEST_AUTO)/xml $(DEST_AUTO) $(DEST_PLUG) $(DEST_RT)
# This will fail when other Vim versions are installed, no worries.
-rmdir $(DEST_VIM)
# Clean up all the files that have been produced, except configure's.
# We support common typing mistakes for Juergen! :-)
clean celan: testclean
-rm -f *.o objects/* core $(VIMTARGET).core $(VIMTARGET) vim xxd/*.o
-rm -f $(TOOLS) auto/osdef.h auto/pathdef.c auto/if_perl.c
-rm -f conftest* *~ auto/link.sed
-rm -f $(UNITTEST_TARGETS)
-rm -f runtime pixmaps
-rm -rf $(APPDIR)
-rm -rf mzscheme_base.c
if test -d $(PODIR); then \
cd $(PODIR); $(MAKE) prefix=$(DESTDIR)$(prefix) clean; \
fi
# Make a shadow directory for compilation on another system or with different
# features.
SHADOWDIR = shadow
shadow: runtime pixmaps
mkdir $(SHADOWDIR)
cd $(SHADOWDIR); ln -s ../*.[ch] ../*.in ../*.sh ../*.xs ../*.xbm ../toolcheck ../proto ../po ../vimtutor ../gvimtutor ../mkinstalldirs .
mkdir $(SHADOWDIR)/auto
cd $(SHADOWDIR)/auto; ln -s ../../auto/configure .
cd $(SHADOWDIR); rm -f auto/link.sed
cp Makefile configure $(SHADOWDIR)
rm -f $(SHADOWDIR)/auto/config.mk $(SHADOWDIR)/config.mk.dist
cp config.mk.dist $(SHADOWDIR)/auto/config.mk
cp config.mk.dist $(SHADOWDIR)
mkdir $(SHADOWDIR)/xxd
cd $(SHADOWDIR)/xxd; ln -s ../../xxd/*.[ch] ../../xxd/Make* .
if test -d $(RSRC_DIR); then \
cd $(SHADOWDIR); \
ln -s ../infplist.xml .; \
ln -s ../$(RSRC_DIR) ../os_mac.rsr.hqx ../dehqx.py .; \
fi
mkdir $(SHADOWDIR)/testdir
cd $(SHADOWDIR)/testdir; ln -s ../../testdir/Makefile \
../../testdir/vimrc.unix \
../../testdir/*.in \
../../testdir/*.vim \
../../testdir/test83-tags? \
../../testdir/*.ok .
# Link needed for doing "make install" in a shadow directory.
runtime:
-ln -s ../runtime .
# Link needed for doing "make" using GTK in a shadow directory.
pixmaps:
-ln -s ../pixmaps .
# Update the synmenu.vim file with the latest Syntax menu.
# This is only needed when runtime/makemenu.vim was changed.
menu: ./vim ../runtime/makemenu.vim
./vim -u ../runtime/makemenu.vim
# Start configure from scratch
scrub scratch:
-rm -f auto/config.status auto/config.cache config.log auto/config.log
-rm -f auto/config.h auto/link.log auto/link.sed auto/config.mk
touch auto/config.h
cp config.mk.dist auto/config.mk
distclean: clean scratch
-rm -f tags
dist: distclean
@echo
@echo Making the distribution has to be done in the top directory
mdepend:
-@rm -f Makefile~
cp Makefile Makefile~
sed -e '/\#\#\# Dependencies/q' < Makefile > tmp_make
@for i in $(ALL_SRC) ; do \
echo "$$i" ; \
echo `echo "$$i" | sed -e 's/[^ ]*\.c$$/objects\/\1.o/'`": $$i" `\
$(CPP) $$i |\
grep '^# .*"\./.*\.h"' |\
sort -t'"' -u +1 -2 |\
sed -e 's/.*"\.\/\(.*\)".*/\1/'\
` >> tmp_make ; \
done
mv tmp_make Makefile
depend:
-@rm -f Makefile~
cp Makefile Makefile~
sed -e '/\#\#\# Dependencies/q' < Makefile > tmp_make
-for i in $(ALL_SRC); do echo $$i; \
$(CPP_DEPEND) $$i | \
sed -e 's+^\([^ ]*\.o\)+objects/\1+' >> tmp_make; done
mv tmp_make Makefile
# Run lint. Clean up the *.ln files that are sometimes left behind.
lint:
$(LINT) $(LINT_OPTIONS) $(LINT_CFLAGS) $(LINT_EXTRA) $(LINT_SRC)
-rm -f *.ln
# Check dosinst.c with lint.
lintinstall:
$(LINT) $(LINT_OPTIONS) -DWIN32 -DUNIX_LINT dosinst.c
-rm -f dosinst.ln
###########################################################################
.c.o:
$(CCC) $<
auto/if_perl.c: if_perl.xs
$(PERL) -e 'unless ( $$] >= 5.005 ) { for (qw(na defgv errgv)) { print "#define PL_$$_ $$_\n" }}' > $@
$(PERL) $(PERLLIB)/ExtUtils/xsubpp -prototypes -typemap \
$(PERLLIB)/ExtUtils/typemap if_perl.xs >> $@
auto/osdef.h: auto/config.h osdef.sh osdef1.h.in osdef2.h.in
CC="$(CC) $(OSDEF_CFLAGS)" srcdir=$(srcdir) sh $(srcdir)/osdef.sh
auto/pathdef.c: Makefile auto/config.mk
-@echo creating $@
-@echo '/* pathdef.c */' > $@
-@echo '/* This file is automatically created by Makefile' >> $@
-@echo ' * DO NOT EDIT! Change Makefile only. */' >> $@
-@echo '#include "vim.h"' >> $@
-@echo 'char_u *default_vim_dir = (char_u *)"$(VIMRCLOC)";' | $(QUOTESED) >> $@
-@echo 'char_u *default_vimruntime_dir = (char_u *)"$(VIMRUNTIMEDIR)";' | $(QUOTESED) >> $@
-@echo 'char_u *all_cflags = (char_u *)"$(CC) -c -I$(srcdir) $(ALL_CFLAGS)";' | $(QUOTESED) >> $@
-@echo 'char_u *all_lflags = (char_u *)"$(CC) $(ALL_LIB_DIRS) $(LDFLAGS) -o $(VIMTARGET) $(ALL_LIBS) ";' | $(QUOTESED) >> $@
-@echo 'char_u *compiled_user = (char_u *)"' | tr -d $(NL) >> $@
-@if test -n "$(COMPILEDBY)"; then \
echo "$(COMPILEDBY)" | tr -d $(NL) >> $@; \
else ((logname) 2>/dev/null || whoami) | tr -d $(NL) >> $@; fi
-@echo '";' >> $@
-@echo 'char_u *compiled_sys = (char_u *)"' | tr -d $(NL) >> $@
-@if test -z "$(COMPILEDBY)"; then hostname | tr -d $(NL) >> $@; fi
-@echo '";' >> $@
-@sh $(srcdir)/pathdef.sh
# All the object files are put in the "objects" directory. Since not all make
# commands understand putting object files in another directory, it must be
# specified for each file separately.
objects:
mkdir objects
objects/blowfish.o: blowfish.c
$(CCC) -o $@ blowfish.c
objects/buffer.o: buffer.c
$(CCC) -o $@ buffer.c
objects/charset.o: charset.c
$(CCC) -o $@ charset.c
objects/diff.o: diff.c
$(CCC) -o $@ diff.c
objects/digraph.o: digraph.c
$(CCC) -o $@ digraph.c
objects/edit.o: edit.c
$(CCC) -o $@ edit.c
objects/eval.o: eval.c
$(CCC) -o $@ eval.c
objects/ex_cmds.o: ex_cmds.c
$(CCC) -o $@ ex_cmds.c
objects/ex_cmds2.o: ex_cmds2.c
$(CCC) -o $@ ex_cmds2.c
objects/ex_docmd.o: ex_docmd.c
$(CCC) -o $@ ex_docmd.c
objects/ex_eval.o: ex_eval.c
$(CCC) -o $@ ex_eval.c
objects/ex_getln.o: ex_getln.c
$(CCC) -o $@ ex_getln.c
objects/fileio.o: fileio.c
$(CCC) -o $@ fileio.c
objects/fold.o: fold.c
$(CCC) -o $@ fold.c
objects/getchar.o: getchar.c
$(CCC) -o $@ getchar.c
objects/hardcopy.o: hardcopy.c
$(CCC) -o $@ hardcopy.c
objects/hashtab.o: hashtab.c
$(CCC) -o $@ hashtab.c
objects/gui.o: gui.c
$(CCC) -o $@ gui.c
objects/gui_at_fs.o: gui_at_fs.c
$(CCC) -o $@ gui_at_fs.c
objects/gui_at_sb.o: gui_at_sb.c
$(CCC) -o $@ gui_at_sb.c
objects/gui_athena.o: gui_athena.c
$(CCC) -o $@ gui_athena.c
objects/gui_beval.o: gui_beval.c
$(CCC) -o $@ gui_beval.c
objects/gui_gtk.o: gui_gtk.c
$(CCC) -o $@ gui_gtk.c
objects/gui_gtk_f.o: gui_gtk_f.c
$(CCC) -o $@ gui_gtk_f.c
objects/gui_gtk_x11.o: gui_gtk_x11.c
$(CCC) -o $@ gui_gtk_x11.c
objects/gui_motif.o: gui_motif.c
$(CCC) -o $@ gui_motif.c
objects/gui_xmdlg.o: gui_xmdlg.c
$(CCC) -o $@ gui_xmdlg.c
objects/gui_xmebw.o: gui_xmebw.c
$(CCC) -o $@ gui_xmebw.c
objects/gui_x11.o: gui_x11.c
$(CCC) -o $@ gui_x11.c
objects/gui_photon.o: gui_photon.c
$(CCC) -o $@ gui_photon.c
objects/gui_mac.o: gui_mac.c
$(CCC) -o $@ gui_mac.c
objects/hangulin.o: hangulin.c
$(CCC) -o $@ hangulin.c
objects/if_cscope.o: if_cscope.c
$(CCC) -o $@ if_cscope.c
objects/if_xcmdsrv.o: if_xcmdsrv.c
$(CCC) -o $@ if_xcmdsrv.c
objects/if_lua.o: if_lua.c
$(CCC) $(LUA_CFLAGS) -o $@ if_lua.c
objects/if_mzsch.o: if_mzsch.c $(MZSCHEME_EXTRA)
$(CCC) -o $@ $(MZSCHEME_CFLAGS_EXTRA) if_mzsch.c
mzscheme_base.c:
$(MZSCHEME_MZC) --c-mods mzscheme_base.c ++lib scheme/base
objects/if_perl.o: auto/if_perl.c
$(CCC) $(PERL_CFLAGS) -o $@ auto/if_perl.c
objects/if_perlsfio.o: if_perlsfio.c
$(CCC) $(PERL_CFLAGS) -o $@ if_perlsfio.c
objects/py_config.o: $(PYTHON_CONFDIR)/config.c
$(CCC) $(PYTHON_CFLAGS) -o $@ $(PYTHON_CONFDIR)/config.c \
-I$(PYTHON_CONFDIR) -DHAVE_CONFIG_H -DNO_MAIN
objects/py_getpath.o: $(PYTHON_CONFDIR)/getpath.c
$(CCC) $(PYTHON_CFLAGS) -o $@ $(PYTHON_CONFDIR)/getpath.c \
-I$(PYTHON_CONFDIR) -DHAVE_CONFIG_H -DNO_MAIN \
$(PYTHON_GETPATH_CFLAGS)
objects/py3_config.o: $(PYTHON3_CONFDIR)/config.c
$(CCC) $(PYTHON3_CFLAGS) -o $@ $(PYTHON3_CONFDIR)/config.c \
-I$(PYTHON3_CONFDIR) -DHAVE_CONFIG_H -DNO_MAIN
objects/if_python.o: if_python.c if_py_both.h
$(CCC) $(PYTHON_CFLAGS) $(PYTHON_CFLAGS_EXTRA) -o $@ if_python.c
objects/if_python3.o: if_python3.c if_py_both.h
$(CCC) $(PYTHON3_CFLAGS) $(PYTHON3_CFLAGS_EXTRA) -o $@ if_python3.c
objects/if_ruby.o: if_ruby.c
$(CCC) $(RUBY_CFLAGS) -o $@ if_ruby.c
objects/if_sniff.o: if_sniff.c
$(CCC) -o $@ if_sniff.c
objects/if_tcl.o: if_tcl.c
$(CCC) -o $@ if_tcl.c
objects/integration.o: integration.c
$(CCC) -o $@ integration.c
objects/main.o: main.c
$(CCC) -o $@ main.c
objects/mark.o: mark.c
$(CCC) -o $@ mark.c
objects/memfile.o: memfile.c
$(CCC) -o $@ memfile.c
objects/memfile_test.o: memfile_test.c
$(CCC) -o $@ memfile_test.c
objects/memline.o: memline.c
$(CCC) -o $@ memline.c
objects/menu.o: menu.c
$(CCC) -o $@ menu.c
objects/message.o: message.c
$(CCC) -o $@ message.c
objects/misc1.o: misc1.c
$(CCC) -o $@ misc1.c
objects/misc2.o: misc2.c
$(CCC) -o $@ misc2.c
objects/move.o: move.c
$(CCC) -o $@ move.c
objects/mbyte.o: mbyte.c
$(CCC) -o $@ mbyte.c
objects/normal.o: normal.c
$(CCC) -o $@ normal.c
objects/ops.o: ops.c
$(CCC) -o $@ ops.c
objects/option.o: option.c
$(CCC) -o $@ option.c
objects/os_beos.o: os_beos.c
$(CCC) -o $@ os_beos.c
objects/os_qnx.o: os_qnx.c
$(CCC) -o $@ os_qnx.c
objects/os_macosx.o: os_macosx.m
$(CCC) -o $@ os_macosx.m
objects/os_mac_conv.o: os_mac_conv.c
$(CCC) -o $@ os_mac_conv.c
objects/os_unix.o: os_unix.c
$(CCC) -o $@ os_unix.c
objects/pathdef.o: auto/pathdef.c
$(CCC) -o $@ auto/pathdef.c
objects/pty.o: pty.c
$(CCC) -o $@ pty.c
objects/popupmnu.o: popupmnu.c
$(CCC) -o $@ popupmnu.c
objects/quickfix.o: quickfix.c
$(CCC) -o $@ quickfix.c
objects/regexp.o: regexp.c
$(CCC) -o $@ regexp.c
objects/screen.o: screen.c
$(CCC) -o $@ screen.c
objects/search.o: search.c
$(CCC) -o $@ search.c
objects/sha256.o: sha256.c
$(CCC) -o $@ sha256.c
objects/spell.o: spell.c
$(CCC) -o $@ spell.c
objects/syntax.o: syntax.c
$(CCC) -o $@ syntax.c
objects/tag.o: tag.c
$(CCC) -o $@ tag.c
objects/term.o: term.c
$(CCC) -o $@ term.c
objects/ui.o: ui.c
$(CCC) -o $@ ui.c
objects/undo.o: undo.c
$(CCC) -o $@ undo.c
objects/window.o: window.c
$(CCC) -o $@ window.c
objects/workshop.o: workshop.c
$(CCC) -o $@ workshop.c
objects/wsdebug.o: wsdebug.c
$(CCC) -o $@ wsdebug.c
objects/netbeans.o: netbeans.c
$(CCC) -o $@ netbeans.c
Makefile:
@echo The name of the makefile MUST be "Makefile" (with capital M)!!!!
###############################################################################
### MacOS X installation
###
### This installs a runnable Vim.app in $(prefix)
REZ = /Developer/Tools/Rez
RESDIR = $(APPDIR)/Contents/Resources
VERSION = $(VIMMAJOR).$(VIMMINOR)
### Common flags
M4FLAGSX = $(M4FLAGS) -DAPP_EXE=$(VIMNAME) -DAPP_NAME=$(VIMNAME) \
-DAPP_VER=$(VERSION)
install_macosx: gui_bundle
# Remove the link to the runtime dir, don't want to copy all of that.
-rm $(RESDIR)/vim/runtime
$(INSTALL_DATA_R) $(APPDIR) $(DESTDIR)$(prefix)
# Generate the help tags file now, it won't work with "make installruntime".
-@srcdir=`pwd`; cd $(HELPSOURCE); $(MAKE) VIMEXE=$$srcdir/$(VIMTARGET) vimtags
# Install the runtime files. Recursive!
-mkdir -p $(DESTDIR)$(prefix)/$(RESDIR)/vim/runtime
# -mkdir $(DESTDIR)$(prefix)/$(APPDIR)/bin
srcdir=`pwd`; $(MAKE) -f Makefile installruntime \
VIMEXE=$$srcdir/$(VIMTARGET) \
prefix=$(DESTDIR)$(prefix)/$(RESDIR)$(VIMDIR) \
exec_prefix=$(DESTDIR)$(prefix)/$(APPDIR)/Contents \
BINDIR=$(DESTDIR)$(prefix)/$(APPDIR)/Contents/MacOS \
VIMLOC=$(DESTDIR)$(prefix)/$(RESDIR)$(VIMDIR) \
VIMRTLOC=$(DESTDIR)$(prefix)/$(RESDIR)$(VIMDIR)/runtime
# Put the link back.
ln -s `pwd`/../runtime $(RESDIR)/vim
# Copy rgb.txt, Mac doesn't always have X11
$(INSTALL_DATA) $(SCRIPTSOURCE)/rgb.txt $(DESTDIR)$(prefix)/$(RESDIR)/vim/runtime
# TODO: Create the vimtutor and/or gvimtutor application.
gui_bundle: $(RESDIR) bundle-dir bundle-executable bundle-info bundle-resource \
bundle-language
$(RESDIR):
mkdir -p $@
bundle-dir: $(APPDIR)/Contents $(VIMTARGET)
# Make a link to the runtime directory, so that we can try out the executable
# without installing it.
mkdir -p $(RESDIR)/vim
-ln -s `pwd`/../runtime $(RESDIR)/vim
bundle-executable: $(VIMTARGET)
mkdir -p $(APPDIR)/Contents/MacOS
cp $(VIMTARGET) $(APPDIR)/Contents/MacOS/$(VIMTARGET)
bundle-info: bundle-dir
@echo "Creating PkgInfo"
@echo -n "APPLVIM!" > $(APPDIR)/Contents/PkgInfo
@echo "Creating Info.plist"
m4 $(M4FLAGSX) infplist.xml > $(APPDIR)/Contents/Info.plist
bundle-resource: bundle-dir bundle-rsrc
cp -f $(RSRC_DIR)/*.icns $(RESDIR)
### Classic resources
# Resource fork (in the form of a .rsrc file) for Classic Vim (Mac OS 9)
# This file is also required for OS X Vim.
bundle-rsrc: os_mac.rsr.hqx
@echo "Creating resource fork"
python dehqx.py $<
rm -f gui_mac.rsrc
mv gui_mac.rsrc.rsrcfork $(RESDIR)/$(VIMNAME).rsrc
# po/Make_osx.pl says something about generating a Mac message file
# for Ukrananian. Would somebody using Mac OS X in Ukranian
# *really* be upset that Carbon Vim was not localised in
# Ukranian?
#
#bundle-language: bundle-dir po/Make_osx.pl
# cd po && perl Make_osx.pl --outdir ../$(RESDIR) $(MULTILANG)
bundle-language: bundle-dir
$(APPDIR)/Contents:
-$(SHELL) ./mkinstalldirs $(APPDIR)/Contents/MacOS
-$(SHELL) ./mkinstalldirs $(RESDIR)/English.lproj
###############################################################################
### (automatically generated by 'make depend')
### Dependencies:
objects/blowfish.o: blowfish.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/buffer.o: buffer.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/charset.o: charset.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/diff.o: diff.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/digraph.o: digraph.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/edit.o: edit.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/eval.o: eval.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/ex_cmds.o: ex_cmds.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/ex_cmds2.o: ex_cmds2.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h version.h
objects/ex_docmd.o: ex_docmd.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/ex_eval.o: ex_eval.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/ex_getln.o: ex_getln.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/fileio.o: fileio.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/fold.o: fold.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/getchar.o: getchar.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/hardcopy.o: hardcopy.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h version.h
objects/hashtab.o: hashtab.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/if_cscope.o: if_cscope.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h if_cscope.h
objects/if_xcmdsrv.o: if_xcmdsrv.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h version.h
objects/main.o: main.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h farsi.c arabic.c
objects/mark.o: mark.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/memfile.o: memfile.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/memline.o: memline.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/menu.o: menu.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/message.o: message.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/misc1.o: misc1.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/misc2.o: misc2.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/move.o: move.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/mbyte.o: mbyte.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/normal.o: normal.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/ops.o: ops.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h ascii.h \
keymap.h term.h macros.h option.h structs.h regexp.h gui.h gui_beval.h \
proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h arabic.h
objects/option.o: option.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/os_unix.o: os_unix.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h os_unixx.h
objects/pathdef.o: auto/pathdef.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/popupmnu.o: popupmnu.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/quickfix.o: quickfix.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/regexp.o: regexp.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/screen.o: screen.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/search.o: search.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/sha256.o: sha256.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/spell.o: spell.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/syntax.o: syntax.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/tag.o: tag.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h ascii.h \
keymap.h term.h macros.h option.h structs.h regexp.h gui.h gui_beval.h \
proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h arabic.h
objects/term.o: term.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/ui.o: ui.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h ascii.h \
keymap.h term.h macros.h option.h structs.h regexp.h gui.h gui_beval.h \
proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h arabic.h
objects/undo.o: undo.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/version.o: version.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/window.o: window.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/gui.o: gui.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h ascii.h \
keymap.h term.h macros.h option.h structs.h regexp.h gui.h gui_beval.h \
proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h arabic.h
objects/gui_gtk.o: gui_gtk.c gui_gtk_f.h vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h ../pixmaps/stock_icons.h
objects/gui_gtk_f.o: gui_gtk_f.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_gtk_f.h
objects/gui_motif.o: gui_motif.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_xmebw.h ../pixmaps/alert.xpm \
../pixmaps/error.xpm ../pixmaps/generic.xpm ../pixmaps/info.xpm \
../pixmaps/quest.xpm gui_x11_pm.h ../pixmaps/tb_new.xpm \
../pixmaps/tb_open.xpm ../pixmaps/tb_close.xpm ../pixmaps/tb_save.xpm \
../pixmaps/tb_print.xpm ../pixmaps/tb_cut.xpm ../pixmaps/tb_copy.xpm \
../pixmaps/tb_paste.xpm ../pixmaps/tb_find.xpm \
../pixmaps/tb_find_next.xpm ../pixmaps/tb_find_prev.xpm \
../pixmaps/tb_find_help.xpm ../pixmaps/tb_exit.xpm \
../pixmaps/tb_undo.xpm ../pixmaps/tb_redo.xpm ../pixmaps/tb_help.xpm \
../pixmaps/tb_macro.xpm ../pixmaps/tb_make.xpm \
../pixmaps/tb_save_all.xpm ../pixmaps/tb_jump.xpm \
../pixmaps/tb_ctags.xpm ../pixmaps/tb_load_session.xpm \
../pixmaps/tb_save_session.xpm ../pixmaps/tb_new_session.xpm \
../pixmaps/tb_blank.xpm ../pixmaps/tb_maximize.xpm \
../pixmaps/tb_split.xpm ../pixmaps/tb_minimize.xpm \
../pixmaps/tb_shell.xpm ../pixmaps/tb_replace.xpm \
../pixmaps/tb_vsplit.xpm ../pixmaps/tb_maxwidth.xpm \
../pixmaps/tb_minwidth.xpm
objects/gui_xmdlg.o: gui_xmdlg.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/gui_xmebw.o: gui_xmebw.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_xmebwp.h gui_xmebw.h
objects/gui_athena.o: gui_athena.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_at_sb.h gui_x11_pm.h \
../pixmaps/tb_new.xpm ../pixmaps/tb_open.xpm ../pixmaps/tb_close.xpm \
../pixmaps/tb_save.xpm ../pixmaps/tb_print.xpm ../pixmaps/tb_cut.xpm \
../pixmaps/tb_copy.xpm ../pixmaps/tb_paste.xpm ../pixmaps/tb_find.xpm \
../pixmaps/tb_find_next.xpm ../pixmaps/tb_find_prev.xpm \
../pixmaps/tb_find_help.xpm ../pixmaps/tb_exit.xpm \
../pixmaps/tb_undo.xpm ../pixmaps/tb_redo.xpm ../pixmaps/tb_help.xpm \
../pixmaps/tb_macro.xpm ../pixmaps/tb_make.xpm \
../pixmaps/tb_save_all.xpm ../pixmaps/tb_jump.xpm \
../pixmaps/tb_ctags.xpm ../pixmaps/tb_load_session.xpm \
../pixmaps/tb_save_session.xpm ../pixmaps/tb_new_session.xpm \
../pixmaps/tb_blank.xpm ../pixmaps/tb_maximize.xpm \
../pixmaps/tb_split.xpm ../pixmaps/tb_minimize.xpm \
../pixmaps/tb_shell.xpm ../pixmaps/tb_replace.xpm \
../pixmaps/tb_vsplit.xpm ../pixmaps/tb_maxwidth.xpm \
../pixmaps/tb_minwidth.xpm
objects/gui_gtk_x11.o: gui_gtk_x11.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_gtk_f.h ../runtime/vim32x32.xpm \
../runtime/vim16x16.xpm ../runtime/vim48x48.xpm
objects/gui_x11.o: gui_x11.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h ../runtime/vim32x32.xpm ../runtime/vim16x16.xpm \
../runtime/vim48x48.xpm
objects/gui_at_sb.o: gui_at_sb.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_at_sb.h
objects/gui_at_fs.o: gui_at_fs.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h gui_at_sb.h
objects/pty.o: pty.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h ascii.h \
keymap.h term.h macros.h option.h structs.h regexp.h gui.h gui_beval.h \
proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h arabic.h
objects/memfile_test.o: memfile_test.c main.c vim.h auto/config.h feature.h \
os_unix.h auto/osdef.h ascii.h keymap.h term.h macros.h option.h \
structs.h regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h \
proto.h globals.h farsi.h arabic.h farsi.c arabic.c memfile.c
objects/hangulin.o: hangulin.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/if_lua.o: if_lua.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/if_mzsch.o: if_mzsch.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h if_mzsch.h
objects/if_perl.o: auto/if_perl.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/if_perlsfio.o: if_perlsfio.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/if_python.o: if_python.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h if_py_both.h
objects/if_python3.o: if_python3.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h if_py_both.h
objects/if_tcl.o: if_tcl.c vim.h auto/config.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h
objects/if_ruby.o: if_ruby.c auto/config.h vim.h feature.h os_unix.h auto/osdef.h \
ascii.h keymap.h term.h macros.h option.h structs.h regexp.h gui.h \
gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h globals.h farsi.h \
arabic.h version.h
objects/if_sniff.o: if_sniff.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h os_unixx.h
objects/gui_beval.o: gui_beval.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h
objects/workshop.o: workshop.c auto/config.h integration.h vim.h feature.h \
os_unix.h auto/osdef.h ascii.h keymap.h term.h macros.h option.h \
structs.h regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h \
proto.h globals.h farsi.h arabic.h version.h workshop.h
objects/wsdebug.o: wsdebug.c
objects/integration.o: integration.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h integration.h
objects/netbeans.o: netbeans.c vim.h auto/config.h feature.h os_unix.h \
auto/osdef.h ascii.h keymap.h term.h macros.h option.h structs.h \
regexp.h gui.h gui_beval.h proto/gui_beval.pro ex_cmds.h proto.h \
globals.h farsi.h arabic.h version.h
| zyz2011-vim | src/Makefile | Makefile | gpl2 | 122,159 |
/* 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.
*/
/*
* ops.c: implementation of various operators: op_shift, op_delete, op_tilde,
* op_change, op_yank, do_put, do_join
*/
#include "vim.h"
/*
* Number of registers.
* 0 = unnamed register, for normal yanks and puts
* 1..9 = registers '1' to '9', for deletes
* 10..35 = registers 'a' to 'z'
* 36 = delete register '-'
* 37 = Selection register '*'. Only if FEAT_CLIPBOARD defined
* 38 = Clipboard register '+'. Only if FEAT_CLIPBOARD and FEAT_X11 defined
*/
/*
* Symbolic names for some registers.
*/
#define DELETION_REGISTER 36
#ifdef FEAT_CLIPBOARD
# define STAR_REGISTER 37
# ifdef FEAT_X11
# define PLUS_REGISTER 38
# else
# define PLUS_REGISTER STAR_REGISTER /* there is only one */
# endif
#endif
#ifdef FEAT_DND
# define TILDE_REGISTER (PLUS_REGISTER + 1)
#endif
#ifdef FEAT_CLIPBOARD
# ifdef FEAT_DND
# define NUM_REGISTERS (TILDE_REGISTER + 1)
# else
# define NUM_REGISTERS (PLUS_REGISTER + 1)
# endif
#else
# define NUM_REGISTERS 37
#endif
/*
* Each yank register is an array of pointers to lines.
*/
static struct yankreg
{
char_u **y_array; /* pointer to array of line pointers */
linenr_T y_size; /* number of lines in y_array */
char_u y_type; /* MLINE, MCHAR or MBLOCK */
#ifdef FEAT_VISUAL
colnr_T y_width; /* only set if y_type == MBLOCK */
#endif
} y_regs[NUM_REGISTERS];
static struct yankreg *y_current; /* ptr to current yankreg */
static int y_append; /* TRUE when appending */
static struct yankreg *y_previous = NULL; /* ptr to last written yankreg */
/*
* structure used by block_prep, op_delete and op_yank for blockwise operators
* also op_change, op_shift, op_insert, op_replace - AKelly
*/
struct block_def
{
int startspaces; /* 'extra' cols before first char */
int endspaces; /* 'extra' cols after last char */
int textlen; /* chars in block */
char_u *textstart; /* pointer to 1st char (partially) in block */
colnr_T textcol; /* index of chars (partially) in block */
colnr_T start_vcol; /* start col of 1st char wholly inside block */
colnr_T end_vcol; /* start col of 1st char wholly after block */
#ifdef FEAT_VISUALEXTRA
int is_short; /* TRUE if line is too short to fit in block */
int is_MAX; /* TRUE if curswant==MAXCOL when starting */
int is_oneChar; /* TRUE if block within one character */
int pre_whitesp; /* screen cols of ws before block */
int pre_whitesp_c; /* chars of ws before block */
colnr_T end_char_vcols; /* number of vcols of post-block char */
#endif
colnr_T start_char_vcols; /* number of vcols of pre-block char */
};
#ifdef FEAT_VISUALEXTRA
static void shift_block __ARGS((oparg_T *oap, int amount));
static void block_insert __ARGS((oparg_T *oap, char_u *s, int b_insert, struct block_def*bdp));
#endif
static int stuff_yank __ARGS((int, char_u *));
static void put_reedit_in_typebuf __ARGS((int silent));
static int put_in_typebuf __ARGS((char_u *s, int esc, int colon,
int silent));
static void stuffescaped __ARGS((char_u *arg, int literally));
#ifdef FEAT_MBYTE
static void mb_adjust_opend __ARGS((oparg_T *oap));
#endif
static void free_yank __ARGS((long));
static void free_yank_all __ARGS((void));
static int yank_copy_line __ARGS((struct block_def *bd, long y_idx));
#ifdef FEAT_CLIPBOARD
static void copy_yank_reg __ARGS((struct yankreg *reg));
# if defined(FEAT_VISUAL) || defined(FEAT_EVAL)
static void may_set_selection __ARGS((void));
# endif
#endif
static void dis_msg __ARGS((char_u *p, int skip_esc));
#if defined(FEAT_COMMENTS) || defined(PROTO)
static char_u *skip_comment __ARGS((char_u *line, int process, int include_space, int *is_comment));
#endif
#ifdef FEAT_VISUAL
static void block_prep __ARGS((oparg_T *oap, struct block_def *, linenr_T, int));
#endif
#if defined(FEAT_CLIPBOARD) || defined(FEAT_EVAL)
static void str_to_reg __ARGS((struct yankreg *y_ptr, int type, char_u *str, long len, long blocklen));
#endif
static int ends_in_white __ARGS((linenr_T lnum));
#ifdef FEAT_COMMENTS
static int same_leader __ARGS((linenr_T lnum, int, char_u *, int, char_u *));
static int fmt_check_par __ARGS((linenr_T, int *, char_u **, int do_comments));
#else
static int fmt_check_par __ARGS((linenr_T));
#endif
/*
* The names of operators.
* IMPORTANT: Index must correspond with defines in vim.h!!!
* The third field indicates whether the operator always works on lines.
*/
static char opchars[][3] =
{
{NUL, NUL, FALSE}, /* OP_NOP */
{'d', NUL, FALSE}, /* OP_DELETE */
{'y', NUL, FALSE}, /* OP_YANK */
{'c', NUL, FALSE}, /* OP_CHANGE */
{'<', NUL, TRUE}, /* OP_LSHIFT */
{'>', NUL, TRUE}, /* OP_RSHIFT */
{'!', NUL, TRUE}, /* OP_FILTER */
{'g', '~', FALSE}, /* OP_TILDE */
{'=', NUL, TRUE}, /* OP_INDENT */
{'g', 'q', TRUE}, /* OP_FORMAT */
{':', NUL, TRUE}, /* OP_COLON */
{'g', 'U', FALSE}, /* OP_UPPER */
{'g', 'u', FALSE}, /* OP_LOWER */
{'J', NUL, TRUE}, /* DO_JOIN */
{'g', 'J', TRUE}, /* DO_JOIN_NS */
{'g', '?', FALSE}, /* OP_ROT13 */
{'r', NUL, FALSE}, /* OP_REPLACE */
{'I', NUL, FALSE}, /* OP_INSERT */
{'A', NUL, FALSE}, /* OP_APPEND */
{'z', 'f', TRUE}, /* OP_FOLD */
{'z', 'o', TRUE}, /* OP_FOLDOPEN */
{'z', 'O', TRUE}, /* OP_FOLDOPENREC */
{'z', 'c', TRUE}, /* OP_FOLDCLOSE */
{'z', 'C', TRUE}, /* OP_FOLDCLOSEREC */
{'z', 'd', TRUE}, /* OP_FOLDDEL */
{'z', 'D', TRUE}, /* OP_FOLDDELREC */
{'g', 'w', TRUE}, /* OP_FORMAT2 */
{'g', '@', FALSE}, /* OP_FUNCTION */
};
/*
* Translate a command name into an operator type.
* Must only be called with a valid operator name!
*/
int
get_op_type(char1, char2)
int char1;
int char2;
{
int i;
if (char1 == 'r') /* ignore second character */
return OP_REPLACE;
if (char1 == '~') /* when tilde is an operator */
return OP_TILDE;
for (i = 0; ; ++i)
if (opchars[i][0] == char1 && opchars[i][1] == char2)
break;
return i;
}
#if defined(FEAT_VISUAL) || defined(PROTO)
/*
* Return TRUE if operator "op" always works on whole lines.
*/
int
op_on_lines(op)
int op;
{
return opchars[op][2];
}
#endif
/*
* Get first operator command character.
* Returns 'g' or 'z' if there is another command character.
*/
int
get_op_char(optype)
int optype;
{
return opchars[optype][0];
}
/*
* Get second operator command character.
*/
int
get_extra_op_char(optype)
int optype;
{
return opchars[optype][1];
}
/*
* op_shift - handle a shift operation
*/
void
op_shift(oap, curs_top, amount)
oparg_T *oap;
int curs_top;
int amount;
{
long i;
int first_char;
char_u *s;
#ifdef FEAT_VISUAL
int block_col = 0;
#endif
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return;
#ifdef FEAT_VISUAL
if (oap->block_mode)
block_col = curwin->w_cursor.col;
#endif
for (i = oap->line_count; --i >= 0; )
{
first_char = *ml_get_curline();
if (first_char == NUL) /* empty line */
curwin->w_cursor.col = 0;
#ifdef FEAT_VISUALEXTRA
else if (oap->block_mode)
shift_block(oap, amount);
#endif
else
/* Move the line right if it doesn't start with '#', 'smartindent'
* isn't set or 'cindent' isn't set or '#' isn't in 'cino'. */
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
if (first_char != '#' || !preprocs_left())
#endif
{
shift_line(oap->op_type == OP_LSHIFT, p_sr, amount, FALSE);
}
++curwin->w_cursor.lnum;
}
changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
#ifdef FEAT_VISUAL
if (oap->block_mode)
{
curwin->w_cursor.lnum = oap->start.lnum;
curwin->w_cursor.col = block_col;
}
else
#endif
if (curs_top) /* put cursor on first line, for ">>" */
{
curwin->w_cursor.lnum = oap->start.lnum;
beginline(BL_SOL | BL_FIX); /* shift_line() may have set cursor.col */
}
else
--curwin->w_cursor.lnum; /* put cursor on last line, for ":>" */
if (oap->line_count > p_report)
{
if (oap->op_type == OP_RSHIFT)
s = (char_u *)">";
else
s = (char_u *)"<";
if (oap->line_count == 1)
{
if (amount == 1)
sprintf((char *)IObuff, _("1 line %sed 1 time"), s);
else
sprintf((char *)IObuff, _("1 line %sed %d times"), s, amount);
}
else
{
if (amount == 1)
sprintf((char *)IObuff, _("%ld lines %sed 1 time"),
oap->line_count, s);
else
sprintf((char *)IObuff, _("%ld lines %sed %d times"),
oap->line_count, s, amount);
}
msg(IObuff);
}
/*
* Set "'[" and "']" marks.
*/
curbuf->b_op_start = oap->start;
curbuf->b_op_end.lnum = oap->end.lnum;
curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
if (curbuf->b_op_end.col > 0)
--curbuf->b_op_end.col;
}
/*
* shift the current line one shiftwidth left (if left != 0) or right
* leaves cursor on first blank in the line
*/
void
shift_line(left, round, amount, call_changed_bytes)
int left;
int round;
int amount;
int call_changed_bytes; /* call changed_bytes() */
{
int count;
int i, j;
int p_sw = (int)curbuf->b_p_sw;
count = get_indent(); /* get current indent */
if (round) /* round off indent */
{
i = count / p_sw; /* number of p_sw rounded down */
j = count % p_sw; /* extra spaces */
if (j && left) /* first remove extra spaces */
--amount;
if (left)
{
i -= amount;
if (i < 0)
i = 0;
}
else
i += amount;
count = i * p_sw;
}
else /* original vi indent */
{
if (left)
{
count -= p_sw * amount;
if (count < 0)
count = 0;
}
else
count += p_sw * amount;
}
/* Set new indent */
#ifdef FEAT_VREPLACE
if (State & VREPLACE_FLAG)
change_indent(INDENT_SET, count, FALSE, NUL, call_changed_bytes);
else
#endif
(void)set_indent(count, call_changed_bytes ? SIN_CHANGED : 0);
}
#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
/*
* Shift one line of the current block one shiftwidth right or left.
* Leaves cursor on first character in block.
*/
static void
shift_block(oap, amount)
oparg_T *oap;
int amount;
{
int left = (oap->op_type == OP_LSHIFT);
int oldstate = State;
int total;
char_u *newp, *oldp;
int oldcol = curwin->w_cursor.col;
int p_sw = (int)curbuf->b_p_sw;
int p_ts = (int)curbuf->b_p_ts;
struct block_def bd;
int incr;
colnr_T ws_vcol;
int i = 0, j = 0;
int len;
#ifdef FEAT_RIGHTLEFT
int old_p_ri = p_ri;
p_ri = 0; /* don't want revins in ident */
#endif
State = INSERT; /* don't want REPLACE for State */
block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
if (bd.is_short)
return;
/* total is number of screen columns to be inserted/removed */
total = amount * p_sw;
oldp = ml_get_curline();
if (!left)
{
/*
* 1. Get start vcol
* 2. Total ws vcols
* 3. Divvy into TABs & spp
* 4. Construct new string
*/
total += bd.pre_whitesp; /* all virtual WS upto & incl a split TAB */
ws_vcol = bd.start_vcol - bd.pre_whitesp;
if (bd.startspaces)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
bd.textstart += (*mb_ptr2len)(bd.textstart);
else
#endif
++bd.textstart;
}
for ( ; vim_iswhite(*bd.textstart); )
{
incr = lbr_chartabsize_adv(&bd.textstart, (colnr_T)(bd.start_vcol));
total += incr;
bd.start_vcol += incr;
}
/* OK, now total=all the VWS reqd, and textstart points at the 1st
* non-ws char in the block. */
if (!curbuf->b_p_et)
i = ((ws_vcol % p_ts) + total) / p_ts; /* number of tabs */
if (i)
j = ((ws_vcol % p_ts) + total) % p_ts; /* number of spp */
else
j = total;
/* if we're splitting a TAB, allow for it */
bd.textcol -= bd.pre_whitesp_c - (bd.startspaces != 0);
len = (int)STRLEN(bd.textstart) + 1;
newp = alloc_check((unsigned)(bd.textcol + i + j + len));
if (newp == NULL)
return;
vim_memset(newp, NUL, (size_t)(bd.textcol + i + j + len));
mch_memmove(newp, oldp, (size_t)bd.textcol);
copy_chars(newp + bd.textcol, (size_t)i, TAB);
copy_spaces(newp + bd.textcol + i, (size_t)j);
/* the end */
mch_memmove(newp + bd.textcol + i + j, bd.textstart, (size_t)len);
}
else /* left */
{
colnr_T destination_col; /* column to which text in block will
be shifted */
char_u *verbatim_copy_end; /* end of the part of the line which is
copied verbatim */
colnr_T verbatim_copy_width;/* the (displayed) width of this part
of line */
unsigned fill; /* nr of spaces that replace a TAB */
unsigned new_line_len; /* the length of the line after the
block shift */
size_t block_space_width;
size_t shift_amount;
char_u *non_white = bd.textstart;
colnr_T non_white_col;
/*
* Firstly, let's find the first non-whitespace character that is
* displayed after the block's start column and the character's column
* number. Also, let's calculate the width of all the whitespace
* characters that are displayed in the block and precede the searched
* non-whitespace character.
*/
/* If "bd.startspaces" is set, "bd.textstart" points to the character,
* the part of which is displayed at the block's beginning. Let's start
* searching from the next character. */
if (bd.startspaces)
mb_ptr_adv(non_white);
/* The character's column is in "bd.start_vcol". */
non_white_col = bd.start_vcol;
while (vim_iswhite(*non_white))
{
incr = lbr_chartabsize_adv(&non_white, non_white_col);
non_white_col += incr;
}
block_space_width = non_white_col - oap->start_vcol;
/* We will shift by "total" or "block_space_width", whichever is less.
*/
shift_amount = (block_space_width < (size_t)total
? block_space_width : (size_t)total);
/* The column to which we will shift the text. */
destination_col = (colnr_T)(non_white_col - shift_amount);
/* Now let's find out how much of the beginning of the line we can
* reuse without modification. */
verbatim_copy_end = bd.textstart;
verbatim_copy_width = bd.start_vcol;
/* If "bd.startspaces" is set, "bd.textstart" points to the character
* preceding the block. We have to subtract its width to obtain its
* column number. */
if (bd.startspaces)
verbatim_copy_width -= bd.start_char_vcols;
while (verbatim_copy_width < destination_col)
{
incr = lbr_chartabsize(verbatim_copy_end, verbatim_copy_width);
if (verbatim_copy_width + incr > destination_col)
break;
verbatim_copy_width += incr;
mb_ptr_adv(verbatim_copy_end);
}
/* If "destination_col" is different from the width of the initial
* part of the line that will be copied, it means we encountered a tab
* character, which we will have to partly replace with spaces. */
fill = destination_col - verbatim_copy_width;
/* The replacement line will consist of:
* - the beginning of the original line up to "verbatim_copy_end",
* - "fill" number of spaces,
* - the rest of the line, pointed to by non_white. */
new_line_len = (unsigned)(verbatim_copy_end - oldp)
+ fill
+ (unsigned)STRLEN(non_white) + 1;
newp = alloc_check(new_line_len);
if (newp == NULL)
return;
mch_memmove(newp, oldp, (size_t)(verbatim_copy_end - oldp));
copy_spaces(newp + (verbatim_copy_end - oldp), (size_t)fill);
STRMOVE(newp + (verbatim_copy_end - oldp) + fill, non_white);
}
/* replace the line */
ml_replace(curwin->w_cursor.lnum, newp, FALSE);
changed_bytes(curwin->w_cursor.lnum, (colnr_T)bd.textcol);
State = oldstate;
curwin->w_cursor.col = oldcol;
#ifdef FEAT_RIGHTLEFT
p_ri = old_p_ri;
#endif
}
#endif
#ifdef FEAT_VISUALEXTRA
/*
* Insert string "s" (b_insert ? before : after) block :AKelly
* Caller must prepare for undo.
*/
static void
block_insert(oap, s, b_insert, bdp)
oparg_T *oap;
char_u *s;
int b_insert;
struct block_def *bdp;
{
int p_ts;
int count = 0; /* extra spaces to replace a cut TAB */
int spaces = 0; /* non-zero if cutting a TAB */
colnr_T offset; /* pointer along new line */
unsigned s_len; /* STRLEN(s) */
char_u *newp, *oldp; /* new, old lines */
linenr_T lnum; /* loop var */
int oldstate = State;
State = INSERT; /* don't want REPLACE for State */
s_len = (unsigned)STRLEN(s);
for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)
{
block_prep(oap, bdp, lnum, TRUE);
if (bdp->is_short && b_insert)
continue; /* OP_INSERT, line ends before block start */
oldp = ml_get(lnum);
if (b_insert)
{
p_ts = bdp->start_char_vcols;
spaces = bdp->startspaces;
if (spaces != 0)
count = p_ts - 1; /* we're cutting a TAB */
offset = bdp->textcol;
}
else /* append */
{
p_ts = bdp->end_char_vcols;
if (!bdp->is_short) /* spaces = padding after block */
{
spaces = (bdp->endspaces ? p_ts - bdp->endspaces : 0);
if (spaces != 0)
count = p_ts - 1; /* we're cutting a TAB */
offset = bdp->textcol + bdp->textlen - (spaces != 0);
}
else /* spaces = padding to block edge */
{
/* if $ used, just append to EOL (ie spaces==0) */
if (!bdp->is_MAX)
spaces = (oap->end_vcol - bdp->end_vcol) + 1;
count = spaces;
offset = bdp->textcol + bdp->textlen;
}
}
newp = alloc_check((unsigned)(STRLEN(oldp)) + s_len + count + 1);
if (newp == NULL)
continue;
/* copy up to shifted part */
mch_memmove(newp, oldp, (size_t)(offset));
oldp += offset;
/* insert pre-padding */
copy_spaces(newp + offset, (size_t)spaces);
/* copy the new text */
mch_memmove(newp + offset + spaces, s, (size_t)s_len);
offset += s_len;
if (spaces && !bdp->is_short)
{
/* insert post-padding */
copy_spaces(newp + offset + spaces, (size_t)(p_ts - spaces));
/* We're splitting a TAB, don't copy it. */
oldp++;
/* We allowed for that TAB, remember this now */
count++;
}
if (spaces > 0)
offset += count;
STRMOVE(newp + offset, oldp);
ml_replace(lnum, newp, FALSE);
if (lnum == oap->end.lnum)
{
/* Set "']" mark to the end of the block instead of the end of
* the insert in the first line. */
curbuf->b_op_end.lnum = oap->end.lnum;
curbuf->b_op_end.col = offset;
}
} /* for all lnum */
changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
State = oldstate;
}
#endif
#if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
/*
* op_reindent - handle reindenting a block of lines.
*/
void
op_reindent(oap, how)
oparg_T *oap;
int (*how) __ARGS((void));
{
long i;
char_u *l;
int count;
linenr_T first_changed = 0;
linenr_T last_changed = 0;
linenr_T start_lnum = curwin->w_cursor.lnum;
/* Don't even try when 'modifiable' is off. */
if (!curbuf->b_p_ma)
{
EMSG(_(e_modifiable));
return;
}
for (i = oap->line_count; --i >= 0 && !got_int; )
{
/* it's a slow thing to do, so give feedback so there's no worry that
* the computer's just hung. */
if (i > 1
&& (i % 50 == 0 || i == oap->line_count - 1)
&& oap->line_count > p_report)
smsg((char_u *)_("%ld lines to indent... "), i);
/*
* Be vi-compatible: For lisp indenting the first line is not
* indented, unless there is only one line.
*/
#ifdef FEAT_LISP
if (i != oap->line_count - 1 || oap->line_count == 1
|| how != get_lisp_indent)
#endif
{
l = skipwhite(ml_get_curline());
if (*l == NUL) /* empty or blank line */
count = 0;
else
count = how(); /* get the indent for this line */
if (set_indent(count, SIN_UNDO))
{
/* did change the indent, call changed_lines() later */
if (first_changed == 0)
first_changed = curwin->w_cursor.lnum;
last_changed = curwin->w_cursor.lnum;
}
}
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0; /* make sure it's valid */
}
/* put cursor on first non-blank of indented line */
curwin->w_cursor.lnum = start_lnum;
beginline(BL_SOL | BL_FIX);
/* Mark changed lines so that they will be redrawn. When Visual
* highlighting was present, need to continue until the last line. When
* there is no change still need to remove the Visual highlighting. */
if (last_changed != 0)
changed_lines(first_changed, 0,
#ifdef FEAT_VISUAL
oap->is_VIsual ? start_lnum + oap->line_count :
#endif
last_changed + 1, 0L);
#ifdef FEAT_VISUAL
else if (oap->is_VIsual)
redraw_curbuf_later(INVERTED);
#endif
if (oap->line_count > p_report)
{
i = oap->line_count - (i + 1);
if (i == 1)
MSG(_("1 line indented "));
else
smsg((char_u *)_("%ld lines indented "), i);
}
/* set '[ and '] marks */
curbuf->b_op_start = oap->start;
curbuf->b_op_end = oap->end;
}
#endif /* defined(FEAT_LISP) || defined(FEAT_CINDENT) */
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Keep the last expression line here, for repeating.
*/
static char_u *expr_line = NULL;
/*
* Get an expression for the "\"=expr1" or "CTRL-R =expr1"
* Returns '=' when OK, NUL otherwise.
*/
int
get_expr_register()
{
char_u *new_line;
new_line = getcmdline('=', 0L, 0);
if (new_line == NULL)
return NUL;
if (*new_line == NUL) /* use previous line */
vim_free(new_line);
else
set_expr_line(new_line);
return '=';
}
/*
* Set the expression for the '=' register.
* Argument must be an allocated string.
*/
void
set_expr_line(new_line)
char_u *new_line;
{
vim_free(expr_line);
expr_line = new_line;
}
/*
* Get the result of the '=' register expression.
* Returns a pointer to allocated memory, or NULL for failure.
*/
char_u *
get_expr_line()
{
char_u *expr_copy;
char_u *rv;
static int nested = 0;
if (expr_line == NULL)
return NULL;
/* Make a copy of the expression, because evaluating it may cause it to be
* changed. */
expr_copy = vim_strsave(expr_line);
if (expr_copy == NULL)
return NULL;
/* When we are invoked recursively limit the evaluation to 10 levels.
* Then return the string as-is. */
if (nested >= 10)
return expr_copy;
++nested;
rv = eval_to_string(expr_copy, NULL, TRUE);
--nested;
vim_free(expr_copy);
return rv;
}
/*
* Get the '=' register expression itself, without evaluating it.
*/
char_u *
get_expr_line_src()
{
if (expr_line == NULL)
return NULL;
return vim_strsave(expr_line);
}
#endif /* FEAT_EVAL */
/*
* Check if 'regname' is a valid name of a yank register.
* Note: There is no check for 0 (default register), caller should do this
*/
int
valid_yank_reg(regname, writing)
int regname;
int writing; /* if TRUE check for writable registers */
{
if ( (regname > 0 && ASCII_ISALNUM(regname))
|| (!writing && vim_strchr((char_u *)
#ifdef FEAT_EVAL
"/.%#:="
#else
"/.%#:"
#endif
, regname) != NULL)
|| regname == '"'
|| regname == '-'
|| regname == '_'
#ifdef FEAT_CLIPBOARD
|| regname == '*'
|| regname == '+'
#endif
#ifdef FEAT_DND
|| (!writing && regname == '~')
#endif
)
return TRUE;
return FALSE;
}
/*
* Set y_current and y_append, according to the value of "regname".
* Cannot handle the '_' register.
* Must only be called with a valid register name!
*
* If regname is 0 and writing, use register 0
* If regname is 0 and reading, use previous register
*/
void
get_yank_register(regname, writing)
int regname;
int writing;
{
int i;
y_append = FALSE;
if ((regname == 0 || regname == '"') && !writing && y_previous != NULL)
{
y_current = y_previous;
return;
}
i = regname;
if (VIM_ISDIGIT(i))
i -= '0';
else if (ASCII_ISLOWER(i))
i = CharOrdLow(i) + 10;
else if (ASCII_ISUPPER(i))
{
i = CharOrdUp(i) + 10;
y_append = TRUE;
}
else if (regname == '-')
i = DELETION_REGISTER;
#ifdef FEAT_CLIPBOARD
/* When selection is not available, use register 0 instead of '*' */
else if (clip_star.available && regname == '*')
i = STAR_REGISTER;
/* When clipboard is not available, use register 0 instead of '+' */
else if (clip_plus.available && regname == '+')
i = PLUS_REGISTER;
#endif
#ifdef FEAT_DND
else if (!writing && regname == '~')
i = TILDE_REGISTER;
#endif
else /* not 0-9, a-z, A-Z or '-': use register 0 */
i = 0;
y_current = &(y_regs[i]);
if (writing) /* remember the register we write into for do_put() */
y_previous = y_current;
}
#if defined(FEAT_CLIPBOARD) || defined(PROTO)
/*
* When "regname" is a clipboard register, obtain the selection. If it's not
* available return zero, otherwise return "regname".
*/
int
may_get_selection(regname)
int regname;
{
if (regname == '*')
{
if (!clip_star.available)
regname = 0;
else
clip_get_selection(&clip_star);
}
else if (regname == '+')
{
if (!clip_plus.available)
regname = 0;
else
clip_get_selection(&clip_plus);
}
return regname;
}
#endif
#if defined(FEAT_VISUAL) || defined(PROTO)
/*
* Obtain the contents of a "normal" register. The register is made empty.
* The returned pointer has allocated memory, use put_register() later.
*/
void *
get_register(name, copy)
int name;
int copy; /* make a copy, if FALSE make register empty. */
{
struct yankreg *reg;
int i;
#ifdef FEAT_CLIPBOARD
/* When Visual area changed, may have to update selection. Obtain the
* selection too. */
if (name == '*' && clip_star.available)
{
if (clip_isautosel())
clip_update_selection();
may_get_selection(name);
}
#endif
get_yank_register(name, 0);
reg = (struct yankreg *)alloc((unsigned)sizeof(struct yankreg));
if (reg != NULL)
{
*reg = *y_current;
if (copy)
{
/* If we run out of memory some or all of the lines are empty. */
if (reg->y_size == 0)
reg->y_array = NULL;
else
reg->y_array = (char_u **)alloc((unsigned)(sizeof(char_u *)
* reg->y_size));
if (reg->y_array != NULL)
{
for (i = 0; i < reg->y_size; ++i)
reg->y_array[i] = vim_strsave(y_current->y_array[i]);
}
}
else
y_current->y_array = NULL;
}
return (void *)reg;
}
/*
* Put "reg" into register "name". Free any previous contents and "reg".
*/
void
put_register(name, reg)
int name;
void *reg;
{
get_yank_register(name, 0);
free_yank_all();
*y_current = *(struct yankreg *)reg;
vim_free(reg);
# ifdef FEAT_CLIPBOARD
/* Send text written to clipboard register to the clipboard. */
may_set_selection();
# endif
}
#endif
#if defined(FEAT_MOUSE) || defined(PROTO)
/*
* return TRUE if the current yank register has type MLINE
*/
int
yank_register_mline(regname)
int regname;
{
if (regname != 0 && !valid_yank_reg(regname, FALSE))
return FALSE;
if (regname == '_') /* black hole is always empty */
return FALSE;
get_yank_register(regname, FALSE);
return (y_current->y_type == MLINE);
}
#endif
/*
* Start or stop recording into a yank register.
*
* Return FAIL for failure, OK otherwise.
*/
int
do_record(c)
int c;
{
char_u *p;
static int regname;
struct yankreg *old_y_previous, *old_y_current;
int retval;
if (Recording == FALSE) /* start recording */
{
/* registers 0-9, a-z and " are allowed */
if (c < 0 || (!ASCII_ISALNUM(c) && c != '"'))
retval = FAIL;
else
{
Recording = TRUE;
showmode();
regname = c;
retval = OK;
}
}
else /* stop recording */
{
/*
* Get the recorded key hits. K_SPECIAL and CSI will be escaped, this
* needs to be removed again to put it in a register. exec_reg then
* adds the escaping back later.
*/
Recording = FALSE;
MSG("");
p = get_recorded();
if (p == NULL)
retval = FAIL;
else
{
/* Remove escaping for CSI and K_SPECIAL in multi-byte chars. */
vim_unescape_csi(p);
/*
* We don't want to change the default register here, so save and
* restore the current register name.
*/
old_y_previous = y_previous;
old_y_current = y_current;
retval = stuff_yank(regname, p);
y_previous = old_y_previous;
y_current = old_y_current;
}
}
return retval;
}
/*
* Stuff string "p" into yank register "regname" as a single line (append if
* uppercase). "p" must have been alloced.
*
* return FAIL for failure, OK otherwise
*/
static int
stuff_yank(regname, p)
int regname;
char_u *p;
{
char_u *lp;
char_u **pp;
/* check for read-only register */
if (regname != 0 && !valid_yank_reg(regname, TRUE))
{
vim_free(p);
return FAIL;
}
if (regname == '_') /* black hole: don't do anything */
{
vim_free(p);
return OK;
}
get_yank_register(regname, TRUE);
if (y_append && y_current->y_array != NULL)
{
pp = &(y_current->y_array[y_current->y_size - 1]);
lp = lalloc((long_u)(STRLEN(*pp) + STRLEN(p) + 1), TRUE);
if (lp == NULL)
{
vim_free(p);
return FAIL;
}
STRCPY(lp, *pp);
STRCAT(lp, p);
vim_free(p);
vim_free(*pp);
*pp = lp;
}
else
{
free_yank_all();
if ((y_current->y_array =
(char_u **)alloc((unsigned)sizeof(char_u *))) == NULL)
{
vim_free(p);
return FAIL;
}
y_current->y_array[0] = p;
y_current->y_size = 1;
y_current->y_type = MCHAR; /* used to be MLINE, why? */
}
return OK;
}
static int execreg_lastc = NUL;
/*
* execute a yank register: copy it into the stuff buffer
*
* return FAIL for failure, OK otherwise
*/
int
do_execreg(regname, colon, addcr, silent)
int regname;
int colon; /* insert ':' before each line */
int addcr; /* always add '\n' to end of line */
int silent; /* set "silent" flag in typeahead buffer */
{
long i;
char_u *p;
int retval = OK;
int remap;
if (regname == '@') /* repeat previous one */
{
if (execreg_lastc == NUL)
{
EMSG(_("E748: No previously used register"));
return FAIL;
}
regname = execreg_lastc;
}
/* check for valid regname */
if (regname == '%' || regname == '#' || !valid_yank_reg(regname, FALSE))
{
emsg_invreg(regname);
return FAIL;
}
execreg_lastc = regname;
#ifdef FEAT_CLIPBOARD
regname = may_get_selection(regname);
#endif
if (regname == '_') /* black hole: don't stuff anything */
return OK;
#ifdef FEAT_CMDHIST
if (regname == ':') /* use last command line */
{
if (last_cmdline == NULL)
{
EMSG(_(e_nolastcmd));
return FAIL;
}
vim_free(new_last_cmdline); /* don't keep the cmdline containing @: */
new_last_cmdline = NULL;
/* Escape all control characters with a CTRL-V */
p = vim_strsave_escaped_ext(last_cmdline,
(char_u *)"\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037", Ctrl_V, FALSE);
if (p != NULL)
{
/* When in Visual mode "'<,'>" will be prepended to the command.
* Remove it when it's already there. */
if (VIsual_active && STRNCMP(p, "'<,'>", 5) == 0)
retval = put_in_typebuf(p + 5, TRUE, TRUE, silent);
else
retval = put_in_typebuf(p, TRUE, TRUE, silent);
}
vim_free(p);
}
#endif
#ifdef FEAT_EVAL
else if (regname == '=')
{
p = get_expr_line();
if (p == NULL)
return FAIL;
retval = put_in_typebuf(p, TRUE, colon, silent);
vim_free(p);
}
#endif
else if (regname == '.') /* use last inserted text */
{
p = get_last_insert_save();
if (p == NULL)
{
EMSG(_(e_noinstext));
return FAIL;
}
retval = put_in_typebuf(p, FALSE, colon, silent);
vim_free(p);
}
else
{
get_yank_register(regname, FALSE);
if (y_current->y_array == NULL)
return FAIL;
/* Disallow remaping for ":@r". */
remap = colon ? REMAP_NONE : REMAP_YES;
/*
* Insert lines into typeahead buffer, from last one to first one.
*/
put_reedit_in_typebuf(silent);
for (i = y_current->y_size; --i >= 0; )
{
char_u *escaped;
/* insert NL between lines and after last line if type is MLINE */
if (y_current->y_type == MLINE || i < y_current->y_size - 1
|| addcr)
{
if (ins_typebuf((char_u *)"\n", remap, 0, TRUE, silent) == FAIL)
return FAIL;
}
escaped = vim_strsave_escape_csi(y_current->y_array[i]);
if (escaped == NULL)
return FAIL;
retval = ins_typebuf(escaped, remap, 0, TRUE, silent);
vim_free(escaped);
if (retval == FAIL)
return FAIL;
if (colon && ins_typebuf((char_u *)":", remap, 0, TRUE, silent)
== FAIL)
return FAIL;
}
Exec_reg = TRUE; /* disable the 'q' command */
}
return retval;
}
/*
* If "restart_edit" is not zero, put it in the typeahead buffer, so that it's
* used only after other typeahead has been processed.
*/
static void
put_reedit_in_typebuf(silent)
int silent;
{
char_u buf[3];
if (restart_edit != NUL)
{
if (restart_edit == 'V')
{
buf[0] = 'g';
buf[1] = 'R';
buf[2] = NUL;
}
else
{
buf[0] = restart_edit == 'I' ? 'i' : restart_edit;
buf[1] = NUL;
}
if (ins_typebuf(buf, REMAP_NONE, 0, TRUE, silent) == OK)
restart_edit = NUL;
}
}
/*
* Insert register contents "s" into the typeahead buffer, so that it will be
* executed again.
* When "esc" is TRUE it is to be taken literally: Escape CSI characters and
* no remapping.
*/
static int
put_in_typebuf(s, esc, colon, silent)
char_u *s;
int esc;
int colon; /* add ':' before the line */
int silent;
{
int retval = OK;
put_reedit_in_typebuf(silent);
if (colon)
retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, TRUE, silent);
if (retval == OK)
{
char_u *p;
if (esc)
p = vim_strsave_escape_csi(s);
else
p = s;
if (p == NULL)
retval = FAIL;
else
retval = ins_typebuf(p, esc ? REMAP_NONE : REMAP_YES,
0, TRUE, silent);
if (esc)
vim_free(p);
}
if (colon && retval == OK)
retval = ins_typebuf((char_u *)":", REMAP_NONE, 0, TRUE, silent);
return retval;
}
/*
* Insert a yank register: copy it into the Read buffer.
* Used by CTRL-R command and middle mouse button in insert mode.
*
* return FAIL for failure, OK otherwise
*/
int
insert_reg(regname, literally)
int regname;
int literally; /* insert literally, not as if typed */
{
long i;
int retval = OK;
char_u *arg;
int allocated;
/*
* It is possible to get into an endless loop by having CTRL-R a in
* register a and then, in insert mode, doing CTRL-R a.
* If you hit CTRL-C, the loop will be broken here.
*/
ui_breakcheck();
if (got_int)
return FAIL;
/* check for valid regname */
if (regname != NUL && !valid_yank_reg(regname, FALSE))
return FAIL;
#ifdef FEAT_CLIPBOARD
regname = may_get_selection(regname);
#endif
if (regname == '.') /* insert last inserted text */
retval = stuff_inserted(NUL, 1L, TRUE);
else if (get_spec_reg(regname, &arg, &allocated, TRUE))
{
if (arg == NULL)
return FAIL;
stuffescaped(arg, literally);
if (allocated)
vim_free(arg);
}
else /* name or number register */
{
get_yank_register(regname, FALSE);
if (y_current->y_array == NULL)
retval = FAIL;
else
{
for (i = 0; i < y_current->y_size; ++i)
{
stuffescaped(y_current->y_array[i], literally);
/*
* Insert a newline between lines and after last line if
* y_type is MLINE.
*/
if (y_current->y_type == MLINE || i < y_current->y_size - 1)
stuffcharReadbuff('\n');
}
}
}
return retval;
}
/*
* Stuff a string into the typeahead buffer, such that edit() will insert it
* literally ("literally" TRUE) or interpret is as typed characters.
*/
static void
stuffescaped(arg, literally)
char_u *arg;
int literally;
{
int c;
char_u *start;
while (*arg != NUL)
{
/* Stuff a sequence of normal ASCII characters, that's fast. Also
* stuff K_SPECIAL to get the effect of a special key when "literally"
* is TRUE. */
start = arg;
while ((*arg >= ' '
#ifndef EBCDIC
&& *arg < DEL /* EBCDIC: chars above space are normal */
#endif
)
|| (*arg == K_SPECIAL && !literally))
++arg;
if (arg > start)
stuffReadbuffLen(start, (long)(arg - start));
/* stuff a single special character */
if (*arg != NUL)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
c = mb_cptr2char_adv(&arg);
else
#endif
c = *arg++;
if (literally && ((c < ' ' && c != TAB) || c == DEL))
stuffcharReadbuff(Ctrl_V);
stuffcharReadbuff(c);
}
}
}
/*
* If "regname" is a special register, return TRUE and store a pointer to its
* value in "argp".
*/
int
get_spec_reg(regname, argp, allocated, errmsg)
int regname;
char_u **argp;
int *allocated; /* return: TRUE when value was allocated */
int errmsg; /* give error message when failing */
{
int cnt;
*argp = NULL;
*allocated = FALSE;
switch (regname)
{
case '%': /* file name */
if (errmsg)
check_fname(); /* will give emsg if not set */
*argp = curbuf->b_fname;
return TRUE;
case '#': /* alternate file name */
*argp = getaltfname(errmsg); /* may give emsg if not set */
return TRUE;
#ifdef FEAT_EVAL
case '=': /* result of expression */
*argp = get_expr_line();
*allocated = TRUE;
return TRUE;
#endif
case ':': /* last command line */
if (last_cmdline == NULL && errmsg)
EMSG(_(e_nolastcmd));
*argp = last_cmdline;
return TRUE;
case '/': /* last search-pattern */
if (last_search_pat() == NULL && errmsg)
EMSG(_(e_noprevre));
*argp = last_search_pat();
return TRUE;
case '.': /* last inserted text */
*argp = get_last_insert_save();
*allocated = TRUE;
if (*argp == NULL && errmsg)
EMSG(_(e_noinstext));
return TRUE;
#ifdef FEAT_SEARCHPATH
case Ctrl_F: /* Filename under cursor */
case Ctrl_P: /* Path under cursor, expand via "path" */
if (!errmsg)
return FALSE;
*argp = file_name_at_cursor(FNAME_MESS | FNAME_HYP
| (regname == Ctrl_P ? FNAME_EXP : 0), 1L, NULL);
*allocated = TRUE;
return TRUE;
#endif
case Ctrl_W: /* word under cursor */
case Ctrl_A: /* WORD (mnemonic All) under cursor */
if (!errmsg)
return FALSE;
cnt = find_ident_under_cursor(argp, regname == Ctrl_W
? (FIND_IDENT|FIND_STRING) : FIND_STRING);
*argp = cnt ? vim_strnsave(*argp, cnt) : NULL;
*allocated = TRUE;
return TRUE;
case '_': /* black hole: always empty */
*argp = (char_u *)"";
return TRUE;
}
return FALSE;
}
/*
* Paste a yank register into the command line.
* Only for non-special registers.
* Used by CTRL-R command in command-line mode
* insert_reg() can't be used here, because special characters from the
* register contents will be interpreted as commands.
*
* return FAIL for failure, OK otherwise
*/
int
cmdline_paste_reg(regname, literally, remcr)
int regname;
int literally; /* Insert text literally instead of "as typed" */
int remcr; /* don't add trailing CR */
{
long i;
get_yank_register(regname, FALSE);
if (y_current->y_array == NULL)
return FAIL;
for (i = 0; i < y_current->y_size; ++i)
{
cmdline_paste_str(y_current->y_array[i], literally);
/* Insert ^M between lines and after last line if type is MLINE.
* Don't do this when "remcr" is TRUE and the next line is empty. */
if (y_current->y_type == MLINE
|| (i < y_current->y_size - 1
&& !(remcr
&& i == y_current->y_size - 2
&& *y_current->y_array[i + 1] == NUL)))
cmdline_paste_str((char_u *)"\r", literally);
/* Check for CTRL-C, in case someone tries to paste a few thousand
* lines and gets bored. */
ui_breakcheck();
if (got_int)
return FAIL;
}
return OK;
}
#if defined(FEAT_CLIPBOARD) || defined(PROTO)
/*
* Adjust the register name pointed to with "rp" for the clipboard being
* used always and the clipboard being available.
*/
void
adjust_clip_reg(rp)
int *rp;
{
/* If no reg. specified, and "unnamed" or "unnamedplus" is in 'clipboard',
* use '*' or '+' reg, respectively. "unnamedplus" prevails. */
if (*rp == 0 && clip_unnamed != 0)
*rp = ((clip_unnamed & CLIP_UNNAMED_PLUS) && clip_plus.available)
? '+' : '*';
if (!clip_star.available && *rp == '*')
*rp = 0;
if (!clip_plus.available && *rp == '+')
*rp = 0;
}
#endif
/*
* Handle a delete operation.
*
* Return FAIL if undo failed, OK otherwise.
*/
int
op_delete(oap)
oparg_T *oap;
{
int n;
linenr_T lnum;
char_u *ptr;
#ifdef FEAT_VISUAL
char_u *newp, *oldp;
struct block_def bd;
#endif
linenr_T old_lcount = curbuf->b_ml.ml_line_count;
int did_yank = FALSE;
if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to do */
return OK;
/* Nothing to delete, return here. Do prepare undo, for op_change(). */
if (oap->empty)
return u_save_cursor();
if (!curbuf->b_p_ma)
{
EMSG(_(e_modifiable));
return FAIL;
}
#ifdef FEAT_CLIPBOARD
adjust_clip_reg(&oap->regname);
#endif
#ifdef FEAT_MBYTE
if (has_mbyte)
mb_adjust_opend(oap);
#endif
/*
* Imitate the strange Vi behaviour: If the delete spans more than one
* line and motion_type == MCHAR and the result is a blank line, make the
* delete linewise. Don't do this for the change command or Visual mode.
*/
if ( oap->motion_type == MCHAR
#ifdef FEAT_VISUAL
&& !oap->is_VIsual
&& !oap->block_mode
#endif
&& oap->line_count > 1
&& oap->motion_force == NUL
&& oap->op_type == OP_DELETE)
{
ptr = ml_get(oap->end.lnum) + oap->end.col;
if (*ptr != NUL)
ptr += oap->inclusive;
ptr = skipwhite(ptr);
if (*ptr == NUL && inindent(0))
oap->motion_type = MLINE;
}
/*
* Check for trying to delete (e.g. "D") in an empty line.
* Note: For the change operator it is ok.
*/
if ( oap->motion_type == MCHAR
&& oap->line_count == 1
&& oap->op_type == OP_DELETE
&& *ml_get(oap->start.lnum) == NUL)
{
/*
* It's an error to operate on an empty region, when 'E' included in
* 'cpoptions' (Vi compatible).
*/
#ifdef FEAT_VIRTUALEDIT
if (virtual_op)
/* Virtual editing: Nothing gets deleted, but we set the '[ and ']
* marks as if it happened. */
goto setmarks;
#endif
if (vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL)
beep_flush();
return OK;
}
/*
* Do a yank of whatever we're about to delete.
* If a yank register was specified, put the deleted text into that
* register. For the black hole register '_' don't yank anything.
*/
if (oap->regname != '_')
{
if (oap->regname != 0)
{
/* check for read-only register */
if (!valid_yank_reg(oap->regname, TRUE))
{
beep_flush();
return OK;
}
get_yank_register(oap->regname, TRUE); /* yank into specif'd reg. */
if (op_yank(oap, TRUE, FALSE) == OK) /* yank without message */
did_yank = TRUE;
}
/*
* Put deleted text into register 1 and shift number registers if the
* delete contains a line break, or when a regname has been specified.
*/
if (oap->regname != 0 || oap->motion_type == MLINE
|| oap->line_count > 1 || oap->use_reg_one)
{
y_current = &y_regs[9];
free_yank_all(); /* free register nine */
for (n = 9; n > 1; --n)
y_regs[n] = y_regs[n - 1];
y_previous = y_current = &y_regs[1];
y_regs[1].y_array = NULL; /* set register one to empty */
if (op_yank(oap, TRUE, FALSE) == OK)
did_yank = TRUE;
}
/* Yank into small delete register when no named register specified
* and the delete is within one line. */
if ((
#ifdef FEAT_CLIPBOARD
((clip_unnamed & CLIP_UNNAMED) && oap->regname == '*') ||
((clip_unnamed & CLIP_UNNAMED_PLUS) && oap->regname == '+') ||
#endif
oap->regname == 0) && oap->motion_type != MLINE
&& oap->line_count == 1)
{
oap->regname = '-';
get_yank_register(oap->regname, TRUE);
if (op_yank(oap, TRUE, FALSE) == OK)
did_yank = TRUE;
oap->regname = 0;
}
/*
* If there's too much stuff to fit in the yank register, then get a
* confirmation before doing the delete. This is crude, but simple.
* And it avoids doing a delete of something we can't put back if we
* want.
*/
if (!did_yank)
{
int msg_silent_save = msg_silent;
msg_silent = 0; /* must display the prompt */
n = ask_yesno((char_u *)_("cannot yank; delete anyway"), TRUE);
msg_silent = msg_silent_save;
if (n != 'y')
{
EMSG(_(e_abort));
return FAIL;
}
}
}
#ifdef FEAT_VISUAL
/*
* block mode delete
*/
if (oap->block_mode)
{
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return FAIL;
for (lnum = curwin->w_cursor.lnum; lnum <= oap->end.lnum; ++lnum)
{
block_prep(oap, &bd, lnum, TRUE);
if (bd.textlen == 0) /* nothing to delete */
continue;
/* Adjust cursor position for tab replaced by spaces and 'lbr'. */
if (lnum == curwin->w_cursor.lnum)
{
curwin->w_cursor.col = bd.textcol + bd.startspaces;
# ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
# endif
}
/* n == number of chars deleted
* If we delete a TAB, it may be replaced by several characters.
* Thus the number of characters may increase!
*/
n = bd.textlen - bd.startspaces - bd.endspaces;
oldp = ml_get(lnum);
newp = alloc_check((unsigned)STRLEN(oldp) + 1 - n);
if (newp == NULL)
continue;
/* copy up to deleted part */
mch_memmove(newp, oldp, (size_t)bd.textcol);
/* insert spaces */
copy_spaces(newp + bd.textcol,
(size_t)(bd.startspaces + bd.endspaces));
/* copy the part after the deleted part */
oldp += bd.textcol + bd.textlen;
STRMOVE(newp + bd.textcol + bd.startspaces + bd.endspaces, oldp);
/* replace the line */
ml_replace(lnum, newp, FALSE);
}
check_cursor_col();
changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
oap->end.lnum + 1, 0L);
oap->line_count = 0; /* no lines deleted */
}
else
#endif
if (oap->motion_type == MLINE)
{
if (oap->op_type == OP_CHANGE)
{
/* Delete the lines except the first one. Temporarily move the
* cursor to the next line. Save the current line number, if the
* last line is deleted it may be changed.
*/
if (oap->line_count > 1)
{
lnum = curwin->w_cursor.lnum;
++curwin->w_cursor.lnum;
del_lines((long)(oap->line_count - 1), TRUE);
curwin->w_cursor.lnum = lnum;
}
if (u_save_cursor() == FAIL)
return FAIL;
if (curbuf->b_p_ai) /* don't delete indent */
{
beginline(BL_WHITE); /* cursor on first non-white */
did_ai = TRUE; /* delete the indent when ESC hit */
ai_col = curwin->w_cursor.col;
}
else
beginline(0); /* cursor in column 0 */
truncate_line(FALSE); /* delete the rest of the line */
/* leave cursor past last char in line */
if (oap->line_count > 1)
u_clearline(); /* "U" command not possible after "2cc" */
}
else
{
del_lines(oap->line_count, TRUE);
beginline(BL_WHITE | BL_FIX);
u_clearline(); /* "U" command not possible after "dd" */
}
}
else
{
#ifdef FEAT_VIRTUALEDIT
if (virtual_op)
{
int endcol = 0;
/* For virtualedit: break the tabs that are partly included. */
if (gchar_pos(&oap->start) == '\t')
{
if (u_save_cursor() == FAIL) /* save first line for undo */
return FAIL;
if (oap->line_count == 1)
endcol = getviscol2(oap->end.col, oap->end.coladd);
coladvance_force(getviscol2(oap->start.col, oap->start.coladd));
oap->start = curwin->w_cursor;
if (oap->line_count == 1)
{
coladvance(endcol);
oap->end.col = curwin->w_cursor.col;
oap->end.coladd = curwin->w_cursor.coladd;
curwin->w_cursor = oap->start;
}
}
/* Break a tab only when it's included in the area. */
if (gchar_pos(&oap->end) == '\t'
&& (int)oap->end.coladd < oap->inclusive)
{
/* save last line for undo */
if (u_save((linenr_T)(oap->end.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return FAIL;
curwin->w_cursor = oap->end;
coladvance_force(getviscol2(oap->end.col, oap->end.coladd));
oap->end = curwin->w_cursor;
curwin->w_cursor = oap->start;
}
}
#endif
if (oap->line_count == 1) /* delete characters within one line */
{
if (u_save_cursor() == FAIL) /* save line for undo */
return FAIL;
/* if 'cpoptions' contains '$', display '$' at end of change */
if ( vim_strchr(p_cpo, CPO_DOLLAR) != NULL
&& oap->op_type == OP_CHANGE
&& oap->end.lnum == curwin->w_cursor.lnum
#ifdef FEAT_VISUAL
&& !oap->is_VIsual
#endif
)
display_dollar(oap->end.col - !oap->inclusive);
n = oap->end.col - oap->start.col + 1 - !oap->inclusive;
#ifdef FEAT_VIRTUALEDIT
if (virtual_op)
{
/* fix up things for virtualedit-delete:
* break the tabs which are going to get in our way
*/
char_u *curline = ml_get_curline();
int len = (int)STRLEN(curline);
if (oap->end.coladd != 0
&& (int)oap->end.col >= len - 1
&& !(oap->start.coladd && (int)oap->end.col >= len - 1))
n++;
/* Delete at least one char (e.g, when on a control char). */
if (n == 0 && oap->start.coladd != oap->end.coladd)
n = 1;
/* When deleted a char in the line, reset coladd. */
if (gchar_cursor() != NUL)
curwin->w_cursor.coladd = 0;
}
#endif
if (oap->op_type == OP_DELETE
&& oap->inclusive
&& oap->end.lnum == curbuf->b_ml.ml_line_count
&& n > (int)STRLEN(ml_get(oap->end.lnum)))
{
/* Special case: gH<Del> deletes the last line. */
del_lines(1L, FALSE);
}
else
{
(void)del_bytes((long)n, !virtual_op, oap->op_type == OP_DELETE
#ifdef FEAT_VISUAL
&& !oap->is_VIsual
#endif
);
}
}
else /* delete characters between lines */
{
pos_T curpos;
int delete_last_line;
/* save deleted and changed lines for undo */
if (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
(linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL)
return FAIL;
delete_last_line = (oap->end.lnum == curbuf->b_ml.ml_line_count);
truncate_line(TRUE); /* delete from cursor to end of line */
curpos = curwin->w_cursor; /* remember curwin->w_cursor */
++curwin->w_cursor.lnum;
del_lines((long)(oap->line_count - 2), FALSE);
if (delete_last_line)
oap->end.lnum = curbuf->b_ml.ml_line_count;
n = (oap->end.col + 1 - !oap->inclusive);
if (oap->inclusive && delete_last_line
&& n > (int)STRLEN(ml_get(oap->end.lnum)))
{
/* Special case: gH<Del> deletes the last line. */
del_lines(1L, FALSE);
curwin->w_cursor = curpos; /* restore curwin->w_cursor */
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
}
else
{
/* delete from start of line until op_end */
curwin->w_cursor.col = 0;
(void)del_bytes((long)n, !virtual_op, oap->op_type == OP_DELETE
#ifdef FEAT_VISUAL
&& !oap->is_VIsual
#endif
);
curwin->w_cursor = curpos; /* restore curwin->w_cursor */
}
if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
(void)do_join(2, FALSE, FALSE, FALSE);
}
}
msgmore(curbuf->b_ml.ml_line_count - old_lcount);
#ifdef FEAT_VIRTUALEDIT
setmarks:
#endif
#ifdef FEAT_VISUAL
if (oap->block_mode)
{
curbuf->b_op_end.lnum = oap->end.lnum;
curbuf->b_op_end.col = oap->start.col;
}
else
#endif
curbuf->b_op_end = oap->start;
curbuf->b_op_start = oap->start;
return OK;
}
#ifdef FEAT_MBYTE
/*
* Adjust end of operating area for ending on a multi-byte character.
* Used for deletion.
*/
static void
mb_adjust_opend(oap)
oparg_T *oap;
{
char_u *p;
if (oap->inclusive)
{
p = ml_get(oap->end.lnum);
oap->end.col += mb_tail_off(p, p + oap->end.col);
}
}
#endif
#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
/*
* Replace a whole area with one character.
*/
int
op_replace(oap, c)
oparg_T *oap;
int c;
{
int n, numc;
#ifdef FEAT_MBYTE
int num_chars;
#endif
char_u *newp, *oldp;
size_t oldlen;
struct block_def bd;
if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty)
return OK; /* nothing to do */
#ifdef FEAT_MBYTE
if (has_mbyte)
mb_adjust_opend(oap);
#endif
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return FAIL;
/*
* block mode replace
*/
if (oap->block_mode)
{
bd.is_MAX = (curwin->w_curswant == MAXCOL);
for ( ; curwin->w_cursor.lnum <= oap->end.lnum; ++curwin->w_cursor.lnum)
{
curwin->w_cursor.col = 0; /* make sure cursor position is valid */
block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
if (bd.textlen == 0 && (!virtual_op || bd.is_MAX))
continue; /* nothing to replace */
/* n == number of extra chars required
* If we split a TAB, it may be replaced by several characters.
* Thus the number of characters may increase!
*/
#ifdef FEAT_VIRTUALEDIT
/* If the range starts in virtual space, count the initial
* coladd offset as part of "startspaces" */
if (virtual_op && bd.is_short && *bd.textstart == NUL)
{
pos_T vpos;
vpos.lnum = curwin->w_cursor.lnum;
getvpos(&vpos, oap->start_vcol);
bd.startspaces += vpos.coladd;
n = bd.startspaces;
}
else
#endif
/* allow for pre spaces */
n = (bd.startspaces ? bd.start_char_vcols - 1 : 0);
/* allow for post spp */
n += (bd.endspaces
#ifdef FEAT_VIRTUALEDIT
&& !bd.is_oneChar
#endif
&& bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0;
/* Figure out how many characters to replace. */
numc = oap->end_vcol - oap->start_vcol + 1;
if (bd.is_short && (!virtual_op || bd.is_MAX))
numc -= (oap->end_vcol - bd.end_vcol) + 1;
#ifdef FEAT_MBYTE
/* A double-wide character can be replaced only up to half the
* times. */
if ((*mb_char2cells)(c) > 1)
{
if ((numc & 1) && !bd.is_short)
{
++bd.endspaces;
++n;
}
numc = numc / 2;
}
/* Compute bytes needed, move character count to num_chars. */
num_chars = numc;
numc *= (*mb_char2len)(c);
#endif
/* oldlen includes textlen, so don't double count */
n += numc - bd.textlen;
oldp = ml_get_curline();
oldlen = STRLEN(oldp);
newp = alloc_check((unsigned)oldlen + 1 + n);
if (newp == NULL)
continue;
vim_memset(newp, NUL, (size_t)(oldlen + 1 + n));
/* copy up to deleted part */
mch_memmove(newp, oldp, (size_t)bd.textcol);
oldp += bd.textcol + bd.textlen;
/* insert pre-spaces */
copy_spaces(newp + bd.textcol, (size_t)bd.startspaces);
/* insert replacement chars CHECK FOR ALLOCATED SPACE */
#ifdef FEAT_MBYTE
if (has_mbyte)
{
n = (int)STRLEN(newp);
while (--num_chars >= 0)
n += (*mb_char2bytes)(c, newp + n);
}
else
#endif
copy_chars(newp + STRLEN(newp), (size_t)numc, c);
if (!bd.is_short)
{
/* insert post-spaces */
copy_spaces(newp + STRLEN(newp), (size_t)bd.endspaces);
/* copy the part after the changed part */
STRMOVE(newp + STRLEN(newp), oldp);
}
/* replace the line */
ml_replace(curwin->w_cursor.lnum, newp, FALSE);
}
}
else
{
/*
* MCHAR and MLINE motion replace.
*/
if (oap->motion_type == MLINE)
{
oap->start.col = 0;
curwin->w_cursor.col = 0;
oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
if (oap->end.col)
--oap->end.col;
}
else if (!oap->inclusive)
dec(&(oap->end));
while (ltoreq(curwin->w_cursor, oap->end))
{
n = gchar_cursor();
if (n != NUL)
{
#ifdef FEAT_MBYTE
if ((*mb_char2len)(c) > 1 || (*mb_char2len)(n) > 1)
{
/* This is slow, but it handles replacing a single-byte
* with a multi-byte and the other way around. */
oap->end.col += (*mb_char2len)(c) - (*mb_char2len)(n);
n = State;
State = REPLACE;
ins_char(c);
State = n;
/* Backup to the replaced character. */
dec_cursor();
}
else
#endif
{
#ifdef FEAT_VIRTUALEDIT
if (n == TAB)
{
int end_vcol = 0;
if (curwin->w_cursor.lnum == oap->end.lnum)
{
/* oap->end has to be recalculated when
* the tab breaks */
end_vcol = getviscol2(oap->end.col,
oap->end.coladd);
}
coladvance_force(getviscol());
if (curwin->w_cursor.lnum == oap->end.lnum)
getvpos(&oap->end, end_vcol);
}
#endif
pchar(curwin->w_cursor, c);
}
}
#ifdef FEAT_VIRTUALEDIT
else if (virtual_op && curwin->w_cursor.lnum == oap->end.lnum)
{
int virtcols = oap->end.coladd;
if (curwin->w_cursor.lnum == oap->start.lnum
&& oap->start.col == oap->end.col && oap->start.coladd)
virtcols -= oap->start.coladd;
/* oap->end has been trimmed so it's effectively inclusive;
* as a result an extra +1 must be counted so we don't
* trample the NUL byte. */
coladvance_force(getviscol2(oap->end.col, oap->end.coladd) + 1);
curwin->w_cursor.col -= (virtcols + 1);
for (; virtcols >= 0; virtcols--)
{
pchar(curwin->w_cursor, c);
if (inc(&curwin->w_cursor) == -1)
break;
}
}
#endif
/* Advance to next character, stop at the end of the file. */
if (inc_cursor() == -1)
break;
}
}
curwin->w_cursor = oap->start;
check_cursor();
changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L);
/* Set "'[" and "']" marks. */
curbuf->b_op_start = oap->start;
curbuf->b_op_end = oap->end;
return OK;
}
#endif
static int swapchars __ARGS((int op_type, pos_T *pos, int length));
/*
* Handle the (non-standard vi) tilde operator. Also for "gu", "gU" and "g?".
*/
void
op_tilde(oap)
oparg_T *oap;
{
pos_T pos;
#ifdef FEAT_VISUAL
struct block_def bd;
#endif
int did_change = FALSE;
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return;
pos = oap->start;
#ifdef FEAT_VISUAL
if (oap->block_mode) /* Visual block mode */
{
for (; pos.lnum <= oap->end.lnum; ++pos.lnum)
{
int one_change;
block_prep(oap, &bd, pos.lnum, FALSE);
pos.col = bd.textcol;
one_change = swapchars(oap->op_type, &pos, bd.textlen);
did_change |= one_change;
# ifdef FEAT_NETBEANS_INTG
if (netbeans_active() && one_change)
{
char_u *ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
netbeans_removed(curbuf, pos.lnum, bd.textcol,
(long)bd.textlen);
netbeans_inserted(curbuf, pos.lnum, bd.textcol,
&ptr[bd.textcol], bd.textlen);
}
# endif
}
if (did_change)
changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
}
else /* not block mode */
#endif
{
if (oap->motion_type == MLINE)
{
oap->start.col = 0;
pos.col = 0;
oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
if (oap->end.col)
--oap->end.col;
}
else if (!oap->inclusive)
dec(&(oap->end));
if (pos.lnum == oap->end.lnum)
did_change = swapchars(oap->op_type, &pos,
oap->end.col - pos.col + 1);
else
for (;;)
{
did_change |= swapchars(oap->op_type, &pos,
pos.lnum == oap->end.lnum ? oap->end.col + 1:
(int)STRLEN(ml_get_pos(&pos)));
if (ltoreq(oap->end, pos) || inc(&pos) == -1)
break;
}
if (did_change)
{
changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1,
0L);
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active() && did_change)
{
char_u *ptr;
int count;
pos = oap->start;
while (pos.lnum < oap->end.lnum)
{
ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
count = (int)STRLEN(ptr) - pos.col;
netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
netbeans_inserted(curbuf, pos.lnum, pos.col,
&ptr[pos.col], count);
pos.col = 0;
pos.lnum++;
}
ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
count = oap->end.col - pos.col + 1;
netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
netbeans_inserted(curbuf, pos.lnum, pos.col,
&ptr[pos.col], count);
}
#endif
}
}
#ifdef FEAT_VISUAL
if (!did_change && oap->is_VIsual)
/* No change: need to remove the Visual selection */
redraw_curbuf_later(INVERTED);
#endif
/*
* Set '[ and '] marks.
*/
curbuf->b_op_start = oap->start;
curbuf->b_op_end = oap->end;
if (oap->line_count > p_report)
{
if (oap->line_count == 1)
MSG(_("1 line changed"));
else
smsg((char_u *)_("%ld lines changed"), oap->line_count);
}
}
/*
* Invoke swapchar() on "length" bytes at position "pos".
* "pos" is advanced to just after the changed characters.
* "length" is rounded up to include the whole last multi-byte character.
* Also works correctly when the number of bytes changes.
* Returns TRUE if some character was changed.
*/
static int
swapchars(op_type, pos, length)
int op_type;
pos_T *pos;
int length;
{
int todo;
int did_change = 0;
for (todo = length; todo > 0; --todo)
{
# ifdef FEAT_MBYTE
if (has_mbyte)
/* we're counting bytes, not characters */
todo -= (*mb_ptr2len)(ml_get_pos(pos)) - 1;
# endif
did_change |= swapchar(op_type, pos);
if (inc(pos) == -1) /* at end of file */
break;
}
return did_change;
}
/*
* If op_type == OP_UPPER: make uppercase,
* if op_type == OP_LOWER: make lowercase,
* if op_type == OP_ROT13: do rot13 encoding,
* else swap case of character at 'pos'
* returns TRUE when something actually changed.
*/
int
swapchar(op_type, pos)
int op_type;
pos_T *pos;
{
int c;
int nc;
c = gchar_pos(pos);
/* Only do rot13 encoding for ASCII characters. */
if (c >= 0x80 && op_type == OP_ROT13)
return FALSE;
#ifdef FEAT_MBYTE
if (op_type == OP_UPPER && c == 0xdf
&& (enc_latin1like || STRCMP(p_enc, "iso-8859-2") == 0))
{
pos_T sp = curwin->w_cursor;
/* Special handling of German sharp s: change to "SS". */
curwin->w_cursor = *pos;
del_char(FALSE);
ins_char('S');
ins_char('S');
curwin->w_cursor = sp;
inc(pos);
}
if (enc_dbcs != 0 && c >= 0x100) /* No lower/uppercase letter */
return FALSE;
#endif
nc = c;
if (MB_ISLOWER(c))
{
if (op_type == OP_ROT13)
nc = ROT13(c, 'a');
else if (op_type != OP_LOWER)
nc = MB_TOUPPER(c);
}
else if (MB_ISUPPER(c))
{
if (op_type == OP_ROT13)
nc = ROT13(c, 'A');
else if (op_type != OP_UPPER)
nc = MB_TOLOWER(c);
}
if (nc != c)
{
#ifdef FEAT_MBYTE
if (enc_utf8 && (c >= 0x80 || nc >= 0x80))
{
pos_T sp = curwin->w_cursor;
curwin->w_cursor = *pos;
/* don't use del_char(), it also removes composing chars */
del_bytes(utf_ptr2len(ml_get_cursor()), FALSE, FALSE);
ins_char(nc);
curwin->w_cursor = sp;
}
else
#endif
pchar(*pos, nc);
return TRUE;
}
return FALSE;
}
#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
/*
* op_insert - Insert and append operators for Visual mode.
*/
void
op_insert(oap, count1)
oparg_T *oap;
long count1;
{
long ins_len, pre_textlen = 0;
char_u *firstline, *ins_text;
struct block_def bd;
int i;
/* edit() changes this - record it for OP_APPEND */
bd.is_MAX = (curwin->w_curswant == MAXCOL);
/* vis block is still marked. Get rid of it now. */
curwin->w_cursor.lnum = oap->start.lnum;
update_screen(INVERTED);
if (oap->block_mode)
{
#ifdef FEAT_VIRTUALEDIT
/* When 'virtualedit' is used, need to insert the extra spaces before
* doing block_prep(). When only "block" is used, virtual edit is
* already disabled, but still need it when calling
* coladvance_force(). */
if (curwin->w_cursor.coladd > 0)
{
int old_ve_flags = ve_flags;
ve_flags = VE_ALL;
if (u_save_cursor() == FAIL)
return;
coladvance_force(oap->op_type == OP_APPEND
? oap->end_vcol + 1 : getviscol());
if (oap->op_type == OP_APPEND)
--curwin->w_cursor.col;
ve_flags = old_ve_flags;
}
#endif
/* Get the info about the block before entering the text */
block_prep(oap, &bd, oap->start.lnum, TRUE);
firstline = ml_get(oap->start.lnum) + bd.textcol;
if (oap->op_type == OP_APPEND)
firstline += bd.textlen;
pre_textlen = (long)STRLEN(firstline);
}
if (oap->op_type == OP_APPEND)
{
if (oap->block_mode
#ifdef FEAT_VIRTUALEDIT
&& curwin->w_cursor.coladd == 0
#endif
)
{
/* Move the cursor to the character right of the block. */
curwin->w_set_curswant = TRUE;
while (*ml_get_cursor() != NUL
&& (curwin->w_cursor.col < bd.textcol + bd.textlen))
++curwin->w_cursor.col;
if (bd.is_short && !bd.is_MAX)
{
/* First line was too short, make it longer and adjust the
* values in "bd". */
if (u_save_cursor() == FAIL)
return;
for (i = 0; i < bd.endspaces; ++i)
ins_char(' ');
bd.textlen += bd.endspaces;
}
}
else
{
curwin->w_cursor = oap->end;
check_cursor_col();
/* Works just like an 'i'nsert on the next character. */
if (!lineempty(curwin->w_cursor.lnum)
&& oap->start_vcol != oap->end_vcol)
inc_cursor();
}
}
edit(NUL, FALSE, (linenr_T)count1);
/* If user has moved off this line, we don't know what to do, so do
* nothing.
* Also don't repeat the insert when Insert mode ended with CTRL-C. */
if (curwin->w_cursor.lnum != oap->start.lnum || got_int)
return;
if (oap->block_mode)
{
struct block_def bd2;
/*
* Spaces and tabs in the indent may have changed to other spaces and
* tabs. Get the starting column again and correct the length.
* Don't do this when "$" used, end-of-line will have changed.
*/
block_prep(oap, &bd2, oap->start.lnum, TRUE);
if (!bd.is_MAX || bd2.textlen < bd.textlen)
{
if (oap->op_type == OP_APPEND)
{
pre_textlen += bd2.textlen - bd.textlen;
if (bd2.endspaces)
--bd2.textlen;
}
bd.textcol = bd2.textcol;
bd.textlen = bd2.textlen;
}
/*
* Subsequent calls to ml_get() flush the firstline data - take a
* copy of the required string.
*/
firstline = ml_get(oap->start.lnum) + bd.textcol;
if (oap->op_type == OP_APPEND)
firstline += bd.textlen;
if (pre_textlen >= 0
&& (ins_len = (long)STRLEN(firstline) - pre_textlen) > 0)
{
ins_text = vim_strnsave(firstline, (int)ins_len);
if (ins_text != NULL)
{
/* block handled here */
if (u_save(oap->start.lnum,
(linenr_T)(oap->end.lnum + 1)) == OK)
block_insert(oap, ins_text, (oap->op_type == OP_INSERT),
&bd);
curwin->w_cursor.col = oap->start.col;
check_cursor();
vim_free(ins_text);
}
}
}
}
#endif
/*
* op_change - handle a change operation
*
* return TRUE if edit() returns because of a CTRL-O command
*/
int
op_change(oap)
oparg_T *oap;
{
colnr_T l;
int retval;
#ifdef FEAT_VISUALEXTRA
long offset;
linenr_T linenr;
long ins_len;
long pre_textlen = 0;
long pre_indent = 0;
char_u *firstline;
char_u *ins_text, *newp, *oldp;
struct block_def bd;
#endif
l = oap->start.col;
if (oap->motion_type == MLINE)
{
l = 0;
#ifdef FEAT_SMARTINDENT
if (!p_paste && curbuf->b_p_si
# ifdef FEAT_CINDENT
&& !curbuf->b_p_cin
# endif
)
can_si = TRUE; /* It's like opening a new line, do si */
#endif
}
/* First delete the text in the region. In an empty buffer only need to
* save for undo */
if (curbuf->b_ml.ml_flags & ML_EMPTY)
{
if (u_save_cursor() == FAIL)
return FALSE;
}
else if (op_delete(oap) == FAIL)
return FALSE;
if ((l > curwin->w_cursor.col) && !lineempty(curwin->w_cursor.lnum)
&& !virtual_op)
inc_cursor();
#ifdef FEAT_VISUALEXTRA
/* check for still on same line (<CR> in inserted text meaningless) */
/* skip blank lines too */
if (oap->block_mode)
{
# ifdef FEAT_VIRTUALEDIT
/* Add spaces before getting the current line length. */
if (virtual_op && (curwin->w_cursor.coladd > 0
|| gchar_cursor() == NUL))
coladvance_force(getviscol());
# endif
firstline = ml_get(oap->start.lnum);
pre_textlen = (long)STRLEN(firstline);
pre_indent = (long)(skipwhite(firstline) - firstline);
bd.textcol = curwin->w_cursor.col;
}
#endif
#if defined(FEAT_LISP) || defined(FEAT_CINDENT)
if (oap->motion_type == MLINE)
fix_indent();
#endif
retval = edit(NUL, FALSE, (linenr_T)1);
#ifdef FEAT_VISUALEXTRA
/*
* In Visual block mode, handle copying the new text to all lines of the
* block.
* Don't repeat the insert when Insert mode ended with CTRL-C.
*/
if (oap->block_mode && oap->start.lnum != oap->end.lnum && !got_int)
{
/* Auto-indenting may have changed the indent. If the cursor was past
* the indent, exclude that indent change from the inserted text. */
firstline = ml_get(oap->start.lnum);
if (bd.textcol > (colnr_T)pre_indent)
{
long new_indent = (long)(skipwhite(firstline) - firstline);
pre_textlen += new_indent - pre_indent;
bd.textcol += new_indent - pre_indent;
}
ins_len = (long)STRLEN(firstline) - pre_textlen;
if (ins_len > 0)
{
/* Subsequent calls to ml_get() flush the firstline data - take a
* copy of the inserted text. */
if ((ins_text = alloc_check((unsigned)(ins_len + 1))) != NULL)
{
vim_strncpy(ins_text, firstline + bd.textcol, (size_t)ins_len);
for (linenr = oap->start.lnum + 1; linenr <= oap->end.lnum;
linenr++)
{
block_prep(oap, &bd, linenr, TRUE);
if (!bd.is_short || virtual_op)
{
# ifdef FEAT_VIRTUALEDIT
pos_T vpos;
/* If the block starts in virtual space, count the
* initial coladd offset as part of "startspaces" */
if (bd.is_short)
{
vpos.lnum = linenr;
(void)getvpos(&vpos, oap->start_vcol);
}
else
vpos.coladd = 0;
# endif
oldp = ml_get(linenr);
newp = alloc_check((unsigned)(STRLEN(oldp)
# ifdef FEAT_VIRTUALEDIT
+ vpos.coladd
# endif
+ ins_len + 1));
if (newp == NULL)
continue;
/* copy up to block start */
mch_memmove(newp, oldp, (size_t)bd.textcol);
offset = bd.textcol;
# ifdef FEAT_VIRTUALEDIT
copy_spaces(newp + offset, (size_t)vpos.coladd);
offset += vpos.coladd;
# endif
mch_memmove(newp + offset, ins_text, (size_t)ins_len);
offset += ins_len;
oldp += bd.textcol;
STRMOVE(newp + offset, oldp);
ml_replace(linenr, newp, FALSE);
}
}
check_cursor();
changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
}
vim_free(ins_text);
}
}
#endif
return retval;
}
/*
* set all the yank registers to empty (called from main())
*/
void
init_yank()
{
int i;
for (i = 0; i < NUM_REGISTERS; ++i)
y_regs[i].y_array = NULL;
}
#if defined(EXITFREE) || defined(PROTO)
void
clear_registers()
{
int i;
for (i = 0; i < NUM_REGISTERS; ++i)
{
y_current = &y_regs[i];
if (y_current->y_array != NULL)
free_yank_all();
}
}
#endif
/*
* Free "n" lines from the current yank register.
* Called for normal freeing and in case of error.
*/
static void
free_yank(n)
long n;
{
if (y_current->y_array != NULL)
{
long i;
for (i = n; --i >= 0; )
{
#ifdef AMIGA /* only for very slow machines */
if ((i & 1023) == 1023) /* this may take a while */
{
/*
* This message should never cause a hit-return message.
* Overwrite this message with any next message.
*/
++no_wait_return;
smsg((char_u *)_("freeing %ld lines"), i + 1);
--no_wait_return;
msg_didout = FALSE;
msg_col = 0;
}
#endif
vim_free(y_current->y_array[i]);
}
vim_free(y_current->y_array);
y_current->y_array = NULL;
#ifdef AMIGA
if (n >= 1000)
MSG("");
#endif
}
}
static void
free_yank_all()
{
free_yank(y_current->y_size);
}
/*
* Yank the text between "oap->start" and "oap->end" into a yank register.
* If we are to append (uppercase register), we first yank into a new yank
* register and then concatenate the old and the new one (so we keep the old
* one in case of out-of-memory).
*
* return FAIL for failure, OK otherwise
*/
int
op_yank(oap, deleting, mess)
oparg_T *oap;
int deleting;
int mess;
{
long y_idx; /* index in y_array[] */
struct yankreg *curr; /* copy of y_current */
struct yankreg newreg; /* new yank register when appending */
char_u **new_ptr;
linenr_T lnum; /* current line number */
long j;
int yanktype = oap->motion_type;
long yanklines = oap->line_count;
linenr_T yankendlnum = oap->end.lnum;
char_u *p;
char_u *pnew;
struct block_def bd;
#if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
int did_star = FALSE;
#endif
/* check for read-only register */
if (oap->regname != 0 && !valid_yank_reg(oap->regname, TRUE))
{
beep_flush();
return FAIL;
}
if (oap->regname == '_') /* black hole: nothing to do */
return OK;
#ifdef FEAT_CLIPBOARD
if (!clip_star.available && oap->regname == '*')
oap->regname = 0;
else if (!clip_plus.available && oap->regname == '+')
oap->regname = 0;
#endif
if (!deleting) /* op_delete() already set y_current */
get_yank_register(oap->regname, TRUE);
curr = y_current;
/* append to existing contents */
if (y_append && y_current->y_array != NULL)
y_current = &newreg;
else
free_yank_all(); /* free previously yanked lines */
/*
* If the cursor was in column 1 before and after the movement, and the
* operator is not inclusive, the yank is always linewise.
*/
if ( oap->motion_type == MCHAR
&& oap->start.col == 0
&& !oap->inclusive
#ifdef FEAT_VISUAL
&& (!oap->is_VIsual || *p_sel == 'o')
&& !oap->block_mode
#endif
&& oap->end.col == 0
&& yanklines > 1)
{
yanktype = MLINE;
--yankendlnum;
--yanklines;
}
y_current->y_size = yanklines;
y_current->y_type = yanktype; /* set the yank register type */
#ifdef FEAT_VISUAL
y_current->y_width = 0;
#endif
y_current->y_array = (char_u **)lalloc_clear((long_u)(sizeof(char_u *) *
yanklines), TRUE);
if (y_current->y_array == NULL)
{
y_current = curr;
return FAIL;
}
y_idx = 0;
lnum = oap->start.lnum;
#ifdef FEAT_VISUAL
if (oap->block_mode)
{
/* Visual block mode */
y_current->y_type = MBLOCK; /* set the yank register type */
y_current->y_width = oap->end_vcol - oap->start_vcol;
if (curwin->w_curswant == MAXCOL && y_current->y_width > 0)
y_current->y_width--;
}
#endif
for ( ; lnum <= yankendlnum; lnum++, y_idx++)
{
switch (y_current->y_type)
{
#ifdef FEAT_VISUAL
case MBLOCK:
block_prep(oap, &bd, lnum, FALSE);
if (yank_copy_line(&bd, y_idx) == FAIL)
goto fail;
break;
#endif
case MLINE:
if ((y_current->y_array[y_idx] =
vim_strsave(ml_get(lnum))) == NULL)
goto fail;
break;
case MCHAR:
{
colnr_T startcol = 0, endcol = MAXCOL;
#ifdef FEAT_VIRTUALEDIT
int is_oneChar = FALSE;
colnr_T cs, ce;
#endif
p = ml_get(lnum);
bd.startspaces = 0;
bd.endspaces = 0;
if (lnum == oap->start.lnum)
{
startcol = oap->start.col;
#ifdef FEAT_VIRTUALEDIT
if (virtual_op)
{
getvcol(curwin, &oap->start, &cs, NULL, &ce);
if (ce != cs && oap->start.coladd > 0)
{
/* Part of a tab selected -- but don't
* double-count it. */
bd.startspaces = (ce - cs + 1)
- oap->start.coladd;
startcol++;
}
}
#endif
}
if (lnum == oap->end.lnum)
{
endcol = oap->end.col;
#ifdef FEAT_VIRTUALEDIT
if (virtual_op)
{
getvcol(curwin, &oap->end, &cs, NULL, &ce);
if (p[endcol] == NUL || (cs + oap->end.coladd < ce
# ifdef FEAT_MBYTE
/* Don't add space for double-wide
* char; endcol will be on last byte
* of multi-byte char. */
&& (*mb_head_off)(p, p + endcol) == 0
# endif
))
{
if (oap->start.lnum == oap->end.lnum
&& oap->start.col == oap->end.col)
{
/* Special case: inside a single char */
is_oneChar = TRUE;
bd.startspaces = oap->end.coladd
- oap->start.coladd + oap->inclusive;
endcol = startcol;
}
else
{
bd.endspaces = oap->end.coladd
+ oap->inclusive;
endcol -= oap->inclusive;
}
}
}
#endif
}
if (endcol == MAXCOL)
endcol = (colnr_T)STRLEN(p);
if (startcol > endcol
#ifdef FEAT_VIRTUALEDIT
|| is_oneChar
#endif
)
bd.textlen = 0;
else
{
bd.textlen = endcol - startcol + oap->inclusive;
}
bd.textstart = p + startcol;
if (yank_copy_line(&bd, y_idx) == FAIL)
goto fail;
break;
}
/* NOTREACHED */
}
}
if (curr != y_current) /* append the new block to the old block */
{
new_ptr = (char_u **)lalloc((long_u)(sizeof(char_u *) *
(curr->y_size + y_current->y_size)), TRUE);
if (new_ptr == NULL)
goto fail;
for (j = 0; j < curr->y_size; ++j)
new_ptr[j] = curr->y_array[j];
vim_free(curr->y_array);
curr->y_array = new_ptr;
if (yanktype == MLINE) /* MLINE overrides MCHAR and MBLOCK */
curr->y_type = MLINE;
/* Concatenate the last line of the old block with the first line of
* the new block, unless being Vi compatible. */
if (curr->y_type == MCHAR && vim_strchr(p_cpo, CPO_REGAPPEND) == NULL)
{
pnew = lalloc((long_u)(STRLEN(curr->y_array[curr->y_size - 1])
+ STRLEN(y_current->y_array[0]) + 1), TRUE);
if (pnew == NULL)
{
y_idx = y_current->y_size - 1;
goto fail;
}
STRCPY(pnew, curr->y_array[--j]);
STRCAT(pnew, y_current->y_array[0]);
vim_free(curr->y_array[j]);
vim_free(y_current->y_array[0]);
curr->y_array[j++] = pnew;
y_idx = 1;
}
else
y_idx = 0;
while (y_idx < y_current->y_size)
curr->y_array[j++] = y_current->y_array[y_idx++];
curr->y_size = j;
vim_free(y_current->y_array);
y_current = curr;
}
if (mess) /* Display message about yank? */
{
if (yanktype == MCHAR
#ifdef FEAT_VISUAL
&& !oap->block_mode
#endif
&& yanklines == 1)
yanklines = 0;
/* Some versions of Vi use ">=" here, some don't... */
if (yanklines > p_report)
{
/* redisplay now, so message is not deleted */
update_topline_redraw();
if (yanklines == 1)
{
#ifdef FEAT_VISUAL
if (oap->block_mode)
MSG(_("block of 1 line yanked"));
else
#endif
MSG(_("1 line yanked"));
}
#ifdef FEAT_VISUAL
else if (oap->block_mode)
smsg((char_u *)_("block of %ld lines yanked"), yanklines);
#endif
else
smsg((char_u *)_("%ld lines yanked"), yanklines);
}
}
/*
* Set "'[" and "']" marks.
*/
curbuf->b_op_start = oap->start;
curbuf->b_op_end = oap->end;
if (yanktype == MLINE
#ifdef FEAT_VISUAL
&& !oap->block_mode
#endif
)
{
curbuf->b_op_start.col = 0;
curbuf->b_op_end.col = MAXCOL;
}
#ifdef FEAT_CLIPBOARD
/*
* If we were yanking to the '*' register, send result to clipboard.
* If no register was specified, and "unnamed" in 'clipboard', make a copy
* to the '*' register.
*/
if (clip_star.available
&& (curr == &(y_regs[STAR_REGISTER])
|| (!deleting && oap->regname == 0
&& (clip_unnamed & CLIP_UNNAMED))))
{
if (curr != &(y_regs[STAR_REGISTER]))
/* Copy the text from register 0 to the clipboard register. */
copy_yank_reg(&(y_regs[STAR_REGISTER]));
clip_own_selection(&clip_star);
clip_gen_set_selection(&clip_star);
# ifdef FEAT_X11
did_star = TRUE;
# endif
}
# ifdef FEAT_X11
/*
* If we were yanking to the '+' register, send result to selection.
* Also copy to the '*' register, in case auto-select is off.
*/
if (clip_plus.available
&& (curr == &(y_regs[PLUS_REGISTER])
|| (!deleting && oap->regname == 0
&& (clip_unnamed & CLIP_UNNAMED_PLUS))))
{
if (curr != &(y_regs[PLUS_REGISTER]))
/* Copy the text from register 0 to the clipboard register. */
copy_yank_reg(&(y_regs[PLUS_REGISTER]));
clip_own_selection(&clip_plus);
clip_gen_set_selection(&clip_plus);
if (!clip_isautosel() && !did_star && curr == &(y_regs[PLUS_REGISTER]))
{
copy_yank_reg(&(y_regs[STAR_REGISTER]));
clip_own_selection(&clip_star);
clip_gen_set_selection(&clip_star);
}
}
# endif
#endif
return OK;
fail: /* free the allocated lines */
free_yank(y_idx + 1);
y_current = curr;
return FAIL;
}
static int
yank_copy_line(bd, y_idx)
struct block_def *bd;
long y_idx;
{
char_u *pnew;
if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))
== NULL)
return FAIL;
y_current->y_array[y_idx] = pnew;
copy_spaces(pnew, (size_t)bd->startspaces);
pnew += bd->startspaces;
mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);
pnew += bd->textlen;
copy_spaces(pnew, (size_t)bd->endspaces);
pnew += bd->endspaces;
*pnew = NUL;
return OK;
}
#ifdef FEAT_CLIPBOARD
/*
* Make a copy of the y_current register to register "reg".
*/
static void
copy_yank_reg(reg)
struct yankreg *reg;
{
struct yankreg *curr = y_current;
long j;
y_current = reg;
free_yank_all();
*y_current = *curr;
y_current->y_array = (char_u **)lalloc_clear(
(long_u)(sizeof(char_u *) * y_current->y_size), TRUE);
if (y_current->y_array == NULL)
y_current->y_size = 0;
else
for (j = 0; j < y_current->y_size; ++j)
if ((y_current->y_array[j] = vim_strsave(curr->y_array[j])) == NULL)
{
free_yank(j);
y_current->y_size = 0;
break;
}
y_current = curr;
}
#endif
/*
* Put contents of register "regname" into the text.
* Caller must check "regname" to be valid!
* "flags": PUT_FIXINDENT make indent look nice
* PUT_CURSEND leave cursor after end of new text
* PUT_LINE force linewise put (":put")
*/
void
do_put(regname, dir, count, flags)
int regname;
int dir; /* BACKWARD for 'P', FORWARD for 'p' */
long count;
int flags;
{
char_u *ptr;
char_u *newp, *oldp;
int yanklen;
int totlen = 0; /* init for gcc */
linenr_T lnum;
colnr_T col;
long i; /* index in y_array[] */
int y_type;
long y_size;
#ifdef FEAT_VISUAL
int oldlen;
long y_width = 0;
colnr_T vcol;
int delcount;
int incr = 0;
long j;
struct block_def bd;
#endif
char_u **y_array = NULL;
long nr_lines = 0;
pos_T new_cursor;
int indent;
int orig_indent = 0; /* init for gcc */
int indent_diff = 0; /* init for gcc */
int first_indent = TRUE;
int lendiff = 0;
pos_T old_pos;
char_u *insert_string = NULL;
int allocated = FALSE;
long cnt;
#ifdef FEAT_CLIPBOARD
/* Adjust register name for "unnamed" in 'clipboard'. */
adjust_clip_reg(®name);
(void)may_get_selection(regname);
#endif
if (flags & PUT_FIXINDENT)
orig_indent = get_indent();
curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */
curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */
/*
* Using inserted text works differently, because the register includes
* special characters (newlines, etc.).
*/
if (regname == '.')
{
(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :
(count == -1 ? 'O' : 'i')), count, FALSE);
/* Putting the text is done later, so can't really move the cursor to
* the next character. Use "l" to simulate it. */
if ((flags & PUT_CURSEND) && gchar_cursor() != NUL)
stuffcharReadbuff('l');
return;
}
/*
* For special registers '%' (file name), '#' (alternate file name) and
* ':' (last command line), etc. we have to create a fake yank register.
*/
if (get_spec_reg(regname, &insert_string, &allocated, TRUE))
{
if (insert_string == NULL)
return;
}
if (insert_string != NULL)
{
y_type = MCHAR;
#ifdef FEAT_EVAL
if (regname == '=')
{
/* For the = register we need to split the string at NL
* characters.
* Loop twice: count the number of lines and save them. */
for (;;)
{
y_size = 0;
ptr = insert_string;
while (ptr != NULL)
{
if (y_array != NULL)
y_array[y_size] = ptr;
++y_size;
ptr = vim_strchr(ptr, '\n');
if (ptr != NULL)
{
if (y_array != NULL)
*ptr = NUL;
++ptr;
/* A trailing '\n' makes the register linewise. */
if (*ptr == NUL)
{
y_type = MLINE;
break;
}
}
}
if (y_array != NULL)
break;
y_array = (char_u **)alloc((unsigned)
(y_size * sizeof(char_u *)));
if (y_array == NULL)
goto end;
}
}
else
#endif
{
y_size = 1; /* use fake one-line yank register */
y_array = &insert_string;
}
}
else
{
get_yank_register(regname, FALSE);
y_type = y_current->y_type;
#ifdef FEAT_VISUAL
y_width = y_current->y_width;
#endif
y_size = y_current->y_size;
y_array = y_current->y_array;
}
#ifdef FEAT_VISUAL
if (y_type == MLINE)
{
if (flags & PUT_LINE_SPLIT)
{
/* "p" or "P" in Visual mode: split the lines to put the text in
* between. */
if (u_save_cursor() == FAIL)
goto end;
ptr = vim_strsave(ml_get_cursor());
if (ptr == NULL)
goto end;
ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);
vim_free(ptr);
ptr = vim_strnsave(ml_get_curline(), curwin->w_cursor.col);
if (ptr == NULL)
goto end;
ml_replace(curwin->w_cursor.lnum, ptr, FALSE);
++nr_lines;
dir = FORWARD;
}
if (flags & PUT_LINE_FORWARD)
{
/* Must be "p" for a Visual block, put lines below the block. */
curwin->w_cursor = curbuf->b_visual.vi_end;
dir = FORWARD;
}
curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */
curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */
}
#endif
if (flags & PUT_LINE) /* :put command or "p" in Visual line mode. */
y_type = MLINE;
if (y_size == 0 || y_array == NULL)
{
EMSG2(_("E353: Nothing in register %s"),
regname == 0 ? (char_u *)"\"" : transchar(regname));
goto end;
}
#ifdef FEAT_VISUAL
if (y_type == MBLOCK)
{
lnum = curwin->w_cursor.lnum + y_size + 1;
if (lnum > curbuf->b_ml.ml_line_count)
lnum = curbuf->b_ml.ml_line_count + 1;
if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)
goto end;
}
else
#endif
if (y_type == MLINE)
{
lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
/* Correct line number for closed fold. Don't move the cursor yet,
* u_save() uses it. */
if (dir == BACKWARD)
(void)hasFolding(lnum, &lnum, NULL);
else
(void)hasFolding(lnum, NULL, &lnum);
#endif
if (dir == FORWARD)
++lnum;
if (u_save(lnum - 1, lnum) == FAIL)
goto end;
#ifdef FEAT_FOLDING
if (dir == FORWARD)
curwin->w_cursor.lnum = lnum - 1;
else
curwin->w_cursor.lnum = lnum;
curbuf->b_op_start = curwin->w_cursor; /* for mark_adjust() */
#endif
}
else if (u_save_cursor() == FAIL)
goto end;
yanklen = (int)STRLEN(y_array[0]);
#ifdef FEAT_VIRTUALEDIT
if (ve_flags == VE_ALL && y_type == MCHAR)
{
if (gchar_cursor() == TAB)
{
/* Don't need to insert spaces when "p" on the last position of a
* tab or "P" on the first position. */
if (dir == FORWARD
? (int)curwin->w_cursor.coladd < curbuf->b_p_ts - 1
: curwin->w_cursor.coladd > 0)
coladvance_force(getviscol());
else
curwin->w_cursor.coladd = 0;
}
else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
coladvance_force(getviscol() + (dir == FORWARD));
}
#endif
lnum = curwin->w_cursor.lnum;
col = curwin->w_cursor.col;
#ifdef FEAT_VISUAL
/*
* Block mode
*/
if (y_type == MBLOCK)
{
char c = gchar_cursor();
colnr_T endcol2 = 0;
if (dir == FORWARD && c != NUL)
{
#ifdef FEAT_VIRTUALEDIT
if (ve_flags == VE_ALL)
getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
else
#endif
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
#ifdef FEAT_MBYTE
if (has_mbyte)
/* move to start of next multi-byte character */
curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
else
#endif
#ifdef FEAT_VIRTUALEDIT
if (c != TAB || ve_flags != VE_ALL)
#endif
++curwin->w_cursor.col;
++col;
}
else
getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
#ifdef FEAT_VIRTUALEDIT
col += curwin->w_cursor.coladd;
if (ve_flags == VE_ALL
&& (curwin->w_cursor.coladd > 0
|| endcol2 == curwin->w_cursor.col))
{
if (dir == FORWARD && c == NUL)
++col;
if (dir != FORWARD && c != NUL)
++curwin->w_cursor.col;
if (c == TAB)
{
if (dir == BACKWARD && curwin->w_cursor.col)
curwin->w_cursor.col--;
if (dir == FORWARD && col - 1 == endcol2)
curwin->w_cursor.col++;
}
}
curwin->w_cursor.coladd = 0;
#endif
bd.textcol = 0;
for (i = 0; i < y_size; ++i)
{
int spaces;
char shortline;
bd.startspaces = 0;
bd.endspaces = 0;
vcol = 0;
delcount = 0;
/* add a new line */
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
{
if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"",
(colnr_T)1, FALSE) == FAIL)
break;
++nr_lines;
}
/* get the old line and advance to the position to insert at */
oldp = ml_get_curline();
oldlen = (int)STRLEN(oldp);
for (ptr = oldp; vcol < col && *ptr; )
{
/* Count a tab for what it's worth (if list mode not on) */
incr = lbr_chartabsize_adv(&ptr, (colnr_T)vcol);
vcol += incr;
}
bd.textcol = (colnr_T)(ptr - oldp);
shortline = (vcol < col) || (vcol == col && !*ptr) ;
if (vcol < col) /* line too short, padd with spaces */
bd.startspaces = col - vcol;
else if (vcol > col)
{
bd.endspaces = vcol - col;
bd.startspaces = incr - bd.endspaces;
--bd.textcol;
delcount = 1;
#ifdef FEAT_MBYTE
if (has_mbyte)
bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);
#endif
if (oldp[bd.textcol] != TAB)
{
/* Only a Tab can be split into spaces. Other
* characters will have to be moved to after the
* block, causing misalignment. */
delcount = 0;
bd.endspaces = 0;
}
}
yanklen = (int)STRLEN(y_array[i]);
/* calculate number of spaces required to fill right side of block*/
spaces = y_width + 1;
for (j = 0; j < yanklen; j++)
spaces -= lbr_chartabsize(&y_array[i][j], 0);
if (spaces < 0)
spaces = 0;
/* insert the new text */
totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;
newp = alloc_check((unsigned)totlen + oldlen + 1);
if (newp == NULL)
break;
/* copy part up to cursor to new line */
ptr = newp;
mch_memmove(ptr, oldp, (size_t)bd.textcol);
ptr += bd.textcol;
/* may insert some spaces before the new text */
copy_spaces(ptr, (size_t)bd.startspaces);
ptr += bd.startspaces;
/* insert the new text */
for (j = 0; j < count; ++j)
{
mch_memmove(ptr, y_array[i], (size_t)yanklen);
ptr += yanklen;
/* insert block's trailing spaces only if there's text behind */
if ((j < count - 1 || !shortline) && spaces)
{
copy_spaces(ptr, (size_t)spaces);
ptr += spaces;
}
}
/* may insert some spaces after the new text */
copy_spaces(ptr, (size_t)bd.endspaces);
ptr += bd.endspaces;
/* move the text after the cursor to the end of the line. */
mch_memmove(ptr, oldp + bd.textcol + delcount,
(size_t)(oldlen - bd.textcol - delcount + 1));
ml_replace(curwin->w_cursor.lnum, newp, FALSE);
++curwin->w_cursor.lnum;
if (i == 0)
curwin->w_cursor.col += bd.startspaces;
}
changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);
/* Set '[ mark. */
curbuf->b_op_start = curwin->w_cursor;
curbuf->b_op_start.lnum = lnum;
/* adjust '] mark */
curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
curbuf->b_op_end.col = bd.textcol + totlen - 1;
# ifdef FEAT_VIRTUALEDIT
curbuf->b_op_end.coladd = 0;
# endif
if (flags & PUT_CURSEND)
{
colnr_T len;
curwin->w_cursor = curbuf->b_op_end;
curwin->w_cursor.col++;
/* in Insert mode we might be after the NUL, correct for that */
len = (colnr_T)STRLEN(ml_get_curline());
if (curwin->w_cursor.col > len)
curwin->w_cursor.col = len;
}
else
curwin->w_cursor.lnum = lnum;
}
else
#endif
{
/*
* Character or Line mode
*/
if (y_type == MCHAR)
{
/* if type is MCHAR, FORWARD is the same as BACKWARD on the next
* char */
if (dir == FORWARD && gchar_cursor() != NUL)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int bytelen = (*mb_ptr2len)(ml_get_cursor());
/* put it on the next of the multi-byte character. */
col += bytelen;
if (yanklen)
{
curwin->w_cursor.col += bytelen;
curbuf->b_op_end.col += bytelen;
}
}
else
#endif
{
++col;
if (yanklen)
{
++curwin->w_cursor.col;
++curbuf->b_op_end.col;
}
}
}
curbuf->b_op_start = curwin->w_cursor;
}
/*
* Line mode: BACKWARD is the same as FORWARD on the previous line
*/
else if (dir == BACKWARD)
--lnum;
new_cursor = curwin->w_cursor;
/*
* simple case: insert into current line
*/
if (y_type == MCHAR && y_size == 1)
{
totlen = count * yanklen;
if (totlen)
{
oldp = ml_get(lnum);
newp = alloc_check((unsigned)(STRLEN(oldp) + totlen + 1));
if (newp == NULL)
goto end; /* alloc() will give error message */
mch_memmove(newp, oldp, (size_t)col);
ptr = newp + col;
for (i = 0; i < count; ++i)
{
mch_memmove(ptr, y_array[0], (size_t)yanklen);
ptr += yanklen;
}
STRMOVE(ptr, oldp + col);
ml_replace(lnum, newp, FALSE);
/* Put cursor on last putted char. */
curwin->w_cursor.col += (colnr_T)(totlen - 1);
}
curbuf->b_op_end = curwin->w_cursor;
/* For "CTRL-O p" in Insert mode, put cursor after last char */
if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
++curwin->w_cursor.col;
changed_bytes(lnum, col);
}
else
{
/*
* Insert at least one line. When y_type is MCHAR, break the first
* line in two.
*/
for (cnt = 1; cnt <= count; ++cnt)
{
i = 0;
if (y_type == MCHAR)
{
/*
* Split the current line in two at the insert position.
* First insert y_array[size - 1] in front of second line.
* Then append y_array[0] to first line.
*/
lnum = new_cursor.lnum;
ptr = ml_get(lnum) + col;
totlen = (int)STRLEN(y_array[y_size - 1]);
newp = alloc_check((unsigned)(STRLEN(ptr) + totlen + 1));
if (newp == NULL)
goto error;
STRCPY(newp, y_array[y_size - 1]);
STRCAT(newp, ptr);
/* insert second line */
ml_append(lnum, newp, (colnr_T)0, FALSE);
vim_free(newp);
oldp = ml_get(lnum);
newp = alloc_check((unsigned)(col + yanklen + 1));
if (newp == NULL)
goto error;
/* copy first part of line */
mch_memmove(newp, oldp, (size_t)col);
/* append to first line */
mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));
ml_replace(lnum, newp, FALSE);
curwin->w_cursor.lnum = lnum;
i = 1;
}
for (; i < y_size; ++i)
{
if ((y_type != MCHAR || i < y_size - 1)
&& ml_append(lnum, y_array[i], (colnr_T)0, FALSE)
== FAIL)
goto error;
lnum++;
++nr_lines;
if (flags & PUT_FIXINDENT)
{
old_pos = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
ptr = ml_get(lnum);
if (cnt == count && i == y_size - 1)
lendiff = (int)STRLEN(ptr);
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
if (*ptr == '#' && preprocs_left())
indent = 0; /* Leave # lines at start */
else
#endif
if (*ptr == NUL)
indent = 0; /* Ignore empty lines */
else if (first_indent)
{
indent_diff = orig_indent - get_indent();
indent = orig_indent;
first_indent = FALSE;
}
else if ((indent = get_indent() + indent_diff) < 0)
indent = 0;
(void)set_indent(indent, 0);
curwin->w_cursor = old_pos;
/* remember how many chars were removed */
if (cnt == count && i == y_size - 1)
lendiff -= (int)STRLEN(ml_get(lnum));
}
}
}
error:
/* Adjust marks. */
if (y_type == MLINE)
{
curbuf->b_op_start.col = 0;
if (dir == FORWARD)
curbuf->b_op_start.lnum++;
}
mark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),
(linenr_T)MAXLNUM, nr_lines, 0L);
/* note changed text for displaying and folding */
if (y_type == MCHAR)
changed_lines(curwin->w_cursor.lnum, col,
curwin->w_cursor.lnum + 1, nr_lines);
else
changed_lines(curbuf->b_op_start.lnum, 0,
curbuf->b_op_start.lnum, nr_lines);
/* put '] mark at last inserted character */
curbuf->b_op_end.lnum = lnum;
/* correct length for change in indent */
col = (colnr_T)STRLEN(y_array[y_size - 1]) - lendiff;
if (col > 1)
curbuf->b_op_end.col = col - 1;
else
curbuf->b_op_end.col = 0;
if (flags & PUT_CURSLINE)
{
/* ":put": put cursor on last inserted line */
curwin->w_cursor.lnum = lnum;
beginline(BL_WHITE | BL_FIX);
}
else if (flags & PUT_CURSEND)
{
/* put cursor after inserted text */
if (y_type == MLINE)
{
if (lnum >= curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
else
curwin->w_cursor.lnum = lnum + 1;
curwin->w_cursor.col = 0;
}
else
{
curwin->w_cursor.lnum = lnum;
curwin->w_cursor.col = col;
}
}
else if (y_type == MLINE)
{
/* put cursor on first non-blank in first inserted line */
curwin->w_cursor.col = 0;
if (dir == FORWARD)
++curwin->w_cursor.lnum;
beginline(BL_WHITE | BL_FIX);
}
else /* put cursor on first inserted character */
curwin->w_cursor = new_cursor;
}
}
msgmore(nr_lines);
curwin->w_set_curswant = TRUE;
end:
if (allocated)
vim_free(insert_string);
if (regname == '=')
vim_free(y_array);
/* If the cursor is past the end of the line put it at the end. */
adjust_cursor_eol();
}
/*
* When the cursor is on the NUL past the end of the line and it should not be
* there move it left.
*/
void
adjust_cursor_eol()
{
if (curwin->w_cursor.col > 0
&& gchar_cursor() == NUL
#ifdef FEAT_VIRTUALEDIT
&& (ve_flags & VE_ONEMORE) == 0
#endif
&& !(restart_edit || (State & INSERT)))
{
/* Put the cursor on the last character in the line. */
dec_cursor();
#ifdef FEAT_VIRTUALEDIT
if (ve_flags == VE_ALL)
{
colnr_T scol, ecol;
/* Coladd is set to the width of the last character. */
getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
curwin->w_cursor.coladd = ecol - scol + 1;
}
#endif
}
}
#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) || defined(PROTO)
/*
* Return TRUE if lines starting with '#' should be left aligned.
*/
int
preprocs_left()
{
return
# ifdef FEAT_SMARTINDENT
# ifdef FEAT_CINDENT
(curbuf->b_p_si && !curbuf->b_p_cin) ||
# else
curbuf->b_p_si
# endif
# endif
# ifdef FEAT_CINDENT
(curbuf->b_p_cin && in_cinkeys('#', ' ', TRUE))
# endif
;
}
#endif
/* Return the character name of the register with the given number */
int
get_register_name(num)
int num;
{
if (num == -1)
return '"';
else if (num < 10)
return num + '0';
else if (num == DELETION_REGISTER)
return '-';
#ifdef FEAT_CLIPBOARD
else if (num == STAR_REGISTER)
return '*';
else if (num == PLUS_REGISTER)
return '+';
#endif
else
{
#ifdef EBCDIC
int i;
/* EBCDIC is really braindead ... */
i = 'a' + (num - 10);
if (i > 'i')
i += 7;
if (i > 'r')
i += 8;
return i;
#else
return num + 'a' - 10;
#endif
}
}
/*
* ":dis" and ":registers": Display the contents of the yank registers.
*/
void
ex_display(eap)
exarg_T *eap;
{
int i, n;
long j;
char_u *p;
struct yankreg *yb;
int name;
int attr;
char_u *arg = eap->arg;
#ifdef FEAT_MBYTE
int clen;
#else
# define clen 1
#endif
if (arg != NULL && *arg == NUL)
arg = NULL;
attr = hl_attr(HLF_8);
/* Highlight title */
MSG_PUTS_TITLE(_("\n--- Registers ---"));
for (i = -1; i < NUM_REGISTERS && !got_int; ++i)
{
name = get_register_name(i);
if (arg != NULL && vim_strchr(arg, name) == NULL
#ifdef ONE_CLIPBOARD
/* Star register and plus register contain the same thing. */
&& (name != '*' || vim_strchr(arg, '+') == NULL)
#endif
)
continue; /* did not ask for this register */
#ifdef FEAT_CLIPBOARD
/* Adjust register name for "unnamed" in 'clipboard'.
* When it's a clipboard register, fill it with the current contents
* of the clipboard. */
adjust_clip_reg(&name);
(void)may_get_selection(name);
#endif
if (i == -1)
{
if (y_previous != NULL)
yb = y_previous;
else
yb = &(y_regs[0]);
}
else
yb = &(y_regs[i]);
#ifdef FEAT_EVAL
if (name == MB_TOLOWER(redir_reg)
|| (redir_reg == '"' && yb == y_previous))
continue; /* do not list register being written to, the
* pointer can be freed */
#endif
if (yb->y_array != NULL)
{
msg_putchar('\n');
msg_putchar('"');
msg_putchar(name);
MSG_PUTS(" ");
n = (int)Columns - 6;
for (j = 0; j < yb->y_size && n > 1; ++j)
{
if (j)
{
MSG_PUTS_ATTR("^J", attr);
n -= 2;
}
for (p = yb->y_array[j]; *p && (n -= ptr2cells(p)) >= 0; ++p)
{
#ifdef FEAT_MBYTE
clen = (*mb_ptr2len)(p);
#endif
msg_outtrans_len(p, clen);
#ifdef FEAT_MBYTE
p += clen - 1;
#endif
}
}
if (n > 1 && yb->y_type == MLINE)
MSG_PUTS_ATTR("^J", attr);
out_flush(); /* show one line at a time */
}
ui_breakcheck();
}
/*
* display last inserted text
*/
if ((p = get_last_insert()) != NULL
&& (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int)
{
MSG_PUTS("\n\". ");
dis_msg(p, TRUE);
}
/*
* display last command line
*/
if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL)
&& !got_int)
{
MSG_PUTS("\n\": ");
dis_msg(last_cmdline, FALSE);
}
/*
* display current file name
*/
if (curbuf->b_fname != NULL
&& (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int)
{
MSG_PUTS("\n\"% ");
dis_msg(curbuf->b_fname, FALSE);
}
/*
* display alternate file name
*/
if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int)
{
char_u *fname;
linenr_T dummy;
if (buflist_name_nr(0, &fname, &dummy) != FAIL)
{
MSG_PUTS("\n\"# ");
dis_msg(fname, FALSE);
}
}
/*
* display last search pattern
*/
if (last_search_pat() != NULL
&& (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int)
{
MSG_PUTS("\n\"/ ");
dis_msg(last_search_pat(), FALSE);
}
#ifdef FEAT_EVAL
/*
* display last used expression
*/
if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL)
&& !got_int)
{
MSG_PUTS("\n\"= ");
dis_msg(expr_line, FALSE);
}
#endif
}
/*
* display a string for do_dis()
* truncate at end of screen line
*/
static void
dis_msg(p, skip_esc)
char_u *p;
int skip_esc; /* if TRUE, ignore trailing ESC */
{
int n;
#ifdef FEAT_MBYTE
int l;
#endif
n = (int)Columns - 6;
while (*p != NUL
&& !(*p == ESC && skip_esc && *(p + 1) == NUL)
&& (n -= ptr2cells(p)) >= 0)
{
#ifdef FEAT_MBYTE
if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
{
msg_outtrans_len(p, l);
p += l;
}
else
#endif
msg_outtrans_len(p++, 1);
}
ui_breakcheck();
}
#if defined(FEAT_COMMENTS) || defined(PROTO)
/*
* If "process" is TRUE and the line begins with a comment leader (possibly
* after some white space), return a pointer to the text after it. Put a boolean
* value indicating whether the line ends with an unclosed comment in
* "is_comment".
* line - line to be processed,
* process - if FALSE, will only check whether the line ends with an unclosed
* comment,
* include_space - whether to also skip space following the comment leader,
* is_comment - will indicate whether the current line ends with an unclosed
* comment.
*/
static char_u *
skip_comment(line, process, include_space, is_comment)
char_u *line;
int process;
int include_space;
int *is_comment;
{
char_u *comment_flags = NULL;
int lead_len;
int leader_offset = get_last_leader_offset(line, &comment_flags);
*is_comment = FALSE;
if (leader_offset != -1)
{
/* Let's check whether the line ends with an unclosed comment.
* If the last comment leader has COM_END in flags, there's no comment.
*/
while (*comment_flags)
{
if (*comment_flags == COM_END
|| *comment_flags == ':')
break;
++comment_flags;
}
if (*comment_flags != COM_END)
*is_comment = TRUE;
}
if (process == FALSE)
return line;
lead_len = get_leader_len(line, &comment_flags, FALSE, include_space);
if (lead_len == 0)
return line;
/* Find:
* - COM_END,
* - colon,
* whichever comes first.
*/
while (*comment_flags)
{
if (*comment_flags == COM_END
|| *comment_flags == ':')
{
break;
}
++comment_flags;
}
/* If we found a colon, it means that we are not processing a line
* starting with a closing part of a three-part comment. That's good,
* because we don't want to remove those as this would be annoying.
*/
if (*comment_flags == ':' || *comment_flags == NUL)
line += lead_len;
return line;
}
#endif
/*
* Join 'count' lines (minimal 2) at cursor position.
* When "save_undo" is TRUE save lines for undo first.
* Set "use_formatoptions" to FALSE when e.g. processing
* backspace and comment leaders should not be removed.
*
* return FAIL for failure, OK otherwise
*/
int
do_join(count, insert_space, save_undo, use_formatoptions)
long count;
int insert_space;
int save_undo;
int use_formatoptions UNUSED;
{
char_u *curr = NULL;
char_u *curr_start = NULL;
char_u *cend;
char_u *newp;
char_u *spaces; /* number of spaces inserted before a line */
int endcurr1 = NUL;
int endcurr2 = NUL;
int currsize = 0; /* size of the current line */
int sumsize = 0; /* size of the long new line */
linenr_T t;
colnr_T col = 0;
int ret = OK;
#if defined(FEAT_COMMENTS) || defined(PROTO)
int *comments = NULL;
int remove_comments = (use_formatoptions == TRUE)
&& has_format_option(FO_REMOVE_COMS);
int prev_was_comment;
#endif
if (save_undo && u_save((linenr_T)(curwin->w_cursor.lnum - 1),
(linenr_T)(curwin->w_cursor.lnum + count)) == FAIL)
return FAIL;
/* Allocate an array to store the number of spaces inserted before each
* line. We will use it to pre-compute the length of the new line and the
* proper placement of each original line in the new one. */
spaces = lalloc_clear((long_u)count, TRUE);
if (spaces == NULL)
return FAIL;
#if defined(FEAT_COMMENTS) || defined(PROTO)
if (remove_comments)
{
comments = (int *)lalloc_clear((long_u)count * sizeof(int), TRUE);
if (comments == NULL)
{
vim_free(spaces);
return FAIL;
}
}
#endif
/*
* Don't move anything, just compute the final line length
* and setup the array of space strings lengths
*/
for (t = 0; t < count; ++t)
{
curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t));
#if defined(FEAT_COMMENTS) || defined(PROTO)
if (remove_comments)
{
/* We don't want to remove the comment leader if the
* previous line is not a comment. */
if (t > 0 && prev_was_comment)
{
char_u *new_curr = skip_comment(curr, TRUE, insert_space,
&prev_was_comment);
comments[t] = (int)(new_curr - curr);
curr = new_curr;
}
else
curr = skip_comment(curr, FALSE, insert_space,
&prev_was_comment);
}
#endif
if (insert_space && t > 0)
{
curr = skipwhite(curr);
if (*curr != ')' && currsize != 0 && endcurr1 != TAB
#ifdef FEAT_MBYTE
&& (!has_format_option(FO_MBYTE_JOIN)
|| (mb_ptr2char(curr) < 0x100 && endcurr1 < 0x100))
&& (!has_format_option(FO_MBYTE_JOIN2)
|| mb_ptr2char(curr) < 0x100 || endcurr1 < 0x100)
#endif
)
{
/* don't add a space if the line is ending in a space */
if (endcurr1 == ' ')
endcurr1 = endcurr2;
else
++spaces[t];
/* extra space when 'joinspaces' set and line ends in '.' */
if ( p_js
&& (endcurr1 == '.'
|| (vim_strchr(p_cpo, CPO_JOINSP) == NULL
&& (endcurr1 == '?' || endcurr1 == '!'))))
++spaces[t];
}
}
currsize = (int)STRLEN(curr);
sumsize += currsize + spaces[t];
endcurr1 = endcurr2 = NUL;
if (insert_space && currsize > 0)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
cend = curr + currsize;
mb_ptr_back(curr, cend);
endcurr1 = (*mb_ptr2char)(cend);
if (cend > curr)
{
mb_ptr_back(curr, cend);
endcurr2 = (*mb_ptr2char)(cend);
}
}
else
#endif
{
endcurr1 = *(curr + currsize - 1);
if (currsize > 1)
endcurr2 = *(curr + currsize - 2);
}
}
line_breakcheck();
if (got_int)
{
ret = FAIL;
goto theend;
}
}
/* store the column position before last line */
col = sumsize - currsize - spaces[count - 1];
/* allocate the space for the new line */
newp = alloc_check((unsigned)(sumsize + 1));
cend = newp + sumsize;
*cend = 0;
/*
* Move affected lines to the new long one.
*
* Move marks from each deleted line to the joined line, adjusting the
* column. This is not Vi compatible, but Vi deletes the marks, thus that
* should not really be a problem.
*/
for (t = count - 1; ; --t)
{
cend -= currsize;
mch_memmove(cend, curr, (size_t)currsize);
if (spaces[t] > 0)
{
cend -= spaces[t];
copy_spaces(cend, (size_t)(spaces[t]));
}
mark_col_adjust(curwin->w_cursor.lnum + t, (colnr_T)0, (linenr_T)-t,
(long)(cend - newp + spaces[t] - (curr - curr_start)));
if (t == 0)
break;
curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1));
#if defined(FEAT_COMMENTS) || defined(PROTO)
if (remove_comments)
curr += comments[t - 1];
#endif
if (insert_space && t > 1)
curr = skipwhite(curr);
currsize = (int)STRLEN(curr);
}
ml_replace(curwin->w_cursor.lnum, newp, FALSE);
/* Only report the change in the first line here, del_lines() will report
* the deleted line. */
changed_lines(curwin->w_cursor.lnum, currsize,
curwin->w_cursor.lnum + 1, 0L);
/*
* Delete following lines. To do this we move the cursor there
* briefly, and then move it back. After del_lines() the cursor may
* have moved up (last line deleted), so the current lnum is kept in t.
*/
t = curwin->w_cursor.lnum;
++curwin->w_cursor.lnum;
del_lines(count - 1, FALSE);
curwin->w_cursor.lnum = t;
/*
* Set the cursor column:
* Vi compatible: use the column of the first join
* vim: use the column of the last join
*/
curwin->w_cursor.col =
(vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col);
check_cursor_col();
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
curwin->w_set_curswant = TRUE;
theend:
vim_free(spaces);
#if defined(FEAT_COMMENTS) || defined(PROTO)
if (remove_comments)
vim_free(comments);
#endif
return ret;
}
#ifdef FEAT_COMMENTS
/*
* Return TRUE if the two comment leaders given are the same. "lnum" is
* the first line. White-space is ignored. Note that the whole of
* 'leader1' must match 'leader2_len' characters from 'leader2' -- webb
*/
static int
same_leader(lnum, leader1_len, leader1_flags, leader2_len, leader2_flags)
linenr_T lnum;
int leader1_len;
char_u *leader1_flags;
int leader2_len;
char_u *leader2_flags;
{
int idx1 = 0, idx2 = 0;
char_u *p;
char_u *line1;
char_u *line2;
if (leader1_len == 0)
return (leader2_len == 0);
/*
* If first leader has 'f' flag, the lines can be joined only if the
* second line does not have a leader.
* If first leader has 'e' flag, the lines can never be joined.
* If fist leader has 's' flag, the lines can only be joined if there is
* some text after it and the second line has the 'm' flag.
*/
if (leader1_flags != NULL)
{
for (p = leader1_flags; *p && *p != ':'; ++p)
{
if (*p == COM_FIRST)
return (leader2_len == 0);
if (*p == COM_END)
return FALSE;
if (*p == COM_START)
{
if (*(ml_get(lnum) + leader1_len) == NUL)
return FALSE;
if (leader2_flags == NULL || leader2_len == 0)
return FALSE;
for (p = leader2_flags; *p && *p != ':'; ++p)
if (*p == COM_MIDDLE)
return TRUE;
return FALSE;
}
}
}
/*
* Get current line and next line, compare the leaders.
* The first line has to be saved, only one line can be locked at a time.
*/
line1 = vim_strsave(ml_get(lnum));
if (line1 != NULL)
{
for (idx1 = 0; vim_iswhite(line1[idx1]); ++idx1)
;
line2 = ml_get(lnum + 1);
for (idx2 = 0; idx2 < leader2_len; ++idx2)
{
if (!vim_iswhite(line2[idx2]))
{
if (line1[idx1++] != line2[idx2])
break;
}
else
while (vim_iswhite(line1[idx1]))
++idx1;
}
vim_free(line1);
}
return (idx2 == leader2_len && idx1 == leader1_len);
}
#endif
/*
* Implementation of the format operator 'gq'.
*/
void
op_format(oap, keep_cursor)
oparg_T *oap;
int keep_cursor; /* keep cursor on same text char */
{
long old_line_count = curbuf->b_ml.ml_line_count;
/* Place the cursor where the "gq" or "gw" command was given, so that "u"
* can put it back there. */
curwin->w_cursor = oap->cursor_start;
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL)
return;
curwin->w_cursor = oap->start;
#ifdef FEAT_VISUAL
if (oap->is_VIsual)
/* When there is no change: need to remove the Visual selection */
redraw_curbuf_later(INVERTED);
#endif
/* Set '[ mark at the start of the formatted area */
curbuf->b_op_start = oap->start;
/* For "gw" remember the cursor position and put it back below (adjusted
* for joined and split lines). */
if (keep_cursor)
saved_cursor = oap->cursor_start;
format_lines(oap->line_count, keep_cursor);
/*
* Leave the cursor at the first non-blank of the last formatted line.
* If the cursor was moved one line back (e.g. with "Q}") go to the next
* line, so "." will do the next lines.
*/
if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
++curwin->w_cursor.lnum;
beginline(BL_WHITE | BL_FIX);
old_line_count = curbuf->b_ml.ml_line_count - old_line_count;
msgmore(old_line_count);
/* put '] mark on the end of the formatted area */
curbuf->b_op_end = curwin->w_cursor;
if (keep_cursor)
{
curwin->w_cursor = saved_cursor;
saved_cursor.lnum = 0;
}
#ifdef FEAT_VISUAL
if (oap->is_VIsual)
{
win_T *wp;
FOR_ALL_WINDOWS(wp)
{
if (wp->w_old_cursor_lnum != 0)
{
/* When lines have been inserted or deleted, adjust the end of
* the Visual area to be redrawn. */
if (wp->w_old_cursor_lnum > wp->w_old_visual_lnum)
wp->w_old_cursor_lnum += old_line_count;
else
wp->w_old_visual_lnum += old_line_count;
}
}
}
#endif
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Implementation of the format operator 'gq' for when using 'formatexpr'.
*/
void
op_formatexpr(oap)
oparg_T *oap;
{
# ifdef FEAT_VISUAL
if (oap->is_VIsual)
/* When there is no change: need to remove the Visual selection */
redraw_curbuf_later(INVERTED);
# endif
if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0)
/* As documented: when 'formatexpr' returns non-zero fall back to
* internal formatting. */
op_format(oap, FALSE);
}
int
fex_format(lnum, count, c)
linenr_T lnum;
long count;
int c; /* character to be inserted */
{
int use_sandbox = was_set_insecurely((char_u *)"formatexpr",
OPT_LOCAL);
int r;
/*
* Set v:lnum to the first line number and v:count to the number of lines.
* Set v:char to the character to be inserted (can be NUL).
*/
set_vim_var_nr(VV_LNUM, lnum);
set_vim_var_nr(VV_COUNT, count);
set_vim_var_char(c);
/*
* Evaluate the function.
*/
if (use_sandbox)
++sandbox;
r = eval_to_number(curbuf->b_p_fex);
if (use_sandbox)
--sandbox;
set_vim_var_string(VV_CHAR, NULL, -1);
return r;
}
#endif
/*
* Format "line_count" lines, starting at the cursor position.
* When "line_count" is negative, format until the end of the paragraph.
* Lines after the cursor line are saved for undo, caller must have saved the
* first line.
*/
void
format_lines(line_count, avoid_fex)
linenr_T line_count;
int avoid_fex; /* don't use 'formatexpr' */
{
int max_len;
int is_not_par; /* current line not part of parag. */
int next_is_not_par; /* next line not part of paragraph */
int is_end_par; /* at end of paragraph */
int prev_is_end_par = FALSE;/* prev. line not part of parag. */
int next_is_start_par = FALSE;
#ifdef FEAT_COMMENTS
int leader_len = 0; /* leader len of current line */
int next_leader_len; /* leader len of next line */
char_u *leader_flags = NULL; /* flags for leader of current line */
char_u *next_leader_flags; /* flags for leader of next line */
int do_comments; /* format comments */
int do_comments_list = 0; /* format comments with 'n' or '2' */
#endif
int advance = TRUE;
int second_indent = -1; /* indent for second line (comment
* aware) */
int do_second_indent;
int do_number_indent;
int do_trail_white;
int first_par_line = TRUE;
int smd_save;
long count;
int need_set_indent = TRUE; /* set indent of next paragraph */
int force_format = FALSE;
int old_State = State;
/* length of a line to force formatting: 3 * 'tw' */
max_len = comp_textwidth(TRUE) * 3;
/* check for 'q', '2' and '1' in 'formatoptions' */
#ifdef FEAT_COMMENTS
do_comments = has_format_option(FO_Q_COMS);
#endif
do_second_indent = has_format_option(FO_Q_SECOND);
do_number_indent = has_format_option(FO_Q_NUMBER);
do_trail_white = has_format_option(FO_WHITE_PAR);
/*
* Get info about the previous and current line.
*/
if (curwin->w_cursor.lnum > 1)
is_not_par = fmt_check_par(curwin->w_cursor.lnum - 1
#ifdef FEAT_COMMENTS
, &leader_len, &leader_flags, do_comments
#endif
);
else
is_not_par = TRUE;
next_is_not_par = fmt_check_par(curwin->w_cursor.lnum
#ifdef FEAT_COMMENTS
, &next_leader_len, &next_leader_flags, do_comments
#endif
);
is_end_par = (is_not_par || next_is_not_par);
if (!is_end_par && do_trail_white)
is_end_par = !ends_in_white(curwin->w_cursor.lnum - 1);
curwin->w_cursor.lnum--;
for (count = line_count; count != 0 && !got_int; --count)
{
/*
* Advance to next paragraph.
*/
if (advance)
{
curwin->w_cursor.lnum++;
prev_is_end_par = is_end_par;
is_not_par = next_is_not_par;
#ifdef FEAT_COMMENTS
leader_len = next_leader_len;
leader_flags = next_leader_flags;
#endif
}
/*
* The last line to be formatted.
*/
if (count == 1 || curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
{
next_is_not_par = TRUE;
#ifdef FEAT_COMMENTS
next_leader_len = 0;
next_leader_flags = NULL;
#endif
}
else
{
next_is_not_par = fmt_check_par(curwin->w_cursor.lnum + 1
#ifdef FEAT_COMMENTS
, &next_leader_len, &next_leader_flags, do_comments
#endif
);
if (do_number_indent)
next_is_start_par =
(get_number_indent(curwin->w_cursor.lnum + 1) > 0);
}
advance = TRUE;
is_end_par = (is_not_par || next_is_not_par || next_is_start_par);
if (!is_end_par && do_trail_white)
is_end_par = !ends_in_white(curwin->w_cursor.lnum);
/*
* Skip lines that are not in a paragraph.
*/
if (is_not_par)
{
if (line_count < 0)
break;
}
else
{
/*
* For the first line of a paragraph, check indent of second line.
* Don't do this for comments and empty lines.
*/
if (first_par_line
&& (do_second_indent || do_number_indent)
&& prev_is_end_par
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
if (do_second_indent && !lineempty(curwin->w_cursor.lnum + 1))
{
#ifdef FEAT_COMMENTS
if (leader_len == 0 && next_leader_len == 0)
{
/* no comment found */
#endif
second_indent =
get_indent_lnum(curwin->w_cursor.lnum + 1);
#ifdef FEAT_COMMENTS
}
else
{
second_indent = next_leader_len;
do_comments_list = 1;
}
#endif
}
else if (do_number_indent)
{
#ifdef FEAT_COMMENTS
if (leader_len == 0 && next_leader_len == 0)
{
/* no comment found */
#endif
second_indent =
get_number_indent(curwin->w_cursor.lnum);
#ifdef FEAT_COMMENTS
}
else
{
/* get_number_indent() is now "comment aware"... */
second_indent =
get_number_indent(curwin->w_cursor.lnum);
do_comments_list = 1;
}
#endif
}
}
/*
* When the comment leader changes, it's the end of the paragraph.
*/
if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count
#ifdef FEAT_COMMENTS
|| !same_leader(curwin->w_cursor.lnum,
leader_len, leader_flags,
next_leader_len, next_leader_flags)
#endif
)
is_end_par = TRUE;
/*
* If we have got to the end of a paragraph, or the line is
* getting long, format it.
*/
if (is_end_par || force_format)
{
if (need_set_indent)
/* replace indent in first line with minimal number of
* tabs and spaces, according to current options */
(void)set_indent(get_indent(), SIN_CHANGED);
/* put cursor on last non-space */
State = NORMAL; /* don't go past end-of-line */
coladvance((colnr_T)MAXCOL);
while (curwin->w_cursor.col && vim_isspace(gchar_cursor()))
dec_cursor();
/* do the formatting, without 'showmode' */
State = INSERT; /* for open_line() */
smd_save = p_smd;
p_smd = FALSE;
insertchar(NUL, INSCHAR_FORMAT
#ifdef FEAT_COMMENTS
+ (do_comments ? INSCHAR_DO_COM : 0)
+ (do_comments && do_comments_list
? INSCHAR_COM_LIST : 0)
#endif
+ (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent);
State = old_State;
p_smd = smd_save;
second_indent = -1;
/* at end of par.: need to set indent of next par. */
need_set_indent = is_end_par;
if (is_end_par)
{
/* When called with a negative line count, break at the
* end of the paragraph. */
if (line_count < 0)
break;
first_par_line = TRUE;
}
force_format = FALSE;
}
/*
* When still in same paragraph, join the lines together. But
* first delete the comment leader from the second line.
*/
if (!is_end_par)
{
advance = FALSE;
curwin->w_cursor.lnum++;
curwin->w_cursor.col = 0;
if (line_count < 0 && u_save_cursor() == FAIL)
break;
#ifdef FEAT_COMMENTS
(void)del_bytes((long)next_leader_len, FALSE, FALSE);
if (next_leader_len > 0)
mark_col_adjust(curwin->w_cursor.lnum, (colnr_T)0, 0L,
(long)-next_leader_len);
#endif
curwin->w_cursor.lnum--;
if (do_join(2, TRUE, FALSE, FALSE) == FAIL)
{
beep_flush();
break;
}
first_par_line = FALSE;
/* If the line is getting long, format it next time */
if (STRLEN(ml_get_curline()) > (size_t)max_len)
force_format = TRUE;
else
force_format = FALSE;
}
}
line_breakcheck();
}
}
/*
* Return TRUE if line "lnum" ends in a white character.
*/
static int
ends_in_white(lnum)
linenr_T lnum;
{
char_u *s = ml_get(lnum);
size_t l;
if (*s == NUL)
return FALSE;
/* Don't use STRLEN() inside vim_iswhite(), SAS/C complains: "macro
* invocation may call function multiple times". */
l = STRLEN(s) - 1;
return vim_iswhite(s[l]);
}
/*
* Blank lines, and lines containing only the comment leader, are left
* untouched by the formatting. The function returns TRUE in this
* case. It also returns TRUE when a line starts with the end of a comment
* ('e' in comment flags), so that this line is skipped, and not joined to the
* previous line. A new paragraph starts after a blank line, or when the
* comment leader changes -- webb.
*/
#ifdef FEAT_COMMENTS
static int
fmt_check_par(lnum, leader_len, leader_flags, do_comments)
linenr_T lnum;
int *leader_len;
char_u **leader_flags;
int do_comments;
{
char_u *flags = NULL; /* init for GCC */
char_u *ptr;
ptr = ml_get(lnum);
if (do_comments)
*leader_len = get_leader_len(ptr, leader_flags, FALSE, TRUE);
else
*leader_len = 0;
if (*leader_len > 0)
{
/*
* Search for 'e' flag in comment leader flags.
*/
flags = *leader_flags;
while (*flags && *flags != ':' && *flags != COM_END)
++flags;
}
return (*skipwhite(ptr + *leader_len) == NUL
|| (*leader_len > 0 && *flags == COM_END)
|| startPS(lnum, NUL, FALSE));
}
#else
static int
fmt_check_par(lnum)
linenr_T lnum;
{
return (*skipwhite(ml_get(lnum)) == NUL || startPS(lnum, NUL, FALSE));
}
#endif
/*
* Return TRUE when a paragraph starts in line "lnum". Return FALSE when the
* previous line is in the same paragraph. Used for auto-formatting.
*/
int
paragraph_start(lnum)
linenr_T lnum;
{
char_u *p;
#ifdef FEAT_COMMENTS
int leader_len = 0; /* leader len of current line */
char_u *leader_flags = NULL; /* flags for leader of current line */
int next_leader_len; /* leader len of next line */
char_u *next_leader_flags; /* flags for leader of next line */
int do_comments; /* format comments */
#endif
if (lnum <= 1)
return TRUE; /* start of the file */
p = ml_get(lnum - 1);
if (*p == NUL)
return TRUE; /* after empty line */
#ifdef FEAT_COMMENTS
do_comments = has_format_option(FO_Q_COMS);
#endif
if (fmt_check_par(lnum - 1
#ifdef FEAT_COMMENTS
, &leader_len, &leader_flags, do_comments
#endif
))
return TRUE; /* after non-paragraph line */
if (fmt_check_par(lnum
#ifdef FEAT_COMMENTS
, &next_leader_len, &next_leader_flags, do_comments
#endif
))
return TRUE; /* "lnum" is not a paragraph line */
if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1))
return TRUE; /* missing trailing space in previous line. */
if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0))
return TRUE; /* numbered item starts in "lnum". */
#ifdef FEAT_COMMENTS
if (!same_leader(lnum - 1, leader_len, leader_flags,
next_leader_len, next_leader_flags))
return TRUE; /* change of comment leader. */
#endif
return FALSE;
}
#ifdef FEAT_VISUAL
/*
* prepare a few things for block mode yank/delete/tilde
*
* for delete:
* - textlen includes the first/last char to be (partly) deleted
* - start/endspaces is the number of columns that are taken by the
* first/last deleted char minus the number of columns that have to be
* deleted.
* for yank and tilde:
* - textlen includes the first/last char to be wholly yanked
* - start/endspaces is the number of columns of the first/last yanked char
* that are to be yanked.
*/
static void
block_prep(oap, bdp, lnum, is_del)
oparg_T *oap;
struct block_def *bdp;
linenr_T lnum;
int is_del;
{
int incr = 0;
char_u *pend;
char_u *pstart;
char_u *line;
char_u *prev_pstart;
char_u *prev_pend;
bdp->startspaces = 0;
bdp->endspaces = 0;
bdp->textlen = 0;
bdp->start_vcol = 0;
bdp->end_vcol = 0;
#ifdef FEAT_VISUALEXTRA
bdp->is_short = FALSE;
bdp->is_oneChar = FALSE;
bdp->pre_whitesp = 0;
bdp->pre_whitesp_c = 0;
bdp->end_char_vcols = 0;
#endif
bdp->start_char_vcols = 0;
line = ml_get(lnum);
pstart = line;
prev_pstart = line;
while (bdp->start_vcol < oap->start_vcol && *pstart)
{
/* Count a tab for what it's worth (if list mode not on) */
incr = lbr_chartabsize(pstart, (colnr_T)bdp->start_vcol);
bdp->start_vcol += incr;
#ifdef FEAT_VISUALEXTRA
if (vim_iswhite(*pstart))
{
bdp->pre_whitesp += incr;
bdp->pre_whitesp_c++;
}
else
{
bdp->pre_whitesp = 0;
bdp->pre_whitesp_c = 0;
}
#endif
prev_pstart = pstart;
mb_ptr_adv(pstart);
}
bdp->start_char_vcols = incr;
if (bdp->start_vcol < oap->start_vcol) /* line too short */
{
bdp->end_vcol = bdp->start_vcol;
#ifdef FEAT_VISUALEXTRA
bdp->is_short = TRUE;
#endif
if (!is_del || oap->op_type == OP_APPEND)
bdp->endspaces = oap->end_vcol - oap->start_vcol + 1;
}
else
{
/* notice: this converts partly selected Multibyte characters to
* spaces, too. */
bdp->startspaces = bdp->start_vcol - oap->start_vcol;
if (is_del && bdp->startspaces)
bdp->startspaces = bdp->start_char_vcols - bdp->startspaces;
pend = pstart;
bdp->end_vcol = bdp->start_vcol;
if (bdp->end_vcol > oap->end_vcol) /* it's all in one character */
{
#ifdef FEAT_VISUALEXTRA
bdp->is_oneChar = TRUE;
#endif
if (oap->op_type == OP_INSERT)
bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
else if (oap->op_type == OP_APPEND)
{
bdp->startspaces += oap->end_vcol - oap->start_vcol + 1;
bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
}
else
{
bdp->startspaces = oap->end_vcol - oap->start_vcol + 1;
if (is_del && oap->op_type != OP_LSHIFT)
{
/* just putting the sum of those two into
* bdp->startspaces doesn't work for Visual replace,
* so we have to split the tab in two */
bdp->startspaces = bdp->start_char_vcols
- (bdp->start_vcol - oap->start_vcol);
bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
}
}
}
else
{
prev_pend = pend;
while (bdp->end_vcol <= oap->end_vcol && *pend != NUL)
{
/* Count a tab for what it's worth (if list mode not on) */
prev_pend = pend;
incr = lbr_chartabsize_adv(&pend, (colnr_T)bdp->end_vcol);
bdp->end_vcol += incr;
}
if (bdp->end_vcol <= oap->end_vcol
&& (!is_del
|| oap->op_type == OP_APPEND
|| oap->op_type == OP_REPLACE)) /* line too short */
{
#ifdef FEAT_VISUALEXTRA
bdp->is_short = TRUE;
#endif
/* Alternative: include spaces to fill up the block.
* Disadvantage: can lead to trailing spaces when the line is
* short where the text is put */
/* if (!is_del || oap->op_type == OP_APPEND) */
if (oap->op_type == OP_APPEND || virtual_op)
bdp->endspaces = oap->end_vcol - bdp->end_vcol
+ oap->inclusive;
else
bdp->endspaces = 0; /* replace doesn't add characters */
}
else if (bdp->end_vcol > oap->end_vcol)
{
bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
if (!is_del && bdp->endspaces)
{
bdp->endspaces = incr - bdp->endspaces;
if (pend != pstart)
pend = prev_pend;
}
}
}
#ifdef FEAT_VISUALEXTRA
bdp->end_char_vcols = incr;
#endif
if (is_del && bdp->startspaces)
pstart = prev_pstart;
bdp->textlen = (int)(pend - pstart);
}
bdp->textcol = (colnr_T) (pstart - line);
bdp->textstart = pstart;
}
#endif /* FEAT_VISUAL */
#ifdef FEAT_RIGHTLEFT
static void reverse_line __ARGS((char_u *s));
static void
reverse_line(s)
char_u *s;
{
int i, j;
char_u c;
if ((i = (int)STRLEN(s) - 1) <= 0)
return;
curwin->w_cursor.col = i - curwin->w_cursor.col;
for (j = 0; j < i; j++, i--)
{
c = s[i]; s[i] = s[j]; s[j] = c;
}
}
# define RLADDSUBFIX(ptr) if (curwin->w_p_rl) reverse_line(ptr);
#else
# define RLADDSUBFIX(ptr)
#endif
/*
* add or subtract 'Prenum1' from a number in a line
* 'command' is CTRL-A for add, CTRL-X for subtract
*
* return FAIL for failure, OK otherwise
*/
int
do_addsub(command, Prenum1)
int command;
linenr_T Prenum1;
{
int col;
char_u *buf1;
char_u buf2[NUMBUFLEN];
int hex; /* 'X' or 'x': hex; '0': octal */
static int hexupper = FALSE; /* 0xABC */
unsigned long n;
long_u oldn;
char_u *ptr;
int c;
int length = 0; /* character length of the number */
int todel;
int dohex;
int dooct;
int doalp;
int firstdigit;
int negative;
int subtract;
dohex = (vim_strchr(curbuf->b_p_nf, 'x') != NULL); /* "heX" */
dooct = (vim_strchr(curbuf->b_p_nf, 'o') != NULL); /* "Octal" */
doalp = (vim_strchr(curbuf->b_p_nf, 'p') != NULL); /* "alPha" */
ptr = ml_get_curline();
RLADDSUBFIX(ptr);
/*
* First check if we are on a hexadecimal number, after the "0x".
*/
col = curwin->w_cursor.col;
if (dohex)
while (col > 0 && vim_isxdigit(ptr[col]))
--col;
if ( dohex
&& col > 0
&& (ptr[col] == 'X'
|| ptr[col] == 'x')
&& ptr[col - 1] == '0'
&& vim_isxdigit(ptr[col + 1]))
{
/*
* Found hexadecimal number, move to its start.
*/
--col;
}
else
{
/*
* Search forward and then backward to find the start of number.
*/
col = curwin->w_cursor.col;
while (ptr[col] != NUL
&& !vim_isdigit(ptr[col])
&& !(doalp && ASCII_ISALPHA(ptr[col])))
++col;
while (col > 0
&& vim_isdigit(ptr[col - 1])
&& !(doalp && ASCII_ISALPHA(ptr[col])))
--col;
}
/*
* If a number was found, and saving for undo works, replace the number.
*/
firstdigit = ptr[col];
RLADDSUBFIX(ptr);
if ((!VIM_ISDIGIT(firstdigit) && !(doalp && ASCII_ISALPHA(firstdigit)))
|| u_save_cursor() != OK)
{
beep_flush();
return FAIL;
}
/* get ptr again, because u_save() may have changed it */
ptr = ml_get_curline();
RLADDSUBFIX(ptr);
if (doalp && ASCII_ISALPHA(firstdigit))
{
/* decrement or increment alphabetic character */
if (command == Ctrl_X)
{
if (CharOrd(firstdigit) < Prenum1)
{
if (isupper(firstdigit))
firstdigit = 'A';
else
firstdigit = 'a';
}
else
#ifdef EBCDIC
firstdigit = EBCDIC_CHAR_ADD(firstdigit, -Prenum1);
#else
firstdigit -= Prenum1;
#endif
}
else
{
if (26 - CharOrd(firstdigit) - 1 < Prenum1)
{
if (isupper(firstdigit))
firstdigit = 'Z';
else
firstdigit = 'z';
}
else
#ifdef EBCDIC
firstdigit = EBCDIC_CHAR_ADD(firstdigit, Prenum1);
#else
firstdigit += Prenum1;
#endif
}
curwin->w_cursor.col = col;
(void)del_char(FALSE);
ins_char(firstdigit);
}
else
{
negative = FALSE;
if (col > 0 && ptr[col - 1] == '-') /* negative number */
{
--col;
negative = TRUE;
}
/* get the number value (unsigned) */
vim_str2nr(ptr + col, &hex, &length, dooct, dohex, NULL, &n);
/* ignore leading '-' for hex and octal numbers */
if (hex && negative)
{
++col;
--length;
negative = FALSE;
}
/* add or subtract */
subtract = FALSE;
if (command == Ctrl_X)
subtract ^= TRUE;
if (negative)
subtract ^= TRUE;
oldn = n;
if (subtract)
n -= (unsigned long)Prenum1;
else
n += (unsigned long)Prenum1;
/* handle wraparound for decimal numbers */
if (!hex)
{
if (subtract)
{
if (n > oldn)
{
n = 1 + (n ^ (unsigned long)-1);
negative ^= TRUE;
}
}
else /* add */
{
if (n < oldn)
{
n = (n ^ (unsigned long)-1);
negative ^= TRUE;
}
}
if (n == 0)
negative = FALSE;
}
/*
* Delete the old number.
*/
curwin->w_cursor.col = col;
todel = length;
c = gchar_cursor();
/*
* Don't include the '-' in the length, only the length of the part
* after it is kept the same.
*/
if (c == '-')
--length;
while (todel-- > 0)
{
if (c < 0x100 && isalpha(c))
{
if (isupper(c))
hexupper = TRUE;
else
hexupper = FALSE;
}
/* del_char() will mark line needing displaying */
(void)del_char(FALSE);
c = gchar_cursor();
}
/*
* Prepare the leading characters in buf1[].
* When there are many leading zeros it could be very long. Allocate
* a bit too much.
*/
buf1 = alloc((unsigned)length + NUMBUFLEN);
if (buf1 == NULL)
return FAIL;
ptr = buf1;
if (negative)
{
*ptr++ = '-';
}
if (hex)
{
*ptr++ = '0';
--length;
}
if (hex == 'x' || hex == 'X')
{
*ptr++ = hex;
--length;
}
/*
* Put the number characters in buf2[].
*/
if (hex == 0)
sprintf((char *)buf2, "%lu", n);
else if (hex == '0')
sprintf((char *)buf2, "%lo", n);
else if (hex && hexupper)
sprintf((char *)buf2, "%lX", n);
else
sprintf((char *)buf2, "%lx", n);
length -= (int)STRLEN(buf2);
/*
* Adjust number of zeros to the new number of digits, so the
* total length of the number remains the same.
* Don't do this when
* the result may look like an octal number.
*/
if (firstdigit == '0' && !(dooct && hex == 0))
while (length-- > 0)
*ptr++ = '0';
*ptr = NUL;
STRCAT(buf1, buf2);
ins_str(buf1); /* insert the new number */
vim_free(buf1);
}
--curwin->w_cursor.col;
curwin->w_set_curswant = TRUE;
#ifdef FEAT_RIGHTLEFT
ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);
RLADDSUBFIX(ptr);
#endif
return OK;
}
#ifdef FEAT_VIMINFO
int
read_viminfo_register(virp, force)
vir_T *virp;
int force;
{
int eof;
int do_it = TRUE;
int size;
int limit;
int i;
int set_prev = FALSE;
char_u *str;
char_u **array = NULL;
/* We only get here (hopefully) if line[0] == '"' */
str = virp->vir_line + 1;
/* If the line starts with "" this is the y_previous register. */
if (*str == '"')
{
set_prev = TRUE;
str++;
}
if (!ASCII_ISALNUM(*str) && *str != '-')
{
if (viminfo_error("E577: ", _("Illegal register name"), virp->vir_line))
return TRUE; /* too many errors, pretend end-of-file */
do_it = FALSE;
}
get_yank_register(*str++, FALSE);
if (!force && y_current->y_array != NULL)
do_it = FALSE;
if (*str == '@')
{
/* "x@: register x used for @@ */
if (force || execreg_lastc == NUL)
execreg_lastc = str[-1];
}
size = 0;
limit = 100; /* Optimized for registers containing <= 100 lines */
if (do_it)
{
if (set_prev)
y_previous = y_current;
vim_free(y_current->y_array);
array = y_current->y_array =
(char_u **)alloc((unsigned)(limit * sizeof(char_u *)));
str = skipwhite(skiptowhite(str));
if (STRNCMP(str, "CHAR", 4) == 0)
y_current->y_type = MCHAR;
#ifdef FEAT_VISUAL
else if (STRNCMP(str, "BLOCK", 5) == 0)
y_current->y_type = MBLOCK;
#endif
else
y_current->y_type = MLINE;
/* get the block width; if it's missing we get a zero, which is OK */
str = skipwhite(skiptowhite(str));
#ifdef FEAT_VISUAL
y_current->y_width = getdigits(&str);
#else
(void)getdigits(&str);
#endif
}
while (!(eof = viminfo_readline(virp))
&& (virp->vir_line[0] == TAB || virp->vir_line[0] == '<'))
{
if (do_it)
{
if (size >= limit)
{
y_current->y_array = (char_u **)
alloc((unsigned)(limit * 2 * sizeof(char_u *)));
for (i = 0; i < limit; i++)
y_current->y_array[i] = array[i];
vim_free(array);
limit *= 2;
array = y_current->y_array;
}
str = viminfo_readstring(virp, 1, TRUE);
if (str != NULL)
array[size++] = str;
else
do_it = FALSE;
}
}
if (do_it)
{
if (size == 0)
{
vim_free(array);
y_current->y_array = NULL;
}
else if (size < limit)
{
y_current->y_array =
(char_u **)alloc((unsigned)(size * sizeof(char_u *)));
for (i = 0; i < size; i++)
y_current->y_array[i] = array[i];
vim_free(array);
}
y_current->y_size = size;
}
return eof;
}
void
write_viminfo_registers(fp)
FILE *fp;
{
int i, j;
char_u *type;
char_u c;
int num_lines;
int max_num_lines;
int max_kbyte;
long len;
fputs(_("\n# Registers:\n"), fp);
/* Get '<' value, use old '"' value if '<' is not found. */
max_num_lines = get_viminfo_parameter('<');
if (max_num_lines < 0)
max_num_lines = get_viminfo_parameter('"');
if (max_num_lines == 0)
return;
max_kbyte = get_viminfo_parameter('s');
if (max_kbyte == 0)
return;
for (i = 0; i < NUM_REGISTERS; i++)
{
if (y_regs[i].y_array == NULL)
continue;
#ifdef FEAT_CLIPBOARD
/* Skip '*'/'+' register, we don't want them back next time */
if (i == STAR_REGISTER || i == PLUS_REGISTER)
continue;
#endif
#ifdef FEAT_DND
/* Neither do we want the '~' register */
if (i == TILDE_REGISTER)
continue;
#endif
/* Skip empty registers. */
num_lines = y_regs[i].y_size;
if (num_lines == 0
|| (num_lines == 1 && y_regs[i].y_type == MCHAR
&& *y_regs[i].y_array[0] == NUL))
continue;
if (max_kbyte > 0)
{
/* Skip register if there is more text than the maximum size. */
len = 0;
for (j = 0; j < num_lines; j++)
len += (long)STRLEN(y_regs[i].y_array[j]) + 1L;
if (len > (long)max_kbyte * 1024L)
continue;
}
switch (y_regs[i].y_type)
{
case MLINE:
type = (char_u *)"LINE";
break;
case MCHAR:
type = (char_u *)"CHAR";
break;
#ifdef FEAT_VISUAL
case MBLOCK:
type = (char_u *)"BLOCK";
break;
#endif
default:
sprintf((char *)IObuff, _("E574: Unknown register type %d"),
y_regs[i].y_type);
emsg(IObuff);
type = (char_u *)"LINE";
break;
}
if (y_previous == &y_regs[i])
fprintf(fp, "\"");
c = get_register_name(i);
fprintf(fp, "\"%c", c);
if (c == execreg_lastc)
fprintf(fp, "@");
fprintf(fp, "\t%s\t%d\n", type,
#ifdef FEAT_VISUAL
(int)y_regs[i].y_width
#else
0
#endif
);
/* If max_num_lines < 0, then we save ALL the lines in the register */
if (max_num_lines > 0 && num_lines > max_num_lines)
num_lines = max_num_lines;
for (j = 0; j < num_lines; j++)
{
putc('\t', fp);
viminfo_writestring(fp, y_regs[i].y_array[j]);
}
}
}
#endif /* FEAT_VIMINFO */
#if defined(FEAT_CLIPBOARD) || defined(PROTO)
/*
* SELECTION / PRIMARY ('*')
*
* Text selection stuff that uses the GUI selection register '*'. When using a
* GUI this may be text from another window, otherwise it is the last text we
* had highlighted with VIsual mode. With mouse support, clicking the middle
* button performs the paste, otherwise you will need to do <"*p>. "
* If not under X, it is synonymous with the clipboard register '+'.
*
* X CLIPBOARD ('+')
*
* Text selection stuff that uses the GUI clipboard register '+'.
* Under X, this matches the standard cut/paste buffer CLIPBOARD selection.
* It will be used for unnamed cut/pasting is 'clipboard' contains "unnamed",
* otherwise you will need to do <"+p>. "
* If not under X, it is synonymous with the selection register '*'.
*/
/*
* Routine to export any final X selection we had to the environment
* so that the text is still available after vim has exited. X selections
* only exist while the owning application exists, so we write to the
* permanent (while X runs) store CUT_BUFFER0.
* Dump the CLIPBOARD selection if we own it (it's logically the more
* 'permanent' of the two), otherwise the PRIMARY one.
* For now, use a hard-coded sanity limit of 1Mb of data.
*/
#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
void
x11_export_final_selection()
{
Display *dpy;
char_u *str = NULL;
long_u len = 0;
int motion_type = -1;
# ifdef FEAT_GUI
if (gui.in_use)
dpy = X_DISPLAY;
else
# endif
# ifdef FEAT_XCLIPBOARD
dpy = xterm_dpy;
# else
return;
# endif
/* Get selection to export */
if (clip_plus.owned)
motion_type = clip_convert_selection(&str, &len, &clip_plus);
else if (clip_star.owned)
motion_type = clip_convert_selection(&str, &len, &clip_star);
/* Check it's OK */
if (dpy != NULL && str != NULL && motion_type >= 0
&& len < 1024*1024 && len > 0)
{
#ifdef FEAT_MBYTE
/* The CUT_BUFFER0 is supposed to always contain latin1. Convert from
* 'enc' when it is a multi-byte encoding. When 'enc' is an 8-bit
* encoding conversion usually doesn't work, so keep the text as-is.
*/
if (has_mbyte)
{
vimconv_T vc;
vc.vc_type = CONV_NONE;
if (convert_setup(&vc, p_enc, (char_u *)"latin1") == OK)
{
int intlen = len;
char_u *conv_str;
conv_str = string_convert(&vc, str, &intlen);
len = intlen;
if (conv_str != NULL)
{
vim_free(str);
str = conv_str;
}
convert_setup(&vc, NULL, NULL);
}
}
#endif
XStoreBuffer(dpy, (char *)str, (int)len, 0);
XFlush(dpy);
}
vim_free(str);
}
#endif
void
clip_free_selection(cbd)
VimClipboard *cbd;
{
struct yankreg *y_ptr = y_current;
if (cbd == &clip_plus)
y_current = &y_regs[PLUS_REGISTER];
else
y_current = &y_regs[STAR_REGISTER];
free_yank_all();
y_current->y_size = 0;
y_current = y_ptr;
}
/*
* Get the selected text and put it in the gui selection register '*' or '+'.
*/
void
clip_get_selection(cbd)
VimClipboard *cbd;
{
struct yankreg *old_y_previous, *old_y_current;
pos_T old_cursor;
#ifdef FEAT_VISUAL
pos_T old_visual;
int old_visual_mode;
#endif
colnr_T old_curswant;
int old_set_curswant;
pos_T old_op_start, old_op_end;
oparg_T oa;
cmdarg_T ca;
if (cbd->owned)
{
if ((cbd == &clip_plus && y_regs[PLUS_REGISTER].y_array != NULL)
|| (cbd == &clip_star && y_regs[STAR_REGISTER].y_array != NULL))
return;
/* Get the text between clip_star.start & clip_star.end */
old_y_previous = y_previous;
old_y_current = y_current;
old_cursor = curwin->w_cursor;
old_curswant = curwin->w_curswant;
old_set_curswant = curwin->w_set_curswant;
old_op_start = curbuf->b_op_start;
old_op_end = curbuf->b_op_end;
#ifdef FEAT_VISUAL
old_visual = VIsual;
old_visual_mode = VIsual_mode;
#endif
clear_oparg(&oa);
oa.regname = (cbd == &clip_plus ? '+' : '*');
oa.op_type = OP_YANK;
vim_memset(&ca, 0, sizeof(ca));
ca.oap = &oa;
ca.cmdchar = 'y';
ca.count1 = 1;
ca.retval = CA_NO_ADJ_OP_END;
do_pending_operator(&ca, 0, TRUE);
y_previous = old_y_previous;
y_current = old_y_current;
curwin->w_cursor = old_cursor;
changed_cline_bef_curs(); /* need to update w_virtcol et al */
curwin->w_curswant = old_curswant;
curwin->w_set_curswant = old_set_curswant;
curbuf->b_op_start = old_op_start;
curbuf->b_op_end = old_op_end;
#ifdef FEAT_VISUAL
VIsual = old_visual;
VIsual_mode = old_visual_mode;
#endif
}
else
{
clip_free_selection(cbd);
/* Try to get selected text from another window */
clip_gen_request_selection(cbd);
}
}
/*
* Convert from the GUI selection string into the '*'/'+' register.
*/
void
clip_yank_selection(type, str, len, cbd)
int type;
char_u *str;
long len;
VimClipboard *cbd;
{
struct yankreg *y_ptr;
if (cbd == &clip_plus)
y_ptr = &y_regs[PLUS_REGISTER];
else
y_ptr = &y_regs[STAR_REGISTER];
clip_free_selection(cbd);
str_to_reg(y_ptr, type, str, len, 0L);
}
/*
* Convert the '*'/'+' register into a GUI selection string returned in *str
* with length *len.
* Returns the motion type, or -1 for failure.
*/
int
clip_convert_selection(str, len, cbd)
char_u **str;
long_u *len;
VimClipboard *cbd;
{
char_u *p;
int lnum;
int i, j;
int_u eolsize;
struct yankreg *y_ptr;
if (cbd == &clip_plus)
y_ptr = &y_regs[PLUS_REGISTER];
else
y_ptr = &y_regs[STAR_REGISTER];
#ifdef USE_CRNL
eolsize = 2;
#else
eolsize = 1;
#endif
*str = NULL;
*len = 0;
if (y_ptr->y_array == NULL)
return -1;
for (i = 0; i < y_ptr->y_size; i++)
*len += (long_u)STRLEN(y_ptr->y_array[i]) + eolsize;
/*
* Don't want newline character at end of last line if we're in MCHAR mode.
*/
if (y_ptr->y_type == MCHAR && *len >= eolsize)
*len -= eolsize;
p = *str = lalloc(*len + 1, TRUE); /* add one to avoid zero */
if (p == NULL)
return -1;
lnum = 0;
for (i = 0, j = 0; i < (int)*len; i++, j++)
{
if (y_ptr->y_array[lnum][j] == '\n')
p[i] = NUL;
else if (y_ptr->y_array[lnum][j] == NUL)
{
#ifdef USE_CRNL
p[i++] = '\r';
#endif
#ifdef USE_CR
p[i] = '\r';
#else
p[i] = '\n';
#endif
lnum++;
j = -1;
}
else
p[i] = y_ptr->y_array[lnum][j];
}
return y_ptr->y_type;
}
# if defined(FEAT_VISUAL) || defined(FEAT_EVAL)
/*
* If we have written to a clipboard register, send the text to the clipboard.
*/
static void
may_set_selection()
{
if (y_current == &(y_regs[STAR_REGISTER]) && clip_star.available)
{
clip_own_selection(&clip_star);
clip_gen_set_selection(&clip_star);
}
else if (y_current == &(y_regs[PLUS_REGISTER]) && clip_plus.available)
{
clip_own_selection(&clip_plus);
clip_gen_set_selection(&clip_plus);
}
}
# endif
#endif /* FEAT_CLIPBOARD || PROTO */
#if defined(FEAT_DND) || defined(PROTO)
/*
* Replace the contents of the '~' register with str.
*/
void
dnd_yank_drag_data(str, len)
char_u *str;
long len;
{
struct yankreg *curr;
curr = y_current;
y_current = &y_regs[TILDE_REGISTER];
free_yank_all();
str_to_reg(y_current, MCHAR, str, len, 0L);
y_current = curr;
}
#endif
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return the type of a register.
* Used for getregtype()
* Returns MAUTO for error.
*/
char_u
get_reg_type(regname, reglen)
int regname;
long *reglen;
{
switch (regname)
{
case '%': /* file name */
case '#': /* alternate file name */
case '=': /* expression */
case ':': /* last command line */
case '/': /* last search-pattern */
case '.': /* last inserted text */
#ifdef FEAT_SEARCHPATH
case Ctrl_F: /* Filename under cursor */
case Ctrl_P: /* Path under cursor, expand via "path" */
#endif
case Ctrl_W: /* word under cursor */
case Ctrl_A: /* WORD (mnemonic All) under cursor */
case '_': /* black hole: always empty */
return MCHAR;
}
#ifdef FEAT_CLIPBOARD
regname = may_get_selection(regname);
#endif
/* Should we check for a valid name? */
get_yank_register(regname, FALSE);
if (y_current->y_array != NULL)
{
#ifdef FEAT_VISUAL
if (reglen != NULL && y_current->y_type == MBLOCK)
*reglen = y_current->y_width;
#endif
return y_current->y_type;
}
return MAUTO;
}
/*
* Return the contents of a register as a single allocated string.
* Used for "@r" in expressions and for getreg().
* Returns NULL for error.
*/
char_u *
get_reg_contents(regname, allowexpr, expr_src)
int regname;
int allowexpr; /* allow "=" register */
int expr_src; /* get expression for "=" register */
{
long i;
char_u *retval;
int allocated;
long len;
/* Don't allow using an expression register inside an expression */
if (regname == '=')
{
if (allowexpr)
{
if (expr_src)
return get_expr_line_src();
return get_expr_line();
}
return NULL;
}
if (regname == '@') /* "@@" is used for unnamed register */
regname = '"';
/* check for valid regname */
if (regname != NUL && !valid_yank_reg(regname, FALSE))
return NULL;
#ifdef FEAT_CLIPBOARD
regname = may_get_selection(regname);
#endif
if (get_spec_reg(regname, &retval, &allocated, FALSE))
{
if (retval == NULL)
return NULL;
if (!allocated)
retval = vim_strsave(retval);
return retval;
}
get_yank_register(regname, FALSE);
if (y_current->y_array == NULL)
return NULL;
/*
* Compute length of resulting string.
*/
len = 0;
for (i = 0; i < y_current->y_size; ++i)
{
len += (long)STRLEN(y_current->y_array[i]);
/*
* Insert a newline between lines and after last line if
* y_type is MLINE.
*/
if (y_current->y_type == MLINE || i < y_current->y_size - 1)
++len;
}
retval = lalloc(len + 1, TRUE);
/*
* Copy the lines of the yank register into the string.
*/
if (retval != NULL)
{
len = 0;
for (i = 0; i < y_current->y_size; ++i)
{
STRCPY(retval + len, y_current->y_array[i]);
len += (long)STRLEN(retval + len);
/*
* Insert a NL between lines and after the last line if y_type is
* MLINE.
*/
if (y_current->y_type == MLINE || i < y_current->y_size - 1)
retval[len++] = '\n';
}
retval[len] = NUL;
}
return retval;
}
/*
* Store string "str" in register "name".
* "maxlen" is the maximum number of bytes to use, -1 for all bytes.
* If "must_append" is TRUE, always append to the register. Otherwise append
* if "name" is an uppercase letter.
* Note: "maxlen" and "must_append" don't work for the "/" register.
* Careful: 'str' is modified, you may have to use a copy!
* If "str" ends in '\n' or '\r', use linewise, otherwise use characterwise.
*/
void
write_reg_contents(name, str, maxlen, must_append)
int name;
char_u *str;
int maxlen;
int must_append;
{
write_reg_contents_ex(name, str, maxlen, must_append, MAUTO, 0L);
}
void
write_reg_contents_ex(name, str, maxlen, must_append, yank_type, block_len)
int name;
char_u *str;
int maxlen;
int must_append;
int yank_type;
long block_len;
{
struct yankreg *old_y_previous, *old_y_current;
long len;
if (maxlen >= 0)
len = maxlen;
else
len = (long)STRLEN(str);
/* Special case: '/' search pattern */
if (name == '/')
{
set_last_search_pat(str, RE_SEARCH, TRUE, TRUE);
return;
}
#ifdef FEAT_EVAL
if (name == '=')
{
char_u *p, *s;
p = vim_strnsave(str, (int)len);
if (p == NULL)
return;
if (must_append)
{
s = concat_str(get_expr_line_src(), p);
vim_free(p);
p = s;
}
set_expr_line(p);
return;
}
#endif
if (!valid_yank_reg(name, TRUE)) /* check for valid reg name */
{
emsg_invreg(name);
return;
}
if (name == '_') /* black hole: nothing to do */
return;
/* Don't want to change the current (unnamed) register */
old_y_previous = y_previous;
old_y_current = y_current;
get_yank_register(name, TRUE);
if (!y_append && !must_append)
free_yank_all();
#ifndef FEAT_VISUAL
/* Just in case - make sure we don't use MBLOCK */
if (yank_type == MBLOCK)
yank_type = MAUTO;
#endif
str_to_reg(y_current, yank_type, str, len, block_len);
# ifdef FEAT_CLIPBOARD
/* Send text of clipboard register to the clipboard. */
may_set_selection();
# endif
/* ':let @" = "val"' should change the meaning of the "" register */
if (name != '"')
y_previous = old_y_previous;
y_current = old_y_current;
}
#endif /* FEAT_EVAL */
#if defined(FEAT_CLIPBOARD) || defined(FEAT_EVAL)
/*
* Put a string into a register. When the register is not empty, the string
* is appended.
*/
static void
str_to_reg(y_ptr, yank_type, str, len, blocklen)
struct yankreg *y_ptr; /* pointer to yank register */
int yank_type; /* MCHAR, MLINE, MBLOCK, MAUTO */
char_u *str; /* string to put in register */
long len; /* length of string */
long blocklen; /* width of Visual block */
{
int type; /* MCHAR, MLINE or MBLOCK */
int lnum;
long start;
long i;
int extra;
int newlines; /* number of lines added */
int extraline = 0; /* extra line at the end */
int append = FALSE; /* append to last line in register */
char_u *s;
char_u **pp;
#ifdef FEAT_VISUAL
long maxlen;
#endif
if (y_ptr->y_array == NULL) /* NULL means empty register */
y_ptr->y_size = 0;
if (yank_type == MAUTO)
type = ((len > 0 && (str[len - 1] == NL || str[len - 1] == CAR))
? MLINE : MCHAR);
else
type = yank_type;
/*
* Count the number of lines within the string
*/
newlines = 0;
for (i = 0; i < len; i++)
if (str[i] == '\n')
++newlines;
if (type == MCHAR || len == 0 || str[len - 1] != '\n')
{
extraline = 1;
++newlines; /* count extra newline at the end */
}
if (y_ptr->y_size > 0 && y_ptr->y_type == MCHAR)
{
append = TRUE;
--newlines; /* uncount newline when appending first line */
}
/*
* Allocate an array to hold the pointers to the new register lines.
* If the register was not empty, move the existing lines to the new array.
*/
pp = (char_u **)lalloc_clear((y_ptr->y_size + newlines)
* sizeof(char_u *), TRUE);
if (pp == NULL) /* out of memory */
return;
for (lnum = 0; lnum < y_ptr->y_size; ++lnum)
pp[lnum] = y_ptr->y_array[lnum];
vim_free(y_ptr->y_array);
y_ptr->y_array = pp;
#ifdef FEAT_VISUAL
maxlen = 0;
#endif
/*
* Find the end of each line and save it into the array.
*/
for (start = 0; start < len + extraline; start += i + 1)
{
for (i = start; i < len; ++i) /* find the end of the line */
if (str[i] == '\n')
break;
i -= start; /* i is now length of line */
#ifdef FEAT_VISUAL
if (i > maxlen)
maxlen = i;
#endif
if (append)
{
--lnum;
extra = (int)STRLEN(y_ptr->y_array[lnum]);
}
else
extra = 0;
s = alloc((unsigned)(i + extra + 1));
if (s == NULL)
break;
if (extra)
mch_memmove(s, y_ptr->y_array[lnum], (size_t)extra);
if (append)
vim_free(y_ptr->y_array[lnum]);
if (i)
mch_memmove(s + extra, str + start, (size_t)i);
extra += i;
s[extra] = NUL;
y_ptr->y_array[lnum++] = s;
while (--extra >= 0)
{
if (*s == NUL)
*s = '\n'; /* replace NUL with newline */
++s;
}
append = FALSE; /* only first line is appended */
}
y_ptr->y_type = type;
y_ptr->y_size = lnum;
# ifdef FEAT_VISUAL
if (type == MBLOCK)
y_ptr->y_width = (blocklen < 0 ? maxlen - 1 : blocklen);
else
y_ptr->y_width = 0;
# endif
}
#endif /* FEAT_CLIPBOARD || FEAT_EVAL || PROTO */
void
clear_oparg(oap)
oparg_T *oap;
{
vim_memset(oap, 0, sizeof(oparg_T));
}
static long line_count_info __ARGS((char_u *line, long *wc, long *cc, long limit, int eol_size));
/*
* Count the number of bytes, characters and "words" in a line.
*
* "Words" are counted by looking for boundaries between non-space and
* space characters. (it seems to produce results that match 'wc'.)
*
* Return value is byte count; word count for the line is added to "*wc".
* Char count is added to "*cc".
*
* The function will only examine the first "limit" characters in the
* line, stopping if it encounters an end-of-line (NUL byte). In that
* case, eol_size will be added to the character count to account for
* the size of the EOL character.
*/
static long
line_count_info(line, wc, cc, limit, eol_size)
char_u *line;
long *wc;
long *cc;
long limit;
int eol_size;
{
long i;
long words = 0;
long chars = 0;
int is_word = 0;
for (i = 0; line[i] && i < limit; )
{
if (is_word)
{
if (vim_isspace(line[i]))
{
words++;
is_word = 0;
}
}
else if (!vim_isspace(line[i]))
is_word = 1;
++chars;
#ifdef FEAT_MBYTE
i += (*mb_ptr2len)(line + i);
#else
++i;
#endif
}
if (is_word)
words++;
*wc += words;
/* Add eol_size if the end of line was reached before hitting limit. */
if (i < limit && line[i] == NUL)
{
i += eol_size;
chars += eol_size;
}
*cc += chars;
return i;
}
/*
* Give some info about the position of the cursor (for "g CTRL-G").
* In Visual mode, give some info about the selected region. (In this case,
* the *_count_cursor variables store running totals for the selection.)
*/
void
cursor_pos_info()
{
char_u *p;
char_u buf1[50];
char_u buf2[40];
linenr_T lnum;
long byte_count = 0;
long byte_count_cursor = 0;
long char_count = 0;
long char_count_cursor = 0;
long word_count = 0;
long word_count_cursor = 0;
int eol_size;
long last_check = 100000L;
#ifdef FEAT_VISUAL
long line_count_selected = 0;
pos_T min_pos, max_pos;
oparg_T oparg;
struct block_def bd;
#endif
/*
* Compute the length of the file in characters.
*/
if (curbuf->b_ml.ml_flags & ML_EMPTY)
{
MSG(_(no_lines_msg));
}
else
{
if (get_fileformat(curbuf) == EOL_DOS)
eol_size = 2;
else
eol_size = 1;
#ifdef FEAT_VISUAL
if (VIsual_active)
{
if (lt(VIsual, curwin->w_cursor))
{
min_pos = VIsual;
max_pos = curwin->w_cursor;
}
else
{
min_pos = curwin->w_cursor;
max_pos = VIsual;
}
if (*p_sel == 'e' && max_pos.col > 0)
--max_pos.col;
if (VIsual_mode == Ctrl_V)
{
#ifdef FEAT_LINEBREAK
char_u * saved_sbr = p_sbr;
/* Make 'sbr' empty for a moment to get the correct size. */
p_sbr = empty_option;
#endif
oparg.is_VIsual = 1;
oparg.block_mode = TRUE;
oparg.op_type = OP_NOP;
getvcols(curwin, &min_pos, &max_pos,
&oparg.start_vcol, &oparg.end_vcol);
#ifdef FEAT_LINEBREAK
p_sbr = saved_sbr;
#endif
if (curwin->w_curswant == MAXCOL)
oparg.end_vcol = MAXCOL;
/* Swap the start, end vcol if needed */
if (oparg.end_vcol < oparg.start_vcol)
{
oparg.end_vcol += oparg.start_vcol;
oparg.start_vcol = oparg.end_vcol - oparg.start_vcol;
oparg.end_vcol -= oparg.start_vcol;
}
}
line_count_selected = max_pos.lnum - min_pos.lnum + 1;
}
#endif
for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
{
/* Check for a CTRL-C every 100000 characters. */
if (byte_count > last_check)
{
ui_breakcheck();
if (got_int)
return;
last_check = byte_count + 100000L;
}
#ifdef FEAT_VISUAL
/* Do extra processing for VIsual mode. */
if (VIsual_active
&& lnum >= min_pos.lnum && lnum <= max_pos.lnum)
{
char_u *s = NULL;
long len = 0L;
switch (VIsual_mode)
{
case Ctrl_V:
# ifdef FEAT_VIRTUALEDIT
virtual_op = virtual_active();
# endif
block_prep(&oparg, &bd, lnum, 0);
# ifdef FEAT_VIRTUALEDIT
virtual_op = MAYBE;
# endif
s = bd.textstart;
len = (long)bd.textlen;
break;
case 'V':
s = ml_get(lnum);
len = MAXCOL;
break;
case 'v':
{
colnr_T start_col = (lnum == min_pos.lnum)
? min_pos.col : 0;
colnr_T end_col = (lnum == max_pos.lnum)
? max_pos.col - start_col + 1 : MAXCOL;
s = ml_get(lnum) + start_col;
len = end_col;
}
break;
}
if (s != NULL)
{
byte_count_cursor += line_count_info(s, &word_count_cursor,
&char_count_cursor, len, eol_size);
if (lnum == curbuf->b_ml.ml_line_count
&& !curbuf->b_p_eol
&& curbuf->b_p_bin
&& (long)STRLEN(s) < len)
byte_count_cursor -= eol_size;
}
}
else
#endif
{
/* In non-visual mode, check for the line the cursor is on */
if (lnum == curwin->w_cursor.lnum)
{
word_count_cursor += word_count;
char_count_cursor += char_count;
byte_count_cursor = byte_count +
line_count_info(ml_get(lnum),
&word_count_cursor, &char_count_cursor,
(long)(curwin->w_cursor.col + 1), eol_size);
}
}
/* Add to the running totals */
byte_count += line_count_info(ml_get(lnum), &word_count,
&char_count, (long)MAXCOL, eol_size);
}
/* Correction for when last line doesn't have an EOL. */
if (!curbuf->b_p_eol && curbuf->b_p_bin)
byte_count -= eol_size;
#ifdef FEAT_VISUAL
if (VIsual_active)
{
if (VIsual_mode == Ctrl_V && curwin->w_curswant < MAXCOL)
{
getvcols(curwin, &min_pos, &max_pos, &min_pos.col,
&max_pos.col);
vim_snprintf((char *)buf1, sizeof(buf1), _("%ld Cols; "),
(long)(oparg.end_vcol - oparg.start_vcol + 1));
}
else
buf1[0] = NUL;
if (char_count_cursor == byte_count_cursor
&& char_count == byte_count)
vim_snprintf((char *)IObuff, IOSIZE,
_("Selected %s%ld of %ld Lines; %ld of %ld Words; %ld of %ld Bytes"),
buf1, line_count_selected,
(long)curbuf->b_ml.ml_line_count,
word_count_cursor, word_count,
byte_count_cursor, byte_count);
else
vim_snprintf((char *)IObuff, IOSIZE,
_("Selected %s%ld of %ld Lines; %ld of %ld Words; %ld of %ld Chars; %ld of %ld Bytes"),
buf1, line_count_selected,
(long)curbuf->b_ml.ml_line_count,
word_count_cursor, word_count,
char_count_cursor, char_count,
byte_count_cursor, byte_count);
}
else
#endif
{
p = ml_get_curline();
validate_virtcol();
col_print(buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1,
(int)curwin->w_virtcol + 1);
col_print(buf2, sizeof(buf2), (int)STRLEN(p), linetabsize(p));
if (char_count_cursor == byte_count_cursor
&& char_count == byte_count)
vim_snprintf((char *)IObuff, IOSIZE,
_("Col %s of %s; Line %ld of %ld; Word %ld of %ld; Byte %ld of %ld"),
(char *)buf1, (char *)buf2,
(long)curwin->w_cursor.lnum,
(long)curbuf->b_ml.ml_line_count,
word_count_cursor, word_count,
byte_count_cursor, byte_count);
else
vim_snprintf((char *)IObuff, IOSIZE,
_("Col %s of %s; Line %ld of %ld; Word %ld of %ld; Char %ld of %ld; Byte %ld of %ld"),
(char *)buf1, (char *)buf2,
(long)curwin->w_cursor.lnum,
(long)curbuf->b_ml.ml_line_count,
word_count_cursor, word_count,
char_count_cursor, char_count,
byte_count_cursor, byte_count);
}
#ifdef FEAT_MBYTE
byte_count = bomb_size();
if (byte_count > 0)
sprintf((char *)IObuff + STRLEN(IObuff), _("(+%ld for BOM)"),
byte_count);
#endif
/* Don't shorten this message, the user asked for it. */
p = p_shm;
p_shm = (char_u *)"";
msg(IObuff);
p_shm = p;
}
}
| zyz2011-vim | src/ops.c | C | gpl2 | 167,520 |
/* 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.
* Changes for Unix by David Leonard.
*
* This consists of four parts:
* 1. Python interpreter main program
* 2. Python output stream: writes output via [e]msg().
* 3. Implementation of the Vim module for Python
* 4. Utility functions for handling the interface between Vim and Python.
*/
#include "vim.h"
#include <limits.h>
/* Python.h defines _POSIX_THREADS itself (if needed) */
#ifdef _POSIX_THREADS
# undef _POSIX_THREADS
#endif
#if defined(_WIN32) && defined(HAVE_FCNTL_H)
# undef HAVE_FCNTL_H
#endif
#ifdef _DEBUG
# undef _DEBUG
#endif
#ifdef HAVE_STDARG_H
# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
#endif
#ifdef _POSIX_C_SOURCE
# undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
#endif
#ifdef _XOPEN_SOURCE
# undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
#endif
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#if defined(MACOS) && !defined(MACOS_X_UNIX)
# include "macglue.h"
# include <CodeFragments.h>
#endif
#undef main /* Defined in python.h - aargh */
#undef HAVE_FCNTL_H /* Clash with os_win32.h */
static void init_structs(void);
/* No-op conversion functions, use with care! */
#define PyString_AsBytes(obj) (obj)
#define PyString_FreeBytes(obj)
#if !defined(FEAT_PYTHON) && defined(PROTO)
/* Use this to be able to generate prototypes without python being used. */
# define PyObject Py_ssize_t
# define PyThreadState Py_ssize_t
# define PyTypeObject Py_ssize_t
struct PyMethodDef { Py_ssize_t a; };
# define PySequenceMethods Py_ssize_t
#endif
#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
# define PyInt Py_ssize_t
# define PyInquiry lenfunc
# define PyIntArgFunc ssizeargfunc
# define PyIntIntArgFunc ssizessizeargfunc
# define PyIntObjArgProc ssizeobjargproc
# define PyIntIntObjArgProc ssizessizeobjargproc
# define Py_ssize_t_fmt "n"
#else
# define PyInt int
# define PyInquiry inquiry
# define PyIntArgFunc intargfunc
# define PyIntIntArgFunc intintargfunc
# define PyIntObjArgProc intobjargproc
# define PyIntIntObjArgProc intintobjargproc
# define Py_ssize_t_fmt "i"
#endif
/* Parser flags */
#define single_input 256
#define file_input 257
#define eval_input 258
#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
/* Python 2.3: can invoke ":python" recursively. */
# define PY_CAN_RECURSE
#endif
# if defined(DYNAMIC_PYTHON) || defined(PROTO)
# ifndef DYNAMIC_PYTHON
# define HINSTANCE long_u /* for generating prototypes */
# endif
# ifndef WIN3264
# include <dlfcn.h>
# define FARPROC void*
# define HINSTANCE void*
# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
# define load_dll(n) dlopen((n), RTLD_LAZY)
# else
# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
# endif
# define close_dll dlclose
# define symbol_from_dll dlsym
# else
# define load_dll vimLoadLib
# define close_dll FreeLibrary
# define symbol_from_dll GetProcAddress
# endif
/* This makes if_python.c compile without warnings against Python 2.5
* on Win32 and Win64. */
# undef PyRun_SimpleString
# undef PyArg_Parse
# undef PyArg_ParseTuple
# undef Py_BuildValue
# undef Py_InitModule4
# undef Py_InitModule4_64
/*
* Wrapper defines
*/
# define PyArg_Parse dll_PyArg_Parse
# define PyArg_ParseTuple dll_PyArg_ParseTuple
# define PyMem_Free dll_PyMem_Free
# define PyDict_SetItemString dll_PyDict_SetItemString
# define PyErr_BadArgument dll_PyErr_BadArgument
# define PyErr_Clear dll_PyErr_Clear
# define PyErr_NoMemory dll_PyErr_NoMemory
# define PyErr_Occurred dll_PyErr_Occurred
# define PyErr_SetNone dll_PyErr_SetNone
# define PyErr_SetString dll_PyErr_SetString
# define PyEval_InitThreads dll_PyEval_InitThreads
# define PyEval_RestoreThread dll_PyEval_RestoreThread
# define PyEval_SaveThread dll_PyEval_SaveThread
# ifdef PY_CAN_RECURSE
# define PyGILState_Ensure dll_PyGILState_Ensure
# define PyGILState_Release dll_PyGILState_Release
# endif
# define PyInt_AsLong dll_PyInt_AsLong
# define PyInt_FromLong dll_PyInt_FromLong
# define PyInt_Type (*dll_PyInt_Type)
# define PyList_GetItem dll_PyList_GetItem
# define PyList_Append dll_PyList_Append
# define PyList_New dll_PyList_New
# define PyList_SetItem dll_PyList_SetItem
# define PyList_Size dll_PyList_Size
# define PyList_Type (*dll_PyList_Type)
# define PyImport_ImportModule dll_PyImport_ImportModule
# define PyDict_New dll_PyDict_New
# define PyDict_GetItemString dll_PyDict_GetItemString
# define PyModule_GetDict dll_PyModule_GetDict
# define PyRun_SimpleString dll_PyRun_SimpleString
# define PyString_AsString dll_PyString_AsString
# define PyString_FromString dll_PyString_FromString
# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
# define PyString_Size dll_PyString_Size
# define PyString_Type (*dll_PyString_Type)
# define PySys_SetObject dll_PySys_SetObject
# define PySys_SetArgv dll_PySys_SetArgv
# define PyType_Type (*dll_PyType_Type)
# define PyType_Ready (*dll_PyType_Ready)
# define Py_BuildValue dll_Py_BuildValue
# define Py_FindMethod dll_Py_FindMethod
# define Py_InitModule4 dll_Py_InitModule4
# define Py_SetPythonHome dll_Py_SetPythonHome
# define Py_Initialize dll_Py_Initialize
# define Py_Finalize dll_Py_Finalize
# define Py_IsInitialized dll_Py_IsInitialized
# define _PyObject_New dll__PyObject_New
# define _Py_NoneStruct (*dll__Py_NoneStruct)
# define PyObject_Init dll__PyObject_Init
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
# define PyType_IsSubtype dll_PyType_IsSubtype
# endif
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
# define PyObject_Malloc dll_PyObject_Malloc
# define PyObject_Free dll_PyObject_Free
# endif
/*
* Pointers for dynamic link
*/
static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
static int(*dll_PyMem_Free)(void *);
static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
static int(*dll_PyErr_BadArgument)(void);
static void(*dll_PyErr_Clear)(void);
static PyObject*(*dll_PyErr_NoMemory)(void);
static PyObject*(*dll_PyErr_Occurred)(void);
static void(*dll_PyErr_SetNone)(PyObject *);
static void(*dll_PyErr_SetString)(PyObject *, const char *);
static void(*dll_PyEval_InitThreads)(void);
static void(*dll_PyEval_RestoreThread)(PyThreadState *);
static PyThreadState*(*dll_PyEval_SaveThread)(void);
# ifdef PY_CAN_RECURSE
static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
static void (*dll_PyGILState_Release)(PyGILState_STATE);
#endif
static long(*dll_PyInt_AsLong)(PyObject *);
static PyObject*(*dll_PyInt_FromLong)(long);
static PyTypeObject* dll_PyInt_Type;
static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
static PyObject*(*dll_PyList_New)(PyInt size);
static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
static PyInt(*dll_PyList_Size)(PyObject *);
static PyTypeObject* dll_PyList_Type;
static PyObject*(*dll_PyImport_ImportModule)(const char *);
static PyObject*(*dll_PyDict_New)(void);
static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
static PyObject*(*dll_PyModule_GetDict)(PyObject *);
static int(*dll_PyRun_SimpleString)(char *);
static char*(*dll_PyString_AsString)(PyObject *);
static PyObject*(*dll_PyString_FromString)(const char *);
static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
static PyInt(*dll_PyString_Size)(PyObject *);
static PyTypeObject* dll_PyString_Type;
static int(*dll_PySys_SetObject)(char *, PyObject *);
static int(*dll_PySys_SetArgv)(int, char **);
static PyTypeObject* dll_PyType_Type;
static int (*dll_PyType_Ready)(PyTypeObject *type);
static PyObject*(*dll_Py_BuildValue)(char *, ...);
static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
static void(*dll_Py_SetPythonHome)(char *home);
static void(*dll_Py_Initialize)(void);
static void(*dll_Py_Finalize)(void);
static int(*dll_Py_IsInitialized)(void);
static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
static PyObject* dll__Py_NoneStruct;
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
# endif
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
static void* (*dll_PyObject_Malloc)(size_t);
static void (*dll_PyObject_Free)(void*);
# endif
static HINSTANCE hinstPython = 0; /* Instance of python.dll */
/* Imported exception objects */
static PyObject *imp_PyExc_AttributeError;
static PyObject *imp_PyExc_IndexError;
static PyObject *imp_PyExc_KeyboardInterrupt;
static PyObject *imp_PyExc_TypeError;
static PyObject *imp_PyExc_ValueError;
# define PyExc_AttributeError imp_PyExc_AttributeError
# define PyExc_IndexError imp_PyExc_IndexError
# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
# define PyExc_TypeError imp_PyExc_TypeError
# define PyExc_ValueError imp_PyExc_ValueError
/*
* Table of name to function pointer of python.
*/
# define PYTHON_PROC FARPROC
static struct
{
char *name;
PYTHON_PROC *ptr;
} python_funcname_table[] =
{
{"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
{"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
{"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
{"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
{"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
{"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
{"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
{"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
{"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
{"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
{"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
{"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
{"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
# ifdef PY_CAN_RECURSE
{"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
{"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
# endif
{"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
{"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
{"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
{"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
{"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
{"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
{"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
{"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
{"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
{"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
{"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
{"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
{"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
{"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
{"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
{"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
{"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
{"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
{"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
{"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
{"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
{"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
{"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
{"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
{"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
{"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
# else
{"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
# endif
{"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
{"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
{"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
{"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
{"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
{"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
{"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
{"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
# endif
# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
{"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
{"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
# endif
{"", NULL},
};
/*
* Free python.dll
*/
static void
end_dynamic_python(void)
{
if (hinstPython)
{
close_dll(hinstPython);
hinstPython = 0;
}
}
/*
* Load library and get all pointers.
* Parameter 'libname' provides name of DLL.
* Return OK or FAIL.
*/
static int
python_runtime_link_init(char *libname, int verbose)
{
int i;
#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
/* Can't have Python and Python3 loaded at the same time.
* It cause a crash, because RTLD_GLOBAL is needed for
* standard C extension libraries of one or both python versions. */
if (python3_loaded())
{
if (verbose)
EMSG(_("E836: This Vim cannot execute :python after using :py3"));
return FAIL;
}
#endif
if (hinstPython)
return OK;
hinstPython = load_dll(libname);
if (!hinstPython)
{
if (verbose)
EMSG2(_(e_loadlib), libname);
return FAIL;
}
for (i = 0; python_funcname_table[i].ptr; ++i)
{
if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
python_funcname_table[i].name)) == NULL)
{
close_dll(hinstPython);
hinstPython = 0;
if (verbose)
EMSG2(_(e_loadfunc), python_funcname_table[i].name);
return FAIL;
}
}
return OK;
}
/*
* If python is enabled (there is installed python on Windows system) return
* TRUE, else FALSE.
*/
int
python_enabled(int verbose)
{
return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
}
/*
* Load the standard Python exceptions - don't import the symbols from the
* DLL, as this can cause errors (importing data symbols is not reliable).
*/
static void
get_exceptions(void)
{
PyObject *exmod = PyImport_ImportModule("exceptions");
PyObject *exdict = PyModule_GetDict(exmod);
imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
Py_XINCREF(imp_PyExc_AttributeError);
Py_XINCREF(imp_PyExc_IndexError);
Py_XINCREF(imp_PyExc_KeyboardInterrupt);
Py_XINCREF(imp_PyExc_TypeError);
Py_XINCREF(imp_PyExc_ValueError);
Py_XDECREF(exmod);
}
#endif /* DYNAMIC_PYTHON */
static PyObject *BufferNew (buf_T *);
static PyObject *WindowNew(win_T *);
static PyObject *LineToString(const char *);
static PyTypeObject RangeType;
/*
* Include the code shared with if_python3.c
*/
#include "if_py_both.h"
/******************************************************
* Internal function prototypes.
*/
static PyInt RangeStart;
static PyInt RangeEnd;
static void PythonIO_Flush(void);
static int PythonIO_Init(void);
static int PythonMod_Init(void);
/* Utility functions for the vim/python interface
* ----------------------------------------------
*/
static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
/******************************************************
* 1. Python interpreter main program.
*/
static int initialised = 0;
#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
typedef PyObject PyThreadState;
#endif
#ifdef PY_CAN_RECURSE
static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
#else
static PyThreadState *saved_python_thread = NULL;
#endif
/*
* Suspend a thread of the Python interpreter, other threads are allowed to
* run.
*/
static void
Python_SaveThread(void)
{
#ifdef PY_CAN_RECURSE
PyGILState_Release(pygilstate);
#else
saved_python_thread = PyEval_SaveThread();
#endif
}
/*
* Restore a thread of the Python interpreter, waits for other threads to
* block.
*/
static void
Python_RestoreThread(void)
{
#ifdef PY_CAN_RECURSE
pygilstate = PyGILState_Ensure();
#else
PyEval_RestoreThread(saved_python_thread);
saved_python_thread = NULL;
#endif
}
void
python_end()
{
static int recurse = 0;
/* If a crash occurs while doing this, don't try again. */
if (recurse != 0)
return;
++recurse;
#ifdef DYNAMIC_PYTHON
if (hinstPython && Py_IsInitialized())
{
Python_RestoreThread(); /* enter python */
Py_Finalize();
}
end_dynamic_python();
#else
if (Py_IsInitialized())
{
Python_RestoreThread(); /* enter python */
Py_Finalize();
}
#endif
--recurse;
}
#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
int
python_loaded()
{
return (hinstPython != 0);
}
#endif
static int
Python_Init(void)
{
if (!initialised)
{
#ifdef DYNAMIC_PYTHON
if (!python_enabled(TRUE))
{
EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
goto fail;
}
#endif
#ifdef PYTHON_HOME
Py_SetPythonHome(PYTHON_HOME);
#endif
init_structs();
#if !defined(MACOS) || defined(MACOS_X_UNIX)
Py_Initialize();
#else
PyMac_Initialize();
#endif
/* initialise threads */
PyEval_InitThreads();
#ifdef DYNAMIC_PYTHON
get_exceptions();
#endif
if (PythonIO_Init())
goto fail;
if (PythonMod_Init())
goto fail;
/* Remove the element from sys.path that was added because of our
* argv[0] value in PythonMod_Init(). Previously we used an empty
* string, but dependinding on the OS we then get an empty entry or
* the current directory in sys.path. */
PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
/* the first python thread is vim's, release the lock */
Python_SaveThread();
initialised = 1;
}
return 0;
fail:
/* We call PythonIO_Flush() here to print any Python errors.
* This is OK, as it is possible to call this function even
* if PythonIO_Init() has not completed successfully (it will
* not do anything in this case).
*/
PythonIO_Flush();
return -1;
}
/*
* External interface
*/
static void
DoPythonCommand(exarg_T *eap, const char *cmd)
{
#ifndef PY_CAN_RECURSE
static int recursive = 0;
#endif
#if defined(MACOS) && !defined(MACOS_X_UNIX)
GrafPtr oldPort;
#endif
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
char *saved_locale;
#endif
#ifndef PY_CAN_RECURSE
if (recursive)
{
EMSG(_("E659: Cannot invoke Python recursively"));
return;
}
++recursive;
#endif
#if defined(MACOS) && !defined(MACOS_X_UNIX)
GetPort(&oldPort);
/* Check if the Python library is available */
if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
goto theend;
#endif
if (Python_Init())
goto theend;
RangeStart = eap->line1;
RangeEnd = eap->line2;
Python_Release_Vim(); /* leave vim */
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
/* Python only works properly when the LC_NUMERIC locale is "C". */
saved_locale = setlocale(LC_NUMERIC, NULL);
if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
saved_locale = NULL;
else
{
/* Need to make a copy, value may change when setting new locale. */
saved_locale = (char *)vim_strsave((char_u *)saved_locale);
(void)setlocale(LC_NUMERIC, "C");
}
#endif
Python_RestoreThread(); /* enter python */
PyRun_SimpleString((char *)(cmd));
Python_SaveThread(); /* leave python */
#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
if (saved_locale != NULL)
{
(void)setlocale(LC_NUMERIC, saved_locale);
vim_free(saved_locale);
}
#endif
Python_Lock_Vim(); /* enter vim */
PythonIO_Flush();
#if defined(MACOS) && !defined(MACOS_X_UNIX)
SetPort(oldPort);
#endif
theend:
#ifndef PY_CAN_RECURSE
--recursive;
#endif
return; /* keeps lint happy */
}
/*
* ":python"
*/
void
ex_python(exarg_T *eap)
{
char_u *script;
script = script_get(eap, eap->arg);
if (!eap->skip)
{
if (script == NULL)
DoPythonCommand(eap, (char *)eap->arg);
else
DoPythonCommand(eap, (char *)script);
}
vim_free(script);
}
#define BUFFER_SIZE 1024
/*
* ":pyfile"
*/
void
ex_pyfile(exarg_T *eap)
{
static char buffer[BUFFER_SIZE];
const char *file = (char *)eap->arg;
char *p;
/* Have to do it like this. PyRun_SimpleFile requires you to pass a
* stdio file pointer, but Vim and the Python DLL are compiled with
* different options under Windows, meaning that stdio pointers aren't
* compatible between the two. Yuk.
*
* Put the string "execfile('file')" into buffer. But, we need to
* escape any backslashes or single quotes in the file name, so that
* Python won't mangle the file name.
*/
strcpy(buffer, "execfile('");
p = buffer + 10; /* size of "execfile('" */
while (*file && p < buffer + (BUFFER_SIZE - 3))
{
if (*file == '\\' || *file == '\'')
*p++ = '\\';
*p++ = *file++;
}
/* If we didn't finish the file name, we hit a buffer overflow */
if (*file != '\0')
return;
/* Put in the terminating "')" and a null */
*p++ = '\'';
*p++ = ')';
*p++ = '\0';
/* Execute the file */
DoPythonCommand(eap, buffer);
}
/******************************************************
* 2. Python output stream: writes output via [e]msg().
*/
/* Implementation functions
*/
static PyObject *
OutputGetattr(PyObject *self, char *name)
{
if (strcmp(name, "softspace") == 0)
return PyInt_FromLong(((OutputObject *)(self))->softspace);
return Py_FindMethod(OutputMethods, self, name);
}
static int
OutputSetattr(PyObject *self, char *name, PyObject *val)
{
if (val == NULL) {
PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
return -1;
}
if (strcmp(name, "softspace") == 0)
{
if (!PyInt_Check(val)) {
PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
return -1;
}
((OutputObject *)(self))->softspace = PyInt_AsLong(val);
return 0;
}
PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
return -1;
}
/***************/
static int
PythonIO_Init(void)
{
/* Fixups... */
PyType_Ready(&OutputType);
return PythonIO_Init_io();
}
/******************************************************
* 3. Implementation of the Vim module for Python
*/
/* Window type - Implementation functions
* --------------------------------------
*/
#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
static void WindowDestructor(PyObject *);
static PyObject *WindowGetattr(PyObject *, char *);
/* Buffer type - Implementation functions
* --------------------------------------
*/
#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
static void BufferDestructor(PyObject *);
static PyObject *BufferGetattr(PyObject *, char *);
static PyObject *BufferRepr(PyObject *);
static PyInt BufferLength(PyObject *);
static PyObject *BufferItem(PyObject *, PyInt);
static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
/* Line range type - Implementation functions
* --------------------------------------
*/
#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
/* Current objects type - Implementation functions
* -----------------------------------------------
*/
static PyObject *CurrentGetattr(PyObject *, char *);
static int CurrentSetattr(PyObject *, char *, PyObject *);
static PySequenceMethods BufferAsSeq = {
(PyInquiry) BufferLength, /* sq_length, len(x) */
(binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
(PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
(PyIntArgFunc) BufferItem, /* sq_item, x[i] */
(PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
(PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
(PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
};
static PyTypeObject BufferType = {
PyObject_HEAD_INIT(0)
0,
"buffer",
sizeof(BufferObject),
0,
(destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
(printfunc) 0, /* tp_print, print x */
(getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
(setattrfunc) 0, /* tp_setattr, x.attr=v */
(cmpfunc) 0, /* tp_compare, x>y */
(reprfunc) BufferRepr, /* tp_repr, `x`, print x */
0, /* as number */
&BufferAsSeq, /* as sequence */
0, /* as mapping */
(hashfunc) 0, /* tp_hash, dict(x) */
(ternaryfunc) 0, /* tp_call, x() */
(reprfunc) 0, /* tp_str, str(x) */
};
/* Buffer object - Implementation
*/
static PyObject *
BufferNew(buf_T *buf)
{
/* We need to handle deletion of buffers underneath us.
* If we add a "b_python_ref" field to the buf_T structure,
* then we can get at it in buf_freeall() in vim. We then
* need to create only ONE Python object per buffer - if
* we try to create a second, just INCREF the existing one
* and return it. The (single) Python object referring to
* the buffer is stored in "b_python_ref".
* Question: what to do on a buf_freeall(). We'll probably
* have to either delete the Python object (DECREF it to
* zero - a bad idea, as it leaves dangling refs!) or
* set the buf_T * value to an invalid value (-1?), which
* means we need checks in all access functions... Bah.
*/
BufferObject *self;
if (buf->b_python_ref != NULL)
{
self = buf->b_python_ref;
Py_INCREF(self);
}
else
{
self = PyObject_NEW(BufferObject, &BufferType);
if (self == NULL)
return NULL;
self->buf = buf;
buf->b_python_ref = self;
}
return (PyObject *)(self);
}
static void
BufferDestructor(PyObject *self)
{
BufferObject *this = (BufferObject *)(self);
if (this->buf && this->buf != INVALID_BUFFER_VALUE)
this->buf->b_python_ref = NULL;
Py_DECREF(self);
}
static PyObject *
BufferGetattr(PyObject *self, char *name)
{
BufferObject *this = (BufferObject *)(self);
if (CheckBuffer(this))
return NULL;
if (strcmp(name, "name") == 0)
return Py_BuildValue("s", this->buf->b_ffname);
else if (strcmp(name, "number") == 0)
return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[ss]", "name", "number");
else
return Py_FindMethod(BufferMethods, self, name);
}
static PyObject *
BufferRepr(PyObject *self)
{
static char repr[100];
BufferObject *this = (BufferObject *)(self);
if (this->buf == INVALID_BUFFER_VALUE)
{
vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
return PyString_FromString(repr);
}
else
{
char *name = (char *)this->buf->b_fname;
PyInt len;
if (name == NULL)
name = "";
len = strlen(name);
if (len > 35)
name = name + (35 - len);
vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
return PyString_FromString(repr);
}
}
/******************/
static PyInt
BufferLength(PyObject *self)
{
/* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
if (CheckBuffer((BufferObject *)(self)))
return -1; /* ??? */
return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
}
static PyObject *
BufferItem(PyObject *self, PyInt n)
{
return RBItem((BufferObject *)(self), n, 1,
(int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
}
static PyObject *
BufferSlice(PyObject *self, PyInt lo, PyInt hi)
{
return RBSlice((BufferObject *)(self), lo, hi, 1,
(int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
}
static PyInt
BufferAssItem(PyObject *self, PyInt n, PyObject *val)
{
return RBAsItem((BufferObject *)(self), n, val, 1,
(PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
NULL);
}
static PyInt
BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
{
return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
(PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
NULL);
}
static PySequenceMethods RangeAsSeq = {
(PyInquiry) RangeLength, /* sq_length, len(x) */
(binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
(PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
(PyIntArgFunc) RangeItem, /* sq_item, x[i] */
(PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
(PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
(PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
};
/* Line range object - Implementation
*/
static void
RangeDestructor(PyObject *self)
{
Py_DECREF(((RangeObject *)(self))->buf);
Py_DECREF(self);
}
static PyObject *
RangeGetattr(PyObject *self, char *name)
{
if (strcmp(name, "start") == 0)
return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
else if (strcmp(name, "end") == 0)
return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
else
return Py_FindMethod(RangeMethods, self, name);
}
/****************/
static PyInt
RangeAssItem(PyObject *self, PyInt n, PyObject *val)
{
return RBAsItem(((RangeObject *)(self))->buf, n, val,
((RangeObject *)(self))->start,
((RangeObject *)(self))->end,
&((RangeObject *)(self))->end);
}
static PyInt
RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
{
return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
((RangeObject *)(self))->start,
((RangeObject *)(self))->end,
&((RangeObject *)(self))->end);
}
/* Buffer list object - Definitions
*/
typedef struct
{
PyObject_HEAD
} BufListObject;
static PySequenceMethods BufListAsSeq = {
(PyInquiry) BufListLength, /* sq_length, len(x) */
(binaryfunc) 0, /* sq_concat, x+y */
(PyIntArgFunc) 0, /* sq_repeat, x*n */
(PyIntArgFunc) BufListItem, /* sq_item, x[i] */
(PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
(PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
(PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
};
static PyTypeObject BufListType = {
PyObject_HEAD_INIT(0)
0,
"buffer list",
sizeof(BufListObject),
0,
(destructor) 0, /* tp_dealloc, refcount==0 */
(printfunc) 0, /* tp_print, print x */
(getattrfunc) 0, /* tp_getattr, x.attr */
(setattrfunc) 0, /* tp_setattr, x.attr=v */
(cmpfunc) 0, /* tp_compare, x>y */
(reprfunc) 0, /* tp_repr, `x`, print x */
0, /* as number */
&BufListAsSeq, /* as sequence */
0, /* as mapping */
(hashfunc) 0, /* tp_hash, dict(x) */
(ternaryfunc) 0, /* tp_call, x() */
(reprfunc) 0, /* tp_str, str(x) */
};
/* Window object - Definitions
*/
static struct PyMethodDef WindowMethods[] = {
/* name, function, calling, documentation */
{ NULL, NULL, 0, NULL }
};
static PyTypeObject WindowType = {
PyObject_HEAD_INIT(0)
0,
"window",
sizeof(WindowObject),
0,
(destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
(printfunc) 0, /* tp_print, print x */
(getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
(setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
(cmpfunc) 0, /* tp_compare, x>y */
(reprfunc) WindowRepr, /* tp_repr, `x`, print x */
0, /* as number */
0, /* as sequence */
0, /* as mapping */
(hashfunc) 0, /* tp_hash, dict(x) */
(ternaryfunc) 0, /* tp_call, x() */
(reprfunc) 0, /* tp_str, str(x) */
};
/* Window object - Implementation
*/
static PyObject *
WindowNew(win_T *win)
{
/* We need to handle deletion of windows underneath us.
* If we add a "w_python_ref" field to the win_T structure,
* then we can get at it in win_free() in vim. We then
* need to create only ONE Python object per window - if
* we try to create a second, just INCREF the existing one
* and return it. The (single) Python object referring to
* the window is stored in "w_python_ref".
* On a win_free() we set the Python 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.
*/
WindowObject *self;
if (win->w_python_ref)
{
self = win->w_python_ref;
Py_INCREF(self);
}
else
{
self = PyObject_NEW(WindowObject, &WindowType);
if (self == NULL)
return NULL;
self->win = win;
win->w_python_ref = self;
}
return (PyObject *)(self);
}
static void
WindowDestructor(PyObject *self)
{
WindowObject *this = (WindowObject *)(self);
if (this->win && this->win != INVALID_WINDOW_VALUE)
this->win->w_python_ref = NULL;
Py_DECREF(self);
}
static PyObject *
WindowGetattr(PyObject *self, char *name)
{
WindowObject *this = (WindowObject *)(self);
if (CheckWindow(this))
return NULL;
if (strcmp(name, "buffer") == 0)
return (PyObject *)BufferNew(this->win->w_buffer);
else if (strcmp(name, "cursor") == 0)
{
pos_T *pos = &this->win->w_cursor;
return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
}
else if (strcmp(name, "height") == 0)
return Py_BuildValue("l", (long)(this->win->w_height));
#ifdef FEAT_VERTSPLIT
else if (strcmp(name, "width") == 0)
return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
#endif
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[sss]", "buffer", "cursor", "height");
else
return Py_FindMethod(WindowMethods, self, name);
}
/* Window list object - Definitions
*/
typedef struct
{
PyObject_HEAD
}
WinListObject;
static PySequenceMethods WinListAsSeq = {
(PyInquiry) WinListLength, /* sq_length, len(x) */
(binaryfunc) 0, /* sq_concat, x+y */
(PyIntArgFunc) 0, /* sq_repeat, x*n */
(PyIntArgFunc) WinListItem, /* sq_item, x[i] */
(PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
(PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
(PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
};
static PyTypeObject WinListType = {
PyObject_HEAD_INIT(0)
0,
"window list",
sizeof(WinListObject),
0,
(destructor) 0, /* tp_dealloc, refcount==0 */
(printfunc) 0, /* tp_print, print x */
(getattrfunc) 0, /* tp_getattr, x.attr */
(setattrfunc) 0, /* tp_setattr, x.attr=v */
(cmpfunc) 0, /* tp_compare, x>y */
(reprfunc) 0, /* tp_repr, `x`, print x */
0, /* as number */
&WinListAsSeq, /* as sequence */
0, /* as mapping */
(hashfunc) 0, /* tp_hash, dict(x) */
(ternaryfunc) 0, /* tp_call, x() */
(reprfunc) 0, /* tp_str, str(x) */
};
/* Current items object - Definitions
*/
typedef struct
{
PyObject_HEAD
} CurrentObject;
static PyTypeObject CurrentType = {
PyObject_HEAD_INIT(0)
0,
"current data",
sizeof(CurrentObject),
0,
(destructor) 0, /* tp_dealloc, refcount==0 */
(printfunc) 0, /* tp_print, print x */
(getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
(setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
(cmpfunc) 0, /* tp_compare, x>y */
(reprfunc) 0, /* tp_repr, `x`, print x */
0, /* as number */
0, /* as sequence */
0, /* as mapping */
(hashfunc) 0, /* tp_hash, dict(x) */
(ternaryfunc) 0, /* tp_call, x() */
(reprfunc) 0, /* tp_str, str(x) */
};
/* Current items object - Implementation
*/
static PyObject *
CurrentGetattr(PyObject *self UNUSED, char *name)
{
if (strcmp(name, "buffer") == 0)
return (PyObject *)BufferNew(curbuf);
else if (strcmp(name, "window") == 0)
return (PyObject *)WindowNew(curwin);
else if (strcmp(name, "line") == 0)
return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
else if (strcmp(name, "range") == 0)
return RangeNew(curbuf, RangeStart, RangeEnd);
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
else
{
PyErr_SetString(PyExc_AttributeError, name);
return NULL;
}
}
static int
CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
{
if (strcmp(name, "line") == 0)
{
if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
return -1;
return 0;
}
else
{
PyErr_SetString(PyExc_AttributeError, name);
return -1;
}
}
/* External interface
*/
void
python_buffer_free(buf_T *buf)
{
if (buf->b_python_ref != NULL)
{
BufferObject *bp = buf->b_python_ref;
bp->buf = INVALID_BUFFER_VALUE;
buf->b_python_ref = NULL;
}
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
void
python_window_free(win_T *win)
{
if (win->w_python_ref != NULL)
{
WindowObject *wp = win->w_python_ref;
wp->win = INVALID_WINDOW_VALUE;
win->w_python_ref = NULL;
}
}
#endif
static BufListObject TheBufferList =
{
PyObject_HEAD_INIT(&BufListType)
};
static WinListObject TheWindowList =
{
PyObject_HEAD_INIT(&WinListType)
};
static CurrentObject TheCurrent =
{
PyObject_HEAD_INIT(&CurrentType)
};
static int
PythonMod_Init(void)
{
PyObject *mod;
PyObject *dict;
/* The special value is removed from sys.path in Python_Init(). */
static char *(argv[2]) = {"/must>not&exist/foo", NULL};
/* Fixups... */
PyType_Ready(&BufferType);
PyType_Ready(&RangeType);
PyType_Ready(&WindowType);
PyType_Ready(&BufListType);
PyType_Ready(&WinListType);
PyType_Ready(&CurrentType);
/* Set sys.argv[] to avoid a crash in warn(). */
PySys_SetArgv(1, argv);
mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
dict = PyModule_GetDict(mod);
VimError = Py_BuildValue("s", "vim.error");
PyDict_SetItemString(dict, "error", VimError);
PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
if (PyErr_Occurred())
return -1;
return 0;
}
/*************************************************************************
* 4. Utility functions for handling the interface between Vim and Python.
*/
/* Convert a Vim line into a Python string.
* All internal newlines are replaced by null characters.
*
* On errors, the Python exception data is set, and NULL is returned.
*/
static PyObject *
LineToString(const char *str)
{
PyObject *result;
PyInt len = strlen(str);
char *p;
/* Allocate an Python string object, with uninitialised contents. We
* must do it this way, so that we can modify the string in place
* later. See the Python source, Objects/stringobject.c for details.
*/
result = PyString_FromStringAndSize(NULL, len);
if (result == NULL)
return NULL;
p = PyString_AsString(result);
while (*str)
{
if (*str == '\n')
*p = '\0';
else
*p = *str;
++p;
++str;
}
return result;
}
/* Don't generate a prototype for the next function, it generates an error on
* newer Python versions. */
#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
char *
Py_GetProgramName(void)
{
return "vim";
}
#endif /* Python 1.4 */
static void
init_structs(void)
{
vim_memset(&OutputType, 0, sizeof(OutputType));
OutputType.tp_name = "message";
OutputType.tp_basicsize = sizeof(OutputObject);
OutputType.tp_getattr = OutputGetattr;
OutputType.tp_setattr = OutputSetattr;
vim_memset(&RangeType, 0, sizeof(RangeType));
RangeType.tp_name = "range";
RangeType.tp_basicsize = sizeof(RangeObject);
RangeType.tp_dealloc = RangeDestructor;
RangeType.tp_getattr = RangeGetattr;
RangeType.tp_repr = RangeRepr;
RangeType.tp_as_sequence = &RangeAsSeq;
}
| zyz2011-vim | src/if_python.c | C | gpl2 | 41,442 |
/*
* if_sniff.h Interface between Vim and SNiFF+
*/
#ifndef __if_sniff_h__
#define __if_sniff_h__
extern int want_sniff_request;
extern int sniff_request_waiting;
extern int sniff_connected;
extern int fd_from_sniff;
extern void sniff_disconnect __ARGS((int immediately));
extern void ProcessSniffRequests __ARGS((void));
extern void ex_sniff __ARGS((exarg_T *eap));
#endif
| zyz2011-vim | src/if_sniff.h | C | gpl2 | 383 |
#!/bin/sh
# Start GUI Vim on a copy of the tutor file.
# Usage: gvimtutor [xx]
# See vimtutor for usage.
exec `dirname $0`/vimtutor -g "$@"
| zyz2011-vim | src/gvimtutor | Shell | gpl2 | 143 |
/* 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_getln.c: Functions for entering and editing an Ex command line.
*/
#include "vim.h"
/*
* Variables shared between getcmdline(), redrawcmdline() and others.
* These need to be saved when using CTRL-R |, that's why they are in a
* structure.
*/
struct cmdline_info
{
char_u *cmdbuff; /* pointer to command line buffer */
int cmdbufflen; /* length of cmdbuff */
int cmdlen; /* number of chars in command line */
int cmdpos; /* current cursor position */
int cmdspos; /* cursor column on screen */
int cmdfirstc; /* ':', '/', '?', '=', '>' or NUL */
int cmdindent; /* number of spaces before cmdline */
char_u *cmdprompt; /* message in front of cmdline */
int cmdattr; /* attributes for prompt */
int overstrike; /* Typing mode on the command line. Shared by
getcmdline() and put_on_cmdline(). */
expand_T *xpc; /* struct being used for expansion, xp_pattern
may point into cmdbuff */
int xp_context; /* type of expansion */
# ifdef FEAT_EVAL
char_u *xp_arg; /* user-defined expansion arg */
int input_fn; /* when TRUE Invoked for input() function */
# endif
};
/* The current cmdline_info. It is initialized in getcmdline() and after that
* used by other functions. When invoking getcmdline() recursively it needs
* to be saved with save_cmdline() and restored with restore_cmdline().
* TODO: make it local to getcmdline() and pass it around. */
static struct cmdline_info ccline;
static int cmd_showtail; /* Only show path tail in lists ? */
#ifdef FEAT_EVAL
static int new_cmdpos; /* position set by set_cmdline_pos() */
#endif
#ifdef FEAT_CMDHIST
typedef struct hist_entry
{
int hisnum; /* identifying number */
char_u *hisstr; /* actual entry, separator char after the NUL */
} histentry_T;
static histentry_T *(history[HIST_COUNT]) = {NULL, NULL, NULL, NULL, NULL};
static int hisidx[HIST_COUNT] = {-1, -1, -1, -1, -1}; /* lastused entry */
static int hisnum[HIST_COUNT] = {0, 0, 0, 0, 0};
/* identifying (unique) number of newest history entry */
static int hislen = 0; /* actual length of history tables */
static int hist_char2type __ARGS((int c));
static int in_history __ARGS((int, char_u *, int, int));
# ifdef FEAT_EVAL
static int calc_hist_idx __ARGS((int histype, int num));
# endif
#endif
#ifdef FEAT_RIGHTLEFT
static int cmd_hkmap = 0; /* Hebrew mapping during command line */
#endif
#ifdef FEAT_FKMAP
static int cmd_fkmap = 0; /* Farsi mapping during command line */
#endif
static int cmdline_charsize __ARGS((int idx));
static void set_cmdspos __ARGS((void));
static void set_cmdspos_cursor __ARGS((void));
#ifdef FEAT_MBYTE
static void correct_cmdspos __ARGS((int idx, int cells));
#endif
static void alloc_cmdbuff __ARGS((int len));
static int realloc_cmdbuff __ARGS((int len));
static void draw_cmdline __ARGS((int start, int len));
static void save_cmdline __ARGS((struct cmdline_info *ccp));
static void restore_cmdline __ARGS((struct cmdline_info *ccp));
static int cmdline_paste __ARGS((int regname, int literally, int remcr));
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
static void redrawcmd_preedit __ARGS((void));
#endif
#ifdef FEAT_WILDMENU
static void cmdline_del __ARGS((int from));
#endif
static void redrawcmdprompt __ARGS((void));
static void cursorcmd __ARGS((void));
static int ccheck_abbr __ARGS((int));
static int nextwild __ARGS((expand_T *xp, int type, int options));
static void escape_fname __ARGS((char_u **pp));
static int showmatches __ARGS((expand_T *xp, int wildmenu));
static void set_expand_context __ARGS((expand_T *xp));
static int ExpandFromContext __ARGS((expand_T *xp, char_u *, int *, char_u ***, int));
static int expand_showtail __ARGS((expand_T *xp));
#ifdef FEAT_CMDL_COMPL
static int expand_shellcmd __ARGS((char_u *filepat, int *num_file, char_u ***file, int flagsarg));
static int ExpandRTDir __ARGS((char_u *pat, int *num_file, char_u ***file, char *dirname[]));
# ifdef FEAT_CMDHIST
static char_u *get_history_arg __ARGS((expand_T *xp, int idx));
# endif
# if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
static int ExpandUserDefined __ARGS((expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file));
static int ExpandUserList __ARGS((expand_T *xp, int *num_file, char_u ***file));
# endif
#endif
#ifdef FEAT_CMDWIN
static int ex_window __ARGS((void));
#endif
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
sort_func_compare __ARGS((const void *s1, const void *s2));
#endif
/*
* getcmdline() - accept a command line starting with firstc.
*
* firstc == ':' get ":" command line.
* firstc == '/' or '?' get search pattern
* firstc == '=' get expression
* firstc == '@' get text for input() function
* firstc == '>' get text for debug mode
* firstc == NUL get text for :insert command
* firstc == -1 like NUL, and break on CTRL-C
*
* The line is collected in ccline.cmdbuff, which is reallocated to fit the
* command line.
*
* Careful: getcmdline() can be called recursively!
*
* Return pointer to allocated string if there is a commandline, NULL
* otherwise.
*/
char_u *
getcmdline(firstc, count, indent)
int firstc;
long count UNUSED; /* only used for incremental search */
int indent; /* indent for inside conditionals */
{
int c;
int i;
int j;
int gotesc = FALSE; /* TRUE when <ESC> just typed */
int do_abbr; /* when TRUE check for abbr. */
#ifdef FEAT_CMDHIST
char_u *lookfor = NULL; /* string to match */
int hiscnt; /* current history line in use */
int histype; /* history type to be used */
#endif
#ifdef FEAT_SEARCH_EXTRA
pos_T old_cursor;
colnr_T old_curswant;
colnr_T old_leftcol;
linenr_T old_topline;
# ifdef FEAT_DIFF
int old_topfill;
# endif
linenr_T old_botline;
int did_incsearch = FALSE;
int incsearch_postponed = FALSE;
#endif
int did_wild_list = FALSE; /* did wild_list() recently */
int wim_index = 0; /* index in wim_flags[] */
int res;
int save_msg_scroll = msg_scroll;
int save_State = State; /* remember State when called */
int some_key_typed = FALSE; /* one of the keys was typed */
#ifdef FEAT_MOUSE
/* mouse drag and release events are ignored, unless they are
* preceded with a mouse down event */
int ignore_drag_release = TRUE;
#endif
#ifdef FEAT_EVAL
int break_ctrl_c = FALSE;
#endif
expand_T xpc;
long *b_im_ptr = NULL;
#if defined(FEAT_WILDMENU) || defined(FEAT_EVAL) || defined(FEAT_SEARCH_EXTRA)
/* Everything that may work recursively should save and restore the
* current command line in save_ccline. That includes update_screen(), a
* custom status line may invoke ":normal". */
struct cmdline_info save_ccline;
#endif
#ifdef FEAT_SNIFF
want_sniff_request = 0;
#endif
#ifdef FEAT_EVAL
if (firstc == -1)
{
firstc = NUL;
break_ctrl_c = TRUE;
}
#endif
#ifdef FEAT_RIGHTLEFT
/* start without Hebrew mapping for a command line */
if (firstc == ':' || firstc == '=' || firstc == '>')
cmd_hkmap = 0;
#endif
ccline.overstrike = FALSE; /* always start in insert mode */
#ifdef FEAT_SEARCH_EXTRA
old_cursor = curwin->w_cursor; /* needs to be restored later */
old_curswant = curwin->w_curswant;
old_leftcol = curwin->w_leftcol;
old_topline = curwin->w_topline;
# ifdef FEAT_DIFF
old_topfill = curwin->w_topfill;
# endif
old_botline = curwin->w_botline;
#endif
/*
* set some variables for redrawcmd()
*/
ccline.cmdfirstc = (firstc == '@' ? 0 : firstc);
ccline.cmdindent = (firstc > 0 ? indent : 0);
/* alloc initial ccline.cmdbuff */
alloc_cmdbuff(exmode_active ? 250 : indent + 1);
if (ccline.cmdbuff == NULL)
return NULL; /* out of memory */
ccline.cmdlen = ccline.cmdpos = 0;
ccline.cmdbuff[0] = NUL;
/* autoindent for :insert and :append */
if (firstc <= 0)
{
copy_spaces(ccline.cmdbuff, indent);
ccline.cmdbuff[indent] = NUL;
ccline.cmdpos = indent;
ccline.cmdspos = indent;
ccline.cmdlen = indent;
}
ExpandInit(&xpc);
ccline.xpc = &xpc;
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
&& (firstc == '/' || firstc == '?'))
cmdmsg_rl = TRUE;
else
cmdmsg_rl = FALSE;
#endif
redir_off = TRUE; /* don't redirect the typed command */
if (!cmd_silent)
{
i = msg_scrolled;
msg_scrolled = 0; /* avoid wait_return message */
gotocmdline(TRUE);
msg_scrolled += i;
redrawcmdprompt(); /* draw prompt or indent */
set_cmdspos();
}
xpc.xp_context = EXPAND_NOTHING;
xpc.xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
xpc.xp_shell = FALSE;
#endif
#if defined(FEAT_EVAL)
if (ccline.input_fn)
{
xpc.xp_context = ccline.xp_context;
xpc.xp_pattern = ccline.cmdbuff;
# if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
xpc.xp_arg = ccline.xp_arg;
# endif
}
#endif
/*
* Avoid scrolling when called by a recursive do_cmdline(), e.g. when
* doing ":@0" when register 0 doesn't contain a CR.
*/
msg_scroll = FALSE;
State = CMDLINE;
if (firstc == '/' || firstc == '?' || firstc == '@')
{
/* Use ":lmap" mappings for search pattern and input(). */
if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
b_im_ptr = &curbuf->b_p_iminsert;
else
b_im_ptr = &curbuf->b_p_imsearch;
if (*b_im_ptr == B_IMODE_LMAP)
State |= LANGMAP;
#ifdef USE_IM_CONTROL
im_set_active(*b_im_ptr == B_IMODE_IM);
#endif
}
#ifdef USE_IM_CONTROL
else if (p_imcmdline)
im_set_active(TRUE);
#endif
#ifdef FEAT_MOUSE
setmouse();
#endif
#ifdef CURSOR_SHAPE
ui_cursor_shape(); /* may show different cursor shape */
#endif
/* When inside an autocommand for writing "exiting" may be set and
* terminal mode set to cooked. Need to set raw mode here then. */
settmode(TMODE_RAW);
#ifdef FEAT_CMDHIST
init_history();
hiscnt = hislen; /* set hiscnt to impossible history value */
histype = hist_char2type(firstc);
#endif
#ifdef FEAT_DIGRAPHS
do_digraph(-1); /* init digraph typeahead */
#endif
/*
* Collect the command string, handling editing keys.
*/
for (;;)
{
redir_off = TRUE; /* Don't redirect the typed command.
Repeated, because a ":redir" inside
completion may switch it on. */
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; /* allow scrolling here */
#endif
quit_more = FALSE; /* reset after CTRL-D which had a more-prompt */
cursorcmd(); /* set the cursor on the right spot */
/* Get a character. Ignore K_IGNORE, it should not do anything, such
* as stop completion. */
do
{
c = safe_vgetc();
} while (c == K_IGNORE);
if (KeyTyped)
{
some_key_typed = TRUE;
#ifdef FEAT_RIGHTLEFT
if (cmd_hkmap)
c = hkmap(c);
# ifdef FEAT_FKMAP
if (cmd_fkmap)
c = cmdl_fkmap(c);
# endif
if (cmdmsg_rl && !KeyStuffed)
{
/* Invert horizontal movements and operations. Only when
* typed by the user directly, not when the result of a
* mapping. */
switch (c)
{
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;
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;
}
}
#endif
}
/*
* Ignore got_int when CTRL-C was typed here.
* Don't ignore it in :global, we really need to break then, e.g., for
* ":g/pat/normal /pat" (without the <CR>).
* Don't ignore it for the input() function.
*/
if ((c == Ctrl_C
#ifdef UNIX
|| c == intr_char
#endif
)
#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
&& firstc != '@'
#endif
#ifdef FEAT_EVAL
&& !break_ctrl_c
#endif
&& !global_busy)
got_int = FALSE;
#ifdef FEAT_CMDHIST
/* free old command line when finished moving around in the history
* list */
if (lookfor != NULL
&& c != K_S_DOWN && c != K_S_UP
&& c != K_DOWN && c != K_UP
&& c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP
&& c != K_LEFT && c != K_RIGHT
&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
{
vim_free(lookfor);
lookfor = NULL;
}
#endif
/*
* When there are matching completions to select <S-Tab> works like
* CTRL-P (unless 'wc' is <S-Tab>).
*/
if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
c = Ctrl_P;
#ifdef FEAT_WILDMENU
/* Special translations for 'wildmenu' */
if (did_wild_list && p_wmnu)
{
if (c == K_LEFT)
c = Ctrl_P;
else if (c == K_RIGHT)
c = Ctrl_N;
}
/* Hitting CR after "emenu Name.": complete submenu */
if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu
&& ccline.cmdpos > 1
&& ccline.cmdbuff[ccline.cmdpos - 1] == '.'
&& ccline.cmdbuff[ccline.cmdpos - 2] != '\\'
&& (c == '\n' || c == '\r' || c == K_KENTER))
c = K_DOWN;
#endif
/* free expanded names when finished walking through matches */
if (xpc.xp_numfiles != -1
&& !(c == p_wc && KeyTyped) && c != p_wcm
&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A
&& c != Ctrl_L)
{
(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
did_wild_list = FALSE;
#ifdef FEAT_WILDMENU
if (!p_wmnu || (c != K_UP && c != K_DOWN))
#endif
xpc.xp_context = EXPAND_NOTHING;
wim_index = 0;
#ifdef FEAT_WILDMENU
if (p_wmnu && wild_menu_showing != 0)
{
int skt = KeyTyped;
int old_RedrawingDisabled = RedrawingDisabled;
if (ccline.input_fn)
RedrawingDisabled = 0;
if (wild_menu_showing == WM_SCROLLED)
{
/* Entered command line, move it up */
cmdline_row--;
redrawcmd();
}
else if (save_p_ls != -1)
{
/* restore 'laststatus' and 'winminheight' */
p_ls = save_p_ls;
p_wmh = save_p_wmh;
last_status(FALSE);
save_cmdline(&save_ccline);
update_screen(VALID); /* redraw the screen NOW */
restore_cmdline(&save_ccline);
redrawcmd();
save_p_ls = -1;
}
else
{
# ifdef FEAT_VERTSPLIT
win_redraw_last_status(topframe);
# else
lastwin->w_redr_status = TRUE;
# endif
redraw_statuslines();
}
KeyTyped = skt;
wild_menu_showing = 0;
if (ccline.input_fn)
RedrawingDisabled = old_RedrawingDisabled;
}
#endif
}
#ifdef FEAT_WILDMENU
/* Special translations for 'wildmenu' */
if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu)
{
/* Hitting <Down> after "emenu Name.": complete submenu */
if (c == K_DOWN && ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == '.')
c = p_wc;
else if (c == K_UP)
{
/* Hitting <Up>: Remove one submenu name in front of the
* cursor */
int found = FALSE;
j = (int)(xpc.xp_pattern - ccline.cmdbuff);
i = 0;
while (--j > 0)
{
/* check for start of menu name */
if (ccline.cmdbuff[j] == ' '
&& ccline.cmdbuff[j - 1] != '\\')
{
i = j + 1;
break;
}
/* check for start of submenu name */
if (ccline.cmdbuff[j] == '.'
&& ccline.cmdbuff[j - 1] != '\\')
{
if (found)
{
i = j + 1;
break;
}
else
found = TRUE;
}
}
if (i > 0)
cmdline_del(i);
c = p_wc;
xpc.xp_context = EXPAND_NOTHING;
}
}
if ((xpc.xp_context == EXPAND_FILES
|| xpc.xp_context == EXPAND_DIRECTORIES
|| xpc.xp_context == EXPAND_SHELLCMD) && p_wmnu)
{
char_u upseg[5];
upseg[0] = PATHSEP;
upseg[1] = '.';
upseg[2] = '.';
upseg[3] = PATHSEP;
upseg[4] = NUL;
if (c == K_DOWN
&& ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == PATHSEP
&& (ccline.cmdpos < 3
|| ccline.cmdbuff[ccline.cmdpos - 2] != '.'
|| ccline.cmdbuff[ccline.cmdpos - 3] != '.'))
{
/* go down a directory */
c = p_wc;
}
else if (STRNCMP(xpc.xp_pattern, upseg + 1, 3) == 0 && c == K_DOWN)
{
/* If in a direct ancestor, strip off one ../ to go down */
int found = FALSE;
j = ccline.cmdpos;
i = (int)(xpc.xp_pattern - ccline.cmdbuff);
while (--j > i)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
#endif
if (vim_ispathsep(ccline.cmdbuff[j]))
{
found = TRUE;
break;
}
}
if (found
&& ccline.cmdbuff[j - 1] == '.'
&& ccline.cmdbuff[j - 2] == '.'
&& (vim_ispathsep(ccline.cmdbuff[j - 3]) || j == i + 2))
{
cmdline_del(j - 2);
c = p_wc;
}
}
else if (c == K_UP)
{
/* go up a directory */
int found = FALSE;
j = ccline.cmdpos - 1;
i = (int)(xpc.xp_pattern - ccline.cmdbuff);
while (--j > i)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
#endif
if (vim_ispathsep(ccline.cmdbuff[j])
#ifdef BACKSLASH_IN_FILENAME
&& vim_strchr(" *?[{`$%#", ccline.cmdbuff[j + 1])
== NULL
#endif
)
{
if (found)
{
i = j + 1;
break;
}
else
found = TRUE;
}
}
if (!found)
j = i;
else if (STRNCMP(ccline.cmdbuff + j, upseg, 4) == 0)
j += 4;
else if (STRNCMP(ccline.cmdbuff + j, upseg + 1, 3) == 0
&& j == i)
j += 3;
else
j = 0;
if (j > 0)
{
/* TODO this is only for DOS/UNIX systems - need to put in
* machine-specific stuff here and in upseg init */
cmdline_del(j);
put_on_cmdline(upseg + 1, 3, FALSE);
}
else if (ccline.cmdpos > i)
cmdline_del(i);
/* Now complete in the new directory. Set KeyTyped in case the
* Up key came from a mapping. */
c = p_wc;
KeyTyped = TRUE;
}
}
#endif /* FEAT_WILDMENU */
/* CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
* mode when 'insertmode' is set, CTRL-\ e prompts for an expression. */
if (c == Ctrl_BSL)
{
++no_mapping;
++allow_keys;
c = plain_vgetc();
--no_mapping;
--allow_keys;
/* CTRL-\ e doesn't work when obtaining an expression. */
if (c != Ctrl_N && c != Ctrl_G
&& (c != 'e' || ccline.cmdfirstc == '='))
{
vungetc(c);
c = Ctrl_BSL;
}
#ifdef FEAT_EVAL
else if (c == 'e')
{
char_u *p = NULL;
int len;
/*
* Replace the command line with the result of an expression.
* Need to save and restore the current command line, to be
* able to enter a new one...
*/
if (ccline.cmdpos == ccline.cmdlen)
new_cmdpos = 99999; /* keep it at the end */
else
new_cmdpos = ccline.cmdpos;
save_cmdline(&save_ccline);
c = get_expr_register();
restore_cmdline(&save_ccline);
if (c == '=')
{
/* Need to save and restore ccline. And set "textlock"
* to avoid nasty things like going to another buffer when
* evaluating an expression. */
save_cmdline(&save_ccline);
++textlock;
p = get_expr_line();
--textlock;
restore_cmdline(&save_ccline);
if (p != NULL)
{
len = (int)STRLEN(p);
if (realloc_cmdbuff(len + 1) == OK)
{
ccline.cmdlen = len;
STRCPY(ccline.cmdbuff, p);
vim_free(p);
/* Restore the cursor or use the position set with
* set_cmdline_pos(). */
if (new_cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
else
ccline.cmdpos = new_cmdpos;
KeyTyped = FALSE; /* Don't do p_wc completion. */
redrawcmd();
goto cmdline_changed;
}
}
}
beep_flush();
got_int = FALSE; /* don't abandon the command line */
did_emsg = FALSE;
emsg_on_display = FALSE;
redrawcmd();
goto cmdline_not_changed;
}
#endif
else
{
if (c == Ctrl_G && p_im && restart_edit == 0)
restart_edit = 'a';
gotesc = TRUE; /* will free ccline.cmdbuff after putting it
in history */
goto returncmd; /* back to Normal mode */
}
}
#ifdef FEAT_CMDWIN
if (c == cedit_key || c == K_CMDWIN)
{
/*
* Open a window to edit the command line (and history).
*/
c = ex_window();
some_key_typed = TRUE;
}
# ifdef FEAT_DIGRAPHS
else
# endif
#endif
#ifdef FEAT_DIGRAPHS
c = do_digraph(c);
#endif
if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
{
/* In Ex mode a backslash escapes a newline. */
if (exmode_active
&& c != ESC
&& ccline.cmdpos == ccline.cmdlen
&& ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
{
if (c == K_KENTER)
c = '\n';
}
else
{
gotesc = FALSE; /* Might have typed ESC previously, don't
truncate the cmdline now. */
if (ccheck_abbr(c + ABBR_OFF))
goto cmdline_changed;
if (!cmd_silent)
{
windgoto(msg_row, 0);
out_flush();
}
break;
}
}
/*
* Completion for 'wildchar' or 'wildcharm' key.
* - hitting <ESC> twice means: abandon command line.
* - wildcard expansion is only done when the 'wildchar' key is really
* typed, not when it comes from a macro
*/
if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
{
if (xpc.xp_numfiles > 0) /* typed p_wc at least twice */
{
/* if 'wildmode' contains "list" may still need to list */
if (xpc.xp_numfiles > 1
&& !did_wild_list
&& (wim_flags[wim_index] & WIM_LIST))
{
(void)showmatches(&xpc, FALSE);
redrawcmd();
did_wild_list = TRUE;
}
if (wim_flags[wim_index] & WIM_LONGEST)
res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
else if (wim_flags[wim_index] & WIM_FULL)
res = nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
else
res = OK; /* don't insert 'wildchar' now */
}
else /* typed p_wc first time */
{
wim_index = 0;
j = ccline.cmdpos;
/* if 'wildmode' first contains "longest", get longest
* common part */
if (wim_flags[0] & WIM_LONGEST)
res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
else
res = nextwild(&xpc, WILD_EXPAND_KEEP, WILD_NO_BEEP);
/* if interrupted while completing, behave like it failed */
if (got_int)
{
(void)vpeekc(); /* remove <C-C> from input stream */
got_int = FALSE; /* don't abandon the command line */
(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
#ifdef FEAT_WILDMENU
xpc.xp_context = EXPAND_NOTHING;
#endif
goto cmdline_changed;
}
/* when more than one match, and 'wildmode' first contains
* "list", or no change and 'wildmode' contains "longest,list",
* list all matches */
if (res == OK && xpc.xp_numfiles > 1)
{
/* a "longest" that didn't do anything is skipped (but not
* "list:longest") */
if (wim_flags[0] == WIM_LONGEST && ccline.cmdpos == j)
wim_index = 1;
if ((wim_flags[wim_index] & WIM_LIST)
#ifdef FEAT_WILDMENU
|| (p_wmnu && (wim_flags[wim_index] & WIM_FULL) != 0)
#endif
)
{
if (!(wim_flags[0] & WIM_LONGEST))
{
#ifdef FEAT_WILDMENU
int p_wmnu_save = p_wmnu;
p_wmnu = 0;
#endif
nextwild(&xpc, WILD_PREV, 0); /* remove match */
#ifdef FEAT_WILDMENU
p_wmnu = p_wmnu_save;
#endif
}
#ifdef FEAT_WILDMENU
(void)showmatches(&xpc, p_wmnu
&& ((wim_flags[wim_index] & WIM_LIST) == 0));
#else
(void)showmatches(&xpc, FALSE);
#endif
redrawcmd();
did_wild_list = TRUE;
if (wim_flags[wim_index] & WIM_LONGEST)
nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
else if (wim_flags[wim_index] & WIM_FULL)
nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
}
else
vim_beep();
}
#ifdef FEAT_WILDMENU
else if (xpc.xp_numfiles == -1)
xpc.xp_context = EXPAND_NOTHING;
#endif
}
if (wim_index < 3)
++wim_index;
if (c == ESC)
gotesc = TRUE;
if (res == OK)
goto cmdline_changed;
}
gotesc = FALSE;
/* <S-Tab> goes to last match, in a clumsy way */
if (c == K_S_TAB && KeyTyped)
{
if (nextwild(&xpc, WILD_EXPAND_KEEP, 0) == OK
&& nextwild(&xpc, WILD_PREV, 0) == OK
&& nextwild(&xpc, WILD_PREV, 0) == OK)
goto cmdline_changed;
}
if (c == NUL || c == K_ZERO) /* NUL is stored as NL */
c = NL;
do_abbr = TRUE; /* default: check for abbreviation */
/*
* Big switch for a typed command line character.
*/
switch (c)
{
case K_BS:
case Ctrl_H:
case K_DEL:
case K_KDEL:
case Ctrl_W:
#ifdef FEAT_FKMAP
if (cmd_fkmap && c == K_BS)
c = K_DEL;
#endif
if (c == K_KDEL)
c = K_DEL;
/*
* delete current character is the same as backspace on next
* character, except at end of line
*/
if (c == K_DEL && ccline.cmdpos != ccline.cmdlen)
++ccline.cmdpos;
#ifdef FEAT_MBYTE
if (has_mbyte && c == K_DEL)
ccline.cmdpos += mb_off_next(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos);
#endif
if (ccline.cmdpos > 0)
{
char_u *p;
j = ccline.cmdpos;
p = ccline.cmdbuff + j;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
p = mb_prevptr(ccline.cmdbuff, p);
if (c == Ctrl_W)
{
while (p > ccline.cmdbuff && vim_isspace(*p))
p = mb_prevptr(ccline.cmdbuff, p);
i = mb_get_class(p);
while (p > ccline.cmdbuff && mb_get_class(p) == i)
p = mb_prevptr(ccline.cmdbuff, p);
if (mb_get_class(p) != i)
p += (*mb_ptr2len)(p);
}
}
else
#endif
if (c == Ctrl_W)
{
while (p > ccline.cmdbuff && vim_isspace(p[-1]))
--p;
i = vim_iswordc(p[-1]);
while (p > ccline.cmdbuff && !vim_isspace(p[-1])
&& vim_iswordc(p[-1]) == i)
--p;
}
else
--p;
ccline.cmdpos = (int)(p - ccline.cmdbuff);
ccline.cmdlen -= j - ccline.cmdpos;
i = ccline.cmdpos;
while (i < ccline.cmdlen)
ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
/* Truncate at the end, required for multi-byte chars. */
ccline.cmdbuff[ccline.cmdlen] = NUL;
redrawcmd();
}
else if (ccline.cmdlen == 0 && c != Ctrl_W
&& ccline.cmdprompt == NULL && indent == 0)
{
/* In ex and debug mode it doesn't make sense to return. */
if (exmode_active
#ifdef FEAT_EVAL
|| ccline.cmdfirstc == '>'
#endif
)
goto cmdline_not_changed;
vim_free(ccline.cmdbuff); /* no commandline to return */
ccline.cmdbuff = NULL;
if (!cmd_silent)
{
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
msg_col = Columns;
else
#endif
msg_col = 0;
msg_putchar(' '); /* delete ':' */
}
redraw_cmdline = TRUE;
goto returncmd; /* back to cmd mode */
}
goto cmdline_changed;
case K_INS:
case K_KINS:
#ifdef FEAT_FKMAP
/* if Farsi mode set, we are in reverse insert mode -
Do not change the mode */
if (cmd_fkmap)
beep_flush();
else
#endif
ccline.overstrike = !ccline.overstrike;
#ifdef CURSOR_SHAPE
ui_cursor_shape(); /* may show different cursor shape */
#endif
goto cmdline_not_changed;
case Ctrl_HAT:
if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
{
/* ":lmap" mappings exists, toggle use of mappings. */
State ^= LANGMAP;
#ifdef USE_IM_CONTROL
im_set_active(FALSE); /* Disable input method */
#endif
if (b_im_ptr != NULL)
{
if (State & LANGMAP)
*b_im_ptr = B_IMODE_LMAP;
else
*b_im_ptr = B_IMODE_NONE;
}
}
#ifdef USE_IM_CONTROL
else
{
/* There are no ":lmap" mappings, toggle IM. When
* 'imdisable' is set don't try getting the status, it's
* always off. */
if ((p_imdisable && b_im_ptr != NULL)
? *b_im_ptr == B_IMODE_IM : im_get_status())
{
im_set_active(FALSE); /* Disable input method */
if (b_im_ptr != NULL)
*b_im_ptr = B_IMODE_NONE;
}
else
{
im_set_active(TRUE); /* Enable input method */
if (b_im_ptr != NULL)
*b_im_ptr = B_IMODE_IM;
}
}
#endif
if (b_im_ptr != NULL)
{
if (b_im_ptr == &curbuf->b_p_iminsert)
set_iminsert_global();
else
set_imsearch_global();
}
#ifdef CURSOR_SHAPE
ui_cursor_shape(); /* may show different cursor shape */
#endif
#if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
/* Show/unshow value of 'keymap' in status lines later. */
status_redraw_curbuf();
#endif
goto cmdline_not_changed;
/* case '@': only in very old vi */
case Ctrl_U:
/* delete all characters left of the cursor */
j = ccline.cmdpos;
ccline.cmdlen -= j;
i = ccline.cmdpos = 0;
while (i < ccline.cmdlen)
ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
/* Truncate at the end, required for multi-byte chars. */
ccline.cmdbuff[ccline.cmdlen] = NUL;
redrawcmd();
goto cmdline_changed;
#ifdef FEAT_CLIPBOARD
case Ctrl_Y:
/* Copy the modeless selection, if there is one. */
if (clip_star.state != SELECT_CLEARED)
{
if (clip_star.state == SELECT_DONE)
clip_copy_modeless_selection(TRUE);
goto cmdline_not_changed;
}
break;
#endif
case ESC: /* get here if p_wc != ESC or when ESC typed twice */
case Ctrl_C:
/* In exmode it doesn't make sense to return. Except when
* ":normal" runs out of characters. */
if (exmode_active
#ifdef FEAT_EX_EXTRA
&& (ex_normal_busy == 0 || typebuf.tb_len > 0)
#endif
)
goto cmdline_not_changed;
gotesc = TRUE; /* will free ccline.cmdbuff after
putting it in history */
goto returncmd; /* back to cmd mode */
case Ctrl_R: /* insert register */
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
putcmdline('"', TRUE);
++no_mapping;
i = c = plain_vgetc(); /* CTRL-R <char> */
if (i == Ctrl_O)
i = Ctrl_R; /* CTRL-R CTRL-O == CTRL-R CTRL-R */
if (i == Ctrl_R)
c = plain_vgetc(); /* CTRL-R CTRL-R <char> */
--no_mapping;
#ifdef FEAT_EVAL
/*
* Insert the result of an expression.
* Need to save the current command line, to be able to enter
* a new one...
*/
new_cmdpos = -1;
if (c == '=')
{
if (ccline.cmdfirstc == '=')/* can't do this recursively */
{
beep_flush();
c = ESC;
}
else
{
save_cmdline(&save_ccline);
c = get_expr_register();
restore_cmdline(&save_ccline);
}
}
#endif
if (c != ESC) /* use ESC to cancel inserting register */
{
cmdline_paste(c, i == Ctrl_R, FALSE);
#ifdef FEAT_EVAL
/* When there was a serious error abort getting the
* command line. */
if (aborting())
{
gotesc = TRUE; /* will free ccline.cmdbuff after
putting it in history */
goto returncmd; /* back to cmd mode */
}
#endif
KeyTyped = FALSE; /* Don't do p_wc completion. */
#ifdef FEAT_EVAL
if (new_cmdpos >= 0)
{
/* set_cmdline_pos() was used */
if (new_cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
else
ccline.cmdpos = new_cmdpos;
}
#endif
}
redrawcmd();
goto cmdline_changed;
case Ctrl_D:
if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
break; /* Use ^D as normal char instead */
redrawcmd();
continue; /* don't do incremental search now */
case K_RIGHT:
case K_S_RIGHT:
case K_C_RIGHT:
do
{
if (ccline.cmdpos >= ccline.cmdlen)
break;
i = cmdline_charsize(ccline.cmdpos);
if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
break;
ccline.cmdspos += i;
#ifdef FEAT_MBYTE
if (has_mbyte)
ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
+ ccline.cmdpos);
else
#endif
++ccline.cmdpos;
}
while ((c == K_S_RIGHT || c == K_C_RIGHT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos] != ' ');
#ifdef FEAT_MBYTE
if (has_mbyte)
set_cmdspos_cursor();
#endif
goto cmdline_not_changed;
case K_LEFT:
case K_S_LEFT:
case K_C_LEFT:
if (ccline.cmdpos == 0)
goto cmdline_not_changed;
do
{
--ccline.cmdpos;
#ifdef FEAT_MBYTE
if (has_mbyte) /* move to first byte of char */
ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos);
#endif
ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
}
while (ccline.cmdpos > 0
&& (c == K_S_LEFT || c == K_C_LEFT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
#ifdef FEAT_MBYTE
if (has_mbyte)
set_cmdspos_cursor();
#endif
goto cmdline_not_changed;
case K_IGNORE:
/* Ignore mouse event or ex_window() result. */
goto cmdline_not_changed;
#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)
{
redrawcmd(); /* somehow the cmdline is cleared */
goto cmdline_not_changed;
}
break;
#endif
#ifdef FEAT_MOUSE
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
goto cmdline_not_changed; /* Ignore mouse */
case K_MIDDLEMOUSE:
# ifdef FEAT_GUI
/* When GUI is active, also paste when 'mouse' is empty */
if (!gui.in_use)
# endif
if (!mouse_has(MOUSE_COMMAND))
goto cmdline_not_changed; /* Ignore mouse */
# ifdef FEAT_CLIPBOARD
if (clip_star.available)
cmdline_paste('*', TRUE, TRUE);
else
# endif
cmdline_paste(0, TRUE, TRUE);
redrawcmd();
goto cmdline_changed;
# ifdef FEAT_DND
case K_DROP:
cmdline_paste('~', TRUE, FALSE);
redrawcmd();
goto cmdline_changed;
# endif
case K_LEFTDRAG:
case K_LEFTRELEASE:
case K_RIGHTDRAG:
case K_RIGHTRELEASE:
/* Ignore drag and release events when the button-down wasn't
* seen before. */
if (ignore_drag_release)
goto cmdline_not_changed;
/* FALLTHROUGH */
case K_LEFTMOUSE:
case K_RIGHTMOUSE:
if (c == K_LEFTRELEASE || c == K_RIGHTRELEASE)
ignore_drag_release = TRUE;
else
ignore_drag_release = FALSE;
# ifdef FEAT_GUI
/* When GUI is active, also move when 'mouse' is empty */
if (!gui.in_use)
# endif
if (!mouse_has(MOUSE_COMMAND))
goto cmdline_not_changed; /* Ignore mouse */
# ifdef FEAT_CLIPBOARD
if (mouse_row < cmdline_row && clip_star.available)
{
int button, is_click, is_drag;
/*
* Handle modeless selection.
*/
button = get_mouse_button(KEY2TERMCAP1(c),
&is_click, &is_drag);
if (mouse_model_popup() && button == MOUSE_LEFT
&& (mod_mask & MOD_MASK_SHIFT))
{
/* Translate shift-left to right button. */
button = MOUSE_RIGHT;
mod_mask &= ~MOD_MASK_SHIFT;
}
clip_modeless(button, is_click, is_drag);
goto cmdline_not_changed;
}
# endif
set_cmdspos();
for (ccline.cmdpos = 0; ccline.cmdpos < ccline.cmdlen;
++ccline.cmdpos)
{
i = cmdline_charsize(ccline.cmdpos);
if (mouse_row <= cmdline_row + ccline.cmdspos / Columns
&& mouse_col < ccline.cmdspos % Columns + i)
break;
# ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Count ">" for double-wide char that doesn't fit. */
correct_cmdspos(ccline.cmdpos, i);
ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
+ ccline.cmdpos) - 1;
}
# endif
ccline.cmdspos += i;
}
goto cmdline_not_changed;
/* Mouse scroll wheel: ignored here */
case K_MOUSEDOWN:
case K_MOUSEUP:
case K_MOUSELEFT:
case K_MOUSERIGHT:
/* Alternate buttons ignored here */
case K_X1MOUSE:
case K_X1DRAG:
case K_X1RELEASE:
case K_X2MOUSE:
case K_X2DRAG:
case K_X2RELEASE:
goto cmdline_not_changed;
#endif /* FEAT_MOUSE */
#ifdef FEAT_GUI
case K_LEFTMOUSE_NM: /* mousefocus click, ignored */
case K_LEFTRELEASE_NM:
goto cmdline_not_changed;
case K_VER_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_scroll();
redrawcmd();
}
goto cmdline_not_changed;
case K_HOR_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_horiz_scroll(scrollbar_value, FALSE);
redrawcmd();
}
goto cmdline_not_changed;
#endif
#ifdef FEAT_GUI_TABLINE
case K_TABLINE:
case K_TABMENU:
/* Don't want to change any tabs here. Make sure the same tab
* is still selected. */
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
goto cmdline_not_changed;
#endif
case K_SELECT: /* end of Select mode mapping - ignore */
goto cmdline_not_changed;
case Ctrl_B: /* begin of command line */
case K_HOME:
case K_KHOME:
case K_S_HOME:
case K_C_HOME:
ccline.cmdpos = 0;
set_cmdspos();
goto cmdline_not_changed;
case Ctrl_E: /* end of command line */
case K_END:
case K_KEND:
case K_S_END:
case K_C_END:
ccline.cmdpos = ccline.cmdlen;
set_cmdspos_cursor();
goto cmdline_not_changed;
case Ctrl_A: /* all matches */
if (nextwild(&xpc, WILD_ALL, 0) == FAIL)
break;
goto cmdline_changed;
case Ctrl_L:
#ifdef FEAT_SEARCH_EXTRA
if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
{
/* Add a character from under the cursor for 'incsearch' */
if (did_incsearch
&& !equalpos(curwin->w_cursor, old_cursor))
{
c = gchar_cursor();
/* If 'ignorecase' and 'smartcase' are set and the
* command line has no uppercase characters, convert
* the character to lowercase */
if (p_ic && p_scs && !pat_has_uppercase(ccline.cmdbuff))
c = MB_TOLOWER(c);
if (c != NUL)
{
if (c == firstc || vim_strchr((char_u *)(
p_magic ? "\\^$.*[" : "\\^$"), c)
!= NULL)
{
/* put a backslash before special characters */
stuffcharReadbuff(c);
c = '\\';
}
break;
}
}
goto cmdline_not_changed;
}
#endif
/* completion: longest common part */
if (nextwild(&xpc, WILD_LONGEST, 0) == FAIL)
break;
goto cmdline_changed;
case Ctrl_N: /* next match */
case Ctrl_P: /* previous match */
if (xpc.xp_numfiles > 0)
{
if (nextwild(&xpc, (c == Ctrl_P) ? WILD_PREV : WILD_NEXT, 0)
== FAIL)
break;
goto cmdline_changed;
}
#ifdef FEAT_CMDHIST
case K_UP:
case K_DOWN:
case K_S_UP:
case K_S_DOWN:
case K_PAGEUP:
case K_KPAGEUP:
case K_PAGEDOWN:
case K_KPAGEDOWN:
if (hislen == 0 || firstc == NUL) /* no history */
goto cmdline_not_changed;
i = hiscnt;
/* save current command string so it can be restored later */
if (lookfor == NULL)
{
if ((lookfor = vim_strsave(ccline.cmdbuff)) == NULL)
goto cmdline_not_changed;
lookfor[ccline.cmdpos] = NUL;
}
j = (int)STRLEN(lookfor);
for (;;)
{
/* one step backwards */
if (c == K_UP|| c == K_S_UP || c == Ctrl_P
|| c == K_PAGEUP || c == K_KPAGEUP)
{
if (hiscnt == hislen) /* first time */
hiscnt = hisidx[histype];
else if (hiscnt == 0 && hisidx[histype] != hislen - 1)
hiscnt = hislen - 1;
else if (hiscnt != hisidx[histype] + 1)
--hiscnt;
else /* at top of list */
{
hiscnt = i;
break;
}
}
else /* one step forwards */
{
/* on last entry, clear the line */
if (hiscnt == hisidx[histype])
{
hiscnt = hislen;
break;
}
/* not on a history line, nothing to do */
if (hiscnt == hislen)
break;
if (hiscnt == hislen - 1) /* wrap around */
hiscnt = 0;
else
++hiscnt;
}
if (hiscnt < 0 || history[histype][hiscnt].hisstr == NULL)
{
hiscnt = i;
break;
}
if ((c != K_UP && c != K_DOWN)
|| hiscnt == i
|| STRNCMP(history[histype][hiscnt].hisstr,
lookfor, (size_t)j) == 0)
break;
}
if (hiscnt != i) /* jumped to other entry */
{
char_u *p;
int len;
int old_firstc;
vim_free(ccline.cmdbuff);
xpc.xp_context = EXPAND_NOTHING;
if (hiscnt == hislen)
p = lookfor; /* back to the old one */
else
p = history[histype][hiscnt].hisstr;
if (histype == HIST_SEARCH
&& p != lookfor
&& (old_firstc = p[STRLEN(p) + 1]) != firstc)
{
/* Correct for the separator character used when
* adding the history entry vs the one used now.
* First loop: count length.
* Second loop: copy the characters. */
for (i = 0; i <= 1; ++i)
{
len = 0;
for (j = 0; p[j] != NUL; ++j)
{
/* Replace old sep with new sep, unless it is
* escaped. */
if (p[j] == old_firstc
&& (j == 0 || p[j - 1] != '\\'))
{
if (i > 0)
ccline.cmdbuff[len] = firstc;
}
else
{
/* Escape new sep, unless it is already
* escaped. */
if (p[j] == firstc
&& (j == 0 || p[j - 1] != '\\'))
{
if (i > 0)
ccline.cmdbuff[len] = '\\';
++len;
}
if (i > 0)
ccline.cmdbuff[len] = p[j];
}
++len;
}
if (i == 0)
{
alloc_cmdbuff(len);
if (ccline.cmdbuff == NULL)
goto returncmd;
}
}
ccline.cmdbuff[len] = NUL;
}
else
{
alloc_cmdbuff((int)STRLEN(p));
if (ccline.cmdbuff == NULL)
goto returncmd;
STRCPY(ccline.cmdbuff, p);
}
ccline.cmdpos = ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
redrawcmd();
goto cmdline_changed;
}
beep_flush();
goto cmdline_not_changed;
#endif
case Ctrl_V:
case Ctrl_Q:
#ifdef FEAT_MOUSE
ignore_drag_release = TRUE;
#endif
putcmdline('^', TRUE);
c = get_literal(); /* get next (two) character(s) */
do_abbr = FALSE; /* don't do abbreviation now */
#ifdef FEAT_MBYTE
/* may need to remove ^ when composing char was typed */
if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
{
draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
msg_putchar(' ');
cursorcmd();
}
#endif
break;
#ifdef FEAT_DIGRAPHS
case Ctrl_K:
#ifdef FEAT_MOUSE
ignore_drag_release = TRUE;
#endif
putcmdline('?', TRUE);
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
c = get_digraph(TRUE);
if (c != NUL)
break;
redrawcmd();
goto cmdline_not_changed;
#endif /* FEAT_DIGRAPHS */
#ifdef FEAT_RIGHTLEFT
case Ctrl__: /* CTRL-_: switch language mode */
if (!p_ari)
break;
#ifdef FEAT_FKMAP
if (p_altkeymap)
{
cmd_fkmap = !cmd_fkmap;
if (cmd_fkmap) /* in Farsi always in Insert mode */
ccline.overstrike = FALSE;
}
else /* Hebrew is default */
#endif
cmd_hkmap = !cmd_hkmap;
goto cmdline_not_changed;
#endif
default:
#ifdef UNIX
if (c == intr_char)
{
gotesc = TRUE; /* will free ccline.cmdbuff after
putting it in history */
goto returncmd; /* back to Normal mode */
}
#endif
/*
* Normal character with no special meaning. Just set mod_mask
* to 0x0 so that typing Shift-Space in the GUI doesn't enter
* the string <S-Space>. This should only happen after ^V.
*/
if (!IS_SPECIAL(c))
mod_mask = 0x0;
break;
}
/*
* End of switch on command line character.
* We come here if we have a normal character.
*/
if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c)) && ccheck_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))
goto cmdline_changed;
/*
* put the character in the command line
*/
if (IS_SPECIAL(c) || mod_mask != 0)
put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
else
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
j = (*mb_char2bytes)(c, IObuff);
IObuff[j] = NUL; /* exclude composing chars */
put_on_cmdline(IObuff, j, TRUE);
}
else
#endif
{
IObuff[0] = c;
put_on_cmdline(IObuff, 1, TRUE);
}
}
goto cmdline_changed;
/*
* This part implements incremental searches for "/" and "?"
* Jump to cmdline_not_changed when a character has been read but the command
* line did not change. Then we only search and redraw if something changed in
* the past.
* Jump to cmdline_changed when the command line did change.
* (Sorry for the goto's, I know it is ugly).
*/
cmdline_not_changed:
#ifdef FEAT_SEARCH_EXTRA
if (!incsearch_postponed)
continue;
#endif
cmdline_changed:
#ifdef FEAT_SEARCH_EXTRA
/*
* 'incsearch' highlighting.
*/
if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
{
pos_T end_pos;
#ifdef FEAT_RELTIME
proftime_T tm;
#endif
/* if there is a character waiting, search and redraw later */
if (char_avail())
{
incsearch_postponed = TRUE;
continue;
}
incsearch_postponed = FALSE;
curwin->w_cursor = old_cursor; /* start at old position */
/* If there is no command line, don't do anything */
if (ccline.cmdlen == 0)
i = 0;
else
{
cursor_off(); /* so the user knows we're busy */
out_flush();
++emsg_off; /* So it doesn't beep if bad expr */
#ifdef FEAT_RELTIME
/* Set the time limit to half a second. */
profile_setlimit(500L, &tm);
#endif
i = do_search(NULL, firstc, ccline.cmdbuff, count,
SEARCH_KEEP + SEARCH_OPT + SEARCH_NOOF + SEARCH_PEEK,
#ifdef FEAT_RELTIME
&tm
#else
NULL
#endif
);
--emsg_off;
/* if interrupted while searching, behave like it failed */
if (got_int)
{
(void)vpeekc(); /* remove <C-C> from input stream */
got_int = FALSE; /* don't abandon the command line */
i = 0;
}
else if (char_avail())
/* cancelled searching because a char was typed */
incsearch_postponed = TRUE;
}
if (i != 0)
highlight_match = TRUE; /* highlight position */
else
highlight_match = FALSE; /* remove highlight */
/* first restore the old curwin values, so the screen is
* positioned in the same way as the actual search command */
curwin->w_leftcol = old_leftcol;
curwin->w_topline = old_topline;
# ifdef FEAT_DIFF
curwin->w_topfill = old_topfill;
# endif
curwin->w_botline = old_botline;
changed_cline_bef_curs();
update_topline();
if (i != 0)
{
pos_T save_pos = curwin->w_cursor;
/*
* First move cursor to end of match, then to the start. This
* moves the whole match onto the screen when 'nowrap' is set.
*/
curwin->w_cursor.lnum += search_match_lines;
curwin->w_cursor.col = search_match_endcol;
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
{
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
coladvance((colnr_T)MAXCOL);
}
validate_cursor();
end_pos = curwin->w_cursor;
curwin->w_cursor = save_pos;
}
else
end_pos = curwin->w_cursor; /* shutup gcc 4 */
validate_cursor();
# ifdef FEAT_WINDOWS
/* May redraw the status line to show the cursor position. */
if (p_ru && curwin->w_status_height > 0)
curwin->w_redr_status = TRUE;
# endif
save_cmdline(&save_ccline);
update_screen(SOME_VALID);
restore_cmdline(&save_ccline);
/* Leave it at the end to make CTRL-R CTRL-W work. */
if (i != 0)
curwin->w_cursor = end_pos;
msg_starthere();
redrawcmdline();
did_incsearch = TRUE;
}
#else /* FEAT_SEARCH_EXTRA */
;
#endif
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl
# ifdef FEAT_ARABIC
|| (p_arshape && !p_tbidi && enc_utf8)
# endif
)
/* Always redraw the whole command line to fix shaping and
* right-left typing. Not efficient, but it works.
* Do it only when there are no characters left to read
* to avoid useless intermediate redraws. */
if (vpeekc() == NUL)
redrawcmd();
#endif
}
returncmd:
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl = FALSE;
#endif
#ifdef FEAT_FKMAP
cmd_fkmap = 0;
#endif
ExpandCleanup(&xpc);
ccline.xpc = NULL;
#ifdef FEAT_SEARCH_EXTRA
if (did_incsearch)
{
curwin->w_cursor = old_cursor;
curwin->w_curswant = old_curswant;
curwin->w_leftcol = old_leftcol;
curwin->w_topline = old_topline;
# ifdef FEAT_DIFF
curwin->w_topfill = old_topfill;
# endif
curwin->w_botline = old_botline;
highlight_match = FALSE;
validate_cursor(); /* needed for TAB */
redraw_later(SOME_VALID);
}
#endif
if (ccline.cmdbuff != NULL)
{
/*
* Put line in history buffer (":" and "=" only when it was typed).
*/
#ifdef FEAT_CMDHIST
if (ccline.cmdlen && firstc != NUL
&& (some_key_typed || histype == HIST_SEARCH))
{
add_to_history(histype, ccline.cmdbuff, TRUE,
histype == HIST_SEARCH ? firstc : NUL);
if (firstc == ':')
{
vim_free(new_last_cmdline);
new_last_cmdline = vim_strsave(ccline.cmdbuff);
}
}
#endif
if (gotesc) /* abandon command line */
{
vim_free(ccline.cmdbuff);
ccline.cmdbuff = NULL;
if (msg_scrolled == 0)
compute_cmdrow();
MSG("");
redraw_cmdline = TRUE;
}
}
/*
* If the screen was shifted up, redraw the whole screen (later).
* If the line is too long, clear it, so ruler and shown command do
* not get printed in the middle of it.
*/
msg_check();
msg_scroll = save_msg_scroll;
redir_off = FALSE;
/* When the command line was typed, no need for a wait-return prompt. */
if (some_key_typed)
need_wait_return = FALSE;
State = save_State;
#ifdef USE_IM_CONTROL
if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
im_save_status(b_im_ptr);
im_set_active(FALSE);
#endif
#ifdef FEAT_MOUSE
setmouse();
#endif
#ifdef CURSOR_SHAPE
ui_cursor_shape(); /* may show different cursor shape */
#endif
{
char_u *p = ccline.cmdbuff;
/* Make ccline empty, getcmdline() may try to use it. */
ccline.cmdbuff = NULL;
return p;
}
}
#if (defined(FEAT_CRYPT) || defined(FEAT_EVAL)) || defined(PROTO)
/*
* Get a command line with a prompt.
* This is prepared to be called recursively from getcmdline() (e.g. by
* f_input() when evaluating an expression from CTRL-R =).
* Returns the command line in allocated memory, or NULL.
*/
char_u *
getcmdline_prompt(firstc, prompt, attr, xp_context, xp_arg)
int firstc;
char_u *prompt; /* command line prompt */
int attr; /* attributes for prompt */
int xp_context; /* type of expansion */
char_u *xp_arg; /* user-defined expansion argument */
{
char_u *s;
struct cmdline_info save_ccline;
int msg_col_save = msg_col;
save_cmdline(&save_ccline);
ccline.cmdprompt = prompt;
ccline.cmdattr = attr;
# ifdef FEAT_EVAL
ccline.xp_context = xp_context;
ccline.xp_arg = xp_arg;
ccline.input_fn = (firstc == '@');
# endif
s = getcmdline(firstc, 1L, 0);
restore_cmdline(&save_ccline);
/* Restore msg_col, the prompt from input() may have changed it.
* But only if called recursively and the commandline is therefore being
* restored to an old one; if not, the input() prompt stays on the screen,
* so we need its modified msg_col left intact. */
if (ccline.cmdbuff != NULL)
msg_col = msg_col_save;
return s;
}
#endif
/*
* Return TRUE when the text must not be changed and we can't switch to
* another window or buffer. Used when editing the command line, evaluating
* 'balloonexpr', etc.
*/
int
text_locked()
{
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
return TRUE;
#endif
return textlock != 0;
}
/*
* Give an error message for a command that isn't allowed while the cmdline
* window is open or editing the cmdline in another way.
*/
void
text_locked_msg()
{
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
EMSG(_(e_cmdwin));
else
#endif
EMSG(_(e_secure));
}
#if defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* Check if "curbuf_lock" or "allbuf_lock" is set and return TRUE when it is
* and give an error message.
*/
int
curbuf_locked()
{
if (curbuf_lock > 0)
{
EMSG(_("E788: Not allowed to edit another buffer now"));
return TRUE;
}
return allbuf_locked();
}
/*
* Check if "allbuf_lock" is set and return TRUE when it is and give an error
* message.
*/
int
allbuf_locked()
{
if (allbuf_lock > 0)
{
EMSG(_("E811: Not allowed to change buffer information now"));
return TRUE;
}
return FALSE;
}
#endif
static int
cmdline_charsize(idx)
int idx;
{
#if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
if (cmdline_star > 0) /* showing '*', always 1 position */
return 1;
#endif
return ptr2cells(ccline.cmdbuff + idx);
}
/*
* Compute the offset of the cursor on the command line for the prompt and
* indent.
*/
static void
set_cmdspos()
{
if (ccline.cmdfirstc != NUL)
ccline.cmdspos = 1 + ccline.cmdindent;
else
ccline.cmdspos = 0 + ccline.cmdindent;
}
/*
* Compute the screen position for the cursor on the command line.
*/
static void
set_cmdspos_cursor()
{
int i, m, c;
set_cmdspos();
if (KeyTyped)
{
m = Columns * Rows;
if (m < 0) /* overflow, Columns or Rows at weird value */
m = MAXCOL;
}
else
m = MAXCOL;
for (i = 0; i < ccline.cmdlen && i < ccline.cmdpos; ++i)
{
c = cmdline_charsize(i);
#ifdef FEAT_MBYTE
/* Count ">" for double-wide multi-byte char that doesn't fit. */
if (has_mbyte)
correct_cmdspos(i, c);
#endif
/* If the cmdline doesn't fit, show cursor on last visible char.
* Don't move the cursor itself, so we can still append. */
if ((ccline.cmdspos += c) >= m)
{
ccline.cmdspos -= c;
break;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
i += (*mb_ptr2len)(ccline.cmdbuff + i) - 1;
#endif
}
}
#ifdef FEAT_MBYTE
/*
* Check if the character at "idx", which is "cells" wide, is a multi-byte
* character that doesn't fit, so that a ">" must be displayed.
*/
static void
correct_cmdspos(idx, cells)
int idx;
int cells;
{
if ((*mb_ptr2len)(ccline.cmdbuff + idx) > 1
&& (*mb_ptr2cells)(ccline.cmdbuff + idx) > 1
&& ccline.cmdspos % Columns + cells > Columns)
ccline.cmdspos++;
}
#endif
/*
* Get an Ex command line for the ":" command.
*/
char_u *
getexline(c, cookie, indent)
int c; /* normally ':', NUL for ":append" */
void *cookie UNUSED;
int indent; /* indent for inside conditionals */
{
/* When executing a register, remove ':' that's in front of each line. */
if (exec_from_reg && vpeekc() == ':')
(void)vgetc();
return getcmdline(c, 1L, indent);
}
/*
* Get an Ex command line for Ex mode.
* In Ex mode we only use the OS supplied line editing features and no
* mappings or abbreviations.
* Returns a string in allocated memory or NULL.
*/
char_u *
getexmodeline(promptc, cookie, indent)
int promptc; /* normally ':', NUL for ":append" and '?' for
:s prompt */
void *cookie UNUSED;
int indent; /* indent for inside conditionals */
{
garray_T line_ga;
char_u *pend;
int startcol = 0;
int c1 = 0;
int escaped = FALSE; /* CTRL-V typed */
int vcol = 0;
char_u *p;
int prev_char;
/* Switch cursor on now. This avoids that it happens after the "\n", which
* confuses the system function that computes tabstops. */
cursor_on();
/* always start in column 0; write a newline if necessary */
compute_cmdrow();
if ((msg_col || msg_didout) && promptc != '?')
msg_putchar('\n');
if (promptc == ':')
{
/* indent that is only displayed, not in the line itself */
if (p_prompt)
msg_putchar(':');
while (indent-- > 0)
msg_putchar(' ');
startcol = msg_col;
}
ga_init2(&line_ga, 1, 30);
/* autoindent for :insert and :append is in the line itself */
if (promptc <= 0)
{
vcol = indent;
while (indent >= 8)
{
ga_append(&line_ga, TAB);
msg_puts((char_u *)" ");
indent -= 8;
}
while (indent-- > 0)
{
ga_append(&line_ga, ' ');
msg_putchar(' ');
}
}
++no_mapping;
++allow_keys;
/*
* Get the line, one character at a time.
*/
got_int = FALSE;
while (!got_int)
{
if (ga_grow(&line_ga, 40) == FAIL)
break;
/* Get one character at a time. Don't use inchar(), it can't handle
* special characters. */
prev_char = c1;
c1 = vgetc();
/*
* Handle line editing.
* Previously this was left to the system, putting the terminal in
* cooked mode, but then CTRL-D and CTRL-T can't be used properly.
*/
if (got_int)
{
msg_putchar('\n');
break;
}
if (!escaped)
{
/* CR typed means "enter", which is NL */
if (c1 == '\r')
c1 = '\n';
if (c1 == BS || c1 == K_BS
|| c1 == DEL || c1 == K_DEL || c1 == K_KDEL)
{
if (line_ga.ga_len > 0)
{
--line_ga.ga_len;
goto redraw;
}
continue;
}
if (c1 == Ctrl_U)
{
msg_col = startcol;
msg_clr_eos();
line_ga.ga_len = 0;
continue;
}
if (c1 == Ctrl_T)
{
p = (char_u *)line_ga.ga_data;
p[line_ga.ga_len] = NUL;
indent = get_indent_str(p, 8);
indent += curbuf->b_p_sw - indent % curbuf->b_p_sw;
add_indent:
while (get_indent_str(p, 8) < indent)
{
char_u *s = skipwhite(p);
ga_grow(&line_ga, 1);
mch_memmove(s + 1, s, line_ga.ga_len - (s - p) + 1);
*s = ' ';
++line_ga.ga_len;
}
redraw:
/* redraw the line */
msg_col = startcol;
vcol = 0;
for (p = (char_u *)line_ga.ga_data;
p < (char_u *)line_ga.ga_data + line_ga.ga_len; ++p)
{
if (*p == TAB)
{
do
{
msg_putchar(' ');
} while (++vcol % 8);
}
else
{
msg_outtrans_len(p, 1);
vcol += char2cells(*p);
}
}
msg_clr_eos();
windgoto(msg_row, msg_col);
continue;
}
if (c1 == Ctrl_D)
{
/* Delete one shiftwidth. */
p = (char_u *)line_ga.ga_data;
if (prev_char == '0' || prev_char == '^')
{
if (prev_char == '^')
ex_keep_indent = TRUE;
indent = 0;
p[--line_ga.ga_len] = NUL;
}
else
{
p[line_ga.ga_len] = NUL;
indent = get_indent_str(p, 8);
--indent;
indent -= indent % curbuf->b_p_sw;
}
while (get_indent_str(p, 8) > indent)
{
char_u *s = skipwhite(p);
mch_memmove(s - 1, s, line_ga.ga_len - (s - p) + 1);
--line_ga.ga_len;
}
goto add_indent;
}
if (c1 == Ctrl_V || c1 == Ctrl_Q)
{
escaped = TRUE;
continue;
}
/* Ignore special key codes: mouse movement, K_IGNORE, etc. */
if (IS_SPECIAL(c1))
continue;
}
if (IS_SPECIAL(c1))
c1 = '?';
((char_u *)line_ga.ga_data)[line_ga.ga_len] = c1;
if (c1 == '\n')
msg_putchar('\n');
else if (c1 == TAB)
{
/* Don't use chartabsize(), 'ts' can be different */
do
{
msg_putchar(' ');
} while (++vcol % 8);
}
else
{
msg_outtrans_len(
((char_u *)line_ga.ga_data) + line_ga.ga_len, 1);
vcol += char2cells(c1);
}
++line_ga.ga_len;
escaped = FALSE;
windgoto(msg_row, msg_col);
pend = (char_u *)(line_ga.ga_data) + line_ga.ga_len;
/* We are done when a NL is entered, but not when it comes after an
* odd number of backslashes, that results in a NUL. */
if (line_ga.ga_len > 0 && pend[-1] == '\n')
{
int bcount = 0;
while (line_ga.ga_len - 2 >= bcount && pend[-2 - bcount] == '\\')
++bcount;
if (bcount > 0)
{
/* Halve the number of backslashes: "\NL" -> "NUL", "\\NL" ->
* "\NL", etc. */
line_ga.ga_len -= (bcount + 1) / 2;
pend -= (bcount + 1) / 2;
pend[-1] = '\n';
}
if ((bcount & 1) == 0)
{
--line_ga.ga_len;
--pend;
*pend = NUL;
break;
}
}
}
--no_mapping;
--allow_keys;
/* make following messages go to the next line */
msg_didout = FALSE;
msg_col = 0;
if (msg_row < Rows - 1)
++msg_row;
emsg_on_display = FALSE; /* don't want ui_delay() */
if (got_int)
ga_clear(&line_ga);
return (char_u *)line_ga.ga_data;
}
# if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
|| defined(FEAT_MOUSESHAPE) || defined(PROTO)
/*
* Return TRUE if ccline.overstrike is on.
*/
int
cmdline_overstrike()
{
return ccline.overstrike;
}
/*
* Return TRUE if the cursor is at the end of the cmdline.
*/
int
cmdline_at_end()
{
return (ccline.cmdpos >= ccline.cmdlen);
}
#endif
#if (defined(FEAT_XIM) && (defined(FEAT_GUI_GTK))) || defined(PROTO)
/*
* Return the virtual column number at the current cursor position.
* This is used by the IM code to obtain the start of the preedit string.
*/
colnr_T
cmdline_getvcol_cursor()
{
if (ccline.cmdbuff == NULL || ccline.cmdpos > ccline.cmdlen)
return MAXCOL;
# ifdef FEAT_MBYTE
if (has_mbyte)
{
colnr_T col;
int i = 0;
for (col = 0; i < ccline.cmdpos; ++col)
i += (*mb_ptr2len)(ccline.cmdbuff + i);
return col;
}
else
# endif
return ccline.cmdpos;
}
#endif
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
/*
* If part of the command line is an IM preedit string, redraw it with
* IM feedback attributes. The cursor position is restored after drawing.
*/
static void
redrawcmd_preedit()
{
if ((State & CMDLINE)
&& xic != NULL
/* && im_get_status() doesn't work when using SCIM */
&& !p_imdisable
&& im_is_preediting())
{
int cmdpos = 0;
int cmdspos;
int old_row;
int old_col;
colnr_T col;
old_row = msg_row;
old_col = msg_col;
cmdspos = ((ccline.cmdfirstc != NUL) ? 1 : 0) + ccline.cmdindent;
# ifdef FEAT_MBYTE
if (has_mbyte)
{
for (col = 0; col < preedit_start_col
&& cmdpos < ccline.cmdlen; ++col)
{
cmdspos += (*mb_ptr2cells)(ccline.cmdbuff + cmdpos);
cmdpos += (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
}
}
else
# endif
{
cmdspos += preedit_start_col;
cmdpos += preedit_start_col;
}
msg_row = cmdline_row + (cmdspos / (int)Columns);
msg_col = cmdspos % (int)Columns;
if (msg_row >= Rows)
msg_row = Rows - 1;
for (col = 0; cmdpos < ccline.cmdlen; ++col)
{
int char_len;
int char_attr;
char_attr = im_get_feedback_attr(col);
if (char_attr < 0)
break; /* end of preedit string */
# ifdef FEAT_MBYTE
if (has_mbyte)
char_len = (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
else
# endif
char_len = 1;
msg_outtrans_len_attr(ccline.cmdbuff + cmdpos, char_len, char_attr);
cmdpos += char_len;
}
msg_row = old_row;
msg_col = old_col;
}
}
#endif /* FEAT_XIM && FEAT_GUI_GTK */
/*
* Allocate a new command line buffer.
* Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
* Returns the new value of ccline.cmdbuff and ccline.cmdbufflen.
*/
static void
alloc_cmdbuff(len)
int len;
{
/*
* give some extra space to avoid having to allocate all the time
*/
if (len < 80)
len = 100;
else
len += 20;
ccline.cmdbuff = alloc(len); /* caller should check for out-of-memory */
ccline.cmdbufflen = len;
}
/*
* Re-allocate the command line to length len + something extra.
* return FAIL for failure, OK otherwise
*/
static int
realloc_cmdbuff(len)
int len;
{
char_u *p;
if (len < ccline.cmdbufflen)
return OK; /* no need to resize */
p = ccline.cmdbuff;
alloc_cmdbuff(len); /* will get some more */
if (ccline.cmdbuff == NULL) /* out of memory */
{
ccline.cmdbuff = p; /* keep the old one */
return FAIL;
}
/* There isn't always a NUL after the command, but it may need to be
* there, thus copy up to the NUL and add a NUL. */
mch_memmove(ccline.cmdbuff, p, (size_t)ccline.cmdlen);
ccline.cmdbuff[ccline.cmdlen] = NUL;
vim_free(p);
if (ccline.xpc != NULL
&& ccline.xpc->xp_pattern != NULL
&& ccline.xpc->xp_context != EXPAND_NOTHING
&& ccline.xpc->xp_context != EXPAND_UNSUCCESSFUL)
{
int i = (int)(ccline.xpc->xp_pattern - p);
/* If xp_pattern points inside the old cmdbuff it needs to be adjusted
* to point into the newly allocated memory. */
if (i >= 0 && i <= ccline.cmdlen)
ccline.xpc->xp_pattern = ccline.cmdbuff + i;
}
return OK;
}
#if defined(FEAT_ARABIC) || defined(PROTO)
static char_u *arshape_buf = NULL;
# if defined(EXITFREE) || defined(PROTO)
void
free_cmdline_buf()
{
vim_free(arshape_buf);
}
# endif
#endif
/*
* Draw part of the cmdline at the current cursor position. But draw stars
* when cmdline_star is TRUE.
*/
static void
draw_cmdline(start, len)
int start;
int len;
{
#if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
int i;
if (cmdline_star > 0)
for (i = 0; i < len; ++i)
{
msg_putchar('*');
# ifdef FEAT_MBYTE
if (has_mbyte)
i += (*mb_ptr2len)(ccline.cmdbuff + start + i) - 1;
# endif
}
else
#endif
#ifdef FEAT_ARABIC
if (p_arshape && !p_tbidi && enc_utf8 && len > 0)
{
static int buflen = 0;
char_u *p;
int j;
int newlen = 0;
int mb_l;
int pc, pc1 = 0;
int prev_c = 0;
int prev_c1 = 0;
int u8c;
int u8cc[MAX_MCO];
int nc = 0;
/*
* Do arabic shaping into a temporary buffer. This is very
* inefficient!
*/
if (len * 2 + 2 > buflen)
{
/* Re-allocate the buffer. We keep it around to avoid a lot of
* alloc()/free() calls. */
vim_free(arshape_buf);
buflen = len * 2 + 2;
arshape_buf = alloc(buflen);
if (arshape_buf == NULL)
return; /* out of memory */
}
if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start)))
{
/* Prepend a space to draw the leading composing char on. */
arshape_buf[0] = ' ';
newlen = 1;
}
for (j = start; j < start + len; j += mb_l)
{
p = ccline.cmdbuff + j;
u8c = utfc_ptr2char_len(p, u8cc, start + len - j);
mb_l = utfc_ptr2len_len(p, start + len - j);
if (ARABIC_CHAR(u8c))
{
/* Do Arabic shaping. */
if (cmdmsg_rl)
{
/* displaying from right to left */
pc = prev_c;
pc1 = prev_c1;
prev_c1 = u8cc[0];
if (j + mb_l >= start + len)
nc = NUL;
else
nc = utf_ptr2char(p + mb_l);
}
else
{
/* displaying from left to right */
if (j + mb_l >= start + len)
pc = NUL;
else
{
int pcc[MAX_MCO];
pc = utfc_ptr2char_len(p + mb_l, pcc,
start + len - j - mb_l);
pc1 = pcc[0];
}
nc = prev_c;
}
prev_c = u8c;
u8c = arabic_shape(u8c, NULL, &u8cc[0], pc, pc1, nc);
newlen += (*mb_char2bytes)(u8c, arshape_buf + newlen);
if (u8cc[0] != 0)
{
newlen += (*mb_char2bytes)(u8cc[0], arshape_buf + newlen);
if (u8cc[1] != 0)
newlen += (*mb_char2bytes)(u8cc[1],
arshape_buf + newlen);
}
}
else
{
prev_c = u8c;
mch_memmove(arshape_buf + newlen, p, mb_l);
newlen += mb_l;
}
}
msg_outtrans_len(arshape_buf, newlen);
}
else
#endif
msg_outtrans_len(ccline.cmdbuff + start, len);
}
/*
* Put a character on the command line. Shifts the following text to the
* right when "shift" is TRUE. Used for CTRL-V, CTRL-K, etc.
* "c" must be printable (fit in one display cell)!
*/
void
putcmdline(c, shift)
int c;
int shift;
{
if (cmd_silent)
return;
msg_no_more = TRUE;
msg_putchar(c);
if (shift)
draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
msg_no_more = FALSE;
cursorcmd();
}
/*
* Undo a putcmdline(c, FALSE).
*/
void
unputcmdline()
{
if (cmd_silent)
return;
msg_no_more = TRUE;
if (ccline.cmdlen == ccline.cmdpos)
msg_putchar(' ');
#ifdef FEAT_MBYTE
else if (has_mbyte)
draw_cmdline(ccline.cmdpos,
(*mb_ptr2len)(ccline.cmdbuff + ccline.cmdpos));
#endif
else
draw_cmdline(ccline.cmdpos, 1);
msg_no_more = FALSE;
cursorcmd();
}
/*
* Put the given string, of the given length, onto the command line.
* If len is -1, then STRLEN() is used to calculate the length.
* If 'redraw' is TRUE then the new part of the command line, and the remaining
* part will be redrawn, otherwise it will not. If this function is called
* twice in a row, then 'redraw' should be FALSE and redrawcmd() should be
* called afterwards.
*/
int
put_on_cmdline(str, len, redraw)
char_u *str;
int len;
int redraw;
{
int retval;
int i;
int m;
int c;
if (len < 0)
len = (int)STRLEN(str);
/* Check if ccline.cmdbuff needs to be longer */
if (ccline.cmdlen + len + 1 >= ccline.cmdbufflen)
retval = realloc_cmdbuff(ccline.cmdlen + len + 1);
else
retval = OK;
if (retval == OK)
{
if (!ccline.overstrike)
{
mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
ccline.cmdbuff + ccline.cmdpos,
(size_t)(ccline.cmdlen - ccline.cmdpos));
ccline.cmdlen += len;
}
else
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Count nr of characters in the new string. */
m = 0;
for (i = 0; i < len; i += (*mb_ptr2len)(str + i))
++m;
/* Count nr of bytes in cmdline that are overwritten by these
* characters. */
for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0;
i += (*mb_ptr2len)(ccline.cmdbuff + i))
--m;
if (i < ccline.cmdlen)
{
mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
ccline.cmdbuff + i, (size_t)(ccline.cmdlen - i));
ccline.cmdlen += ccline.cmdpos + len - i;
}
else
ccline.cmdlen = ccline.cmdpos + len;
}
else
#endif
if (ccline.cmdpos + len > ccline.cmdlen)
ccline.cmdlen = ccline.cmdpos + len;
}
mch_memmove(ccline.cmdbuff + ccline.cmdpos, str, (size_t)len);
ccline.cmdbuff[ccline.cmdlen] = NUL;
#ifdef FEAT_MBYTE
if (enc_utf8)
{
/* When the inserted text starts with a composing character,
* backup to the character before it. There could be two of them.
*/
i = 0;
c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
while (ccline.cmdpos > 0 && utf_iscomposing(c))
{
i = (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos - 1) + 1;
ccline.cmdpos -= i;
len += i;
c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
}
# ifdef FEAT_ARABIC
if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c))
{
/* Check the previous character for Arabic combining pair. */
i = (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos - 1) + 1;
if (arabic_combine(utf_ptr2char(ccline.cmdbuff
+ ccline.cmdpos - i), c))
{
ccline.cmdpos -= i;
len += i;
}
else
i = 0;
}
# endif
if (i != 0)
{
/* Also backup the cursor position. */
i = ptr2cells(ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= i;
msg_col -= i;
if (msg_col < 0)
{
msg_col += Columns;
--msg_row;
}
}
}
#endif
if (redraw && !cmd_silent)
{
msg_no_more = TRUE;
i = cmdline_row;
cursorcmd();
draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
/* Avoid clearing the rest of the line too often. */
if (cmdline_row != i || ccline.overstrike)
msg_clr_eos();
msg_no_more = FALSE;
}
#ifdef FEAT_FKMAP
/*
* If we are in Farsi command mode, the character input must be in
* Insert mode. So do not advance the cmdpos.
*/
if (!cmd_fkmap)
#endif
{
if (KeyTyped)
{
m = Columns * Rows;
if (m < 0) /* overflow, Columns or Rows at weird value */
m = MAXCOL;
}
else
m = MAXCOL;
for (i = 0; i < len; ++i)
{
c = cmdline_charsize(ccline.cmdpos);
#ifdef FEAT_MBYTE
/* count ">" for a double-wide char that doesn't fit. */
if (has_mbyte)
correct_cmdspos(ccline.cmdpos, c);
#endif
/* Stop cursor at the end of the screen, but do increment the
* insert position, so that entering a very long command
* works, even though you can't see it. */
if (ccline.cmdspos + c < m)
ccline.cmdspos += c;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
c = (*mb_ptr2len)(ccline.cmdbuff + ccline.cmdpos) - 1;
if (c > len - i - 1)
c = len - i - 1;
ccline.cmdpos += c;
i += c;
}
#endif
++ccline.cmdpos;
}
}
}
if (redraw)
msg_check();
return retval;
}
static struct cmdline_info prev_ccline;
static int prev_ccline_used = FALSE;
/*
* Save ccline, because obtaining the "=" register may execute "normal :cmd"
* and overwrite it. But get_cmdline_str() may need it, thus make it
* available globally in prev_ccline.
*/
static void
save_cmdline(ccp)
struct cmdline_info *ccp;
{
if (!prev_ccline_used)
{
vim_memset(&prev_ccline, 0, sizeof(struct cmdline_info));
prev_ccline_used = TRUE;
}
*ccp = prev_ccline;
prev_ccline = ccline;
ccline.cmdbuff = NULL;
ccline.cmdprompt = NULL;
ccline.xpc = NULL;
}
/*
* Restore ccline after it has been saved with save_cmdline().
*/
static void
restore_cmdline(ccp)
struct cmdline_info *ccp;
{
ccline = prev_ccline;
prev_ccline = *ccp;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Save the command line into allocated memory. Returns a pointer to be
* passed to restore_cmdline_alloc() later.
* Returns NULL when failed.
*/
char_u *
save_cmdline_alloc()
{
struct cmdline_info *p;
p = (struct cmdline_info *)alloc((unsigned)sizeof(struct cmdline_info));
if (p != NULL)
save_cmdline(p);
return (char_u *)p;
}
/*
* Restore the command line from the return value of save_cmdline_alloc().
*/
void
restore_cmdline_alloc(p)
char_u *p;
{
if (p != NULL)
{
restore_cmdline((struct cmdline_info *)p);
vim_free(p);
}
}
#endif
/*
* paste a yank register into the command line.
* used by CTRL-R command in command-line mode
* insert_reg() can't be used here, because special characters from the
* register contents will be interpreted as commands.
*
* return FAIL for failure, OK otherwise
*/
static int
cmdline_paste(regname, literally, remcr)
int regname;
int literally; /* Insert text literally instead of "as typed" */
int remcr; /* remove trailing CR */
{
long i;
char_u *arg;
char_u *p;
int allocated;
struct cmdline_info save_ccline;
/* check for valid regname; also accept special characters for CTRL-R in
* the command line */
if (regname != Ctrl_F && regname != Ctrl_P && regname != Ctrl_W
&& regname != Ctrl_A && !valid_yank_reg(regname, FALSE))
return FAIL;
/* A register containing CTRL-R can cause an endless loop. Allow using
* CTRL-C to break the loop. */
line_breakcheck();
if (got_int)
return FAIL;
#ifdef FEAT_CLIPBOARD
regname = may_get_selection(regname);
#endif
/* Need to save and restore ccline. And set "textlock" to avoid nasty
* things like going to another buffer when evaluating an expression. */
save_cmdline(&save_ccline);
++textlock;
i = get_spec_reg(regname, &arg, &allocated, TRUE);
--textlock;
restore_cmdline(&save_ccline);
if (i)
{
/* Got the value of a special register in "arg". */
if (arg == NULL)
return FAIL;
/* When 'incsearch' is set and CTRL-R CTRL-W used: skip the duplicate
* part of the word. */
p = arg;
if (p_is && regname == Ctrl_W)
{
char_u *w;
int len;
/* Locate start of last word in the cmd buffer. */
for (w = ccline.cmdbuff + ccline.cmdpos; w > ccline.cmdbuff; )
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
len = (*mb_head_off)(ccline.cmdbuff, w - 1) + 1;
if (!vim_iswordc(mb_ptr2char(w - len)))
break;
w -= len;
}
else
#endif
{
if (!vim_iswordc(w[-1]))
break;
--w;
}
}
len = (int)((ccline.cmdbuff + ccline.cmdpos) - w);
if (p_ic ? STRNICMP(w, arg, len) == 0 : STRNCMP(w, arg, len) == 0)
p += len;
}
cmdline_paste_str(p, literally);
if (allocated)
vim_free(arg);
return OK;
}
return cmdline_paste_reg(regname, literally, remcr);
}
/*
* Put a string on the command line.
* When "literally" is TRUE, insert literally.
* When "literally" is FALSE, insert as typed, but don't leave the command
* line.
*/
void
cmdline_paste_str(s, literally)
char_u *s;
int literally;
{
int c, cv;
if (literally)
put_on_cmdline(s, -1, TRUE);
else
while (*s != NUL)
{
cv = *s;
if (cv == Ctrl_V && s[1])
++s;
#ifdef FEAT_MBYTE
if (has_mbyte)
c = mb_cptr2char_adv(&s);
else
#endif
c = *s++;
if (cv == Ctrl_V || c == ESC || c == Ctrl_C || c == CAR || c == NL
#ifdef UNIX
|| c == intr_char
#endif
|| (c == Ctrl_BSL && *s == Ctrl_N))
stuffcharReadbuff(Ctrl_V);
stuffcharReadbuff(c);
}
}
#ifdef FEAT_WILDMENU
/*
* Delete characters on the command line, from "from" to the current
* position.
*/
static void
cmdline_del(from)
int from;
{
mch_memmove(ccline.cmdbuff + from, ccline.cmdbuff + ccline.cmdpos,
(size_t)(ccline.cmdlen - ccline.cmdpos + 1));
ccline.cmdlen -= ccline.cmdpos - from;
ccline.cmdpos = from;
}
#endif
/*
* this function is called when the screen size changes and with incremental
* search
*/
void
redrawcmdline()
{
if (cmd_silent)
return;
need_wait_return = FALSE;
compute_cmdrow();
redrawcmd();
cursorcmd();
}
static void
redrawcmdprompt()
{
int i;
if (cmd_silent)
return;
if (ccline.cmdfirstc != NUL)
msg_putchar(ccline.cmdfirstc);
if (ccline.cmdprompt != NULL)
{
msg_puts_attr(ccline.cmdprompt, ccline.cmdattr);
ccline.cmdindent = msg_col + (msg_row - cmdline_row) * Columns;
/* do the reverse of set_cmdspos() */
if (ccline.cmdfirstc != NUL)
--ccline.cmdindent;
}
else
for (i = ccline.cmdindent; i > 0; --i)
msg_putchar(' ');
}
/*
* Redraw what is currently on the command line.
*/
void
redrawcmd()
{
if (cmd_silent)
return;
/* when 'incsearch' is set there may be no command line while redrawing */
if (ccline.cmdbuff == NULL)
{
windgoto(cmdline_row, 0);
msg_clr_eos();
return;
}
msg_start();
redrawcmdprompt();
/* Don't use more prompt, truncate the cmdline if it doesn't fit. */
msg_no_more = TRUE;
draw_cmdline(0, ccline.cmdlen);
msg_clr_eos();
msg_no_more = FALSE;
set_cmdspos_cursor();
/*
* An emsg() before may have set msg_scroll. This is used in normal mode,
* in cmdline mode we can reset them now.
*/
msg_scroll = FALSE; /* next message overwrites cmdline */
/* Typing ':' at the more prompt may set skip_redraw. We don't want this
* in cmdline mode */
skip_redraw = FALSE;
}
void
compute_cmdrow()
{
if (exmode_active || msg_scrolled != 0)
cmdline_row = Rows - 1;
else
cmdline_row = W_WINROW(lastwin) + lastwin->w_height
+ W_STATUS_HEIGHT(lastwin);
}
static void
cursorcmd()
{
if (cmd_silent)
return;
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
{
msg_row = cmdline_row + (ccline.cmdspos / (int)(Columns - 1));
msg_col = (int)Columns - (ccline.cmdspos % (int)(Columns - 1)) - 1;
if (msg_row <= 0)
msg_row = Rows - 1;
}
else
#endif
{
msg_row = cmdline_row + (ccline.cmdspos / (int)Columns);
msg_col = ccline.cmdspos % (int)Columns;
if (msg_row >= Rows)
msg_row = Rows - 1;
}
windgoto(msg_row, msg_col);
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
redrawcmd_preedit();
#endif
#ifdef MCH_CURSOR_SHAPE
mch_update_cursor();
#endif
}
void
gotocmdline(clr)
int clr;
{
msg_start();
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
msg_col = Columns - 1;
else
#endif
msg_col = 0; /* always start in column 0 */
if (clr) /* clear the bottom line(s) */
msg_clr_eos(); /* will reset clear_cmdline */
windgoto(cmdline_row, 0);
}
/*
* 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 with
* backspaces and the replacement string is inserted, followed by "c".
*/
static int
ccheck_abbr(c)
int c;
{
if (p_paste || no_abbr) /* no abbreviations or in paste mode */
return FALSE;
return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, 0);
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
sort_func_compare(s1, s2)
const void *s1;
const void *s2;
{
char_u *p1 = *(char_u **)s1;
char_u *p2 = *(char_u **)s2;
if (*p1 != '<' && *p2 == '<') return -1;
if (*p1 == '<' && *p2 != '<') return 1;
return STRCMP(p1, p2);
}
#endif
/*
* Return FAIL if this is not an appropriate context in which to do
* completion of anything, return OK if it is (even if there are no matches).
* For the caller, this means that the character is just passed through like a
* normal character (instead of being expanded). This allows :s/^I^D etc.
*/
static int
nextwild(xp, type, options)
expand_T *xp;
int type;
int options; /* extra options for ExpandOne() */
{
int i, j;
char_u *p1;
char_u *p2;
int difflen;
int v;
if (xp->xp_numfiles == -1)
{
set_expand_context(xp);
cmd_showtail = expand_showtail(xp);
}
if (xp->xp_context == EXPAND_UNSUCCESSFUL)
{
beep_flush();
return OK; /* Something illegal on command line */
}
if (xp->xp_context == EXPAND_NOTHING)
{
/* Caller can use the character as a normal char instead */
return FAIL;
}
MSG_PUTS("..."); /* show that we are busy */
out_flush();
i = (int)(xp->xp_pattern - ccline.cmdbuff);
xp->xp_pattern_len = ccline.cmdpos - i;
if (type == WILD_NEXT || type == WILD_PREV)
{
/*
* Get next/previous match for a previous expanded pattern.
*/
p2 = ExpandOne(xp, NULL, NULL, 0, type);
}
else
{
/*
* Translate string into pattern and expand it.
*/
if ((p1 = addstar(xp->xp_pattern, xp->xp_pattern_len,
xp->xp_context)) == NULL)
p2 = NULL;
else
{
int use_options = options |
WILD_HOME_REPLACE|WILD_ADD_SLASH|WILD_SILENT|WILD_ESCAPE;
if (p_wic)
use_options += WILD_ICASE;
p2 = ExpandOne(xp, p1,
vim_strnsave(&ccline.cmdbuff[i], xp->xp_pattern_len),
use_options, type);
vim_free(p1);
/* longest match: make sure it is not shorter, happens with :help */
if (p2 != NULL && type == WILD_LONGEST)
{
for (j = 0; j < xp->xp_pattern_len; ++j)
if (ccline.cmdbuff[i + j] == '*'
|| ccline.cmdbuff[i + j] == '?')
break;
if ((int)STRLEN(p2) < j)
{
vim_free(p2);
p2 = NULL;
}
}
}
}
if (p2 != NULL && !got_int)
{
difflen = (int)STRLEN(p2) - xp->xp_pattern_len;
if (ccline.cmdlen + difflen + 4 > ccline.cmdbufflen)
{
v = realloc_cmdbuff(ccline.cmdlen + difflen + 4);
xp->xp_pattern = ccline.cmdbuff + i;
}
else
v = OK;
if (v == OK)
{
mch_memmove(&ccline.cmdbuff[ccline.cmdpos + difflen],
&ccline.cmdbuff[ccline.cmdpos],
(size_t)(ccline.cmdlen - ccline.cmdpos + 1));
mch_memmove(&ccline.cmdbuff[i], p2, STRLEN(p2));
ccline.cmdlen += difflen;
ccline.cmdpos += difflen;
}
}
vim_free(p2);
redrawcmd();
cursorcmd();
/* When expanding a ":map" command and no matches are found, assume that
* the key is supposed to be inserted literally */
if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL)
return FAIL;
if (xp->xp_numfiles <= 0 && p2 == NULL)
beep_flush();
else if (xp->xp_numfiles == 1)
/* free expanded pattern */
(void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
return OK;
}
/*
* Do wildcard expansion on the string 'str'.
* Chars that should not be expanded must be preceded with a backslash.
* Return a pointer to allocated memory containing the new string.
* Return NULL for failure.
*
* "orig" is the originally expanded string, copied to allocated memory. It
* should either be kept in orig_save or freed. When "mode" is WILD_NEXT or
* WILD_PREV "orig" should be NULL.
*
* Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
* is WILD_EXPAND_FREE or WILD_ALL.
*
* mode = WILD_FREE: just free previously expanded matches
* mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
* mode = WILD_EXPAND_KEEP: normal expansion, keep matches
* mode = WILD_NEXT: use next match in multiple match, wrap to first
* mode = WILD_PREV: use previous match in multiple match, wrap to first
* mode = WILD_ALL: return all matches concatenated
* mode = WILD_LONGEST: return longest matched part
* mode = WILD_ALL_KEEP: get all matches, keep matches
*
* options = WILD_LIST_NOTFOUND: list entries without a match
* options = WILD_HOME_REPLACE: do home_replace() for buffer names
* options = WILD_USE_NL: Use '\n' for WILD_ALL
* options = WILD_NO_BEEP: Don't beep for multiple matches
* options = WILD_ADD_SLASH: add a slash after directory names
* options = WILD_KEEP_ALL: don't remove 'wildignore' entries
* options = WILD_SILENT: don't print warning messages
* options = WILD_ESCAPE: put backslash before special chars
* options = WILD_ICASE: ignore case for files
*
* The variables xp->xp_context and xp->xp_backslash must have been set!
*/
char_u *
ExpandOne(xp, str, orig, options, mode)
expand_T *xp;
char_u *str;
char_u *orig; /* allocated copy of original of expanded string */
int options;
int mode;
{
char_u *ss = NULL;
static int findex;
static char_u *orig_save = NULL; /* kept value of orig */
int orig_saved = FALSE;
int i;
long_u len;
int non_suf_match; /* number without matching suffix */
/*
* first handle the case of using an old match
*/
if (mode == WILD_NEXT || mode == WILD_PREV)
{
if (xp->xp_numfiles > 0)
{
if (mode == WILD_PREV)
{
if (findex == -1)
findex = xp->xp_numfiles;
--findex;
}
else /* mode == WILD_NEXT */
++findex;
/*
* When wrapping around, return the original string, set findex to
* -1.
*/
if (findex < 0)
{
if (orig_save == NULL)
findex = xp->xp_numfiles - 1;
else
findex = -1;
}
if (findex >= xp->xp_numfiles)
{
if (orig_save == NULL)
findex = 0;
else
findex = -1;
}
#ifdef FEAT_WILDMENU
if (p_wmnu)
win_redr_status_matches(xp, xp->xp_numfiles, xp->xp_files,
findex, cmd_showtail);
#endif
if (findex == -1)
return vim_strsave(orig_save);
return vim_strsave(xp->xp_files[findex]);
}
else
return NULL;
}
/* free old names */
if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
{
FreeWild(xp->xp_numfiles, xp->xp_files);
xp->xp_numfiles = -1;
vim_free(orig_save);
orig_save = NULL;
}
findex = 0;
if (mode == WILD_FREE) /* only release file name */
return NULL;
if (xp->xp_numfiles == -1)
{
vim_free(orig_save);
orig_save = orig;
orig_saved = TRUE;
/*
* Do the expansion.
*/
if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files,
options) == FAIL)
{
#ifdef FNAME_ILLEGAL
/* Illegal file name has been silently skipped. But when there
* are wildcards, the real problem is that there was no match,
* causing the pattern to be added, which has illegal characters.
*/
if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND))
EMSG2(_(e_nomatch2), str);
#endif
}
else if (xp->xp_numfiles == 0)
{
if (!(options & WILD_SILENT))
EMSG2(_(e_nomatch2), str);
}
else
{
/* Escape the matches for use on the command line. */
ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
/*
* Check for matching suffixes in file names.
*/
if (mode != WILD_ALL && mode != WILD_ALL_KEEP
&& mode != WILD_LONGEST)
{
if (xp->xp_numfiles)
non_suf_match = xp->xp_numfiles;
else
non_suf_match = 1;
if ((xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_DIRECTORIES)
&& xp->xp_numfiles > 1)
{
/*
* More than one match; check suffix.
* The files will have been sorted on matching suffix in
* expand_wildcards, only need to check the first two.
*/
non_suf_match = 0;
for (i = 0; i < 2; ++i)
if (match_suffix(xp->xp_files[i]))
++non_suf_match;
}
if (non_suf_match != 1)
{
/* Can we ever get here unless it's while expanding
* interactively? If not, we can get rid of this all
* together. Don't really want to wait for this message
* (and possibly have to hit return to continue!).
*/
if (!(options & WILD_SILENT))
EMSG(_(e_toomany));
else if (!(options & WILD_NO_BEEP))
beep_flush();
}
if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE))
ss = vim_strsave(xp->xp_files[0]);
}
}
}
/* Find longest common part */
if (mode == WILD_LONGEST && xp->xp_numfiles > 0)
{
for (len = 0; xp->xp_files[0][len]; ++len)
{
for (i = 0; i < xp->xp_numfiles; ++i)
{
#ifdef CASE_INSENSITIVE_FILENAME
if (xp->xp_context == EXPAND_DIRECTORIES
|| xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_SHELLCMD
|| xp->xp_context == EXPAND_BUFFERS)
{
if (TOLOWER_LOC(xp->xp_files[i][len]) !=
TOLOWER_LOC(xp->xp_files[0][len]))
break;
}
else
#endif
if (xp->xp_files[i][len] != xp->xp_files[0][len])
break;
}
if (i < xp->xp_numfiles)
{
if (!(options & WILD_NO_BEEP))
vim_beep();
break;
}
}
ss = alloc((unsigned)len + 1);
if (ss)
vim_strncpy(ss, xp->xp_files[0], (size_t)len);
findex = -1; /* next p_wc gets first one */
}
/* Concatenate all matching names */
if (mode == WILD_ALL && xp->xp_numfiles > 0)
{
len = 0;
for (i = 0; i < xp->xp_numfiles; ++i)
len += (long_u)STRLEN(xp->xp_files[i]) + 1;
ss = lalloc(len, TRUE);
if (ss != NULL)
{
*ss = NUL;
for (i = 0; i < xp->xp_numfiles; ++i)
{
STRCAT(ss, xp->xp_files[i]);
if (i != xp->xp_numfiles - 1)
STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " ");
}
}
}
if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
ExpandCleanup(xp);
/* Free "orig" if it wasn't stored in "orig_save". */
if (!orig_saved)
vim_free(orig);
return ss;
}
/*
* Prepare an expand structure for use.
*/
void
ExpandInit(xp)
expand_T *xp;
{
xp->xp_pattern = NULL;
xp->xp_pattern_len = 0;
xp->xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
xp->xp_shell = FALSE;
#endif
xp->xp_numfiles = -1;
xp->xp_files = NULL;
#if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
xp->xp_arg = NULL;
#endif
}
/*
* Cleanup an expand structure after use.
*/
void
ExpandCleanup(xp)
expand_T *xp;
{
if (xp->xp_numfiles >= 0)
{
FreeWild(xp->xp_numfiles, xp->xp_files);
xp->xp_numfiles = -1;
}
}
void
ExpandEscape(xp, str, numfiles, files, options)
expand_T *xp;
char_u *str;
int numfiles;
char_u **files;
int options;
{
int i;
char_u *p;
/*
* May change home directory back to "~"
*/
if (options & WILD_HOME_REPLACE)
tilde_replace(str, numfiles, files);
if (options & WILD_ESCAPE)
{
if (xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_FILES_IN_PATH
|| xp->xp_context == EXPAND_SHELLCMD
|| xp->xp_context == EXPAND_BUFFERS
|| xp->xp_context == EXPAND_DIRECTORIES)
{
/*
* Insert a backslash into a file name before a space, \, %, #
* and wildmatch characters, except '~'.
*/
for (i = 0; i < numfiles; ++i)
{
/* for ":set path=" we need to escape spaces twice */
if (xp->xp_backslash == XP_BS_THREE)
{
p = vim_strsave_escaped(files[i], (char_u *)" ");
if (p != NULL)
{
vim_free(files[i]);
files[i] = p;
#if defined(BACKSLASH_IN_FILENAME)
p = vim_strsave_escaped(files[i], (char_u *)" ");
if (p != NULL)
{
vim_free(files[i]);
files[i] = p;
}
#endif
}
}
#ifdef BACKSLASH_IN_FILENAME
p = vim_strsave_fnameescape(files[i], FALSE);
#else
p = vim_strsave_fnameescape(files[i], xp->xp_shell);
#endif
if (p != NULL)
{
vim_free(files[i]);
files[i] = p;
}
/* If 'str' starts with "\~", replace "~" at start of
* files[i] with "\~". */
if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~')
escape_fname(&files[i]);
}
xp->xp_backslash = XP_BS_NONE;
/* If the first file starts with a '+' escape it. Otherwise it
* could be seen as "+cmd". */
if (*files[0] == '+')
escape_fname(&files[0]);
}
else if (xp->xp_context == EXPAND_TAGS)
{
/*
* Insert a backslash before characters in a tag name that
* would terminate the ":tag" command.
*/
for (i = 0; i < numfiles; ++i)
{
p = vim_strsave_escaped(files[i], (char_u *)"\\|\"");
if (p != NULL)
{
vim_free(files[i]);
files[i] = p;
}
}
}
}
}
/*
* Escape special characters in "fname" for when used as a file name argument
* after a Vim command, or, when "shell" is non-zero, a shell command.
* Returns the result in allocated memory.
*/
char_u *
vim_strsave_fnameescape(fname, shell)
char_u *fname;
int shell;
{
char_u *p;
#ifdef BACKSLASH_IN_FILENAME
char_u buf[20];
int j = 0;
/* Don't escape '[' and '{' if they are in 'isfname'. */
for (p = PATH_ESC_CHARS; *p != NUL; ++p)
if ((*p != '[' && *p != '{') || !vim_isfilec(*p))
buf[j++] = *p;
buf[j] = NUL;
p = vim_strsave_escaped(fname, buf);
#else
p = vim_strsave_escaped(fname, shell ? SHELL_ESC_CHARS : PATH_ESC_CHARS);
if (shell && csh_like_shell() && p != NULL)
{
char_u *s;
/* For csh and similar shells need to put two backslashes before '!'.
* One is taken by Vim, one by the shell. */
s = vim_strsave_escaped(p, (char_u *)"!");
vim_free(p);
p = s;
}
#endif
/* '>' and '+' are special at the start of some commands, e.g. ":edit" and
* ":write". "cd -" has a special meaning. */
if (p != NULL && (*p == '>' || *p == '+' || (*p == '-' && p[1] == NUL)))
escape_fname(&p);
return p;
}
/*
* Put a backslash before the file name in "pp", which is in allocated memory.
*/
static void
escape_fname(pp)
char_u **pp;
{
char_u *p;
p = alloc((unsigned)(STRLEN(*pp) + 2));
if (p != NULL)
{
p[0] = '\\';
STRCPY(p + 1, *pp);
vim_free(*pp);
*pp = p;
}
}
/*
* For each file name in files[num_files]:
* If 'orig_pat' starts with "~/", replace the home directory with "~".
*/
void
tilde_replace(orig_pat, num_files, files)
char_u *orig_pat;
int num_files;
char_u **files;
{
int i;
char_u *p;
if (orig_pat[0] == '~' && vim_ispathsep(orig_pat[1]))
{
for (i = 0; i < num_files; ++i)
{
p = home_replace_save(NULL, files[i]);
if (p != NULL)
{
vim_free(files[i]);
files[i] = p;
}
}
}
}
/*
* Show all matches for completion on the command line.
* Returns EXPAND_NOTHING when the character that triggered expansion should
* be inserted like a normal character.
*/
static int
showmatches(xp, wildmenu)
expand_T *xp;
int wildmenu UNUSED;
{
#define L_SHOWFILE(m) (showtail ? sm_gettail(files_found[m]) : files_found[m])
int num_files;
char_u **files_found;
int i, j, k;
int maxlen;
int lines;
int columns;
char_u *p;
int lastlen;
int attr;
int showtail;
if (xp->xp_numfiles == -1)
{
set_expand_context(xp);
i = expand_cmdline(xp, ccline.cmdbuff, ccline.cmdpos,
&num_files, &files_found);
showtail = expand_showtail(xp);
if (i != EXPAND_OK)
return i;
}
else
{
num_files = xp->xp_numfiles;
files_found = xp->xp_files;
showtail = cmd_showtail;
}
#ifdef FEAT_WILDMENU
if (!wildmenu)
{
#endif
msg_didany = FALSE; /* lines_left will be set */
msg_start(); /* prepare for paging */
msg_putchar('\n');
out_flush();
cmdline_row = msg_row;
msg_didany = FALSE; /* lines_left will be set again */
msg_start(); /* prepare for paging */
#ifdef FEAT_WILDMENU
}
#endif
if (got_int)
got_int = FALSE; /* only int. the completion, not the cmd line */
#ifdef FEAT_WILDMENU
else if (wildmenu)
win_redr_status_matches(xp, num_files, files_found, 0, showtail);
#endif
else
{
/* find the length of the longest file name */
maxlen = 0;
for (i = 0; i < num_files; ++i)
{
if (!showtail && (xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_SHELLCMD
|| xp->xp_context == EXPAND_BUFFERS))
{
home_replace(NULL, files_found[i], NameBuff, MAXPATHL, TRUE);
j = vim_strsize(NameBuff);
}
else
j = vim_strsize(L_SHOWFILE(i));
if (j > maxlen)
maxlen = j;
}
if (xp->xp_context == EXPAND_TAGS_LISTFILES)
lines = num_files;
else
{
/* compute the number of columns and lines for the listing */
maxlen += 2; /* two spaces between file names */
columns = ((int)Columns + 2) / maxlen;
if (columns < 1)
columns = 1;
lines = (num_files + columns - 1) / columns;
}
attr = hl_attr(HLF_D); /* find out highlighting for directories */
if (xp->xp_context == EXPAND_TAGS_LISTFILES)
{
MSG_PUTS_ATTR(_("tagname"), hl_attr(HLF_T));
msg_clr_eos();
msg_advance(maxlen - 3);
MSG_PUTS_ATTR(_(" kind file\n"), hl_attr(HLF_T));
}
/* list the files line by line */
for (i = 0; i < lines; ++i)
{
lastlen = 999;
for (k = i; k < num_files; k += lines)
{
if (xp->xp_context == EXPAND_TAGS_LISTFILES)
{
msg_outtrans_attr(files_found[k], hl_attr(HLF_D));
p = files_found[k] + STRLEN(files_found[k]) + 1;
msg_advance(maxlen + 1);
msg_puts(p);
msg_advance(maxlen + 3);
msg_puts_long_attr(p + 2, hl_attr(HLF_D));
break;
}
for (j = maxlen - lastlen; --j >= 0; )
msg_putchar(' ');
if (xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_SHELLCMD
|| xp->xp_context == EXPAND_BUFFERS)
{
/* highlight directories */
if (xp->xp_numfiles != -1)
{
char_u *halved_slash;
char_u *exp_path;
/* Expansion was done before and special characters
* were escaped, need to halve backslashes. Also
* $HOME has been replaced with ~/. */
exp_path = expand_env_save_opt(files_found[k], TRUE);
halved_slash = backslash_halve_save(
exp_path != NULL ? exp_path : files_found[k]);
j = mch_isdir(halved_slash != NULL ? halved_slash
: files_found[k]);
vim_free(exp_path);
vim_free(halved_slash);
}
else
/* Expansion was done here, file names are literal. */
j = mch_isdir(files_found[k]);
if (showtail)
p = L_SHOWFILE(k);
else
{
home_replace(NULL, files_found[k], NameBuff, MAXPATHL,
TRUE);
p = NameBuff;
}
}
else
{
j = FALSE;
p = L_SHOWFILE(k);
}
lastlen = msg_outtrans_attr(p, j ? attr : 0);
}
if (msg_col > 0) /* when not wrapped around */
{
msg_clr_eos();
msg_putchar('\n');
}
out_flush(); /* show one line at a time */
if (got_int)
{
got_int = FALSE;
break;
}
}
/*
* we redraw the command below the lines that we have just listed
* This is a bit tricky, but it saves a lot of screen updating.
*/
cmdline_row = msg_row; /* will put it back later */
}
if (xp->xp_numfiles == -1)
FreeWild(num_files, files_found);
return EXPAND_OK;
}
/*
* Private gettail for showmatches() (and win_redr_status_matches()):
* Find tail of file name path, but ignore trailing "/".
*/
char_u *
sm_gettail(s)
char_u *s;
{
char_u *p;
char_u *t = s;
int had_sep = FALSE;
for (p = s; *p != NUL; )
{
if (vim_ispathsep(*p)
#ifdef BACKSLASH_IN_FILENAME
&& !rem_backslash(p)
#endif
)
had_sep = TRUE;
else if (had_sep)
{
t = p;
had_sep = FALSE;
}
mb_ptr_adv(p);
}
return t;
}
/*
* Return TRUE if we only need to show the tail of completion matches.
* When not completing file names or there is a wildcard in the path FALSE is
* returned.
*/
static int
expand_showtail(xp)
expand_T *xp;
{
char_u *s;
char_u *end;
/* When not completing file names a "/" may mean something different. */
if (xp->xp_context != EXPAND_FILES
&& xp->xp_context != EXPAND_SHELLCMD
&& xp->xp_context != EXPAND_DIRECTORIES)
return FALSE;
end = gettail(xp->xp_pattern);
if (end == xp->xp_pattern) /* there is no path separator */
return FALSE;
for (s = xp->xp_pattern; s < end; s++)
{
/* Skip escaped wildcards. Only when the backslash is not a path
* separator, on DOS the '*' "path\*\file" must not be skipped. */
if (rem_backslash(s))
++s;
else if (vim_strchr((char_u *)"*?[", *s) != NULL)
return FALSE;
}
return TRUE;
}
/*
* Prepare a string for expansion.
* When expanding file names: The string will be used with expand_wildcards().
* Copy the file name into allocated memory and add a '*' at the end.
* When expanding other names: The string will be used with regcomp(). Copy
* the name into allocated memory and prepend "^".
*/
char_u *
addstar(fname, len, context)
char_u *fname;
int len;
int context; /* EXPAND_FILES etc. */
{
char_u *retval;
int i, j;
int new_len;
char_u *tail;
int ends_in_star;
if (context != EXPAND_FILES
&& context != EXPAND_FILES_IN_PATH
&& context != EXPAND_SHELLCMD
&& context != EXPAND_DIRECTORIES)
{
/*
* Matching will be done internally (on something other than files).
* So we convert the file-matching-type wildcards into our kind for
* use with vim_regcomp(). First work out how long it will be:
*/
/* For help tags the translation is done in find_help_tags().
* For a tag pattern starting with "/" no translation is needed. */
if (context == EXPAND_HELP
|| context == EXPAND_COLORS
|| context == EXPAND_COMPILER
|| context == EXPAND_OWNSYNTAX
|| context == EXPAND_FILETYPE
|| (context == EXPAND_TAGS && fname[0] == '/'))
retval = vim_strnsave(fname, len);
else
{
new_len = len + 2; /* +2 for '^' at start, NUL at end */
for (i = 0; i < len; i++)
{
if (fname[i] == '*' || fname[i] == '~')
new_len++; /* '*' needs to be replaced by ".*"
'~' needs to be replaced by "\~" */
/* Buffer names are like file names. "." should be literal */
if (context == EXPAND_BUFFERS && fname[i] == '.')
new_len++; /* "." becomes "\." */
/* Custom expansion takes care of special things, match
* backslashes literally (perhaps also for other types?) */
if ((context == EXPAND_USER_DEFINED
|| context == EXPAND_USER_LIST) && fname[i] == '\\')
new_len++; /* '\' becomes "\\" */
}
retval = alloc(new_len);
if (retval != NULL)
{
retval[0] = '^';
j = 1;
for (i = 0; i < len; i++, j++)
{
/* Skip backslash. But why? At least keep it for custom
* expansion. */
if (context != EXPAND_USER_DEFINED
&& context != EXPAND_USER_LIST
&& fname[i] == '\\'
&& ++i == len)
break;
switch (fname[i])
{
case '*': retval[j++] = '.';
break;
case '~': retval[j++] = '\\';
break;
case '?': retval[j] = '.';
continue;
case '.': if (context == EXPAND_BUFFERS)
retval[j++] = '\\';
break;
case '\\': if (context == EXPAND_USER_DEFINED
|| context == EXPAND_USER_LIST)
retval[j++] = '\\';
break;
}
retval[j] = fname[i];
}
retval[j] = NUL;
}
}
}
else
{
retval = alloc(len + 4);
if (retval != NULL)
{
vim_strncpy(retval, fname, len);
/*
* Don't add a star to *, ~, ~user, $var or `cmd`.
* * would become **, which walks the whole tree.
* ~ would be at the start of the file name, but not the tail.
* $ could be anywhere in the tail.
* ` could be anywhere in the file name.
* When the name ends in '$' don't add a star, remove the '$'.
*/
tail = gettail(retval);
ends_in_star = (len > 0 && retval[len - 1] == '*');
#ifndef BACKSLASH_IN_FILENAME
for (i = len - 2; i >= 0; --i)
{
if (retval[i] != '\\')
break;
ends_in_star = !ends_in_star;
}
#endif
if ((*retval != '~' || tail != retval)
&& !ends_in_star
&& vim_strchr(tail, '$') == NULL
&& vim_strchr(retval, '`') == NULL)
retval[len++] = '*';
else if (len > 0 && retval[len - 1] == '$')
--len;
retval[len] = NUL;
}
}
return retval;
}
/*
* Must parse the command line so far to work out what context we are in.
* Completion can then be done based on that context.
* This routine sets the variables:
* xp->xp_pattern The start of the pattern to be expanded within
* the command line (ends at the cursor).
* xp->xp_context The type of thing to expand. Will be one of:
*
* EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on
* the command line, like an unknown command. Caller
* should beep.
* EXPAND_NOTHING Unrecognised context for completion, use char like
* a normal char, rather than for completion. eg
* :s/^I/
* EXPAND_COMMANDS Cursor is still touching the command, so complete
* it.
* EXPAND_BUFFERS Complete file names for :buf and :sbuf commands.
* EXPAND_FILES After command with XFILE set, or after setting
* with P_EXPAND set. eg :e ^I, :w>>^I
* EXPAND_DIRECTORIES In some cases this is used instead of the latter
* when we know only directories are of interest. eg
* :set dir=^I
* EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd".
* EXPAND_SETTINGS Complete variable names. eg :set d^I
* EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I
* EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I
* EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect
* EXPAND_HELP Complete tags from the file 'helpfile'/tags
* EXPAND_EVENTS Complete event names
* EXPAND_SYNTAX Complete :syntax command arguments
* EXPAND_HIGHLIGHT Complete highlight (syntax) group names
* EXPAND_AUGROUP Complete autocommand group names
* EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I
* EXPAND_MAPPINGS Complete mapping and abbreviation names,
* eg :unmap a^I , :cunab x^I
* EXPAND_FUNCTIONS Complete internal or user defined function names,
* eg :call sub^I
* EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I
* EXPAND_EXPRESSION Complete internal or user defined function/variable
* names in expressions, eg :while s^I
* EXPAND_ENV_VARS Complete environment variable names
*/
static void
set_expand_context(xp)
expand_T *xp;
{
/* only expansion for ':', '>' and '=' command-lines */
if (ccline.cmdfirstc != ':'
#ifdef FEAT_EVAL
&& ccline.cmdfirstc != '>' && ccline.cmdfirstc != '='
&& !ccline.input_fn
#endif
)
{
xp->xp_context = EXPAND_NOTHING;
return;
}
set_cmd_context(xp, ccline.cmdbuff, ccline.cmdlen, ccline.cmdpos);
}
void
set_cmd_context(xp, str, len, col)
expand_T *xp;
char_u *str; /* start of command line */
int len; /* length of command line (excl. NUL) */
int col; /* position of cursor */
{
int old_char = NUL;
char_u *nextcomm;
/*
* Avoid a UMR warning from Purify, only save the character if it has been
* written before.
*/
if (col < len)
old_char = str[col];
str[col] = NUL;
nextcomm = str;
#ifdef FEAT_EVAL
if (ccline.cmdfirstc == '=')
{
# ifdef FEAT_CMDL_COMPL
/* pass CMD_SIZE because there is no real command */
set_context_for_expression(xp, str, CMD_SIZE);
# endif
}
else if (ccline.input_fn)
{
xp->xp_context = ccline.xp_context;
xp->xp_pattern = ccline.cmdbuff;
# if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
xp->xp_arg = ccline.xp_arg;
# endif
}
else
#endif
while (nextcomm != NULL)
nextcomm = set_one_cmd_context(xp, nextcomm);
str[col] = old_char;
}
/*
* Expand the command line "str" from context "xp".
* "xp" must have been set by set_cmd_context().
* xp->xp_pattern points into "str", to where the text that is to be expanded
* starts.
* Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
* cursor.
* Returns EXPAND_NOTHING when there is nothing to expand, might insert the
* key that triggered expansion literally.
* Returns EXPAND_OK otherwise.
*/
int
expand_cmdline(xp, str, col, matchcount, matches)
expand_T *xp;
char_u *str; /* start of command line */
int col; /* position of cursor */
int *matchcount; /* return: nr of matches */
char_u ***matches; /* return: array of pointers to matches */
{
char_u *file_str = NULL;
int options = WILD_ADD_SLASH|WILD_SILENT;
if (xp->xp_context == EXPAND_UNSUCCESSFUL)
{
beep_flush();
return EXPAND_UNSUCCESSFUL; /* Something illegal on command line */
}
if (xp->xp_context == EXPAND_NOTHING)
{
/* Caller can use the character as a normal char instead */
return EXPAND_NOTHING;
}
/* add star to file name, or convert to regexp if not exp. files. */
xp->xp_pattern_len = (int)(str + col - xp->xp_pattern);
file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
if (file_str == NULL)
return EXPAND_UNSUCCESSFUL;
if (p_wic)
options += WILD_ICASE;
/* find all files that match the description */
if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL)
{
*matchcount = 0;
*matches = NULL;
}
vim_free(file_str);
return EXPAND_OK;
}
#ifdef FEAT_MULTI_LANG
/*
* Cleanup matches for help tags: remove "@en" if "en" is the only language.
*/
static void cleanup_help_tags __ARGS((int num_file, char_u **file));
static void
cleanup_help_tags(num_file, file)
int num_file;
char_u **file;
{
int i, j;
int len;
for (i = 0; i < num_file; ++i)
{
len = (int)STRLEN(file[i]) - 3;
if (len > 0 && STRCMP(file[i] + len, "@en") == 0)
{
/* Sorting on priority means the same item in another language may
* be anywhere. Search all items for a match up to the "@en". */
for (j = 0; j < num_file; ++j)
if (j != i
&& (int)STRLEN(file[j]) == len + 3
&& STRNCMP(file[i], file[j], len + 1) == 0)
break;
if (j == num_file)
file[i][len] = NUL;
}
}
}
#endif
/*
* Do the expansion based on xp->xp_context and "pat".
*/
static int
ExpandFromContext(xp, pat, num_file, file, options)
expand_T *xp;
char_u *pat;
int *num_file;
char_u ***file;
int options; /* EW_ flags */
{
#ifdef FEAT_CMDL_COMPL
regmatch_T regmatch;
#endif
int ret;
int flags;
flags = EW_DIR; /* include directories */
if (options & WILD_LIST_NOTFOUND)
flags |= EW_NOTFOUND;
if (options & WILD_ADD_SLASH)
flags |= EW_ADDSLASH;
if (options & WILD_KEEP_ALL)
flags |= EW_KEEPALL;
if (options & WILD_SILENT)
flags |= EW_SILENT;
if (xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_DIRECTORIES
|| xp->xp_context == EXPAND_FILES_IN_PATH)
{
/*
* Expand file or directory names.
*/
int free_pat = FALSE;
int i;
/* for ":set path=" and ":set tags=" halve backslashes for escaped
* space */
if (xp->xp_backslash != XP_BS_NONE)
{
free_pat = TRUE;
pat = vim_strsave(pat);
for (i = 0; pat[i]; ++i)
if (pat[i] == '\\')
{
if (xp->xp_backslash == XP_BS_THREE
&& pat[i + 1] == '\\'
&& pat[i + 2] == '\\'
&& pat[i + 3] == ' ')
STRMOVE(pat + i, pat + i + 3);
if (xp->xp_backslash == XP_BS_ONE
&& pat[i + 1] == ' ')
STRMOVE(pat + i, pat + i + 1);
}
}
if (xp->xp_context == EXPAND_FILES)
flags |= EW_FILE;
else if (xp->xp_context == EXPAND_FILES_IN_PATH)
flags |= (EW_FILE | EW_PATH);
else
flags = (flags | EW_DIR) & ~EW_FILE;
if (options & WILD_ICASE)
flags |= EW_ICASE;
/* Expand wildcards, supporting %:h and the like. */
ret = expand_wildcards_eval(&pat, num_file, file, flags);
if (free_pat)
vim_free(pat);
return ret;
}
*file = (char_u **)"";
*num_file = 0;
if (xp->xp_context == EXPAND_HELP)
{
/* With an empty argument we would get all the help tags, which is
* very slow. Get matches for "help" instead. */
if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
num_file, file, FALSE) == OK)
{
#ifdef FEAT_MULTI_LANG
cleanup_help_tags(*num_file, *file);
#endif
return OK;
}
return FAIL;
}
#ifndef FEAT_CMDL_COMPL
return FAIL;
#else
if (xp->xp_context == EXPAND_SHELLCMD)
return expand_shellcmd(pat, num_file, file, flags);
if (xp->xp_context == EXPAND_OLD_SETTING)
return ExpandOldSetting(num_file, file);
if (xp->xp_context == EXPAND_BUFFERS)
return ExpandBufnames(pat, num_file, file, options);
if (xp->xp_context == EXPAND_TAGS
|| xp->xp_context == EXPAND_TAGS_LISTFILES)
return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
if (xp->xp_context == EXPAND_COLORS)
{
char *directories[] = {"colors", NULL};
return ExpandRTDir(pat, num_file, file, directories);
}
if (xp->xp_context == EXPAND_COMPILER)
{
char *directories[] = {"compiler", NULL};
return ExpandRTDir(pat, num_file, file, directories);
}
if (xp->xp_context == EXPAND_OWNSYNTAX)
{
char *directories[] = {"syntax", NULL};
return ExpandRTDir(pat, num_file, file, directories);
}
if (xp->xp_context == EXPAND_FILETYPE)
{
char *directories[] = {"syntax", "indent", "ftplugin", NULL};
return ExpandRTDir(pat, num_file, file, directories);
}
# if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
if (xp->xp_context == EXPAND_USER_LIST)
return ExpandUserList(xp, num_file, file);
# endif
regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
if (regmatch.regprog == NULL)
return FAIL;
/* set ignore-case according to p_ic, p_scs and pat */
regmatch.rm_ic = ignorecase(pat);
if (xp->xp_context == EXPAND_SETTINGS
|| xp->xp_context == EXPAND_BOOL_SETTINGS)
ret = ExpandSettings(xp, ®match, num_file, file);
else if (xp->xp_context == EXPAND_MAPPINGS)
ret = ExpandMappings(®match, num_file, file);
# if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
else if (xp->xp_context == EXPAND_USER_DEFINED)
ret = ExpandUserDefined(xp, ®match, num_file, file);
# endif
else
{
static struct expgen
{
int context;
char_u *((*func)__ARGS((expand_T *, int)));
int ic;
int escaped;
} tab[] =
{
{EXPAND_COMMANDS, get_command_name, FALSE, TRUE},
{EXPAND_BEHAVE, get_behave_arg, TRUE, TRUE},
#ifdef FEAT_CMDHIST
{EXPAND_HISTORY, get_history_arg, TRUE, TRUE},
#endif
#ifdef FEAT_USR_CMDS
{EXPAND_USER_COMMANDS, get_user_commands, FALSE, TRUE},
{EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE, TRUE},
{EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE, TRUE},
{EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE, TRUE},
#endif
#ifdef FEAT_EVAL
{EXPAND_USER_VARS, get_user_var_name, FALSE, TRUE},
{EXPAND_FUNCTIONS, get_function_name, FALSE, TRUE},
{EXPAND_USER_FUNC, get_user_func_name, FALSE, TRUE},
{EXPAND_EXPRESSION, get_expr_name, FALSE, TRUE},
#endif
#ifdef FEAT_MENU
{EXPAND_MENUS, get_menu_name, FALSE, TRUE},
{EXPAND_MENUNAMES, get_menu_names, FALSE, TRUE},
#endif
#ifdef FEAT_SYN_HL
{EXPAND_SYNTAX, get_syntax_name, TRUE, TRUE},
#endif
{EXPAND_HIGHLIGHT, get_highlight_name, TRUE, TRUE},
#ifdef FEAT_AUTOCMD
{EXPAND_EVENTS, get_event_name, TRUE, TRUE},
{EXPAND_AUGROUP, get_augroup_name, TRUE, TRUE},
#endif
#ifdef FEAT_CSCOPE
{EXPAND_CSCOPE, get_cscope_name, TRUE, TRUE},
#endif
#ifdef FEAT_SIGNS
{EXPAND_SIGN, get_sign_name, TRUE, TRUE},
#endif
#ifdef FEAT_PROFILE
{EXPAND_PROFILE, get_profile_name, TRUE, TRUE},
#endif
#if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
{EXPAND_LANGUAGE, get_lang_arg, TRUE, FALSE},
{EXPAND_LOCALES, get_locales, TRUE, FALSE},
#endif
{EXPAND_ENV_VARS, get_env_name, TRUE, TRUE},
};
int i;
/*
* Find a context in the table and call the ExpandGeneric() with the
* right function to do the expansion.
*/
ret = FAIL;
for (i = 0; i < (int)(sizeof(tab) / sizeof(struct expgen)); ++i)
if (xp->xp_context == tab[i].context)
{
if (tab[i].ic)
regmatch.rm_ic = TRUE;
ret = ExpandGeneric(xp, ®match, num_file, file,
tab[i].func, tab[i].escaped);
break;
}
}
vim_free(regmatch.regprog);
return ret;
#endif /* FEAT_CMDL_COMPL */
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Expand a list of names.
*
* Generic function for command line completion. It calls a function to
* obtain strings, one by one. The strings are matched against a regexp
* program. Matching strings are copied into an array, which is returned.
*
* Returns OK when no problems encountered, FAIL for error (out of memory).
*/
int
ExpandGeneric(xp, regmatch, num_file, file, func, escaped)
expand_T *xp;
regmatch_T *regmatch;
int *num_file;
char_u ***file;
char_u *((*func)__ARGS((expand_T *, int)));
/* returns a string from the list */
int escaped;
{
int i;
int count = 0;
int round;
char_u *str;
/* do this loop twice:
* round == 0: count the number of matching names
* round == 1: copy the matching names into allocated memory
*/
for (round = 0; round <= 1; ++round)
{
for (i = 0; ; ++i)
{
str = (*func)(xp, i);
if (str == NULL) /* end of list */
break;
if (*str == NUL) /* skip empty strings */
continue;
if (vim_regexec(regmatch, str, (colnr_T)0))
{
if (round)
{
if (escaped)
str = vim_strsave_escaped(str, (char_u *)" \t\\.");
else
str = vim_strsave(str);
(*file)[count] = str;
#ifdef FEAT_MENU
if (func == get_menu_names && str != NULL)
{
/* test for separator added by get_menu_names() */
str += STRLEN(str) - 1;
if (*str == '\001')
*str = '.';
}
#endif
}
++count;
}
}
if (round == 0)
{
if (count == 0)
return OK;
*num_file = count;
*file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
if (*file == NULL)
{
*file = (char_u **)"";
return FAIL;
}
count = 0;
}
}
/* Sort the results. Keep menu's in the specified order. */
if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
{
if (xp->xp_context == EXPAND_EXPRESSION
|| xp->xp_context == EXPAND_FUNCTIONS
|| xp->xp_context == EXPAND_USER_FUNC)
/* <SNR> functions should be sorted to the end. */
qsort((void *)*file, (size_t)*num_file, sizeof(char_u *),
sort_func_compare);
else
sort_strings(*file, *num_file);
}
#ifdef FEAT_CMDL_COMPL
/* Reset the variables used for special highlight names expansion, so that
* they don't show up when getting normal highlight names by ID. */
reset_expand_highlight();
#endif
return OK;
}
/*
* Complete a shell command.
* Returns FAIL or OK;
*/
static int
expand_shellcmd(filepat, num_file, file, flagsarg)
char_u *filepat; /* pattern to match with command names */
int *num_file; /* return: number of matches */
char_u ***file; /* return: array with matches */
int flagsarg; /* EW_ flags */
{
char_u *pat;
int i;
char_u *path;
int mustfree = FALSE;
garray_T ga;
char_u *buf = alloc(MAXPATHL);
size_t l;
char_u *s, *e;
int flags = flagsarg;
int ret;
if (buf == NULL)
return FAIL;
/* for ":set path=" and ":set tags=" halve backslashes for escaped
* space */
pat = vim_strsave(filepat);
for (i = 0; pat[i]; ++i)
if (pat[i] == '\\' && pat[i + 1] == ' ')
STRMOVE(pat + i, pat + i + 1);
flags |= EW_FILE | EW_EXEC;
/* For an absolute name we don't use $PATH. */
if (mch_isFullName(pat))
path = (char_u *)" ";
else if ((pat[0] == '.' && (vim_ispathsep(pat[1])
|| (pat[1] == '.' && vim_ispathsep(pat[2])))))
path = (char_u *)".";
else
{
path = vim_getenv((char_u *)"PATH", &mustfree);
if (path == NULL)
path = (char_u *)"";
}
/*
* Go over all directories in $PATH. Expand matches in that directory and
* collect them in "ga".
*/
ga_init2(&ga, (int)sizeof(char *), 10);
for (s = path; *s != NUL; s = e)
{
if (*s == ' ')
++s; /* Skip space used for absolute path name. */
#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
e = vim_strchr(s, ';');
#else
e = vim_strchr(s, ':');
#endif
if (e == NULL)
e = s + STRLEN(s);
l = e - s;
if (l > MAXPATHL - 5)
break;
vim_strncpy(buf, s, l);
add_pathsep(buf);
l = STRLEN(buf);
vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
/* Expand matches in one directory of $PATH. */
ret = expand_wildcards(1, &buf, num_file, file, flags);
if (ret == OK)
{
if (ga_grow(&ga, *num_file) == FAIL)
FreeWild(*num_file, *file);
else
{
for (i = 0; i < *num_file; ++i)
{
s = (*file)[i];
if (STRLEN(s) > l)
{
/* Remove the path again. */
STRMOVE(s, s + l);
((char_u **)ga.ga_data)[ga.ga_len++] = s;
}
else
vim_free(s);
}
vim_free(*file);
}
}
if (*e != NUL)
++e;
}
*file = ga.ga_data;
*num_file = ga.ga_len;
vim_free(buf);
vim_free(pat);
if (mustfree)
vim_free(path);
return OK;
}
# if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
static void * call_user_expand_func __ARGS((void *(*user_expand_func) __ARGS((char_u *, int, char_u **, int)), expand_T *xp, int *num_file, char_u ***file));
/*
* Call "user_expand_func()" to invoke a user defined VimL function and return
* the result (either a string or a List).
*/
static void *
call_user_expand_func(user_expand_func, xp, num_file, file)
void *(*user_expand_func) __ARGS((char_u *, int, char_u **, int));
expand_T *xp;
int *num_file;
char_u ***file;
{
char_u keep;
char_u num[50];
char_u *args[3];
int save_current_SID = current_SID;
void *ret;
struct cmdline_info save_ccline;
if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0')
return NULL;
*num_file = 0;
*file = NULL;
if (ccline.cmdbuff == NULL)
{
/* Completion from Insert mode, pass fake arguments. */
keep = 0;
sprintf((char *)num, "%d", (int)STRLEN(xp->xp_pattern));
args[1] = xp->xp_pattern;
}
else
{
/* Completion on the command line, pass real arguments. */
keep = ccline.cmdbuff[ccline.cmdlen];
ccline.cmdbuff[ccline.cmdlen] = 0;
sprintf((char *)num, "%d", ccline.cmdpos);
args[1] = ccline.cmdbuff;
}
args[0] = vim_strnsave(xp->xp_pattern, xp->xp_pattern_len);
args[2] = num;
/* Save the cmdline, we don't know what the function may do. */
save_ccline = ccline;
ccline.cmdbuff = NULL;
ccline.cmdprompt = NULL;
current_SID = xp->xp_scriptID;
ret = user_expand_func(xp->xp_arg, 3, args, FALSE);
ccline = save_ccline;
current_SID = save_current_SID;
if (ccline.cmdbuff != NULL)
ccline.cmdbuff[ccline.cmdlen] = keep;
vim_free(args[0]);
return ret;
}
/*
* Expand names with a function defined by the user.
*/
static int
ExpandUserDefined(xp, regmatch, num_file, file)
expand_T *xp;
regmatch_T *regmatch;
int *num_file;
char_u ***file;
{
char_u *retstr;
char_u *s;
char_u *e;
char_u keep;
garray_T ga;
retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
if (retstr == NULL)
return FAIL;
ga_init2(&ga, (int)sizeof(char *), 3);
for (s = retstr; *s != NUL; s = e)
{
e = vim_strchr(s, '\n');
if (e == NULL)
e = s + STRLEN(s);
keep = *e;
*e = 0;
if (xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0)
{
*e = keep;
if (*e != NUL)
++e;
continue;
}
if (ga_grow(&ga, 1) == FAIL)
break;
((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
++ga.ga_len;
*e = keep;
if (*e != NUL)
++e;
}
vim_free(retstr);
*file = ga.ga_data;
*num_file = ga.ga_len;
return OK;
}
/*
* Expand names with a list returned by a function defined by the user.
*/
static int
ExpandUserList(xp, num_file, file)
expand_T *xp;
int *num_file;
char_u ***file;
{
list_T *retlist;
listitem_T *li;
garray_T ga;
retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
if (retlist == NULL)
return FAIL;
ga_init2(&ga, (int)sizeof(char *), 3);
/* Loop over the items in the list. */
for (li = retlist->lv_first; li != NULL; li = li->li_next)
{
if (li->li_tv.v_type != VAR_STRING || li->li_tv.vval.v_string == NULL)
continue; /* Skip non-string items and empty strings */
if (ga_grow(&ga, 1) == FAIL)
break;
((char_u **)ga.ga_data)[ga.ga_len] =
vim_strsave(li->li_tv.vval.v_string);
++ga.ga_len;
}
list_unref(retlist);
*file = ga.ga_data;
*num_file = ga.ga_len;
return OK;
}
#endif
/*
* Expand color scheme, compiler or filetype names:
* 'runtimepath'/{dirnames}/{pat}.vim
* "dirnames" is an array with one or more directory names.
*/
static int
ExpandRTDir(pat, num_file, file, dirnames)
char_u *pat;
int *num_file;
char_u ***file;
char *dirnames[];
{
char_u *matches;
char_u *s;
char_u *e;
garray_T ga;
int i;
int pat_len;
*num_file = 0;
*file = NULL;
pat_len = (int)STRLEN(pat);
ga_init2(&ga, (int)sizeof(char *), 10);
for (i = 0; dirnames[i] != NULL; ++i)
{
s = alloc((unsigned)(STRLEN(dirnames[i]) + pat_len + 7));
if (s == NULL)
{
ga_clear_strings(&ga);
return FAIL;
}
sprintf((char *)s, "%s/%s*.vim", dirnames[i], pat);
matches = globpath(p_rtp, s, 0);
vim_free(s);
if (matches == NULL)
continue;
for (s = matches; *s != NUL; s = e)
{
e = vim_strchr(s, '\n');
if (e == NULL)
e = s + STRLEN(s);
if (ga_grow(&ga, 1) == FAIL)
break;
if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
{
for (s = e - 4; s > matches; mb_ptr_back(matches, s))
if (*s == '\n' || vim_ispathsep(*s))
break;
++s;
((char_u **)ga.ga_data)[ga.ga_len] =
vim_strnsave(s, (int)(e - s - 4));
++ga.ga_len;
}
if (*e != NUL)
++e;
}
vim_free(matches);
}
if (ga.ga_len == 0)
return FAIL;
/* Sort and remove duplicates which can happen when specifying multiple
* directories in dirnames. */
remove_duplicates(&ga);
*file = ga.ga_data;
*num_file = ga.ga_len;
return OK;
}
#endif
#if defined(FEAT_CMDL_COMPL) || defined(FEAT_EVAL) || defined(PROTO)
/*
* Expand "file" for all comma-separated directories in "path".
* Returns an allocated string with all matches concatenated, separated by
* newlines. Returns NULL for an error or no matches.
*/
char_u *
globpath(path, file, expand_options)
char_u *path;
char_u *file;
int expand_options;
{
expand_T xpc;
char_u *buf;
garray_T ga;
int i;
int len;
int num_p;
char_u **p;
char_u *cur = NULL;
buf = alloc(MAXPATHL);
if (buf == NULL)
return NULL;
ExpandInit(&xpc);
xpc.xp_context = EXPAND_FILES;
ga_init2(&ga, 1, 100);
/* Loop over all entries in {path}. */
while (*path != NUL)
{
/* Copy one item of the path to buf[] and concatenate the file name. */
copy_option_part(&path, buf, MAXPATHL, ",");
if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
{
# if defined(MSWIN) || defined(MSDOS)
/* Using the platform's path separator (\) makes vim incorrectly
* treat it as an escape character, use '/' instead. */
if (*buf != NUL && !after_pathsep(buf, buf + STRLEN(buf)))
STRCAT(buf, "/");
# else
add_pathsep(buf);
# endif
STRCAT(buf, file);
if (ExpandFromContext(&xpc, buf, &num_p, &p,
WILD_SILENT|expand_options) != FAIL && num_p > 0)
{
ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
for (len = 0, i = 0; i < num_p; ++i)
len += (int)STRLEN(p[i]) + 1;
/* Concatenate new results to previous ones. */
if (ga_grow(&ga, len) == OK)
{
cur = (char_u *)ga.ga_data + ga.ga_len;
for (i = 0; i < num_p; ++i)
{
STRCPY(cur, p[i]);
cur += STRLEN(p[i]);
*cur++ = '\n';
}
ga.ga_len += len;
}
FreeWild(num_p, p);
}
}
}
if (cur != NULL)
*--cur = 0; /* Replace trailing newline with NUL */
vim_free(buf);
return (char_u *)ga.ga_data;
}
#endif
#if defined(FEAT_CMDHIST) || defined(PROTO)
/*********************************
* Command line history stuff *
*********************************/
/*
* Translate a history character to the associated type number.
*/
static int
hist_char2type(c)
int c;
{
if (c == ':')
return HIST_CMD;
if (c == '=')
return HIST_EXPR;
if (c == '@')
return HIST_INPUT;
if (c == '>')
return HIST_DEBUG;
return HIST_SEARCH; /* must be '?' or '/' */
}
/*
* Table of history names.
* These names are used in :history and various hist...() functions.
* It is sufficient to give the significant prefix of a history name.
*/
static char *(history_names[]) =
{
"cmd",
"search",
"expr",
"input",
"debug",
NULL
};
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Function given to ExpandGeneric() to obtain the possible first
* arguments of the ":history command.
*/
static char_u *
get_history_arg(xp, idx)
expand_T *xp UNUSED;
int idx;
{
static char_u compl[2] = { NUL, NUL };
char *short_names = ":=@>?/";
int short_names_count = (int)STRLEN(short_names);
int history_name_count = sizeof(history_names) / sizeof(char *) - 1;
if (idx < short_names_count)
{
compl[0] = (char_u)short_names[idx];
return compl;
}
if (idx < short_names_count + history_name_count)
return (char_u *)history_names[idx - short_names_count];
if (idx == short_names_count + history_name_count)
return (char_u *)"all";
return NULL;
}
#endif
/*
* init_history() - Initialize the command line history.
* Also used to re-allocate the history when the size changes.
*/
void
init_history()
{
int newlen; /* new length of history table */
histentry_T *temp;
int i;
int j;
int type;
/*
* If size of history table changed, reallocate it
*/
newlen = (int)p_hi;
if (newlen != hislen) /* history length changed */
{
for (type = 0; type < HIST_COUNT; ++type) /* adjust the tables */
{
if (newlen)
{
temp = (histentry_T *)lalloc(
(long_u)(newlen * sizeof(histentry_T)), TRUE);
if (temp == NULL) /* out of memory! */
{
if (type == 0) /* first one: just keep the old length */
{
newlen = hislen;
break;
}
/* Already changed one table, now we can only have zero
* length for all tables. */
newlen = 0;
type = -1;
continue;
}
}
else
temp = NULL;
if (newlen == 0 || temp != NULL)
{
if (hisidx[type] < 0) /* there are no entries yet */
{
for (i = 0; i < newlen; ++i)
{
temp[i].hisnum = 0;
temp[i].hisstr = NULL;
}
}
else if (newlen > hislen) /* array becomes bigger */
{
for (i = 0; i <= hisidx[type]; ++i)
temp[i] = history[type][i];
j = i;
for ( ; i <= newlen - (hislen - hisidx[type]); ++i)
{
temp[i].hisnum = 0;
temp[i].hisstr = NULL;
}
for ( ; j < hislen; ++i, ++j)
temp[i] = history[type][j];
}
else /* array becomes smaller or 0 */
{
j = hisidx[type];
for (i = newlen - 1; ; --i)
{
if (i >= 0) /* copy newest entries */
temp[i] = history[type][j];
else /* remove older entries */
vim_free(history[type][j].hisstr);
if (--j < 0)
j = hislen - 1;
if (j == hisidx[type])
break;
}
hisidx[type] = newlen - 1;
}
vim_free(history[type]);
history[type] = temp;
}
}
hislen = newlen;
}
}
/*
* Check if command line 'str' is already in history.
* If 'move_to_front' is TRUE, matching entry is moved to end of history.
*/
static int
in_history(type, str, move_to_front, sep)
int type;
char_u *str;
int move_to_front; /* Move the entry to the front if it exists */
int sep;
{
int i;
int last_i = -1;
char_u *p;
if (hisidx[type] < 0)
return FALSE;
i = hisidx[type];
do
{
if (history[type][i].hisstr == NULL)
return FALSE;
/* For search history, check that the separator character matches as
* well. */
p = history[type][i].hisstr;
if (STRCMP(str, p) == 0
&& (type != HIST_SEARCH || sep == p[STRLEN(p) + 1]))
{
if (!move_to_front)
return TRUE;
last_i = i;
break;
}
if (--i < 0)
i = hislen - 1;
} while (i != hisidx[type]);
if (last_i >= 0)
{
str = history[type][i].hisstr;
while (i != hisidx[type])
{
if (++i >= hislen)
i = 0;
history[type][last_i] = history[type][i];
last_i = i;
}
history[type][i].hisstr = str;
history[type][i].hisnum = ++hisnum[type];
return TRUE;
}
return FALSE;
}
/*
* Convert history name (from table above) to its HIST_ equivalent.
* When "name" is empty, return "cmd" history.
* Returns -1 for unknown history name.
*/
int
get_histtype(name)
char_u *name;
{
int i;
int len = (int)STRLEN(name);
/* No argument: use current history. */
if (len == 0)
return hist_char2type(ccline.cmdfirstc);
for (i = 0; history_names[i] != NULL; ++i)
if (STRNICMP(name, history_names[i], len) == 0)
return i;
if (vim_strchr((char_u *)":=@>?/", name[0]) != NULL && name[1] == NUL)
return hist_char2type(name[0]);
return -1;
}
static int last_maptick = -1; /* last seen maptick */
/*
* Add the given string to the given history. If the string is already in the
* history then it is moved to the front. "histype" may be one of he HIST_
* values.
*/
void
add_to_history(histype, new_entry, in_map, sep)
int histype;
char_u *new_entry;
int in_map; /* consider maptick when inside a mapping */
int sep; /* separator character used (search hist) */
{
histentry_T *hisptr;
int len;
if (hislen == 0) /* no history */
return;
/*
* Searches inside the same mapping overwrite each other, so that only
* the last line is kept. Be careful not to remove a line that was moved
* down, only lines that were added.
*/
if (histype == HIST_SEARCH && in_map)
{
if (maptick == last_maptick)
{
/* Current line is from the same mapping, remove it */
hisptr = &history[HIST_SEARCH][hisidx[HIST_SEARCH]];
vim_free(hisptr->hisstr);
hisptr->hisstr = NULL;
hisptr->hisnum = 0;
--hisnum[histype];
if (--hisidx[HIST_SEARCH] < 0)
hisidx[HIST_SEARCH] = hislen - 1;
}
last_maptick = -1;
}
if (!in_history(histype, new_entry, TRUE, sep))
{
if (++hisidx[histype] == hislen)
hisidx[histype] = 0;
hisptr = &history[histype][hisidx[histype]];
vim_free(hisptr->hisstr);
/* Store the separator after the NUL of the string. */
len = (int)STRLEN(new_entry);
hisptr->hisstr = vim_strnsave(new_entry, len + 2);
if (hisptr->hisstr != NULL)
hisptr->hisstr[len + 1] = sep;
hisptr->hisnum = ++hisnum[histype];
if (histype == HIST_SEARCH && in_map)
last_maptick = maptick;
}
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Get identifier of newest history entry.
* "histype" may be one of the HIST_ values.
*/
int
get_history_idx(histype)
int histype;
{
if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
|| hisidx[histype] < 0)
return -1;
return history[histype][hisidx[histype]].hisnum;
}
static struct cmdline_info *get_ccline_ptr __ARGS((void));
/*
* Get pointer to the command line info to use. cmdline_paste() may clear
* ccline and put the previous value in prev_ccline.
*/
static struct cmdline_info *
get_ccline_ptr()
{
if ((State & CMDLINE) == 0)
return NULL;
if (ccline.cmdbuff != NULL)
return &ccline;
if (prev_ccline_used && prev_ccline.cmdbuff != NULL)
return &prev_ccline;
return NULL;
}
/*
* Get the current command line in allocated memory.
* Only works when the command line is being edited.
* Returns NULL when something is wrong.
*/
char_u *
get_cmdline_str()
{
struct cmdline_info *p = get_ccline_ptr();
if (p == NULL)
return NULL;
return vim_strnsave(p->cmdbuff, p->cmdlen);
}
/*
* Get the current command line position, counted in bytes.
* Zero is the first position.
* Only works when the command line is being edited.
* Returns -1 when something is wrong.
*/
int
get_cmdline_pos()
{
struct cmdline_info *p = get_ccline_ptr();
if (p == NULL)
return -1;
return p->cmdpos;
}
/*
* Set the command line byte position to "pos". Zero is the first position.
* Only works when the command line is being edited.
* Returns 1 when failed, 0 when OK.
*/
int
set_cmdline_pos(pos)
int pos;
{
struct cmdline_info *p = get_ccline_ptr();
if (p == NULL)
return 1;
/* The position is not set directly but after CTRL-\ e or CTRL-R = has
* changed the command line. */
if (pos < 0)
new_cmdpos = 0;
else
new_cmdpos = pos;
return 0;
}
/*
* Get the current command-line type.
* Returns ':' or '/' or '?' or '@' or '>' or '-'
* Only works when the command line is being edited.
* Returns NUL when something is wrong.
*/
int
get_cmdline_type()
{
struct cmdline_info *p = get_ccline_ptr();
if (p == NULL)
return NUL;
if (p->cmdfirstc == NUL)
return (p->input_fn) ? '@' : '-';
return p->cmdfirstc;
}
/*
* Calculate history index from a number:
* num > 0: seen as identifying number of a history entry
* num < 0: relative position in history wrt newest entry
* "histype" may be one of the HIST_ values.
*/
static int
calc_hist_idx(histype, num)
int histype;
int num;
{
int i;
histentry_T *hist;
int wrapped = FALSE;
if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
|| (i = hisidx[histype]) < 0 || num == 0)
return -1;
hist = history[histype];
if (num > 0)
{
while (hist[i].hisnum > num)
if (--i < 0)
{
if (wrapped)
break;
i += hislen;
wrapped = TRUE;
}
if (hist[i].hisnum == num && hist[i].hisstr != NULL)
return i;
}
else if (-num <= hislen)
{
i += num + 1;
if (i < 0)
i += hislen;
if (hist[i].hisstr != NULL)
return i;
}
return -1;
}
/*
* Get a history entry by its index.
* "histype" may be one of the HIST_ values.
*/
char_u *
get_history_entry(histype, idx)
int histype;
int idx;
{
idx = calc_hist_idx(histype, idx);
if (idx >= 0)
return history[histype][idx].hisstr;
else
return (char_u *)"";
}
/*
* Clear all entries of a history.
* "histype" may be one of the HIST_ values.
*/
int
clr_history(histype)
int histype;
{
int i;
histentry_T *hisptr;
if (hislen != 0 && histype >= 0 && histype < HIST_COUNT)
{
hisptr = history[histype];
for (i = hislen; i--;)
{
vim_free(hisptr->hisstr);
hisptr->hisnum = 0;
hisptr++->hisstr = NULL;
}
hisidx[histype] = -1; /* mark history as cleared */
hisnum[histype] = 0; /* reset identifier counter */
return OK;
}
return FAIL;
}
/*
* Remove all entries matching {str} from a history.
* "histype" may be one of the HIST_ values.
*/
int
del_history_entry(histype, str)
int histype;
char_u *str;
{
regmatch_T regmatch;
histentry_T *hisptr;
int idx;
int i;
int last;
int found = FALSE;
regmatch.regprog = NULL;
regmatch.rm_ic = FALSE; /* always match case */
if (hislen != 0
&& histype >= 0
&& histype < HIST_COUNT
&& *str != NUL
&& (idx = hisidx[histype]) >= 0
&& (regmatch.regprog = vim_regcomp(str, RE_MAGIC + RE_STRING))
!= NULL)
{
i = last = idx;
do
{
hisptr = &history[histype][i];
if (hisptr->hisstr == NULL)
break;
if (vim_regexec(®match, hisptr->hisstr, (colnr_T)0))
{
found = TRUE;
vim_free(hisptr->hisstr);
hisptr->hisstr = NULL;
hisptr->hisnum = 0;
}
else
{
if (i != last)
{
history[histype][last] = *hisptr;
hisptr->hisstr = NULL;
hisptr->hisnum = 0;
}
if (--last < 0)
last += hislen;
}
if (--i < 0)
i += hislen;
} while (i != idx);
if (history[histype][idx].hisstr == NULL)
hisidx[histype] = -1;
}
vim_free(regmatch.regprog);
return found;
}
/*
* Remove an indexed entry from a history.
* "histype" may be one of the HIST_ values.
*/
int
del_history_idx(histype, idx)
int histype;
int idx;
{
int i, j;
i = calc_hist_idx(histype, idx);
if (i < 0)
return FALSE;
idx = hisidx[histype];
vim_free(history[histype][i].hisstr);
/* When deleting the last added search string in a mapping, reset
* last_maptick, so that the last added search string isn't deleted again.
*/
if (histype == HIST_SEARCH && maptick == last_maptick && i == idx)
last_maptick = -1;
while (i != idx)
{
j = (i + 1) % hislen;
history[histype][i] = history[histype][j];
i = j;
}
history[histype][i].hisstr = NULL;
history[histype][i].hisnum = 0;
if (--i < 0)
i += hislen;
hisidx[histype] = i;
return TRUE;
}
#endif /* FEAT_EVAL */
#if defined(FEAT_CRYPT) || defined(PROTO)
/*
* Very specific function to remove the value in ":set key=val" from the
* history.
*/
void
remove_key_from_history()
{
char_u *p;
int i;
i = hisidx[HIST_CMD];
if (i < 0)
return;
p = history[HIST_CMD][i].hisstr;
if (p != NULL)
for ( ; *p; ++p)
if (STRNCMP(p, "key", 3) == 0 && !isalpha(p[3]))
{
p = vim_strchr(p + 3, '=');
if (p == NULL)
break;
++p;
for (i = 0; p[i] && !vim_iswhite(p[i]); ++i)
if (p[i] == '\\' && p[i + 1])
++i;
STRMOVE(p, p + i);
--p;
}
}
#endif
#endif /* FEAT_CMDHIST */
#if defined(FEAT_QUICKFIX) || defined(FEAT_CMDHIST) || defined(PROTO)
/*
* Get indices "num1,num2" that specify a range within a list (not a range of
* text lines in a buffer!) from a string. Used for ":history" and ":clist".
* Returns OK if parsed successfully, otherwise FAIL.
*/
int
get_list_range(str, num1, num2)
char_u **str;
int *num1;
int *num2;
{
int len;
int first = FALSE;
long num;
*str = skipwhite(*str);
if (**str == '-' || vim_isdigit(**str)) /* parse "from" part of range */
{
vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
*str += len;
*num1 = (int)num;
first = TRUE;
}
*str = skipwhite(*str);
if (**str == ',') /* parse "to" part of range */
{
*str = skipwhite(*str + 1);
vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
if (len > 0)
{
*num2 = (int)num;
*str = skipwhite(*str + len);
}
else if (!first) /* no number given at all */
return FAIL;
}
else if (first) /* only one number given */
*num2 = *num1;
return OK;
}
#endif
#if defined(FEAT_CMDHIST) || defined(PROTO)
/*
* :history command - print a history
*/
void
ex_history(eap)
exarg_T *eap;
{
histentry_T *hist;
int histype1 = HIST_CMD;
int histype2 = HIST_CMD;
int hisidx1 = 1;
int hisidx2 = -1;
int idx;
int i, j, k;
char_u *end;
char_u *arg = eap->arg;
if (hislen == 0)
{
MSG(_("'history' option is zero"));
return;
}
if (!(VIM_ISDIGIT(*arg) || *arg == '-' || *arg == ','))
{
end = arg;
while (ASCII_ISALPHA(*end)
|| vim_strchr((char_u *)":=@>/?", *end) != NULL)
end++;
i = *end;
*end = NUL;
histype1 = get_histtype(arg);
if (histype1 == -1)
{
if (STRNICMP(arg, "all", STRLEN(arg)) == 0)
{
histype1 = 0;
histype2 = HIST_COUNT-1;
}
else
{
*end = i;
EMSG(_(e_trailing));
return;
}
}
else
histype2 = histype1;
*end = i;
}
else
end = arg;
if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL)
{
EMSG(_(e_trailing));
return;
}
for (; !got_int && histype1 <= histype2; ++histype1)
{
STRCPY(IObuff, "\n # ");
STRCAT(STRCAT(IObuff, history_names[histype1]), " history");
MSG_PUTS_TITLE(IObuff);
idx = hisidx[histype1];
hist = history[histype1];
j = hisidx1;
k = hisidx2;
if (j < 0)
j = (-j > hislen) ? 0 : hist[(hislen+j+idx+1) % hislen].hisnum;
if (k < 0)
k = (-k > hislen) ? 0 : hist[(hislen+k+idx+1) % hislen].hisnum;
if (idx >= 0 && j <= k)
for (i = idx + 1; !got_int; ++i)
{
if (i == hislen)
i = 0;
if (hist[i].hisstr != NULL
&& hist[i].hisnum >= j && hist[i].hisnum <= k)
{
msg_putchar('\n');
sprintf((char *)IObuff, "%c%6d ", i == idx ? '>' : ' ',
hist[i].hisnum);
if (vim_strsize(hist[i].hisstr) > (int)Columns - 10)
trunc_string(hist[i].hisstr, IObuff + STRLEN(IObuff),
(int)Columns - 10, IOSIZE - (int)STRLEN(IObuff));
else
STRCAT(IObuff, hist[i].hisstr);
msg_outtrans(IObuff);
out_flush();
}
if (i == idx)
break;
}
}
}
#endif
#if (defined(FEAT_VIMINFO) && defined(FEAT_CMDHIST)) || defined(PROTO)
static char_u **viminfo_history[HIST_COUNT] = {NULL, NULL, NULL, NULL};
static int viminfo_hisidx[HIST_COUNT] = {0, 0, 0, 0};
static int viminfo_hislen[HIST_COUNT] = {0, 0, 0, 0};
static int viminfo_add_at_front = FALSE;
static int hist_type2char __ARGS((int type, int use_question));
/*
* Translate a history type number to the associated character.
*/
static int
hist_type2char(type, use_question)
int type;
int use_question; /* use '?' instead of '/' */
{
if (type == HIST_CMD)
return ':';
if (type == HIST_SEARCH)
{
if (use_question)
return '?';
else
return '/';
}
if (type == HIST_EXPR)
return '=';
return '@';
}
/*
* Prepare for reading the history from the viminfo file.
* This allocates history arrays to store the read history lines.
*/
void
prepare_viminfo_history(asklen)
int asklen;
{
int i;
int num;
int type;
int len;
init_history();
viminfo_add_at_front = (asklen != 0);
if (asklen > hislen)
asklen = hislen;
for (type = 0; type < HIST_COUNT; ++type)
{
/*
* Count the number of empty spaces in the history list. If there are
* more spaces available than we request, then fill them up.
*/
for (i = 0, num = 0; i < hislen; i++)
if (history[type][i].hisstr == NULL)
num++;
len = asklen;
if (num > len)
len = num;
if (len <= 0)
viminfo_history[type] = NULL;
else
viminfo_history[type] =
(char_u **)lalloc((long_u)(len * sizeof(char_u *)), FALSE);
if (viminfo_history[type] == NULL)
len = 0;
viminfo_hislen[type] = len;
viminfo_hisidx[type] = 0;
}
}
/*
* Accept a line from the viminfo, store it in the history array when it's
* new.
*/
int
read_viminfo_history(virp)
vir_T *virp;
{
int type;
long_u len;
char_u *val;
char_u *p;
type = hist_char2type(virp->vir_line[0]);
if (viminfo_hisidx[type] < viminfo_hislen[type])
{
val = viminfo_readstring(virp, 1, TRUE);
if (val != NULL && *val != NUL)
{
int sep = (*val == ' ' ? NUL : *val);
if (!in_history(type, val + (type == HIST_SEARCH),
viminfo_add_at_front, sep))
{
/* Need to re-allocate to append the separator byte. */
len = STRLEN(val);
p = lalloc(len + 2, TRUE);
if (p != NULL)
{
if (type == HIST_SEARCH)
{
/* Search entry: Move the separator from the first
* column to after the NUL. */
mch_memmove(p, val + 1, (size_t)len);
p[len] = sep;
}
else
{
/* Not a search entry: No separator in the viminfo
* file, add a NUL separator. */
mch_memmove(p, val, (size_t)len + 1);
p[len + 1] = NUL;
}
viminfo_history[type][viminfo_hisidx[type]++] = p;
}
}
}
vim_free(val);
}
return viminfo_readline(virp);
}
void
finish_viminfo_history()
{
int idx;
int i;
int type;
for (type = 0; type < HIST_COUNT; ++type)
{
if (history[type] == NULL)
return;
idx = hisidx[type] + viminfo_hisidx[type];
if (idx >= hislen)
idx -= hislen;
else if (idx < 0)
idx = hislen - 1;
if (viminfo_add_at_front)
hisidx[type] = idx;
else
{
if (hisidx[type] == -1)
hisidx[type] = hislen - 1;
do
{
if (history[type][idx].hisstr != NULL)
break;
if (++idx == hislen)
idx = 0;
} while (idx != hisidx[type]);
if (idx != hisidx[type] && --idx < 0)
idx = hislen - 1;
}
for (i = 0; i < viminfo_hisidx[type]; i++)
{
vim_free(history[type][idx].hisstr);
history[type][idx].hisstr = viminfo_history[type][i];
if (--idx < 0)
idx = hislen - 1;
}
idx += 1;
idx %= hislen;
for (i = 0; i < viminfo_hisidx[type]; i++)
{
history[type][idx++].hisnum = ++hisnum[type];
idx %= hislen;
}
vim_free(viminfo_history[type]);
viminfo_history[type] = NULL;
}
}
void
write_viminfo_history(fp)
FILE *fp;
{
int i;
int type;
int num_saved;
char_u *p;
int c;
init_history();
if (hislen == 0)
return;
for (type = 0; type < HIST_COUNT; ++type)
{
num_saved = get_viminfo_parameter(hist_type2char(type, FALSE));
if (num_saved == 0)
continue;
if (num_saved < 0) /* Use default */
num_saved = hislen;
fprintf(fp, _("\n# %s History (newest to oldest):\n"),
type == HIST_CMD ? _("Command Line") :
type == HIST_SEARCH ? _("Search String") :
type == HIST_EXPR ? _("Expression") :
_("Input Line"));
if (num_saved > hislen)
num_saved = hislen;
i = hisidx[type];
if (i >= 0)
while (num_saved--)
{
p = history[type][i].hisstr;
if (p != NULL)
{
fputc(hist_type2char(type, TRUE), fp);
/* For the search history: put the separator in the second
* column; use a space if there isn't one. */
if (type == HIST_SEARCH)
{
c = p[STRLEN(p) + 1];
putc(c == NUL ? ' ' : c, fp);
}
viminfo_writestring(fp, p);
}
if (--i < 0)
i = hislen - 1;
}
}
}
#endif /* FEAT_VIMINFO */
#if defined(FEAT_FKMAP) || defined(PROTO)
/*
* Write a character at the current cursor+offset position.
* It is directly written into the command buffer block.
*/
void
cmd_pchar(c, offset)
int c, offset;
{
if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
{
EMSG(_("E198: cmd_pchar beyond the command length"));
return;
}
ccline.cmdbuff[ccline.cmdpos + offset] = (char_u)c;
ccline.cmdbuff[ccline.cmdlen] = NUL;
}
int
cmd_gchar(offset)
int offset;
{
if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
{
/* EMSG(_("cmd_gchar beyond the command length")); */
return NUL;
}
return (int)ccline.cmdbuff[ccline.cmdpos + offset];
}
#endif
#if defined(FEAT_CMDWIN) || defined(PROTO)
/*
* Open a window on the current command line and history. Allow editing in
* the window. Returns when the window is closed.
* Returns:
* CR if the command is to be executed
* Ctrl_C if it is to be abandoned
* K_IGNORE if editing continues
*/
static int
ex_window()
{
struct cmdline_info save_ccline;
buf_T *old_curbuf = curbuf;
win_T *old_curwin = curwin;
buf_T *bp;
win_T *wp;
int i;
linenr_T lnum;
int histtype;
garray_T winsizes;
#ifdef FEAT_AUTOCMD
char_u typestr[2];
#endif
int save_restart_edit = restart_edit;
int save_State = State;
int save_exmode = exmode_active;
#ifdef FEAT_RIGHTLEFT
int save_cmdmsg_rl = cmdmsg_rl;
#endif
/* Can't do this recursively. Can't do it when typing a password. */
if (cmdwin_type != 0
# if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
|| cmdline_star > 0
# endif
)
{
beep_flush();
return K_IGNORE;
}
/* Save current window sizes. */
win_size_save(&winsizes);
# ifdef FEAT_AUTOCMD
/* Don't execute autocommands while creating the window. */
block_autocmds();
# endif
/* don't use a new tab page */
cmdmod.tab = 0;
/* Create a window for the command-line buffer. */
if (win_split((int)p_cwh, WSP_BOT) == FAIL)
{
beep_flush();
# ifdef FEAT_AUTOCMD
unblock_autocmds();
# endif
return K_IGNORE;
}
cmdwin_type = get_cmdline_type();
/* Create the command-line buffer empty. */
(void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, NULL);
(void)setfname(curbuf, (char_u *)"[Command Line]", NULL, TRUE);
set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL);
set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL);
curbuf->b_p_ma = TRUE;
#ifdef FEAT_FOLDING
curwin->w_p_fen = FALSE;
#endif
# ifdef FEAT_RIGHTLEFT
curwin->w_p_rl = cmdmsg_rl;
cmdmsg_rl = FALSE;
# endif
RESET_BINDING(curwin);
# ifdef FEAT_AUTOCMD
/* Do execute autocommands for setting the filetype (load syntax). */
unblock_autocmds();
# endif
/* Showing the prompt may have set need_wait_return, reset it. */
need_wait_return = FALSE;
histtype = hist_char2type(cmdwin_type);
if (histtype == HIST_CMD || histtype == HIST_DEBUG)
{
if (p_wc == TAB)
{
add_map((char_u *)"<buffer> <Tab> <C-X><C-V>", INSERT);
add_map((char_u *)"<buffer> <Tab> a<C-X><C-V>", NORMAL);
}
set_option_value((char_u *)"ft", 0L, (char_u *)"vim", OPT_LOCAL);
}
/* Reset 'textwidth' after setting 'filetype' (the Vim filetype plugin
* sets 'textwidth' to 78). */
curbuf->b_p_tw = 0;
/* Fill the buffer with the history. */
init_history();
if (hislen > 0)
{
i = hisidx[histtype];
if (i >= 0)
{
lnum = 0;
do
{
if (++i == hislen)
i = 0;
if (history[histtype][i].hisstr != NULL)
ml_append(lnum++, history[histtype][i].hisstr,
(colnr_T)0, FALSE);
}
while (i != hisidx[histtype]);
}
}
/* Replace the empty last line with the current command-line and put the
* cursor there. */
ml_replace(curbuf->b_ml.ml_line_count, ccline.cmdbuff, TRUE);
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
curwin->w_cursor.col = ccline.cmdpos;
changed_line_abv_curs();
invalidate_botline();
redraw_later(SOME_VALID);
/* Save the command line info, can be used recursively. */
save_ccline = ccline;
ccline.cmdbuff = NULL;
ccline.cmdprompt = NULL;
/* No Ex mode here! */
exmode_active = 0;
State = NORMAL;
# ifdef FEAT_MOUSE
setmouse();
# endif
# ifdef FEAT_AUTOCMD
/* Trigger CmdwinEnter autocommands. */
typestr[0] = cmdwin_type;
typestr[1] = NUL;
apply_autocmds(EVENT_CMDWINENTER, typestr, typestr, FALSE, curbuf);
if (restart_edit != 0) /* autocmd with ":startinsert" */
stuffcharReadbuff(K_NOP);
# endif
i = RedrawingDisabled;
RedrawingDisabled = 0;
/*
* Call the main loop until <CR> or CTRL-C is typed.
*/
cmdwin_result = 0;
main_loop(TRUE, FALSE);
RedrawingDisabled = i;
# ifdef FEAT_AUTOCMD
/* Trigger CmdwinLeave autocommands. */
apply_autocmds(EVENT_CMDWINLEAVE, typestr, typestr, FALSE, curbuf);
# endif
/* Restore the command line info. */
ccline = save_ccline;
cmdwin_type = 0;
exmode_active = save_exmode;
/* Safety check: The old window or buffer was deleted: It's a bug when
* this happens! */
if (!win_valid(old_curwin) || !buf_valid(old_curbuf))
{
cmdwin_result = Ctrl_C;
EMSG(_("E199: Active window or buffer deleted"));
}
else
{
# if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
/* autocmds may abort script processing */
if (aborting() && cmdwin_result != K_IGNORE)
cmdwin_result = Ctrl_C;
# endif
/* Set the new command line from the cmdline buffer. */
vim_free(ccline.cmdbuff);
if (cmdwin_result == K_XF1 || cmdwin_result == K_XF2) /* :qa[!] typed */
{
char *p = (cmdwin_result == K_XF2) ? "qa" : "qa!";
if (histtype == HIST_CMD)
{
/* Execute the command directly. */
ccline.cmdbuff = vim_strsave((char_u *)p);
cmdwin_result = CAR;
}
else
{
/* First need to cancel what we were doing. */
ccline.cmdbuff = NULL;
stuffcharReadbuff(':');
stuffReadbuff((char_u *)p);
stuffcharReadbuff(CAR);
}
}
else if (cmdwin_result == K_XF2) /* :qa typed */
{
ccline.cmdbuff = vim_strsave((char_u *)"qa");
cmdwin_result = CAR;
}
else if (cmdwin_result == Ctrl_C)
{
/* :q or :close, don't execute any command
* and don't modify the cmd window. */
ccline.cmdbuff = NULL;
}
else
ccline.cmdbuff = vim_strsave(ml_get_curline());
if (ccline.cmdbuff == NULL)
cmdwin_result = Ctrl_C;
else
{
ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
ccline.cmdbufflen = ccline.cmdlen + 1;
ccline.cmdpos = curwin->w_cursor.col;
if (ccline.cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
if (cmdwin_result == K_IGNORE)
{
set_cmdspos_cursor();
redrawcmd();
}
}
# ifdef FEAT_AUTOCMD
/* Don't execute autocommands while deleting the window. */
block_autocmds();
# endif
wp = curwin;
bp = curbuf;
win_goto(old_curwin);
win_close(wp, TRUE);
/* win_close() may have already wiped the buffer when 'bh' is
* set to 'wipe' */
if (buf_valid(bp))
close_buffer(NULL, bp, DOBUF_WIPE, FALSE);
/* Restore window sizes. */
win_size_restore(&winsizes);
# ifdef FEAT_AUTOCMD
unblock_autocmds();
# endif
}
ga_clear(&winsizes);
restart_edit = save_restart_edit;
# ifdef FEAT_RIGHTLEFT
cmdmsg_rl = save_cmdmsg_rl;
# endif
State = save_State;
# ifdef FEAT_MOUSE
setmouse();
# endif
return cmdwin_result;
}
#endif /* FEAT_CMDWIN */
/*
* Used for commands that either take a simple command string argument, or:
* cmd << endmarker
* {script}
* endmarker
* Returns a pointer to allocated memory with {script} or NULL.
*/
char_u *
script_get(eap, cmd)
exarg_T *eap;
char_u *cmd;
{
char_u *theline;
char *end_pattern = NULL;
char dot[] = ".";
garray_T ga;
if (cmd[0] != '<' || cmd[1] != '<' || eap->getline == NULL)
return NULL;
ga_init2(&ga, 1, 0x400);
if (cmd[2] != NUL)
end_pattern = (char *)skipwhite(cmd + 2);
else
end_pattern = dot;
for (;;)
{
theline = eap->getline(
#ifdef FEAT_EVAL
eap->cstack->cs_looplevel > 0 ? -1 :
#endif
NUL, eap->cookie, 0);
if (theline == NULL || STRCMP(end_pattern, theline) == 0)
{
vim_free(theline);
break;
}
ga_concat(&ga, theline);
ga_append(&ga, '\n');
vim_free(theline);
}
ga_append(&ga, NUL);
return (char_u *)ga.ga_data;
}
| zyz2011-vim | src/ex_getln.c | C | gpl2 | 159,077 |
/* 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.
*/
/*
* Keycode definitions for special keys.
*
* Any special key code sequences are replaced by these codes.
*/
/*
* For MSDOS some keys produce codes larger than 0xff. They are split into two
* chars, the first one is K_NUL (same value used in term.h).
*/
#define K_NUL (0xce) /* for MSDOS: special key follows */
/*
* K_SPECIAL is the first byte of a special key code and is always followed by
* two bytes.
* The second byte can have any value. ASCII is used for normal termcap
* entries, 0x80 and higher for special keys, see below.
* The third byte is guaranteed to be between 0x02 and 0x7f.
*/
#define K_SPECIAL (0x80)
/*
* Positive characters are "normal" characters.
* Negative characters are special key codes. Only characters below -0x200
* are used to so that the absolute value can't be mistaken for a single-byte
* character.
*/
#define IS_SPECIAL(c) ((c) < 0)
/*
* Characters 0x0100 - 0x01ff have a special meaning for abbreviations.
* Multi-byte characters also have ABBR_OFF added, thus are above 0x0200.
*/
#define ABBR_OFF 0x100
/*
* NUL cannot be in the input string, therefore it is replaced by
* K_SPECIAL KS_ZERO KE_FILLER
*/
#define KS_ZERO 255
/*
* K_SPECIAL cannot be in the input string, therefore it is replaced by
* K_SPECIAL KS_SPECIAL KE_FILLER
*/
#define KS_SPECIAL 254
/*
* KS_EXTRA is used for keys that have no termcap name
* K_SPECIAL KS_EXTRA KE_xxx
*/
#define KS_EXTRA 253
/*
* KS_MODIFIER is used when a modifier is given for a (special) key
* K_SPECIAL KS_MODIFIER bitmask
*/
#define KS_MODIFIER 252
/*
* These are used for the GUI
* K_SPECIAL KS_xxx KE_FILLER
*/
#define KS_MOUSE 251
#define KS_MENU 250
#define KS_VER_SCROLLBAR 249
#define KS_HOR_SCROLLBAR 248
/*
* These are used for DEC mouse
*/
#define KS_NETTERM_MOUSE 247
#define KS_DEC_MOUSE 246
/*
* Used for switching Select mode back on after a mapping or menu.
*/
#define KS_SELECT 245
#define K_SELECT_STRING (char_u *)"\200\365X"
/*
* Used for tearing off a menu.
*/
#define KS_TEAROFF 244
/* Used for JSB term mouse. */
#define KS_JSBTERM_MOUSE 243
/* Used a termcap entry that produces a normal character. */
#define KS_KEY 242
/* Used for the qnx pterm mouse. */
#define KS_PTERM_MOUSE 241
/* Used for click in a tab pages label. */
#define KS_TABLINE 240
/* Used for menu in a tab pages line. */
#define KS_TABMENU 239
/* Used for the urxvt mouse. */
#define KS_URXVT_MOUSE 238
/*
* Filler used after KS_SPECIAL and others
*/
#define KE_FILLER ('X')
/*
* translation of three byte code "K_SPECIAL a b" into int "K_xxx" and back
*/
#define TERMCAP2KEY(a, b) (-((a) + ((int)(b) << 8)))
#define KEY2TERMCAP0(x) ((-(x)) & 0xff)
#define KEY2TERMCAP1(x) (((unsigned)(-(x)) >> 8) & 0xff)
/*
* get second or third byte when translating special key code into three bytes
*/
#define K_SECOND(c) ((c) == K_SPECIAL ? KS_SPECIAL : (c) == NUL ? KS_ZERO : KEY2TERMCAP0(c))
#define K_THIRD(c) (((c) == K_SPECIAL || (c) == NUL) ? KE_FILLER : KEY2TERMCAP1(c))
/*
* get single int code from second byte after K_SPECIAL
*/
#define TO_SPECIAL(a, b) ((a) == KS_SPECIAL ? K_SPECIAL : (a) == KS_ZERO ? K_ZERO : TERMCAP2KEY(a, b))
/*
* Codes for keys that do not have a termcap name.
*
* K_SPECIAL KS_EXTRA KE_xxx
*/
enum key_extra
{
KE_NAME = 3 /* name of this terminal entry */
, KE_S_UP /* shift-up */
, KE_S_DOWN /* shift-down */
, KE_S_F1 /* shifted function keys */
, KE_S_F2
, KE_S_F3
, KE_S_F4
, KE_S_F5
, KE_S_F6
, KE_S_F7
, KE_S_F8
, KE_S_F9
, KE_S_F10
, KE_S_F11
, KE_S_F12
, KE_S_F13
, KE_S_F14
, KE_S_F15
, KE_S_F16
, KE_S_F17
, KE_S_F18
, KE_S_F19
, KE_S_F20
, KE_S_F21
, KE_S_F22
, KE_S_F23
, KE_S_F24
, KE_S_F25
, KE_S_F26
, KE_S_F27
, KE_S_F28
, KE_S_F29
, KE_S_F30
, KE_S_F31
, KE_S_F32
, KE_S_F33
, KE_S_F34
, KE_S_F35
, KE_S_F36
, KE_S_F37
, KE_MOUSE /* mouse event start */
/*
* Symbols for pseudo keys which are translated from the real key symbols
* above.
*/
, KE_LEFTMOUSE /* Left mouse button click */
, KE_LEFTDRAG /* Drag with left mouse button down */
, KE_LEFTRELEASE /* Left mouse button release */
, KE_MIDDLEMOUSE /* Middle mouse button click */
, KE_MIDDLEDRAG /* Drag with middle mouse button down */
, KE_MIDDLERELEASE /* Middle mouse button release */
, KE_RIGHTMOUSE /* Right mouse button click */
, KE_RIGHTDRAG /* Drag with right mouse button down */
, KE_RIGHTRELEASE /* Right mouse button release */
, KE_IGNORE /* Ignored mouse drag/release */
, KE_TAB /* unshifted TAB key */
, KE_S_TAB_OLD /* shifted TAB key (no longer used) */
, KE_SNIFF /* SNiFF+ input waiting */
, KE_XF1 /* extra vt100 function keys for xterm */
, KE_XF2
, KE_XF3
, KE_XF4
, KE_XEND /* extra (vt100) end key for xterm */
, KE_ZEND /* extra (vt100) end key for xterm */
, KE_XHOME /* extra (vt100) home key for xterm */
, KE_ZHOME /* extra (vt100) home key for xterm */
, KE_XUP /* extra vt100 cursor keys for xterm */
, KE_XDOWN
, KE_XLEFT
, KE_XRIGHT
, KE_LEFTMOUSE_NM /* non-mappable Left mouse button click */
, KE_LEFTRELEASE_NM /* non-mappable left mouse button release */
, KE_S_XF1 /* extra vt100 shifted function keys for xterm */
, KE_S_XF2
, KE_S_XF3
, KE_S_XF4
/* NOTE: The scroll wheel events are inverted: i.e. UP is the same as
* moving the actual scroll wheel down, LEFT is the same as moving the
* scroll wheel right. */
, KE_MOUSEDOWN /* scroll wheel pseudo-button Down */
, KE_MOUSEUP /* scroll wheel pseudo-button Up */
, KE_MOUSELEFT /* scroll wheel pseudo-button Left */
, KE_MOUSERIGHT /* scroll wheel pseudo-button Right */
, KE_KINS /* keypad Insert key */
, KE_KDEL /* keypad Delete key */
, KE_CSI /* CSI typed directly */
, KE_SNR /* <SNR> */
, KE_PLUG /* <Plug> */
, KE_CMDWIN /* open command-line window from Command-line Mode */
, KE_C_LEFT /* control-left */
, KE_C_RIGHT /* control-right */
, KE_C_HOME /* control-home */
, KE_C_END /* control-end */
, KE_X1MOUSE /* X1/X2 mouse-buttons */
, KE_X1DRAG
, KE_X1RELEASE
, KE_X2MOUSE
, KE_X2DRAG
, KE_X2RELEASE
, KE_DROP /* DnD data is available */
, KE_CURSORHOLD /* CursorHold event */
, KE_NOP /* doesn't do something */
, KE_FOCUSGAINED /* focus gained */
, KE_FOCUSLOST /* focus lost */
};
/*
* the three byte codes are replaced with the following int when using vgetc()
*/
#define K_ZERO TERMCAP2KEY(KS_ZERO, KE_FILLER)
#define K_UP TERMCAP2KEY('k', 'u')
#define K_DOWN TERMCAP2KEY('k', 'd')
#define K_LEFT TERMCAP2KEY('k', 'l')
#define K_RIGHT TERMCAP2KEY('k', 'r')
#define K_S_UP TERMCAP2KEY(KS_EXTRA, KE_S_UP)
#define K_S_DOWN TERMCAP2KEY(KS_EXTRA, KE_S_DOWN)
#define K_S_LEFT TERMCAP2KEY('#', '4')
#define K_C_LEFT TERMCAP2KEY(KS_EXTRA, KE_C_LEFT)
#define K_S_RIGHT TERMCAP2KEY('%', 'i')
#define K_C_RIGHT TERMCAP2KEY(KS_EXTRA, KE_C_RIGHT)
#define K_S_HOME TERMCAP2KEY('#', '2')
#define K_C_HOME TERMCAP2KEY(KS_EXTRA, KE_C_HOME)
#define K_S_END TERMCAP2KEY('*', '7')
#define K_C_END TERMCAP2KEY(KS_EXTRA, KE_C_END)
#define K_TAB TERMCAP2KEY(KS_EXTRA, KE_TAB)
#define K_S_TAB TERMCAP2KEY('k', 'B')
/* extra set of function keys F1-F4, for vt100 compatible xterm */
#define K_XF1 TERMCAP2KEY(KS_EXTRA, KE_XF1)
#define K_XF2 TERMCAP2KEY(KS_EXTRA, KE_XF2)
#define K_XF3 TERMCAP2KEY(KS_EXTRA, KE_XF3)
#define K_XF4 TERMCAP2KEY(KS_EXTRA, KE_XF4)
/* extra set of cursor keys for vt100 compatible xterm */
#define K_XUP TERMCAP2KEY(KS_EXTRA, KE_XUP)
#define K_XDOWN TERMCAP2KEY(KS_EXTRA, KE_XDOWN)
#define K_XLEFT TERMCAP2KEY(KS_EXTRA, KE_XLEFT)
#define K_XRIGHT TERMCAP2KEY(KS_EXTRA, KE_XRIGHT)
#define K_F1 TERMCAP2KEY('k', '1') /* function keys */
#define K_F2 TERMCAP2KEY('k', '2')
#define K_F3 TERMCAP2KEY('k', '3')
#define K_F4 TERMCAP2KEY('k', '4')
#define K_F5 TERMCAP2KEY('k', '5')
#define K_F6 TERMCAP2KEY('k', '6')
#define K_F7 TERMCAP2KEY('k', '7')
#define K_F8 TERMCAP2KEY('k', '8')
#define K_F9 TERMCAP2KEY('k', '9')
#define K_F10 TERMCAP2KEY('k', ';')
#define K_F11 TERMCAP2KEY('F', '1')
#define K_F12 TERMCAP2KEY('F', '2')
#define K_F13 TERMCAP2KEY('F', '3')
#define K_F14 TERMCAP2KEY('F', '4')
#define K_F15 TERMCAP2KEY('F', '5')
#define K_F16 TERMCAP2KEY('F', '6')
#define K_F17 TERMCAP2KEY('F', '7')
#define K_F18 TERMCAP2KEY('F', '8')
#define K_F19 TERMCAP2KEY('F', '9')
#define K_F20 TERMCAP2KEY('F', 'A')
#define K_F21 TERMCAP2KEY('F', 'B')
#define K_F22 TERMCAP2KEY('F', 'C')
#define K_F23 TERMCAP2KEY('F', 'D')
#define K_F24 TERMCAP2KEY('F', 'E')
#define K_F25 TERMCAP2KEY('F', 'F')
#define K_F26 TERMCAP2KEY('F', 'G')
#define K_F27 TERMCAP2KEY('F', 'H')
#define K_F28 TERMCAP2KEY('F', 'I')
#define K_F29 TERMCAP2KEY('F', 'J')
#define K_F30 TERMCAP2KEY('F', 'K')
#define K_F31 TERMCAP2KEY('F', 'L')
#define K_F32 TERMCAP2KEY('F', 'M')
#define K_F33 TERMCAP2KEY('F', 'N')
#define K_F34 TERMCAP2KEY('F', 'O')
#define K_F35 TERMCAP2KEY('F', 'P')
#define K_F36 TERMCAP2KEY('F', 'Q')
#define K_F37 TERMCAP2KEY('F', 'R')
/* extra set of shifted function keys F1-F4, for vt100 compatible xterm */
#define K_S_XF1 TERMCAP2KEY(KS_EXTRA, KE_S_XF1)
#define K_S_XF2 TERMCAP2KEY(KS_EXTRA, KE_S_XF2)
#define K_S_XF3 TERMCAP2KEY(KS_EXTRA, KE_S_XF3)
#define K_S_XF4 TERMCAP2KEY(KS_EXTRA, KE_S_XF4)
#define K_S_F1 TERMCAP2KEY(KS_EXTRA, KE_S_F1) /* shifted func. keys */
#define K_S_F2 TERMCAP2KEY(KS_EXTRA, KE_S_F2)
#define K_S_F3 TERMCAP2KEY(KS_EXTRA, KE_S_F3)
#define K_S_F4 TERMCAP2KEY(KS_EXTRA, KE_S_F4)
#define K_S_F5 TERMCAP2KEY(KS_EXTRA, KE_S_F5)
#define K_S_F6 TERMCAP2KEY(KS_EXTRA, KE_S_F6)
#define K_S_F7 TERMCAP2KEY(KS_EXTRA, KE_S_F7)
#define K_S_F8 TERMCAP2KEY(KS_EXTRA, KE_S_F8)
#define K_S_F9 TERMCAP2KEY(KS_EXTRA, KE_S_F9)
#define K_S_F10 TERMCAP2KEY(KS_EXTRA, KE_S_F10)
#define K_S_F11 TERMCAP2KEY(KS_EXTRA, KE_S_F11)
#define K_S_F12 TERMCAP2KEY(KS_EXTRA, KE_S_F12)
/* K_S_F13 to K_S_F37 are currently not used */
#define K_HELP TERMCAP2KEY('%', '1')
#define K_UNDO TERMCAP2KEY('&', '8')
#define K_BS TERMCAP2KEY('k', 'b')
#define K_INS TERMCAP2KEY('k', 'I')
#define K_KINS TERMCAP2KEY(KS_EXTRA, KE_KINS)
#define K_DEL TERMCAP2KEY('k', 'D')
#define K_KDEL TERMCAP2KEY(KS_EXTRA, KE_KDEL)
#define K_HOME TERMCAP2KEY('k', 'h')
#define K_KHOME TERMCAP2KEY('K', '1') /* keypad home (upper left) */
#define K_XHOME TERMCAP2KEY(KS_EXTRA, KE_XHOME)
#define K_ZHOME TERMCAP2KEY(KS_EXTRA, KE_ZHOME)
#define K_END TERMCAP2KEY('@', '7')
#define K_KEND TERMCAP2KEY('K', '4') /* keypad end (lower left) */
#define K_XEND TERMCAP2KEY(KS_EXTRA, KE_XEND)
#define K_ZEND TERMCAP2KEY(KS_EXTRA, KE_ZEND)
#define K_PAGEUP TERMCAP2KEY('k', 'P')
#define K_PAGEDOWN TERMCAP2KEY('k', 'N')
#define K_KPAGEUP TERMCAP2KEY('K', '3') /* keypad pageup (upper R.) */
#define K_KPAGEDOWN TERMCAP2KEY('K', '5') /* keypad pagedown (lower R.) */
#define K_KPLUS TERMCAP2KEY('K', '6') /* keypad plus */
#define K_KMINUS TERMCAP2KEY('K', '7') /* keypad minus */
#define K_KDIVIDE TERMCAP2KEY('K', '8') /* keypad / */
#define K_KMULTIPLY TERMCAP2KEY('K', '9') /* keypad * */
#define K_KENTER TERMCAP2KEY('K', 'A') /* keypad Enter */
#define K_KPOINT TERMCAP2KEY('K', 'B') /* keypad . or ,*/
#define K_K0 TERMCAP2KEY('K', 'C') /* keypad 0 */
#define K_K1 TERMCAP2KEY('K', 'D') /* keypad 1 */
#define K_K2 TERMCAP2KEY('K', 'E') /* keypad 2 */
#define K_K3 TERMCAP2KEY('K', 'F') /* keypad 3 */
#define K_K4 TERMCAP2KEY('K', 'G') /* keypad 4 */
#define K_K5 TERMCAP2KEY('K', 'H') /* keypad 5 */
#define K_K6 TERMCAP2KEY('K', 'I') /* keypad 6 */
#define K_K7 TERMCAP2KEY('K', 'J') /* keypad 7 */
#define K_K8 TERMCAP2KEY('K', 'K') /* keypad 8 */
#define K_K9 TERMCAP2KEY('K', 'L') /* keypad 9 */
#define K_MOUSE TERMCAP2KEY(KS_MOUSE, KE_FILLER)
#define K_MENU TERMCAP2KEY(KS_MENU, KE_FILLER)
#define K_VER_SCROLLBAR TERMCAP2KEY(KS_VER_SCROLLBAR, KE_FILLER)
#define K_HOR_SCROLLBAR TERMCAP2KEY(KS_HOR_SCROLLBAR, KE_FILLER)
#define K_NETTERM_MOUSE TERMCAP2KEY(KS_NETTERM_MOUSE, KE_FILLER)
#define K_DEC_MOUSE TERMCAP2KEY(KS_DEC_MOUSE, KE_FILLER)
#define K_JSBTERM_MOUSE TERMCAP2KEY(KS_JSBTERM_MOUSE, KE_FILLER)
#define K_PTERM_MOUSE TERMCAP2KEY(KS_PTERM_MOUSE, KE_FILLER)
#define K_URXVT_MOUSE TERMCAP2KEY(KS_URXVT_MOUSE, KE_FILLER)
#define K_SELECT TERMCAP2KEY(KS_SELECT, KE_FILLER)
#define K_TEAROFF TERMCAP2KEY(KS_TEAROFF, KE_FILLER)
#define K_TABLINE TERMCAP2KEY(KS_TABLINE, KE_FILLER)
#define K_TABMENU TERMCAP2KEY(KS_TABMENU, KE_FILLER)
/*
* Symbols for pseudo keys which are translated from the real key symbols
* above.
*/
#define K_LEFTMOUSE TERMCAP2KEY(KS_EXTRA, KE_LEFTMOUSE)
#define K_LEFTMOUSE_NM TERMCAP2KEY(KS_EXTRA, KE_LEFTMOUSE_NM)
#define K_LEFTDRAG TERMCAP2KEY(KS_EXTRA, KE_LEFTDRAG)
#define K_LEFTRELEASE TERMCAP2KEY(KS_EXTRA, KE_LEFTRELEASE)
#define K_LEFTRELEASE_NM TERMCAP2KEY(KS_EXTRA, KE_LEFTRELEASE_NM)
#define K_MIDDLEMOUSE TERMCAP2KEY(KS_EXTRA, KE_MIDDLEMOUSE)
#define K_MIDDLEDRAG TERMCAP2KEY(KS_EXTRA, KE_MIDDLEDRAG)
#define K_MIDDLERELEASE TERMCAP2KEY(KS_EXTRA, KE_MIDDLERELEASE)
#define K_RIGHTMOUSE TERMCAP2KEY(KS_EXTRA, KE_RIGHTMOUSE)
#define K_RIGHTDRAG TERMCAP2KEY(KS_EXTRA, KE_RIGHTDRAG)
#define K_RIGHTRELEASE TERMCAP2KEY(KS_EXTRA, KE_RIGHTRELEASE)
#define K_X1MOUSE TERMCAP2KEY(KS_EXTRA, KE_X1MOUSE)
#define K_X1MOUSE TERMCAP2KEY(KS_EXTRA, KE_X1MOUSE)
#define K_X1DRAG TERMCAP2KEY(KS_EXTRA, KE_X1DRAG)
#define K_X1RELEASE TERMCAP2KEY(KS_EXTRA, KE_X1RELEASE)
#define K_X2MOUSE TERMCAP2KEY(KS_EXTRA, KE_X2MOUSE)
#define K_X2DRAG TERMCAP2KEY(KS_EXTRA, KE_X2DRAG)
#define K_X2RELEASE TERMCAP2KEY(KS_EXTRA, KE_X2RELEASE)
#define K_IGNORE TERMCAP2KEY(KS_EXTRA, KE_IGNORE)
#define K_NOP TERMCAP2KEY(KS_EXTRA, KE_NOP)
#define K_SNIFF TERMCAP2KEY(KS_EXTRA, KE_SNIFF)
#define K_MOUSEDOWN TERMCAP2KEY(KS_EXTRA, KE_MOUSEDOWN)
#define K_MOUSEUP TERMCAP2KEY(KS_EXTRA, KE_MOUSEUP)
#define K_MOUSELEFT TERMCAP2KEY(KS_EXTRA, KE_MOUSELEFT)
#define K_MOUSERIGHT TERMCAP2KEY(KS_EXTRA, KE_MOUSERIGHT)
#define K_CSI TERMCAP2KEY(KS_EXTRA, KE_CSI)
#define K_SNR TERMCAP2KEY(KS_EXTRA, KE_SNR)
#define K_PLUG TERMCAP2KEY(KS_EXTRA, KE_PLUG)
#define K_CMDWIN TERMCAP2KEY(KS_EXTRA, KE_CMDWIN)
#define K_DROP TERMCAP2KEY(KS_EXTRA, KE_DROP)
#define K_FOCUSGAINED TERMCAP2KEY(KS_EXTRA, KE_FOCUSGAINED)
#define K_FOCUSLOST TERMCAP2KEY(KS_EXTRA, KE_FOCUSLOST)
#define K_CURSORHOLD TERMCAP2KEY(KS_EXTRA, KE_CURSORHOLD)
/* Bits for modifier mask */
/* 0x01 cannot be used, because the modifier must be 0x02 or higher */
#define MOD_MASK_SHIFT 0x02
#define MOD_MASK_CTRL 0x04
#define MOD_MASK_ALT 0x08 /* aka META */
#define MOD_MASK_META 0x10 /* META when it's different from ALT */
#define MOD_MASK_2CLICK 0x20 /* use MOD_MASK_MULTI_CLICK */
#define MOD_MASK_3CLICK 0x40 /* use MOD_MASK_MULTI_CLICK */
#define MOD_MASK_4CLICK 0x60 /* use MOD_MASK_MULTI_CLICK */
#ifdef MACOS
# define MOD_MASK_CMD 0x80
#endif
#define MOD_MASK_MULTI_CLICK (MOD_MASK_2CLICK|MOD_MASK_3CLICK|MOD_MASK_4CLICK)
/*
* The length of the longest special key name, including modifiers.
* Current longest is <M-C-S-T-4-MiddleRelease> (length includes '<' and '>').
*/
#define MAX_KEY_NAME_LEN 25
/* Maximum length of a special key event as tokens. This includes modifiers.
* The longest event is something like <M-C-S-T-4-LeftDrag> which would be the
* following string of tokens:
*
* <K_SPECIAL> <KS_MODIFIER> bitmask <K_SPECIAL> <KS_EXTRA> <KT_LEFTDRAG>.
*
* This is a total of 6 tokens, and is currently the longest one possible.
*/
#define MAX_KEY_CODE_LEN 6
| zyz2011-vim | src/keymap.h | C | gpl2 | 16,092 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Script1.rc
//
#define IDR_TOOLBAR1 101
//#define ID_TB_BLOB 40001
//#define ID_TB_CIRCLE 40002
| zyz2011-vim | src/gui_w32_rc.h | C | gpl2 | 193 |
/* 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.
*/
#ifdef HAVE_CONFIG_H
# include "auto/config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#endif
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <X11/Intrinsic.h>
#include <Xm/Xm.h>
#include <Xm/PushB.h>
#include "integration.h" /* <EditPlugin/integration.h> */
#include "vim.h"
#include "version.h"
#include "gui_beval.h"
#include "workshop.h"
void workshop_hotkeys(Boolean);
static Boolean isShowing(int);
static win_T *get_window(buf_T *);
static void updatePriority(Boolean);
static char *addUniqueMnemonic(char *, char *);
static char *fixup(char *);
static char *get_selection(buf_T *);
static char *append_selection(int, char *, int *, int *);
static void load_buffer_by_name(char *, int);
static void load_window(char *, int lnum);
static void warp_to_pc(int);
#ifdef FEAT_BEVAL
void workshop_beval_cb(BalloonEval *, int);
static int computeIndex(int, char_u *, int);
#endif
static char *fixAccelText(char *);
static void addMenu(char *, char *, char *);
static char *lookupVerb(char *, int);
static void coloncmd(char *, Boolean);
extern Widget vimShell;
extern Widget textArea;
extern XtAppContext app_context;
static int tbpri; /* ToolBar priority */
int usingSunWorkShop = 0; /* set if -ws flag is used */
char curMenuName[BUFSIZ];
char curMenuPriority[BUFSIZ];
static Boolean workshopInitDone = False;
static Boolean workshopHotKeysEnabled = False;
/*
* The following enum is from <gp_dbx/gp_dbx_common.h>. We can't include it
* here because its C++.
*/
enum
{
GPLineEval_EVALUATE, /* evaluate expression */
GPLineEval_INDIRECT, /* evaluate *<expression> */
GPLineEval_TYPE /* type of expression */
};
/*
* Store each verb in the MenuMap. This lets us map from a verb to a menu.
* There may be multiple matches for a single verb in this table.
*/
#define MENU_INC 50 /* menuMap incremental size increases */
typedef struct
{
char *name; /* name of the menu */
char *accel; /* optional accelerator key */
char *verb; /* menu verb */
} MenuMap;
static MenuMap *menuMap; /* list of verb/menu mappings */
static int menuMapSize; /* current size of menuMap */
static int menuMapMax; /* allocated size of menuMap */
static char *initialFileCmd; /* save command but defer doing it */
void
workshop_init()
{
char_u buf[64];
int is_dirty = FALSE;
int width, height;
XtInputMask mask;
/*
* Turn on MenuBar, ToolBar, and Footer.
*/
STRCPY(buf, p_go);
if (vim_strchr(p_go, GO_MENUS) == NULL)
{
STRCAT(buf, "m");
is_dirty = TRUE;
}
if (vim_strchr(p_go, GO_TOOLBAR) == NULL)
{
STRCAT(buf, "T");
is_dirty = TRUE;
}
if (vim_strchr(p_go, GO_FOOTER) == NULL)
{
STRCAT(buf, "F");
is_dirty = TRUE;
}
if (is_dirty)
set_option_value((char_u *)"go", 0L, buf, 0);
/*
* Set size from workshop_get_width_height().
*/
width = height = 0;
if (workshop_get_width_height(&width, &height))
{
XtVaSetValues(vimShell,
XmNwidth, width,
XmNheight, height,
NULL);
}
/*
* Now read in the initial messages from eserve.
*/
while ((mask = XtAppPending(app_context))
&& (mask & XtIMAlternateInput) && !workshopInitDone)
XtAppProcessEvent(app_context, (XtInputMask)XtIMAlternateInput);
}
void
workshop_postinit()
{
do_cmdline_cmd((char_u *)initialFileCmd);
ALT_INPUT_LOCK_OFF;
free(initialFileCmd);
initialFileCmd = NULL;
}
void
ex_wsverb(exarg_T *eap)
{
msg_clr_cmdline();
workshop_perform_verb((char *) eap->arg, NULL);
}
/*
* Editor name
* This string is recognized by eserve and should be all lower case.
* This is how the editor detects that it is talking to gvim instead
* of NEdit, for example, when the connection is initiated from the editor.
*/
char *
workshop_get_editor_name()
{
return "gvim";
}
/*
* Version number of the editor.
* This number is communicated along with the protocol
* version to the application.
*/
char *
workshop_get_editor_version()
{
return Version;
}
/*
* Answer functions: called by eserve
*/
/*
* Name:
* workshop_load_file
*
* Function:
* Load a given file into the WorkShop buffer.
*/
void
workshop_load_file(
char *filename, /* the file to load */
int line, /* an optional line number (or 0) */
char *frameid UNUSED) /* used for multi-frame support */
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_load_file(%s, %d)\n", filename, line);
#endif
#ifdef FEAT_BEVAL
bevalServers |= BEVAL_WORKSHOP;
#endif
load_window(filename, line);
}
/*
* Reload the WorkShop buffer
*/
void
workshop_reload_file(
char *filename,
int line)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_reload_file(%s, %d)\n", filename, line);
#endif
load_window(filename, line);
}
void
workshop_show_file(
char *filename)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_show_file(%s)\n", filename);
#endif
load_window(filename, 0);
}
void
workshop_goto_line(
char *filename,
int lineno)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_goto_line(%s, %d)\n", filename, lineno);
#endif
load_window(filename, lineno);
}
void
workshop_front_file(
char *filename UNUSED)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_front_file()\n");
#endif
/*
* Assumption: This function will always be called after a call to
* workshop_show_file(), so the file is always showing.
*/
if (vimShell != NULL)
XRaiseWindow(gui.dpy, XtWindow(vimShell));
}
void
workshop_save_file(
char *filename)
{
char cbuf[BUFSIZ]; /* build vim command here */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_save_file(%s)\n", filename);
#endif
/* Save the given file */
vim_snprintf(cbuf, sizeof(cbuf), "w %s", filename);
coloncmd(cbuf, TRUE);
}
void
workshop_save_files()
{
/* Save the given file */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_save_files()\n");
#endif
add_to_input_buf((char_u *) ":wall\n", 6);
}
void
workshop_quit()
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_quit()\n");
#endif
add_to_input_buf((char_u *) ":qall\n", 6);
}
void
workshop_minimize()
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_minimize()\n");
#endif
workshop_minimize_shell(vimShell);
}
void
workshop_maximize()
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_maximize()\n");
#endif
workshop_maximize_shell(vimShell);
}
void
workshop_add_mark_type(
int idx,
char *colorspec,
char *sign)
{
char gbuf[BUFSIZ]; /* buffer for sign name */
char cibuf[BUFSIZ]; /* color information */
char cbuf[BUFSIZ]; /* command buffer */
char *bp;
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
{
char *cp;
cp = strrchr(sign, '/');
if (cp == NULL)
cp = sign;
else
cp++; /* skip '/' character */
wstrace("workshop_add_mark_type(%d, \"%s\", \"%s\")\n", idx,
colorspec && *colorspec ? colorspec : "<None>", cp);
}
#endif
/*
* Isolate the basename of sign in gbuf. We will use this for the
* GroupName in the highlight command sent to vim.
*/
STRCPY(gbuf, gettail((char_u *)sign));
bp = strrchr(gbuf, '.');
if (bp != NULL)
*bp = NUL;
if (gbuf[0] != '-' && gbuf[1] != NUL)
{
if (colorspec != NULL && *colorspec)
{
vim_snprintf(cbuf, sizeof(cbuf),
"highlight WS%s guibg=%s", gbuf, colorspec);
coloncmd(cbuf, FALSE);
vim_snprintf(cibuf, sizeof(cibuf), "linehl=WS%s", gbuf);
}
else
cibuf[0] = NUL;
vim_snprintf(cbuf, sizeof(cbuf),
"sign define %d %s icon=%s", idx, cibuf, sign);
coloncmd(cbuf, TRUE);
}
}
void
workshop_set_mark(
char *filename, /* filename which gets the mark */
int lineno, /* line number which gets the mark */
int markId, /* unique mark identifier */
int idx) /* which mark to use */
{
char cbuf[BUFSIZ]; /* command buffer */
/* Set mark in a given file */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_set_mark(%s, %d (ln), %d (id), %d (idx))\n",
filename, lineno, markId, idx);
#endif
vim_snprintf(cbuf, sizeof(cbuf), "sign place %d line=%d name=%d file=%s",
markId, lineno, idx, filename);
coloncmd(cbuf, TRUE);
}
void
workshop_change_mark_type(
char *filename, /* filename which gets the mark */
int markId, /* unique mark identifier */
int idx) /* which mark to use */
{
char cbuf[BUFSIZ]; /* command buffer */
/* Change mark type */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_change_mark_type(%s, %d, %d)\n",
filename, markId, idx);
#endif
vim_snprintf(cbuf, sizeof(cbuf),
"sign place %d name=%d file=%s", markId, idx, filename);
coloncmd(cbuf, TRUE);
}
/*
* Goto the given mark in a file (e.g. show it).
* If message is not null, display it in the footer.
*/
void
workshop_goto_mark(
char *filename,
int markId,
char *message)
{
char cbuf[BUFSIZ]; /* command buffer */
/* Goto mark */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_goto_mark(%s, %d (id), %s)\n",
filename, markId, message && *message &&
!(*message == ' ' && message[1] == NULL) ?
message : "<None>");
#endif
vim_snprintf(cbuf, sizeof(cbuf), "sign jump %d file=%s", markId, filename);
coloncmd(cbuf, TRUE);
if (message != NULL && *message != NUL)
gui_mch_set_footer((char_u *)message);
}
void
workshop_delete_mark(
char *filename,
int markId)
{
char cbuf[BUFSIZ]; /* command buffer */
/* Delete mark */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_delete_mark(%s, %d (id))\n",
filename, markId);
#endif
vim_snprintf(cbuf, sizeof(cbuf),
"sign unplace %d file=%s", markId, filename);
coloncmd(cbuf, TRUE);
}
int
workshop_get_mark_lineno(
char *filename,
int markId)
{
buf_T *buf; /* buffer containing filename */
int lineno; /* line number of filename in buf */
/* Get mark line number */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_get_mark_lineno(%s, %d)\n",
filename, markId);
#endif
lineno = 0;
buf = buflist_findname((char_u *)filename);
if (buf != NULL)
lineno = buf_findsign(buf, markId);
return lineno;
}
/*
* Are there any moved marks? If so, call workshop_move_mark on
* each of them now. This is how eserve can find out if for example
* breakpoints have moved when a program has been recompiled and
* reloaded into dbx.
*/
void
workshop_moved_marks(char *filename UNUSED)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("XXXworkshop_moved_marks(%s)\n", filename);
#endif
}
int
workshop_get_font_height()
{
XmFontList fontList; /* fontList made from gui.norm_font */
XmString str;
Dimension w;
Dimension h;
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_get_font_height()\n");
#endif
/* Pick the proper signs for this font size */
fontList = gui_motif_create_fontlist((XFontStruct *)gui.norm_font);
h = 0;
if (fontList != NULL)
{
str = XmStringCreateLocalized("A");
XmStringExtent(fontList, str, &w, &h);
XmStringFree(str);
XmFontListFree(fontList);
}
return (int)h;
}
void
workshop_footer_message(
char *message,
int severity UNUSED) /* severity is currently unused */
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_footer_message(%s, %d)\n", message, severity);
#endif
gui_mch_set_footer((char_u *) message);
}
/*
* workshop_menu_begin() is passed the menu name. We determine its mnemonic
* here and store its name and priority.
*/
void
workshop_menu_begin(
char *label)
{
vimmenu_T *menu; /* pointer to last menu */
int menuPriority = 0; /* priority of new menu */
char mnembuf[64]; /* store menubar mnemonics here */
char *name; /* label with a mnemonic */
char *p; /* used to find mnemonics */
int idx; /* index into mnembuf */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_menu_begin()\n");
#endif
/*
* Look through all existing (non-PopUp and non-Toolbar) menus
* and gather their mnemonics. Use this list to decide what
* mnemonic should be used for label.
*/
idx = 0;
mnembuf[idx++] = 'H'; /* H is mnemonic for Help */
for (menu = root_menu; menu != NULL; menu = menu->next)
{
if (menu_is_menubar(menu->name))
{
p = strchr((char *)menu->name, '&');
if (p != NULL)
mnembuf[idx++] = *++p;
}
if (menu->next != NULL
&& strcmp((char *) menu->next->dname, "Help") == 0)
{
menuPriority = menu->priority + 10;
break;
}
}
mnembuf[idx++] = NUL;
name = addUniqueMnemonic(mnembuf, label);
vim_snprintf(curMenuName, sizeof(curMenuName), "%s", name);
sprintf(curMenuPriority, "%d.0", menuPriority);
}
/*
* Append the name and priority to strings to be used in vim menu commands.
*/
void
workshop_submenu_begin(
char *label)
{
#ifdef WSDEBUG_TRACE
if (ws_debug && ws_dlevel & WS_TRACE
&& strncmp(curMenuName, "ToolBar", 7) != 0)
wstrace("workshop_submenu_begin(%s)\n", label);
#endif
strcat(curMenuName, ".");
strcat(curMenuName, fixup(label));
updatePriority(True);
}
/*
* Remove the submenu name and priority from curMenu*.
*/
void
workshop_submenu_end()
{
char *p;
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE)
&& strncmp(curMenuName, "ToolBar", 7) != 0)
wstrace("workshop_submenu_end()\n");
#endif
p = strrchr(curMenuPriority, '.');
ASSERT(p != NULL);
*p = NUL;
p = strrchr(curMenuName, '.');
ASSERT(p != NULL);
*p = NUL;
}
/*
* This is where menus are really made. Each item will generate an amenu vim
* command. The globals curMenuName and curMenuPriority contain the name and
* priority of the parent menu tree.
*/
void
workshop_menu_item(
char *label,
char *verb,
char *accelerator UNUSED,
char *acceleratorText,
char *name UNUSED,
char *filepos UNUSED,
char *sensitive)
{
char cbuf[BUFSIZ];
char namebuf[BUFSIZ];
char accText[BUFSIZ];
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE)
&& strncmp(curMenuName, "ToolBar", 7) != 0)
{
if (ws_dlevel & WS_TRACE_VERBOSE)
wsdebug("workshop_menu_item(\n"
"\tlabel = \"%s\",\n"
"\tverb = %s,\n"
"\taccelerator = %s,\n"
"\tacceleratorText = \"%s\",\n"
"\tname = %s,\n"
"\tfilepos = %s,\n"
"\tsensitive = %s)\n",
label && *label ? label : "<None>",
verb && *verb ? verb : "<None>",
accelerator && *accelerator ?
accelerator : "<None>",
acceleratorText && *acceleratorText ?
acceleratorText : "<None>",
name && *name ? name : "<None>",
filepos && *filepos ? filepos : "<None>",
sensitive);
else if (ws_dlevel & WS_TRACE)
wstrace("workshop_menu_item(\"%s\", %s)\n",
label && *label ? label : "<None>",
verb && *verb ? verb : "<None>", sensitive);
}
#endif
#ifdef WSDEBUG_SENSE
if (ws_debug)
wstrace("menu: %-21.20s%-21.20s(%s)\n", label, verb,
*sensitive == '1' ? "Sensitive" : "Insensitive");
#endif
if (acceleratorText != NULL)
vim_snprintf(accText, sizeof(accText), "<Tab>%s", acceleratorText);
else
accText[0] = NUL;
updatePriority(False);
vim_snprintf(namebuf, sizeof(namebuf), "%s.%s", curMenuName, fixup(label));
vim_snprintf(cbuf, sizeof(cbuf), "amenu %s %s%s\t:wsverb %s<CR>",
curMenuPriority, namebuf, accText, verb);
coloncmd(cbuf, TRUE);
addMenu(namebuf, fixAccelText(acceleratorText), verb);
if (*sensitive == '0')
{
vim_snprintf(cbuf, sizeof(cbuf), "amenu disable %s", namebuf);
coloncmd(cbuf, TRUE);
}
}
/*
* This function is called when a complete WorkShop menu description has been
* sent over from eserve. We do some menu cleanup.
*/
void
workshop_menu_end()
{
Boolean using_tearoff; /* set per current option setting */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_menu_end()\n");
#endif
using_tearoff = vim_strchr(p_go, GO_TEAROFF) != NULL;
gui_mch_toggle_tearoffs(using_tearoff);
}
void
workshop_toolbar_begin()
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_toolbar_begin()\n");
#endif
coloncmd("aunmenu ToolBar", True);
tbpri = 10;
}
void
workshop_toolbar_end()
{
char_u buf[64];
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
{
wstrace("workshop_toolbar_end()\n");
}
#endif
/*
* Turn on ToolBar.
*/
STRCPY(buf, p_go);
if (vim_strchr(p_go, 'T') == NULL)
{
STRCAT(buf, "T");
set_option_value((char_u *)"go", 0L, buf, 0);
}
workshopInitDone = True;
}
void
workshop_toolbar_button(
char *label,
char *verb,
char *senseVerb UNUSED,
char *filepos UNUSED,
char *help,
char *sense,
char *file,
char *left)
{
char cbuf[BUFSIZ + MAXPATHLEN];
char namebuf[BUFSIZ];
static int tbid = 1;
char_u *p;
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE))
wsdebug("workshop_toolbar_button(\"%s\", %s, %s,\n"
"\t%s, \"%s\", %s,\n\t\"%s\",\n\t<%s>)\n",
label && *label ? label : "<None>",
verb && *verb ? verb : "<None>",
senseVerb && *senseVerb ? senseVerb : "<None>",
filepos && *filepos ? filepos : "<None>",
help && *help ? help : "<None>",
sense && *sense ? sense : "<None>",
file && *file ? file : "<None>",
left && *left ? left : "<None>");
else if (WSDLEVEL(WS_TRACE))
wstrace("workshop_toolbar_button(\"%s\", %s)\n",
label && *label ? label : "<None>",
verb && *verb ? verb : "<None>");
#endif
#ifdef WSDEBUG_SENSE
if (ws_debug)
wsdebug("button: %-21.20s%-21.20s(%s)\n", label, verb,
*sense == '1' ? "Sensitive" : "Insensitive");
#endif
if (left && *left && atoi(left) > 0)
{
/* Add a separator (but pass the width passed after the ':') */
sprintf(cbuf, "amenu 1.%d ToolBar.-sep%d:%s- <nul>",
tbpri - 5, tbid++, left);
coloncmd(cbuf, True);
}
p = vim_strsave_escaped((char_u *)label, (char_u *)"\\. ");
vim_snprintf(namebuf, sizeof(namebuf), "ToolBar.%s", p);
vim_free(p);
STRCPY(cbuf, "amenu <silent> ");
if (file != NULL && *file != NUL)
{
p = vim_strsave_escaped((char_u *)file, (char_u *)" ");
vim_snprintf_add(cbuf, sizeof(cbuf), "icon=%s ", p);
vim_free(p);
}
vim_snprintf_add(cbuf, sizeof(cbuf),"1.%d %s :wsverb %s<CR>",
tbpri, namebuf, verb);
/* Define the menu item */
coloncmd(cbuf, True);
if (*sense == '0')
{
/* If menu isn't sensitive at startup... */
vim_snprintf(cbuf, sizeof(cbuf), "amenu disable %s", namebuf);
coloncmd(cbuf, True);
}
if (help && *help)
{
/* Do the tooltip */
vim_snprintf(cbuf, sizeof(cbuf), "tmenu %s %s", namebuf, help);
coloncmd(cbuf, True);
}
addMenu(namebuf, NULL, verb);
tbpri += 10;
}
void
workshop_frame_sensitivities(
VerbSense *vs) /* list of verbs to (de)sensitize */
{
VerbSense *vp; /* iterate through vs */
char *menu_name; /* used in menu lookup */
int cnt; /* count of verbs to skip */
int len; /* length of nonvariant part of command */
char cbuf[4096];
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE) || WSDLEVEL(4))
{
wsdebug("workshop_frame_sensitivities(\n");
for (vp = vs; vp->verb != NULL; vp++)
wsdebug("\t%-25s%d\n", vp->verb, vp->sense);
wsdebug(")\n");
}
else if (WSDLEVEL(WS_TRACE))
wstrace("workshop_frame_sensitivities()\n");
#endif
#ifdef WSDEBUG_SENSE
if (ws_debug)
for (vp = vs; vp->verb != NULL; vp++)
wsdebug("change: %-21.20s%-21.20s(%s)\n",
"", vp->verb, vp->sense == 1 ?
"Sensitive" : "Insensitive");
#endif
/*
* Look for all matching menu entries for the verb. There may be more
* than one if the verb has both a menu and toolbar entry.
*/
for (vp = vs; vp->verb != NULL; vp++)
{
cnt = 0;
strcpy(cbuf, "amenu");
strcat(cbuf, " ");
strcat(cbuf, vp->sense ? "enable" : "disable");
strcat(cbuf, " ");
len = strlen(cbuf);
while ((menu_name = lookupVerb(vp->verb, cnt++)) != NULL)
{
strcpy(&cbuf[len], menu_name);
coloncmd(cbuf, FALSE);
}
}
gui_update_menus(0);
gui_mch_flush();
}
void
workshop_set_option(
char *option, /* name of a supported option */
char *value) /* value to set option to */
{
char cbuf[BUFSIZ]; /* command buffer */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
{
wstrace("workshop_set_option(%s, %s)\n", option, value);
}
#endif
cbuf[0] = NUL;
switch (*option) /* switch on 1st letter */
{
case 's':
if (strcmp(option, "syntax") == 0)
vim_snprintf(cbuf, sizeof(cbuf), "syntax %s", value);
else if (strcmp(option, "savefiles") == 0)
{
/* XXX - Not yet implemented */
}
break;
case 'l':
if (strcmp(option, "lineno") == 0)
sprintf(cbuf, "set %snu",
(strcmp(value, "on") == 0) ? "" : "no");
break;
case 'p':
if (strcmp(option, "parentheses") == 0)
sprintf(cbuf, "set %ssm",
(strcmp(value, "on") == 0) ? "" : "no");
break;
case 'w':
/* this option is set by a direct call */
#ifdef WSDEBUG
wsdebug("workshop_set_option: "
"Got unexpected workshopkeys option");
#endif
break;
case 'b': /* these options are set from direct calls */
if (option[7] == NUL && strcmp(option, "balloon") == 0)
{
#ifdef WSDEBUG
/* set by direct call to workshop_balloon_mode */
wsdebug("workshop_set_option: "
"Got unexpected ballooneval option");
#endif
}
else if (strcmp(option, "balloondelay") == 0)
{
#ifdef WSDEBUG
/* set by direct call to workshop_balloon_delay */
wsdebug("workshop_set_option: "
"Got unexpected balloondelay option");
#endif
}
break;
}
if (cbuf[0] != NUL)
coloncmd(cbuf, TRUE);
}
void
workshop_balloon_mode(
Boolean on)
{
char cbuf[BUFSIZ]; /* command buffer */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_balloon_mode(%s)\n", on ? "True" : "False");
#endif
sprintf(cbuf, "set %sbeval", on ? "" : "no");
coloncmd(cbuf, TRUE);
}
void
workshop_balloon_delay(
int delay)
{
char cbuf[BUFSIZ]; /* command buffer */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_balloon_delay(%d)\n", delay);
#endif
sprintf(cbuf, "set bdlay=%d", delay);
coloncmd(cbuf, TRUE);
}
void
workshop_show_balloon_tip(
char *tip)
{
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_show_balloon_tip(%s)\n", tip);
#endif
if (balloonEval != NULL)
gui_mch_post_balloon(balloonEval, (char_u *)tip);
}
void
workshop_hotkeys(
Boolean on)
{
char cbuf[BUFSIZ]; /* command buffer */
MenuMap *mp; /* iterate over menuMap entries */
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_hotkeys(%s)\n", on ? "True" : "False");
#endif
workshopHotKeysEnabled = on;
if (workshopHotKeysEnabled)
for (mp = menuMap; mp < &menuMap[menuMapSize]; mp++)
{
if (mp->accel != NULL)
{
vim_snprintf(cbuf, sizeof(cbuf),
"map %s :wsverb %s<CR>", mp->accel, mp->verb);
coloncmd(cbuf, TRUE);
}
}
else
for (mp = menuMap; mp < &menuMap[menuMapSize]; mp++)
{
if (mp->accel != NULL)
{
vim_snprintf(cbuf, sizeof(cbuf), "unmap %s", mp->accel);
coloncmd(cbuf, TRUE);
}
}
}
/*
* A button in the toolbar has been pushed.
*/
int
workshop_get_positions(
void *clientData UNUSED,
char **filename, /* output data */
int *curLine, /* output data */
int *curCol, /* output data */
int *selStartLine, /* output data */
int *selStartCol, /* output data */
int *selEndLine, /* output data */
int *selEndCol, /* output data */
int *selLength, /* output data */
char **selection) /* output data */
{
static char ffname[MAXPATHLEN];
#ifdef WSDEBUG_TRACE
if (WSDLEVEL(WS_TRACE_VERBOSE | WS_TRACE))
wstrace("workshop_get_positions(%#x, \"%s\", ...)\n",
clientData, (curbuf && curbuf->b_sfname != NULL)
? (char *)curbuf->b_sfname : "<None>");
#endif
if (curbuf->b_ffname == NULL)
ffname[0] = NUL;
else
/* copy so nobody can change b_ffname */
strcpy(ffname, (char *) curbuf->b_ffname);
*filename = ffname;
*curLine = curwin->w_cursor.lnum;
*curCol = curwin->w_cursor.col;
if (curbuf->b_visual.vi_mode == 'v' &&
equalpos(curwin->w_cursor, curbuf->b_visual.vi_end))
{
*selStartLine = curbuf->b_visual.vi_start.lnum;
*selStartCol = curbuf->b_visual.vi_start.col;
*selEndLine = curbuf->b_visual.vi_end.lnum;
*selEndCol = curbuf->b_visual.vi_end.col;
*selection = get_selection(curbuf);
if (*selection)
*selLength = strlen(*selection);
else
*selLength = 0;
}
else
{
*selStartLine = *selEndLine = -1;
*selStartCol = *selEndCol = -1;
*selLength = 0;
*selection = "";
}
return True;
}
/************************************************************************
* Utility functions
************************************************************************/
static char *
get_selection(
buf_T *buf) /* buffer whose selection we want */
{
pos_T *start; /* start of the selection */
pos_T *end; /* end of the selection */
char *lp; /* pointer to actual line data */
int llen; /* length of actual line data */
char *sp; /* pointer to selection buffer */
int slen; /* string length in selection buffer */
int size; /* size of selection buffer */
char *new_sp; /* temp pointer to new sp */
int lnum; /* line number we are appending */
if (buf->b_visual.vi_mode == 'v')
{
start = &buf->b_visual.vi_start;
end = &buf->b_visual.vi_end;
if (start->lnum == end->lnum)
{
/* selection is all on one line */
lp = (char *) ml_get_pos(start);
llen = end->col - start->col + 1;
sp = (char *) malloc(llen + 1);
if (sp != NULL)
{
strncpy(sp, lp, llen);
sp[llen] = NUL;
}
}
else
{
/* multi-line selection */
lp = (char *) ml_get_pos(start);
llen = strlen(lp);
sp = (char *) malloc(BUFSIZ + llen);
if (sp != NULL)
{
size = BUFSIZ + llen;
strcpy(sp, lp);
sp[llen] = '\n';
slen = llen + 1;
lnum = start->lnum + 1;
while (lnum < end->lnum)
sp = append_selection(lnum++, sp, &size, &slen);
lp = (char *) ml_get(end->lnum);
llen = end->col + 1;
if ((slen + llen) >= size)
{
new_sp = (char *)
realloc(sp, slen + llen + 1);
if (new_sp != NULL)
{
size += llen + 1;
sp = new_sp;
}
}
if ((slen + llen) < size)
{
strncpy(&sp[slen], lp, llen);
sp[slen + llen] = NUL;
}
}
}
}
else
sp = NULL;
return sp;
}
static char *
append_selection(
int lnum, /* line number to append */
char *sp, /* pointer to selection buffer */
int *size, /* ptr to size of sp */
int *slen) /* ptr to length of selection string */
{
char *lp; /* line of data from buffer */
int llen; /* strlen of lp */
char *new_sp; /* temp pointer to new sp */
lp = (char *)ml_get((linenr_T)lnum);
llen = strlen(lp);
if ((*slen + llen) <= *size)
{
new_sp = (char *) realloc((void *) sp, BUFSIZ + *slen + llen);
if (*new_sp != NUL)
{
*size = BUFSIZ + *slen + llen;
sp = new_sp;
}
}
if ((*slen + llen) > *size)
{
strcat(&sp[*slen], lp);
*slen += llen;
sp[*slen++] = '\n';
}
return sp;
}
static void
load_buffer_by_name(
char *filename, /* the file to load */
int lnum) /* an optional line number (or 0) */
{
char lnumbuf[16]; /* make line number option for :e */
char cbuf[BUFSIZ]; /* command buffer */
if (lnum > 0)
sprintf(lnumbuf, "+%d", lnum);
else
lnumbuf[0] = NUL;
vim_snprintf(cbuf, sizeof(cbuf), "e %s %s", lnumbuf, filename);
coloncmd(cbuf, False);
}
static void
load_window(
char *filename, /* filename to load */
int lnum) /* linenumber to go to */
{
buf_T *buf; /* buffer filename is stored in */
win_T *win; /* window filenme is displayed in */
/*
* Make sure filename is displayed and is the current window.
*/
buf = buflist_findname((char_u *)filename);
if (buf == NULL || (win = get_window(buf)) == NULL)
{
/* No buffer or buffer is not in current window */
/* wsdebug("load_window: load_buffer_by_name(\"%s\", %d)\n",
filename, lnum); */
load_buffer_by_name(filename, lnum);
}
else
{
#ifdef FEAT_WINDOWS
/* buf is in a window */
if (win != curwin)
{
win_enter(win, False);
/* wsdebug("load_window: window enter %s\n",
win->w_buffer->b_sfname); */
}
#endif
if (lnum > 0 && win->w_cursor.lnum != lnum)
{
warp_to_pc(lnum);
/* wsdebug("load_window: warp to %s[%d]\n",
win->w_buffer->b_sfname, lnum); */
}
}
out_flush();
}
static void
warp_to_pc(
int lnum) /* line number to warp to */
{
char lbuf[256]; /* build line command here */
if (lnum > 0)
{
if (State & INSERT)
add_to_input_buf((char_u *) "\033", 1);
if (isShowing(lnum))
sprintf(lbuf, "%dG", lnum);
else
sprintf(lbuf, "%dz.", lnum);
add_to_input_buf((char_u *) lbuf, strlen(lbuf));
}
}
static Boolean
isShowing(
int lnum) /* tell if line number is showing */
{
return lnum >= curwin->w_topline && lnum < curwin->w_botline;
}
static win_T *
get_window(
buf_T *buf) /* buffer to find window for */
{
win_T *wp = NULL; /* window filename is in */
for (wp = firstwin; wp != NULL; wp = W_NEXT(wp))
if (buf == wp->w_buffer)
break;
return wp;
}
static void
updatePriority(
Boolean subMenu) /* if True then start new submenu pri */
{
int pri; /* priority of this menu/item */
char *p;
p = strrchr(curMenuPriority, '.');
ASSERT(p != NULL);
*p++ = NUL;
pri = atoi(p) + 10; /* our new priority */
if (subMenu)
vim_snprintf(curMenuPriority, sizeof(curMenuPriority),
"%s.%d.0", curMenuPriority, pri);
else
vim_snprintf(curMenuPriority, sizeof(curMenuPriority),
"%s.%d", curMenuPriority, pri);
}
static char *
addUniqueMnemonic(
char *mnemonics, /* currently used mnemonics */
char *label) /* label of menu needing mnemonic */
{
static char name[BUFSIZ]; /* buffer for the updated name */
char *p; /* pointer into label */
char *found; /* pointer to possible mnemonic */
found = NULL;
for (p = label; *p != NUL; p++)
if (strchr(mnemonics, *p) == 0)
if (found == NULL || (isupper((int)*p) && islower((int)*found)))
found = p;
if (found != NULL)
{
strncpy(name, label, (found - label));
strcat(name, "&");
strcat(name, found);
}
else
strcpy(name, label);
return name;
}
/*
* Some characters in a menu name must be escaped in vim. Since this is vim
* specific, it must be done on this side.
*/
static char *
fixup(
char *label)
{
static char buf[BUFSIZ];
char *bp; /* pointer into buf */
char *lp; /* pointer into label */
lp = label;
bp = buf;
while (*lp != NUL)
{
if (*lp == ' ' || *lp == '.')
*bp++ = '\\';
*bp++ = *lp++;
}
*bp = NUL;
return buf;
}
#ifdef NOHANDS_SUPPORT_FUNCTIONS
/* For the NoHands test suite */
char *
workshop_test_getcurrentfile()
{
char *filename, *selection;
int curLine, curCol, selStartLine, selStartCol, selEndLine;
int selEndCol, selLength;
if (workshop_get_positions(
NULL, &filename, &curLine, &curCol, &selStartLine,
&selStartCol, &selEndLine, &selEndCol, &selLength,
&selection))
return filename;
else
return NULL;
}
int
workshop_test_getcursorrow()
{
return 0;
}
int
workshop_test_getcursorcol()
{
char *filename, *selection;
int curLine, curCol, selStartLine, selStartCol, selEndLine;
int selEndCol, selLength;
if (workshop_get_positions(
NULL, &filename, &curLine, &curCol, &selStartLine,
&selStartCol, &selEndLine, &selEndCol, &selLength,
&selection))
return curCol;
else
return -1;
}
char *
workshop_test_getcursorrowtext()
{
return NULL;
}
char *
workshop_test_getselectedtext()
{
char *filename, *selection;
int curLine, curCol, selStartLine, selStartCol, selEndLine;
int selEndCol, selLength;
if (workshop_get_positions(
NULL, &filename, &curLine, &curCol, &selStartLine,
&selStartCol, &selEndLine, &selEndCol, &selLength,
&selection))
return selection;
else
return NULL;
}
void
workshop_save_sensitivity(char *filename UNUSED)
{
}
#endif
static char *
fixAccelText(
char *ap) /* original acceleratorText */
{
char buf[256]; /* build in temp buffer */
char *shift; /* shift string of "" */
if (ap == NULL)
return NULL;
/* If the accelerator is shifted use the vim form */
if (strncmp("Shift+", ap, 6) == 0)
{
shift = "S-";
ap += 6;
}
else
shift = "";
if (*ap == 'F' && atoi(&ap[1]) > 0)
{
vim_snprintf(buf, sizeof(buf), "<%s%s>", shift, ap);
return strdup(buf);
}
else
return NULL;
}
#ifdef FEAT_BEVAL
void
workshop_beval_cb(
BalloonEval *beval,
int state)
{
win_T *wp;
char_u *text;
int type;
linenr_T lnum;
int col;
int idx;
char buf[MAXPATHLEN * 2];
static int serialNo = -1;
if (!p_beval)
return;
if (get_beval_info(beval, FALSE, &wp, &lnum, &text, &col) == OK)
{
if (text && text[0])
{
/* Send debugger request */
if (strlen((char *) text) > (MAXPATHLEN/2))
{
/*
* The user has probably selected the entire
* buffer or something like that - don't attempt
* to evaluate it
*/
return;
}
/*
* WorkShop expects the col to be a character index, not
* a column number. Compute the index from col. Also set
* line to 0 because thats what dbx expects.
*/
idx = computeIndex(col, text, beval->ts);
if (idx > 0)
{
lnum = 0;
/*
* If successful, it will respond with a balloon cmd.
*/
if (state & ControlMask)
/* Evaluate *(expression) */
type = (int)GPLineEval_INDIRECT;
else if (state & ShiftMask)
/* Evaluate type(expression) */
type = (int)GPLineEval_TYPE;
else
/* Evaluate value(expression) */
type = (int)GPLineEval_EVALUATE;
/* Send request to dbx */
vim_snprintf(buf, sizeof(buf), "toolVerb debug.balloonEval "
"%s %ld,0 %d,0 %d,%d %ld %s\n",
(char *)wp->w_buffer->b_ffname,
(long)lnum, idx, type, serialNo++,
(long)strlen((char *)text), (char *)text);
balloonEval = beval;
workshop_send_message(buf);
}
}
}
}
static int
computeIndex(
int wantedCol,
char_u *line,
int ts)
{
int col = 0;
int idx = 0;
while (line[idx])
{
if (line[idx] == '\t')
col += ts - (col % ts);
else
col++;
idx++;
if (col >= wantedCol)
return idx;
}
return -1;
}
#endif
static void
addMenu(
char *menu, /* menu name */
char *accel, /* accelerator text (optional) */
char *verb) /* WorkShop action-verb */
{
MenuMap *newMap;
char cbuf[BUFSIZ];
if (menuMapSize >= menuMapMax)
{
newMap = realloc(menuMap,
sizeof(MenuMap) * (menuMapMax + MENU_INC));
if (newMap != NULL)
{
menuMap = newMap;
menuMapMax += MENU_INC;
}
}
if (menuMapSize < menuMapMax)
{
menuMap[menuMapSize].name = strdup(menu);
menuMap[menuMapSize].accel = accel && *accel ? strdup(accel) : NULL;
menuMap[menuMapSize++].verb = strdup(verb);
if (accel && workshopHotKeysEnabled)
{
vim_snprintf(cbuf, sizeof(cbuf),
"map %s :wsverb %s<CR>", accel, verb);
coloncmd(cbuf, TRUE);
}
}
}
static char *
nameStrip(
char *raw) /* menu name, possibly with & chars */
{
static char buf[BUFSIZ]; /* build stripped name here */
char *bp = buf;
while (*raw)
{
if (*raw != '&')
*bp++ = *raw;
raw++;
}
*bp = NUL;
return buf;
}
static char *
lookupVerb(
char *verb,
int skip) /* number of matches to skip */
{
int i; /* loop iterator */
for (i = 0; i < menuMapSize; i++)
if (strcmp(menuMap[i].verb, verb) == 0 && skip-- == 0)
return nameStrip(menuMap[i].name);
return NULL;
}
static void
coloncmd(
char *cmd, /* the command to print */
Boolean force) /* force cursor update */
{
char_u *cpo_save = p_cpo;
#ifdef WSDEBUG
if (WSDLEVEL(WS_TRACE_COLONCMD))
wsdebug("Cmd: %s\n", cmd);
#endif
p_cpo = empty_option;
ALT_INPUT_LOCK_ON;
do_cmdline_cmd((char_u *)cmd);
ALT_INPUT_LOCK_OFF;
p_cpo = cpo_save;
if (force)
gui_update_screen();
}
/*
* setDollarVim - Given the run directory, search for the vim install
* directory and set $VIM.
*
* We can be running out of SUNWspro/bin or out of
* SUNWspro/contrib/contrib6/vim5.6/bin so we check
* relative to both of these directories.
*/
static void
setDollarVim(
char *rundir)
{
char buf[MAXPATHLEN];
char *cp;
/*
* First case: Running from <install-dir>/SUNWspro/bin
*/
strcpy(buf, rundir);
strcat(buf, "/../contrib/contrib6/vim" VIM_VERSION_SHORT "/share/vim/"
VIM_VERSION_NODOT "/syntax/syntax.vim");
if (access(buf, R_OK) == 0)
{
strcpy(buf, "SPRO_WSDIR=");
strcat(buf, rundir);
cp = strrchr(buf, '/');
if (cp != NULL)
strcpy(cp, "/WS6U2");
putenv(strdup(buf));
strcpy(buf, "VIM=");
strcat(buf, rundir);
strcat(buf, "/../contrib/contrib6/vim" VIM_VERSION_SHORT "/share/vim/"
VIM_VERSION_NODOT);
putenv(strdup(buf));
return;
}
/*
* Second case: Probably running from
* <install-dir>/SUNWspro/contrib/contrib6/vim5.6/bin
*/
strcpy(buf, rundir);
strcat(buf, "/../../../contrib/contrib6/vim" VIM_VERSION_SHORT
"/share/vim/" VIM_VERSION_NODOT "/syntax/syntax.vim");
if (access(buf, R_OK) == 0)
{
strcpy(buf, "SPRO_WSDIR=");
strcat(buf, rundir);
cp = strrchr(buf, '/');
if (cp != NULL)
strcpy(cp, "../../../../WS6U2");
putenv(strdup(buf));
strcpy(buf, "VIM=");
strcat(buf, rundir);
strcat(buf, "/../../../contrib/contrib6/vim" VIM_VERSION_SHORT
"/share/vim/" VIM_VERSION_NODOT);
putenv(strdup(buf));
return;
}
}
/*
* findYourself - Find the directory we are running from. This is used to
* set $VIM. We need to set this because users can install
* the package in a different directory than the compiled
* directory. This is a Sun Visual WorkShop requirement!
*
* Note: We override a user's $VIM because it won't have the
* WorkShop specific files. S/he may not like this but its
* better than getting the wrong files (especially as the
* user is likely to have $VIM set to 5.4 or later).
*/
void
findYourself(
char *argv0)
{
char *runpath = NULL;
char *path;
char *pathbuf;
if (*argv0 == '/')
runpath = strdup(argv0);
else if (*argv0 == '.' || strchr(argv0, '/'))
{
runpath = (char *) malloc(MAXPATHLEN);
if (getcwd(runpath, MAXPATHLEN) == NULL)
runpath[0] = NUL;
strcat(runpath, "/");
strcat(runpath, argv0);
}
else
{
path = getenv("PATH");
if (path != NULL)
{
runpath = (char *) malloc(MAXPATHLEN);
pathbuf = strdup(path);
path = strtok(pathbuf, ":");
do
{
strcpy(runpath, path);
strcat(runpath, "/");
strcat(runpath, argv0);
if (access(runpath, X_OK) == 0)
break;
} while ((path = strtok(NULL, ":")) != NULL);
free(pathbuf);
}
}
if (runpath != NULL)
{
char runbuf[MAXPATHLEN];
/*
* We found the run directory. Now find the install dir.
*/
(void)vim_FullName((char_u *)runpath, (char_u *)runbuf, MAXPATHLEN, 1);
path = strrchr(runbuf, '/');
if (path != NULL)
*path = NUL; /* remove the vim/gvim name */
path = strrchr(runbuf, '/');
if (path != NULL)
{
if (strncmp(path, "/bin", 4) == 0)
setDollarVim(runbuf);
else if (strncmp(path, "/src", 4) == 0)
{
*path = NUL; /* development tree */
setDollarVim(runbuf);
}
}
free(runpath);
}
}
| zyz2011-vim | src/workshop.c | C | gpl2 | 41,456 |
/* 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.
*/
/* Visual Studio 2005 has 'deprecated' many of the standard CRT functions */
#if _MSC_VER >= 1400
# define _CRT_SECURE_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
#endif
#include <io.h>
| zyz2011-vim | src/vimio.h | C | gpl2 | 463 |
/* 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) 2001,2005 by Marcin Dalecki <martin@dalecki.de>
*
* Implementation of dialog functions for the Motif GUI variant.
*
* Note about Lesstif: Apparently lesstif doesn't get the widget layout right,
* when using a dynamic scrollbar policy.
*/
#include <Xm/Form.h>
#include <Xm/PushBG.h>
#include <Xm/Text.h>
#include <Xm/TextF.h>
#include <Xm/Label.h>
#include <Xm/Frame.h>
#include <Xm/LabelG.h>
#include <Xm/ToggleBG.h>
#include <Xm/SeparatoG.h>
#include <Xm/DialogS.h>
#include <Xm/List.h>
#include <Xm/RowColumn.h>
#include <Xm/AtomMgr.h>
#include <Xm/Protocols.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#include "vim.h"
extern Widget vimShell;
#ifdef FEAT_MENU
# define apply_fontlist(w) gui_motif_menu_fontlist(w)
#else
# define apply_fontlist(w)
#endif
/****************************************************************************
* Font selection dialogue implementation.
*/
static char wild[3] = "*";
/*
* FIXME: This is a generic function, which should be used throughout the whole
* application.
*
* Add close_callback, which will be called when the user selects close from
* the window menu. The close menu item usually activates f.kill which sends a
* WM_DELETE_WINDOW protocol request for the window.
*/
static void
add_cancel_action(Widget shell, XtCallbackProc close_callback, void *arg)
{
static Atom wmp_atom = 0;
static Atom dw_atom = 0;
Display *display = XtDisplay(shell);
/* deactivate the built-in delete response of killing the application */
XtVaSetValues(shell, XmNdeleteResponse, XmDO_NOTHING, NULL);
/* add a delete window protocol callback instead */
if (!dw_atom)
{
wmp_atom = XmInternAtom(display, "WM_PROTOCOLS", True);
dw_atom = XmInternAtom(display, "WM_DELETE_WINDOW", True);
}
XmAddProtocolCallback(shell, wmp_atom, dw_atom, close_callback, arg);
}
#define MAX_FONTS 65535
#define MAX_FONT_NAME_LEN 256
#define MAX_ENTRIES_IN_LIST 5000
#define MAX_DISPLAY_SIZE 150
#define TEMP_BUF_SIZE 256
enum ListSpecifier
{
ENCODING,
NAME,
STYLE,
SIZE,
NONE
};
typedef struct _SharedFontSelData
{
Widget dialog;
Widget ok;
Widget cancel;
Widget encoding_pulldown;
Widget encoding_menu;
Widget list[NONE];
Widget name;
Widget sample;
char **names; /* font name array of arrays */
int num; /* number of font names */
String sel[NONE]; /* selection category */
Boolean in_pixels; /* toggle state - size in pixels */
char *font_name; /* current font name */
XFontStruct *old; /* font data structure for sample display */
XmFontList old_list; /* font data structure for sample display */
Boolean exit; /* used for program exit control */
} SharedFontSelData;
/*
* Checking access to the font name array for validity.
*/
static char *
fn(SharedFontSelData *data, int i)
{
/* Assertion checks: */
if (data->num < 0)
abort();
if (i >= data->num)
i = data->num - 1;
if (i < 0)
i = 0;
return data->names[i];
}
/*
* Get a specific substring from a font name.
*/
static void
get_part(char *in, int pos, char *out)
{
int i;
int j;
*out = '\0';
for (i = 0; (pos > 0) && (in[i] != '\0'); ++i)
if (in[i] == '-')
pos--;
if (in[i] == '\0')
return;
for (j = 0; (in[i] != '-') && (in[i] != '\0'); ++i, ++j)
out[j] = in[i];
out[j] = '\0';
}
/*
* Given a font name this function returns the part used in the first
* scroll list.
*/
static void
name_part(char *font, char *buf)
{
char buf2[TEMP_BUF_SIZE];
char buf3[TEMP_BUF_SIZE];
get_part(font, 2, buf2);
get_part(font, 1, buf3);
if (*buf3 != NUL)
vim_snprintf(buf, TEMP_BUF_SIZE, "%s (%s)", buf2, buf3);
else
vim_snprintf(buf, TEMP_BUF_SIZE, "%s", buf2);
}
/*
* Given a font name this function returns the part used in the second scroll list.
*/
static void
style_part(char *font, char *buf)
{
char buf2[TEMP_BUF_SIZE];
char buf3[TEMP_BUF_SIZE];
get_part(font, 3, buf3);
get_part(font, 5, buf2);
if (!strcmp(buf2, "normal") && !strcmp(buf2, "Normal")
&& !strcmp(buf2, "NORMAL"))
vim_snprintf(buf, TEMP_BUF_SIZE, "%s %s", buf3, buf2);
else
strcpy(buf, buf3);
get_part(font, 6, buf2);
if (buf2[0] != '\0')
vim_snprintf(buf3, TEMP_BUF_SIZE, "%s %s", buf, buf2);
else
strcpy(buf3, buf);
get_part(font, 4, buf2);
if (!strcmp(buf2, "o") || !strcmp(buf2, "O"))
vim_snprintf(buf, TEMP_BUF_SIZE, "%s oblique", buf3);
else if (!strcmp(buf2, "i") || !strcmp(buf2, "I"))
vim_snprintf(buf, TEMP_BUF_SIZE, "%s italic", buf3);
if (!strcmp(buf, " "))
strcpy(buf, "-");
}
/*
* Given a font name this function returns the part used in the third
* scroll list.
*/
static void
size_part(char *font, char *buf, int inPixels)
{
int size;
float temp;
*buf = '\0';
if (inPixels)
{
get_part(font, 7, buf);
if (*buf != NUL)
{
size = atoi(buf);
sprintf(buf, "%3d", size);
}
}
else
{
get_part(font, 8, buf);
if (*buf != NUL)
{
size = atoi(buf);
temp = (float)size / 10.0;
size = temp;
if (buf[strlen(buf) - 1] == '0')
sprintf(buf, "%3d", size);
else
sprintf(buf, "%4.1f", temp);
}
}
}
/*
* Given a font name this function returns the part used in the choice menu.
*/
static void
encoding_part(char *font, char *buf)
{
char buf1[TEMP_BUF_SIZE];
char buf2[TEMP_BUF_SIZE];
*buf = '\0';
get_part(font, 13, buf1);
get_part(font, 14, buf2);
if (*buf1 != NUL && *buf2 != NUL)
vim_snprintf(buf, TEMP_BUF_SIZE, "%s-%s", buf1, buf2);
if (!strcmp(buf, " "))
strcpy(buf, "-");
}
/*
* Inserts a string into correct sorted position in a list.
*/
static void
add_to_list(char **buf, char *item, int *count)
{
int i;
int j;
if (*count == MAX_ENTRIES_IN_LIST)
return;
/* avoid duplication */
for (i = 0; i < *count; ++i)
{
if (!strcmp(buf[i], item))
return;
}
/* find order place, but make sure that wild card comes first */
if (!strcmp(item, wild))
i = 0;
else
for (i = 0; i < *count; ++i)
if (strcmp(buf[i], item) > 0 && strcmp(buf[i], wild))
break;
/* now insert the item */
for (j = *count; j > i; --j)
buf[j] = buf[j-1];
buf[i] = XtNewString(item);
++(*count);
}
/*
* True if the font matches some field.
*/
static Boolean
match(SharedFontSelData *data, enum ListSpecifier l, int i)
{
char buf[TEMP_BUF_SIZE];
/* An empty selection or a wild card matches anything.
*/
if (!data->sel[l] || !strcmp(data->sel[l], wild))
return True;
/* chunk out the desired part... */
switch (l)
{
case ENCODING:
encoding_part(fn(data, i), buf);
break;
case NAME:
name_part(fn(data, i), buf);
break;
case STYLE:
style_part(fn(data, i), buf);
break;
case SIZE:
size_part(fn(data, i), buf, data->in_pixels);
break;
default:
;
}
/* ...and chew it now */
return !strcmp(buf, data->sel[l]);
}
static Boolean
proportional(char *font)
{
char buf[TEMP_BUF_SIZE];
get_part(font, 11, buf);
return !strcmp(buf, "p") || !strcmp(buf, "P");
}
static void encoding_callback(Widget w, SharedFontSelData *data,
XtPointer dummy);
/*
* Parse through the fontlist data and set up the three scroll lists. The fix
* parameter can be used to exclude a list from any changes. This is used for
* updates after selections caused by the users actions.
*/
static void
fill_lists(enum ListSpecifier fix, SharedFontSelData *data)
{
char *list[NONE][MAX_ENTRIES_IN_LIST];
int count[NONE];
char buf[TEMP_BUF_SIZE];
XmString items[MAX_ENTRIES_IN_LIST];
int i;
int idx;
for (idx = (int)ENCODING; idx < (int)NONE; ++idx)
count[idx] = 0;
/* First we insert the wild char into every single list. */
if (fix != ENCODING)
add_to_list(list[ENCODING], wild, &count[ENCODING]);
if (fix != NAME)
add_to_list(list[NAME], wild, &count[NAME]);
if (fix != STYLE)
add_to_list(list[STYLE], wild, &count[STYLE]);
if (fix != SIZE)
add_to_list(list[SIZE], wild, &count[SIZE]);
for (i = 0; i < data->num && i < MAX_ENTRIES_IN_LIST; i++)
{
if (proportional(fn(data, i)))
continue;
if (fix != ENCODING
&& match(data, NAME, i)
&& match(data, STYLE, i)
&& match(data, SIZE, i))
{
encoding_part(fn(data, i), buf);
add_to_list(list[ENCODING], buf, &count[ENCODING]);
}
if (fix != NAME
&& match(data, ENCODING, i)
&& match(data, STYLE, i)
&& match(data, SIZE, i))
{
name_part(fn(data, i), buf);
add_to_list(list[NAME], buf, &count[NAME]);
}
if (fix != STYLE
&& match(data, ENCODING, i)
&& match(data, NAME, i)
&& match(data, SIZE, i))
{
style_part(fn(data, i), buf);
add_to_list(list[STYLE], buf, &count[STYLE]);
}
if (fix != SIZE
&& match(data, ENCODING, i)
&& match(data, NAME, i)
&& match(data, STYLE, i))
{
size_part(fn(data, i), buf, data->in_pixels);
add_to_list(list[SIZE], buf, &count[SIZE]);
}
}
/*
* And now do the preselection in all lists where there was one:
*/
if (fix != ENCODING)
{
Cardinal n_items;
WidgetList children;
Widget selected_button = 0;
/* Get and update the current button list. */
XtVaGetValues(data->encoding_pulldown,
XmNchildren, &children,
XmNnumChildren, &n_items,
NULL);
for (i = 0; i < count[ENCODING]; ++i)
{
Widget button;
items[i] = XmStringCreateLocalized(list[ENCODING][i]);
if (i < (int)n_items)
{
/* recycle old button */
XtVaSetValues(children[i],
XmNlabelString, items[i],
XmNuserData, i,
NULL);
button = children[i];
}
else
{
/* create a new button */
button = XtVaCreateManagedWidget("button",
xmPushButtonGadgetClass,
data->encoding_pulldown,
XmNlabelString, items[i],
XmNuserData, i,
NULL);
XtAddCallback(button, XmNactivateCallback,
(XtCallbackProc) encoding_callback, (XtPointer) data);
XtManageChild(button);
}
if (data->sel[ENCODING])
{
if (!strcmp(data->sel[ENCODING], list[ENCODING][i]))
selected_button = button;
}
XtFree(list[ENCODING][i]);
}
/* Destroy all the outstanding menu items.
*/
for (i = count[ENCODING]; i < (int)n_items; ++i)
{
XtUnmanageChild(children[i]);
XtDestroyWidget(children[i]);
}
/* Preserve the current selection visually.
*/
if (selected_button)
{
XtVaSetValues(data->encoding_menu,
XmNmenuHistory, selected_button,
NULL);
}
for (i = 0; i < count[ENCODING]; ++i)
XmStringFree(items[i]);
}
/*
* Now loop trough the remaining lists and set them up.
*/
for (idx = (int)NAME; idx < (int)NONE; ++idx)
{
Widget w;
if (fix == (enum ListSpecifier)idx)
continue;
switch ((enum ListSpecifier)idx)
{
case NAME:
w = data->list[NAME];
break;
case STYLE:
w = data->list[STYLE];
break;
case SIZE:
w = data->list[SIZE];
break;
default:
w = (Widget)0; /* for lint */
}
for (i = 0; i < count[idx]; ++i)
{
items[i] = XmStringCreateLocalized(list[idx][i]);
XtFree(list[idx][i]);
}
XmListDeleteAllItems(w);
XmListAddItems(w, items, count[idx], 1);
if (data->sel[idx])
{
XmStringFree(items[0]);
items[0] = XmStringCreateLocalized(data->sel[idx]);
XmListSelectItem(w, items[0], False);
XmListSetBottomItem(w, items[0]);
}
for (i = 0; i < count[idx]; ++i)
XmStringFree(items[i]);
}
}
static void
stoggle_callback(Widget w UNUSED,
SharedFontSelData *data,
XmToggleButtonCallbackStruct *call_data)
{
int i, do_sel;
char newSize[TEMP_BUF_SIZE];
XmString str;
if (call_data->reason != (int)XmCR_VALUE_CHANGED)
return;
do_sel = (data->sel[SIZE] != NULL) && strcmp(data->sel[SIZE], wild);
for (i = 0; do_sel && (i < data->num); i++)
if (match(data, ENCODING, i)
&& match(data, NAME, i)
&& match(data, STYLE, i)
&& match(data, SIZE, i))
{
size_part(fn(data, i), newSize, !data->in_pixels);
break;
}
data->in_pixels = !data->in_pixels;
if (data->sel[SIZE])
XtFree(data->sel[SIZE]);
data->sel[SIZE] = NULL;
fill_lists(NONE, data);
if (do_sel)
{
str = XmStringCreateLocalized(newSize);
XmListSelectItem(data->list[SIZE], str, True);
XmListSetBottomItem(data->list[SIZE], str);
XmStringFree(str);
}
}
/*
* Show the currently selected font in the sample text label.
*/
static void
display_sample(SharedFontSelData *data)
{
Arg args[2];
int n;
XFontStruct * font;
XmFontList font_list;
Display * display;
XmString str;
display = XtDisplay(data->dialog);
font = XLoadQueryFont(display, data->font_name);
font_list = gui_motif_create_fontlist(font);
n = 0;
str = XmStringCreateLocalized("AaBbZzYy 0123456789");
XtSetArg(args[n], XmNlabelString, str); n++;
XtSetArg(args[n], XmNfontList, font_list); n++;
XtSetValues(data->sample, args, n);
XmStringFree(str);
if (data->old)
{
XFreeFont(display, data->old);
XmFontListFree(data->old_list);
}
data->old = font;
data->old_list = font_list;
}
static Boolean
do_choice(Widget w,
SharedFontSelData *data,
XmListCallbackStruct *call_data,
enum ListSpecifier which)
{
char *sel;
XmStringGetLtoR(call_data->item, XmSTRING_DEFAULT_CHARSET, &sel);
if (!data->sel[which])
data->sel[which] = XtNewString(sel);
else
{
if (!strcmp(data->sel[which], sel))
{
/* unselecting current selection */
XtFree(data->sel[which]);
data->sel[which] = NULL;
if (w)
XmListDeselectItem(w, call_data->item);
}
else
{
XtFree(data->sel[which]);
data->sel[which] = XtNewString(sel);
}
}
XtFree(sel);
fill_lists(which, data);
/* If there is a font selection, we display it. */
if (data->sel[ENCODING]
&& data->sel[NAME]
&& data->sel[STYLE]
&& data->sel[SIZE]
&& strcmp(data->sel[ENCODING], wild)
&& strcmp(data->sel[NAME], wild)
&& strcmp(data->sel[STYLE], wild)
&& strcmp(data->sel[SIZE], wild))
{
int i;
if (data->font_name)
XtFree(data->font_name);
data->font_name = NULL;
for (i = 0; i < data->num; i++)
{
if (match(data, ENCODING, i)
&& match(data, NAME, i)
&& match(data, STYLE, i)
&& match(data, SIZE, i))
{
data->font_name = XtNewString(fn(data, i));
break;
}
}
if (data->font_name)
{
XmTextSetString(data->name, data->font_name);
display_sample(data);
}
else
do_dialog(VIM_ERROR,
(char_u *)_("Error"),
(char_u *)_("Invalid font specification"),
(char_u *)_("&Dismiss"), 1, NULL, FALSE);
return True;
}
else
{
int n;
XmString str;
Arg args[4];
char *nomatch_msg = _("no specific match");
n = 0;
str = XmStringCreateLocalized(nomatch_msg);
XtSetArg(args[n], XmNlabelString, str); ++n;
XtSetValues(data->sample, args, n);
apply_fontlist(data->sample);
XmTextSetString(data->name, nomatch_msg);
XmStringFree(str);
return False;
}
}
static void
encoding_callback(Widget w,
SharedFontSelData *data,
XtPointer dummy UNUSED)
{
XmString str;
XmListCallbackStruct fake_data;
XtVaGetValues(w, XmNlabelString, &str, NULL);
if (!str)
return;
fake_data.item = str;
do_choice(0, data, &fake_data, ENCODING);
}
static void
name_callback(Widget w,
SharedFontSelData *data,
XmListCallbackStruct *call_data)
{
do_choice(w, data, call_data, NAME);
}
static void
style_callback(Widget w,
SharedFontSelData *data,
XmListCallbackStruct *call_data)
{
do_choice(w, data, call_data, STYLE);
}
static void
size_callback(Widget w,
SharedFontSelData *data,
XmListCallbackStruct *call_data)
{
do_choice(w, data, call_data, SIZE);
}
static void
cancel_callback(Widget w UNUSED,
SharedFontSelData *data,
XmListCallbackStruct *call_data UNUSED)
{
if (data->sel[ENCODING])
{
XtFree(data->sel[ENCODING]);
data->sel[ENCODING] = NULL;
}
if (data->sel[NAME])
{
XtFree(data->sel[NAME]);
data->sel[NAME] = NULL;
}
if (data->sel[STYLE])
{
XtFree(data->sel[STYLE]);
data->sel[STYLE] = NULL;
}
if (data->sel[SIZE])
{
XtFree(data->sel[SIZE]);
data->sel[SIZE] = NULL;
}
if (data->font_name)
XtFree(data->font_name);
data->font_name = NULL;
data->num = 0;
XFreeFontNames(data->names);
data->names = NULL;
data->exit = True;
}
static void
ok_callback(Widget w UNUSED,
SharedFontSelData *data,
XmPushButtonCallbackStruct *call_data UNUSED)
{
char *pattern;
char **name;
int i;
pattern = XmTextGetString(data->name);
name = XListFonts(XtDisplay(data->dialog), pattern, 1, &i);
XtFree(pattern);
if (i != 1)
{
do_dialog(VIM_ERROR,
(char_u *)_("Error"),
(char_u *)_("Invalid font specification"),
(char_u *)_("&Dismiss"), 1, NULL, FALSE);
XFreeFontNames(name);
}
else
{
if (data->font_name)
XtFree(data->font_name);
data->font_name = XtNewString(name[0]);
if (data->sel[ENCODING])
{
XtFree(data->sel[ENCODING]);
data->sel[ENCODING] = NULL;
}
if (data->sel[NAME])
{
XtFree(data->sel[NAME]);
data->sel[NAME] = NULL;
}
if (data->sel[STYLE])
{
XtFree(data->sel[STYLE]);
data->sel[STYLE] = NULL;
}
if (data->sel[SIZE])
{
XtFree(data->sel[SIZE]);
data->sel[SIZE] = NULL;
}
XFreeFontNames(name);
data->num = 0;
XFreeFontNames(data->names);
data->names = NULL;
data->exit = True;
}
}
/*
* Returns pointer to an ASCII character string that contains the name of the
* selected font (in X format for naming fonts); it is the users responsibility
* to free the space allocated to this string.
*/
char_u *
gui_xm_select_font(char_u *current)
{
static SharedFontSelData _data;
Widget parent;
Widget form;
Widget separator;
Widget sub_form;
Widget size_toggle;
Widget name;
Widget disp_frame;
Widget frame;
Arg args[64];
int n;
XmString str;
char big_font[MAX_FONT_NAME_LEN];
SharedFontSelData *data;
data = &_data;
parent = vimShell;
data->names = XListFonts(XtDisplay(parent), "-*-*-*-*-*-*-*-*-*-*-*-*-*-*",
MAX_FONTS, &data->num);
/*
* Find the name of the biggest font less than the given limit
* MAX_DISPLAY_SIZE used to set up the initial height of the display
* widget.
*/
{
int i;
int max;
int idx = 0;
int size;
char buf[128];
for (i = 0, max = 0; i < data->num; i++)
{
get_part(fn(data, i), 7, buf);
size = atoi(buf);
if ((size > max) && (size < MAX_DISPLAY_SIZE))
{
idx = i;
max = size;
}
}
strcpy(big_font, fn(data, idx));
}
data->old = XLoadQueryFont(XtDisplay(parent), big_font);
data->old_list = gui_motif_create_fontlist(data->old);
/* Set the title of the Dialog window. */
data->dialog = XmCreateDialogShell(parent, "fontSelector", NULL, 0);
str = XmStringCreateLocalized(_("Vim - Font Selector"));
/* Create form popup dialog widget. */
form = XtVaCreateWidget("form",
xmFormWidgetClass, data->dialog,
XmNdialogTitle, str,
XmNautoUnmanage, False,
XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL,
NULL);
XmStringFree(str);
sub_form = XtVaCreateManagedWidget("subForm",
xmFormWidgetClass, form,
XmNbottomAttachment, XmATTACH_FORM,
XmNbottomOffset, 4,
XmNrightAttachment, XmATTACH_FORM,
XmNrightOffset, 4,
XmNtopAttachment, XmATTACH_FORM,
XmNtopOffset, 4,
XmNorientation, XmVERTICAL,
NULL);
data->ok = XtVaCreateManagedWidget(_("OK"),
xmPushButtonGadgetClass, sub_form,
XmNleftAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
XmNtopAttachment, XmATTACH_FORM,
XmNtopOffset, 4,
NULL);
apply_fontlist(data->ok);
data->cancel = XtVaCreateManagedWidget(_("Cancel"),
xmPushButtonGadgetClass, sub_form,
XmNrightAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_FORM,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, data->ok,
XmNtopOffset, 4,
XmNshowAsDefault, True,
NULL);
apply_fontlist(data->cancel);
/* Create the separator for beauty. */
n = 0;
XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); n++;
XtSetArg(args[n], XmNrightWidget, sub_form); n++;
XtSetArg(args[n], XmNrightOffset, 4); n++;
separator = XmCreateSeparatorGadget(form, "separator", args, n);
XtManageChild(separator);
/* Create font name text widget and the corresponding label. */
data->name = XtVaCreateManagedWidget("fontName",
xmTextWidgetClass, form,
XmNbottomAttachment, XmATTACH_FORM,
XmNbottomOffset, 4,
XmNleftAttachment, XmATTACH_FORM,
XmNleftOffset, 4,
XmNrightAttachment, XmATTACH_WIDGET,
XmNrightWidget, separator,
XmNrightOffset, 4,
XmNeditable, False,
XmNeditMode, XmSINGLE_LINE_EDIT,
XmNmaxLength, MAX_FONT_NAME_LEN,
XmNcolumns, 60,
NULL);
str = XmStringCreateLocalized(_("Name:"));
name = XtVaCreateManagedWidget("fontNameLabel",
xmLabelGadgetClass, form,
XmNlabelString, str,
XmNuserData, data->name,
XmNleftAttachment, XmATTACH_OPPOSITE_WIDGET,
XmNleftWidget, data->name,
XmNbottomAttachment, XmATTACH_WIDGET,
XmNbottomWidget, data->name,
XmNtopOffset, 1,
NULL);
XmStringFree(str);
apply_fontlist(name);
/* create sample display label widget */
disp_frame = XtVaCreateManagedWidget("sampleFrame",
xmFrameWidgetClass, form,
XmNshadowType, XmSHADOW_ETCHED_IN,
XmNleftAttachment, XmATTACH_FORM,
XmNleftOffset, 4,
XmNbottomAttachment, XmATTACH_WIDGET,
XmNbottomWidget, name,
XmNrightAttachment, XmATTACH_WIDGET,
XmNrightWidget, separator,
XmNrightOffset, 4,
XmNalignment, XmALIGNMENT_BEGINNING,
NULL);
data->sample = XtVaCreateManagedWidget("sampleLabel",
xmLabelWidgetClass, disp_frame,
XmNleftAttachment, XmATTACH_FORM,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
XmNalignment, XmALIGNMENT_BEGINNING,
XmNrecomputeSize, False,
XmNfontList, data->old_list,
NULL);
/* create toggle button */
str = XmStringCreateLocalized(_("Show size in Points"));
size_toggle = XtVaCreateManagedWidget("sizeToggle",
xmToggleButtonGadgetClass, form,
XmNlabelString, str,
XmNleftAttachment, XmATTACH_FORM,
XmNleftOffset, 4,
XmNbottomAttachment, XmATTACH_WIDGET,
XmNbottomWidget, disp_frame,
XmNbottomOffset, 4,
NULL);
XmStringFree(str);
apply_fontlist(size_toggle);
XtManageChild(size_toggle);
/* Encoding pulldown menu.
*/
data->encoding_pulldown = XmCreatePulldownMenu(form,
"encodingPulldown", NULL, 0);
str = XmStringCreateLocalized(_("Encoding:"));
n = 0;
XtSetArg(args[n], XmNsubMenuId, data->encoding_pulldown); ++n;
XtSetArg(args[n], XmNlabelString, str); ++n;
XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
XtSetArg(args[n], XmNleftOffset, 4); ++n;
XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
XtSetArg(args[n], XmNbottomWidget, size_toggle); ++n;
XtSetArg(args[n], XmNbottomOffset, 4); ++n;
XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); ++n;
XtSetArg(args[n], XmNrightWidget, separator); ++n;
XtSetArg(args[n], XmNrightOffset, 4); ++n;
data->encoding_menu = XmCreateOptionMenu(form, "encodingMenu", args, n);
XmStringFree(str);
XmAddTabGroup(data->encoding_menu);
/*
* Create scroll list widgets in a separate subform used to manage the
* different sizes of the lists.
*/
sub_form = XtVaCreateManagedWidget("subForm",
xmFormWidgetClass, form,
XmNbottomAttachment, XmATTACH_WIDGET,
XmNbottomWidget, data->encoding_menu,
XmNbottomOffset, 4,
XmNleftAttachment, XmATTACH_FORM,
XmNleftOffset, 4,
XmNrightAttachment, XmATTACH_WIDGET,
XmNrightWidget, separator,
XmNrightOffset, 4,
XmNtopAttachment, XmATTACH_FORM,
XmNtopOffset, 2,
XmNorientation, XmVERTICAL,
NULL);
/* font list */
frame = XtVaCreateManagedWidget("frame", xmFrameWidgetClass, sub_form,
XmNshadowThickness, 0,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 50,
NULL);
str = XmStringCreateLocalized(_("Font:"));
name = XtVaCreateManagedWidget("nameListLabel", xmLabelGadgetClass, frame,
XmNchildType, XmFRAME_TITLE_CHILD,
XmNchildVerticalAlignment, XmALIGNMENT_CENTER,
XmNchildHorizontalAlignment, XmALIGNMENT_BEGINNING,
XmNlabelString, str,
NULL);
XmStringFree(str);
apply_fontlist(name);
n = 0;
XtSetArg(args[n], XmNvisibleItemCount, 8); ++n;
XtSetArg(args[n], XmNresizable, True); ++n;
XtSetArg(args[n], XmNlistSizePolicy, XmCONSTANT); ++n;
XtSetArg(args[n], XmNvisualPolicy, XmVARIABLE); ++n;
#ifdef LESSTIF_VERSION
XtSetArg(args[n], XmNscrollBarDisplayPolicy, XmSTATIC); ++n;
#endif
data->list[NAME] = XmCreateScrolledList(frame, "fontList", args, n);
XtVaSetValues(name, XmNuserData, data->list[NAME], NULL);
/* style list */
frame = XtVaCreateManagedWidget("frame", xmFrameWidgetClass, sub_form,
XmNshadowThickness, 0,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 50,
XmNleftOffset, 4,
XmNrightAttachment, XmATTACH_POSITION,
XmNrightPosition, 80,
NULL);
str = XmStringCreateLocalized(_("Style:"));
name = XtVaCreateManagedWidget("styleListLabel", xmLabelWidgetClass, frame,
XmNchildType, XmFRAME_TITLE_CHILD,
XmNchildVerticalAlignment, XmALIGNMENT_CENTER,
XmNchildHorizontalAlignment, XmALIGNMENT_BEGINNING,
XmNlabelString, str,
NULL);
XmStringFree(str);
apply_fontlist(name);
n = 0;
XtSetArg(args[n], XmNvisibleItemCount, 8); ++n;
XtSetArg(args[n], XmNresizable, True); ++n;
XtSetArg(args[n], XmNlistSizePolicy, XmCONSTANT); ++n;
XtSetArg(args[n], XmNvisualPolicy, XmVARIABLE); ++n;
#ifdef LESSTIF_VERSION
XtSetArg(args[n], XmNscrollBarDisplayPolicy, XmSTATIC); ++n;
#endif
data->list[STYLE] = XmCreateScrolledList(frame, "styleList", args, n);
XtVaSetValues(name, XmNuserData, data->list[STYLE], NULL);
/* size list */
frame = XtVaCreateManagedWidget("frame", xmFrameWidgetClass, sub_form,
XmNshadowThickness, 0,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_POSITION,
XmNleftPosition, 80,
XmNleftOffset, 4,
XmNrightAttachment, XmATTACH_FORM,
NULL);
str = XmStringCreateLocalized(_("Size:"));
name = XtVaCreateManagedWidget("sizeListLabel", xmLabelGadgetClass, frame,
XmNchildType, XmFRAME_TITLE_CHILD,
XmNchildVerticalAlignment, XmALIGNMENT_CENTER,
XmNchildHorizontalAlignment, XmALIGNMENT_BEGINNING,
XmNlabelString, str,
NULL);
XmStringFree(str);
apply_fontlist(name);
n = 0;
XtSetArg(args[n], XmNvisibleItemCount, 8); ++n;
XtSetArg(args[n], XmNresizable, True); ++n;
XtSetArg(args[n], XmNlistSizePolicy, XmCONSTANT); ++n;
XtSetArg(args[n], XmNvisualPolicy, XmVARIABLE); ++n;
#ifdef LESSTIF_VERSION
XtSetArg(args[n], XmNscrollBarDisplayPolicy, XmSTATIC); ++n;
#endif
data->list[SIZE] = XmCreateScrolledList(frame, "sizeList", args, n);
XtVaSetValues(name, XmNuserData, data->list[SIZE], NULL);
/* update form widgets cancel button */
XtVaSetValues(form, XmNcancelButton, data->cancel, NULL);
XtAddCallback(size_toggle, XmNvalueChangedCallback,
(XtCallbackProc)stoggle_callback, (XtPointer)data);
XtAddCallback(data->list[NAME], XmNbrowseSelectionCallback,
(XtCallbackProc)name_callback, (XtPointer)data);
XtAddCallback(data->list[STYLE], XmNbrowseSelectionCallback,
(XtCallbackProc)style_callback, (XtPointer)data);
XtAddCallback(data->list[SIZE], XmNbrowseSelectionCallback,
(XtCallbackProc)size_callback, (XtPointer)data);
XtAddCallback(data->ok, XmNactivateCallback,
(XtCallbackProc)ok_callback, (XtPointer)data);
XtAddCallback(data->cancel, XmNactivateCallback,
(XtCallbackProc)cancel_callback, (XtPointer)data);
XmProcessTraversal(data->list[NAME], XmTRAVERSE_CURRENT);
/* setup tabgroups */
XmAddTabGroup(data->list[NAME]);
XmAddTabGroup(data->list[STYLE]);
XmAddTabGroup(data->list[SIZE]);
XmAddTabGroup(size_toggle);
XmAddTabGroup(data->name);
XmAddTabGroup(data->ok);
XmAddTabGroup(data->cancel);
add_cancel_action(data->dialog, (XtCallbackProc)cancel_callback, data);
/* Preset selection data. */
data->exit = False;
data->in_pixels= True;
data->sel[ENCODING] = NULL;
data->sel[NAME] = NULL;
data->sel[STYLE] = NULL;
data->sel[SIZE] = NULL;
data->font_name = NULL;
/* set up current font parameters */
if (current && current[0] != '\0')
{
int i;
char **names;
names = XListFonts(XtDisplay(form), (char *) current, 1, &i);
if (i != 0)
{
char namebuf[TEMP_BUF_SIZE];
char stylebuf[TEMP_BUF_SIZE];
char sizebuf[TEMP_BUF_SIZE];
char encodingbuf[TEMP_BUF_SIZE];
char *found;
found = names[0];
name_part(found, namebuf);
style_part(found, stylebuf);
size_part(found, sizebuf, data->in_pixels);
encoding_part(found, encodingbuf);
if (*namebuf != NUL
&& *stylebuf != NUL
&& *sizebuf != NUL
&& *encodingbuf != NUL)
{
data->sel[NAME] = XtNewString(namebuf);
data->sel[STYLE] = XtNewString(stylebuf);
data->sel[SIZE] = XtNewString(sizebuf);
data->sel[ENCODING] = XtNewString(encodingbuf);
data->font_name = XtNewString(names[0]);
display_sample(data);
XmTextSetString(data->name, data->font_name);
}
else
{
/* We can't preset a symbolic name, which isn't a full font
* description. Therefore we just behave the same way as if the
* user didn't have selected anything thus far.
*
* Unfortunately there is no known way to expand an abbreviated
* font name.
*/
data->font_name = NULL;
}
}
XFreeFontNames(names);
}
fill_lists(NONE, data);
/* Unfortunately LessTif doesn't align the list widget's properly. I don't
* have currently any idea how to fix this problem.
*/
XtManageChild(data->list[NAME]);
XtManageChild(data->list[STYLE]);
XtManageChild(data->list[SIZE]);
XtManageChild(data->encoding_menu);
manage_centered(form);
/* modal event loop */
while (!data->exit)
XtAppProcessEvent(XtWidgetToApplicationContext(data->dialog),
(XtInputMask)XtIMAll);
if (data->old)
{
XFreeFont(XtDisplay(data->dialog), data->old);
XmFontListFree(data->old_list);
}
XtDestroyWidget(data->dialog);
gui_motif_synch_fonts();
return (char_u *) data->font_name;
}
| zyz2011-vim | src/gui_xmdlg.c | C | gpl2 | 32,005 |
# A very (if not the most) simplistic Makefile for OS/2
CC=gcc
CFLAGS=-O2 -fno-strength-reduce
tee.exe: tee.o
$(CC) $(CFLAGS) -s -o $@ $<
tee.o: tee.c
$(CC) $(CFLAGS) -c $<
clean:
- del tee.o
- del tee.exe
| zyz2011-vim | src/tee/Makefile | Makefile | gpl2 | 215 |
/* vim:set ts=4 sw=4:
*
* Copyright (c) 1996, Paul Slootman
*
* Author: Paul Slootman
* (paul@wurtel.hobby.nl, paul@murphy.nl, paulS@toecompst.nl)
*
* This source code is released into the public domain. It is provided on an
* as-is basis and no responsibility is accepted for its failure to perform
* as expected. It is worth at least as much as you paid for it!
*
* tee.c - pipe fitting
*
* tee reads stdin, and writes what it reads to each of the specified
* files. The primary reason of existence for this version is a quick
* and dirty implementation to distribute with Vim, to make one of the
* most useful features of Vim possible on OS/2: quickfix.
*
* Of course, not using tee but instead redirecting make's output directly
* into a temp file and then processing that is possible, but if we have a
* system capable of correctly piping (unlike DOS, for example), why not
* use it as well as possible? This tee should also work on other systems,
* but it's not been tested there, only on OS/2.
*
* tee is also available in the GNU shellutils package, which is available
* precompiled for OS/2. That one probably works better.
*/
#include <unistd.h>
#include <malloc.h>
#include <stdio.h>
void usage(void)
{
fprintf(stderr,
"tee usage:\n\
\ttee [-a] file ... file_n\n\
\n\
\t-a\tappend to files instead of truncating\n\
\nTee reads its input, and writes to each of the specified files,\n\
as well as to the standard output.\n\
\n\
This version supplied with Vim 4.2 to make ':make' possible.\n\
For a more complete and stable version, consider getting\n\
[a port of] the GNU shellutils package.\n\
");
}
/*
* fread only returns when count is read or at EOF.
* We could use fgets, but I want to be able to handle binary blubber.
*/
int
myfread(char *buf, int elsize /*ignored*/, int max, FILE *fp)
{
int c;
int n = 0;
while ((n < max) && ((c = getchar()) != EOF))
{
*(buf++) = c;
n++;
if (c == '\n' || c == '\r')
break;
}
return n;
}
void
main(int argc, char *argv[])
{
int append = 0;
int numfiles;
int opt;
int maxfiles;
FILE **filepointers;
int i;
char buf[BUFSIZ];
int n;
extern int optind;
while ((opt = getopt(argc, argv, "a")) != EOF)
{
switch (opt)
{
case 'a': append++;
break;
default: usage();
exit(2);
}
}
numfiles = argc - optind;
if (numfiles == 0)
{
fprintf(stderr, "doesn't make much sense using tee without any file name arguments...\n");
usage();
exit(2);
}
maxfiles = sysconf(_SC_OPEN_MAX); /* or fill in 10 or so */
if (maxfiles < 0)
maxfiles = 10;
if (numfiles + 3 > maxfiles) /* +3 accounts for stdin, out, err */
{
fprintf(stderr, "Sorry, there is a limit of max %d files.\n", maxfiles - 3);
exit(1);
}
filepointers = calloc(numfiles, sizeof(FILE *));
if (filepointers == NULL)
{
fprintf(stderr, "Error allocating memory for %d files\n", numfiles);
exit(1);
}
for (i = 0; i < numfiles; i++)
{
filepointers[i] = fopen(argv[i+optind], append ? "ab" : "wb");
if (filepointers[i] == NULL)
{
fprintf(stderr, "Can't open \"%s\"\n", argv[i+optind]);
exit(1);
}
}
_fsetmode(stdin, "b");
fflush(stdout); /* needed for _fsetmode(stdout) */
_fsetmode(stdout, "b");
while ((n = myfread(buf, sizeof(char), sizeof(buf), stdin)) > 0)
{
fwrite(buf, sizeof(char), n, stdout);
fflush(stdout);
for (i = 0; i < numfiles; i++)
{
if (filepointers[i] &&
fwrite(buf, sizeof(char), n, filepointers[i]) != n)
{
fprintf(stderr, "Error writing to file \"%s\"\n", argv[i+optind]);
fclose(filepointers[i]);
filepointers[i] = NULL;
}
}
}
for (i = 0; i < numfiles; i++)
{
if (filepointers[i])
fclose(filepointers[i]);
}
exit(0);
}
| zyz2011-vim | src/tee/tee.c | C | gpl2 | 3,722 |
/* 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.
*/
/*
* macros.h: macro definitions for often used code
*/
/*
* pchar(lp, c) - put character 'c' at position 'lp'
*/
#define pchar(lp, c) (*(ml_get_buf(curbuf, (lp).lnum, TRUE) + (lp).col) = (c))
/*
* Position comparisons
*/
#ifdef FEAT_VIRTUALEDIT
# define lt(a, b) (((a).lnum != (b).lnum) \
? (a).lnum < (b).lnum \
: (a).col != (b).col \
? (a).col < (b).col \
: (a).coladd < (b).coladd)
# define ltp(a, b) (((a)->lnum != (b)->lnum) \
? (a)->lnum < (b)->lnum \
: (a)->col != (b)->col \
? (a)->col < (b)->col \
: (a)->coladd < (b)->coladd)
# define equalpos(a, b) (((a).lnum == (b).lnum) && ((a).col == (b).col) && ((a).coladd == (b).coladd))
# define clearpos(a) {(a)->lnum = 0; (a)->col = 0; (a)->coladd = 0;}
#else
# define lt(a, b) (((a).lnum != (b).lnum) \
? ((a).lnum < (b).lnum) : ((a).col < (b).col))
# define ltp(a, b) (((a)->lnum != (b)->lnum) \
? ((a)->lnum < (b)->lnum) : ((a)->col < (b)->col))
# define equalpos(a, b) (((a).lnum == (b).lnum) && ((a).col == (b).col))
# define clearpos(a) {(a)->lnum = 0; (a)->col = 0;}
#endif
#define ltoreq(a, b) (lt(a, b) || equalpos(a, b))
/*
* lineempty() - return TRUE if the line is empty
*/
#define lineempty(p) (*ml_get(p) == NUL)
/*
* bufempty() - return TRUE if the current buffer is empty
*/
#define bufempty() (curbuf->b_ml.ml_line_count == 1 && *ml_get((linenr_T)1) == NUL)
/*
* toupper() and tolower() that use the current locale.
* On some systems toupper()/tolower() only work on lower/uppercase
* characters, first use islower() or isupper() then.
* Careful: Only call TOUPPER_LOC() and TOLOWER_LOC() with a character in the
* range 0 - 255. toupper()/tolower() on some systems can't handle others.
* Note: It is often better to use MB_TOLOWER() and MB_TOUPPER(), because many
* toupper() and tolower() implementations only work for ASCII.
*/
#ifdef MSWIN
# define TOUPPER_LOC(c) toupper_tab[(c) & 255]
# define TOLOWER_LOC(c) tolower_tab[(c) & 255]
#else
# ifdef BROKEN_TOUPPER
# define TOUPPER_LOC(c) (islower(c) ? toupper(c) : (c))
# define TOLOWER_LOC(c) (isupper(c) ? tolower(c) : (c))
# else
# define TOUPPER_LOC toupper
# define TOLOWER_LOC tolower
# endif
#endif
/* toupper() and tolower() for ASCII only and ignore the current locale. */
#ifdef EBCDIC
# define TOUPPER_ASC(c) (islower(c) ? toupper(c) : (c))
# define TOLOWER_ASC(c) (isupper(c) ? tolower(c) : (c))
#else
# define TOUPPER_ASC(c) (((c) < 'a' || (c) > 'z') ? (c) : (c) - ('a' - 'A'))
# define TOLOWER_ASC(c) (((c) < 'A' || (c) > 'Z') ? (c) : (c) + ('a' - 'A'))
#endif
/*
* MB_ISLOWER() and MB_ISUPPER() are to be used on multi-byte characters. But
* don't use them for negative values!
*/
#ifdef FEAT_MBYTE
# define MB_ISLOWER(c) vim_islower(c)
# define MB_ISUPPER(c) vim_isupper(c)
# define MB_TOLOWER(c) vim_tolower(c)
# define MB_TOUPPER(c) vim_toupper(c)
#else
# define MB_ISLOWER(c) islower(c)
# define MB_ISUPPER(c) isupper(c)
# define MB_TOLOWER(c) TOLOWER_LOC(c)
# define MB_TOUPPER(c) TOUPPER_LOC(c)
#endif
/* Like isalpha() but reject non-ASCII characters. Can't be used with a
* special key (negative value). */
#ifdef EBCDIC
# define ASCII_ISALPHA(c) isalpha(c)
# define ASCII_ISALNUM(c) isalnum(c)
# define ASCII_ISLOWER(c) islower(c)
# define ASCII_ISUPPER(c) isupper(c)
#else
# define ASCII_ISALPHA(c) ((c) < 0x7f && isalpha(c))
# define ASCII_ISALNUM(c) ((c) < 0x7f && isalnum(c))
# define ASCII_ISLOWER(c) ((c) < 0x7f && islower(c))
# define ASCII_ISUPPER(c) ((c) < 0x7f && isupper(c))
#endif
/* Use our own isdigit() replacement, because on MS-Windows isdigit() returns
* non-zero for superscript 1. Also avoids that isdigit() crashes for numbers
* below 0 and above 255. For complicated arguments and in/decrement use
* vim_isdigit() instead. */
#define VIM_ISDIGIT(c) ((c) >= '0' && (c) <= '9')
/* macro version of chartab().
* Only works with values 0-255!
* Doesn't work for UTF-8 mode with chars >= 0x80. */
#define CHARSIZE(c) (chartab[c] & CT_CELL_MASK)
#ifdef FEAT_LANGMAP
/*
* Adjust chars in a language according to 'langmap' option.
* NOTE that there is no noticeable overhead if 'langmap' is not set.
* When set the overhead for characters < 256 is small.
* Don't apply 'langmap' if the character comes from the Stuff buffer.
* The do-while is just to ignore a ';' after the macro.
*/
# ifdef FEAT_MBYTE
# define LANGMAP_ADJUST(c, condition) \
do { \
if (*p_langmap && (condition) && !KeyStuffed && (c) >= 0) \
{ \
if ((c) < 256) \
c = langmap_mapchar[c]; \
else \
c = langmap_adjust_mb(c); \
} \
} while (0)
# else
# define LANGMAP_ADJUST(c, condition) \
do { \
if (*p_langmap && (condition) && !KeyStuffed && (c) >= 0 && (c) < 256) \
c = langmap_mapchar[c]; \
} while (0)
# endif
#else
# define LANGMAP_ADJUST(c, condition) /* nop */
#endif
/*
* vim_isbreak() is used very often if 'linebreak' is set, use a macro to make
* it work fast.
*/
#define vim_isbreak(c) (breakat_flags[(char_u)(c)])
/*
* On VMS file names are different and require a translation.
* On the Mac open() has only two arguments.
*/
#ifdef VMS
# define mch_access(n, p) access(vms_fixfilename(n), (p))
/* see mch_open() comment */
# define mch_fopen(n, p) fopen(vms_fixfilename(n), (p))
# define mch_fstat(n, p) fstat(vms_fixfilename(n), (p))
/* VMS does not have lstat() */
# define mch_stat(n, p) stat(vms_fixfilename(n), (p))
#else
# ifndef WIN32
# define mch_access(n, p) access((n), (p))
# endif
# if !(defined(FEAT_MBYTE) && defined(WIN3264))
# define mch_fopen(n, p) fopen((n), (p))
# endif
# define mch_fstat(n, p) fstat((n), (p))
# ifdef MSWIN /* has it's own mch_stat() function */
# define mch_stat(n, p) vim_stat((n), (p))
# else
# ifdef STAT_IGNORES_SLASH
/* On Solaris stat() accepts "file/" as if it was "file". Return -1 if
* the name ends in "/" and it's not a directory. */
# define mch_stat(n, p) (illegal_slash(n) ? -1 : stat((n), (p)))
# else
# define mch_stat(n, p) stat((n), (p))
# endif
# endif
#endif
#ifdef HAVE_LSTAT
# define mch_lstat(n, p) lstat((n), (p))
#else
# define mch_lstat(n, p) mch_stat((n), (p))
#endif
#ifdef MACOS_CLASSIC
/* MacOS classic doesn't support perm but MacOS X does. */
# define mch_open(n, m, p) open((n), (m))
#else
# ifdef VMS
/*
* It is possible to force some record format with:
* # define mch_open(n, m, p) open(vms_fixfilename(n), (m), (p)), "rat=cr", "rfm=stmlf", "mrs=0")
* but it is not recommended, because it can destroy indexes etc.
*/
# define mch_open(n, m, p) open(vms_fixfilename(n), (m), (p))
# else
# if !(defined(FEAT_MBYTE) && defined(WIN3264))
# define mch_open(n, m, p) open((n), (m), (p))
# endif
# endif
#endif
/* mch_open_rw(): invoke mch_open() with third argument for user R/W. */
#if defined(UNIX) || defined(VMS) /* open in rw------- mode */
# define mch_open_rw(n, f) mch_open((n), (f), (mode_t)0600)
#else
# if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* open read/write */
# define mch_open_rw(n, f) mch_open((n), (f), S_IREAD | S_IWRITE)
# else
# define mch_open_rw(n, f) mch_open((n), (f), 0)
# endif
#endif
#ifdef STARTUPTIME
# define TIME_MSG(s) { if (time_fd != NULL) time_msg(s, NULL); }
#else
# define TIME_MSG(s)
#endif
#ifdef FEAT_VREPLACE
# define REPLACE_NORMAL(s) (((s) & REPLACE_FLAG) && !((s) & VREPLACE_FLAG))
#else
# define REPLACE_NORMAL(s) ((s) & REPLACE_FLAG)
#endif
#ifdef FEAT_ARABIC
# define UTF_COMPOSINGLIKE(p1, p2) utf_composinglike((p1), (p2))
#else
# define UTF_COMPOSINGLIKE(p1, p2) utf_iscomposing(utf_ptr2char(p2))
#endif
#ifdef FEAT_RIGHTLEFT
/* Whether to draw the vertical bar on the right side of the cell. */
# define CURSOR_BAR_RIGHT (curwin->w_p_rl && (!(State & CMDLINE) || cmdmsg_rl))
#endif
/*
* mb_ptr_adv(): advance a pointer to the next character, taking care of
* multi-byte characters if needed.
* mb_ptr_back(): backup a pointer to the previous character, taking care of
* multi-byte characters if needed.
* MB_COPY_CHAR(f, t): copy one char from "f" to "t" and advance the pointers.
* PTR2CHAR(): get character from pointer.
*/
#ifdef FEAT_MBYTE
/* Advance multi-byte pointer, skip over composing chars. */
# define mb_ptr_adv(p) p += has_mbyte ? (*mb_ptr2len)(p) : 1
/* Advance multi-byte pointer, do not skip over composing chars. */
# define mb_cptr_adv(p) p += enc_utf8 ? utf_ptr2len(p) : has_mbyte ? (*mb_ptr2len)(p) : 1
/* Backup multi-byte pointer. */
# define mb_ptr_back(s, p) p -= has_mbyte ? ((*mb_head_off)(s, p - 1) + 1) : 1
/* get length of multi-byte char, not including composing chars */
# define mb_cptr2len(p) (enc_utf8 ? utf_ptr2len(p) : (*mb_ptr2len)(p))
# define MB_COPY_CHAR(f, t) if (has_mbyte) mb_copy_char(&f, &t); else *t++ = *f++
# define MB_CHARLEN(p) (has_mbyte ? mb_charlen(p) : (int)STRLEN(p))
# define PTR2CHAR(p) (has_mbyte ? mb_ptr2char(p) : (int)*(p))
#else
# define mb_ptr_adv(p) ++p
# define mb_cptr_adv(p) ++p
# define mb_ptr_back(s, p) --p
# define MB_COPY_CHAR(f, t) *t++ = *f++
# define MB_CHARLEN(p) STRLEN(p)
# define PTR2CHAR(p) ((int)*(p))
#endif
#ifdef FEAT_AUTOCHDIR
# define DO_AUTOCHDIR if (p_acd) do_autochdir();
#else
# define DO_AUTOCHDIR
#endif
#if defined(FEAT_SCROLLBIND) && defined(FEAT_CURSORBIND)
# define RESET_BINDING(wp) (wp)->w_p_scb = FALSE; (wp)->w_p_crb = FALSE
#else
# if defined(FEAT_SCROLLBIND)
# define RESET_BINDING(wp) (wp)->w_p_scb = FALSE
# else
# if defined(FEAT_CURSORBIND)
# define RESET_BINDING(wp) (wp)->w_p_crb = FALSE
# else
# define RESET_BINDING(wp)
# endif
# endif
#endif
| zyz2011-vim | src/macros.h | C | gpl2 | 9,819 |
/*
* Header file for xpm_w32.c
*/
#ifndef XPM_W32__H
int LoadXpmImage __ARGS((char *filename, HBITMAP *hImage, HBITMAP *hShape));
#endif
| zyz2011-vim | src/xpm_w32.h | C | gpl2 | 140 |
/* 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.
*/
#ifdef GLOBAL_IME
#ifndef _INC_GLOBAL_IME
#define _INC_GLOBAL_IME
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void global_ime_init(ATOM, HWND);
void global_ime_end(void);
LRESULT WINAPI global_ime_DefWindowProc(HWND, UINT, WPARAM, LPARAM);
BOOL WINAPI global_ime_TranslateMessage(CONST MSG *);
void WINAPI global_ime_set_position(POINT*);
void WINAPI global_ime_set_font(LOGFONT*);
#if 0
void WINAPI global_ime_status_evacuate(void);
void WINAPI global_ime_status_restore(void);
#endif
void WINAPI global_ime_set_status(int status);
int WINAPI global_ime_get_status(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _INC_GLOBAL_IME */
#endif /* GLOBAL_IME */
| zyz2011-vim | src/glbl_ime.h | C | gpl2 | 942 |
### USEDLL no for statically linked version of run-time, yes for DLL runtime
### BOR path to root of Borland C install (c:\bc5)
### (requires cc3250.dll be available in %PATH%)
!if ("$(USEDLL)"=="")
USEDLL = no
!endif
### BOR: root of the BC installation
!if ("$(BOR)"=="")
BOR = c:\bc5
!endif
CC = $(BOR)\bin\Bcc32
BRC = $(BOR)\bin\brc32
LINK = $(BOR)\BIN\ILink32
INCLUDE = $(BOR)\include;.
LIB = $(BOR)\lib
!if ("$(USEDLL)"=="yes")
RT_DEF = -D_RTLDLL
RT_LIB = cw32i.lib
!else
RT_DEF =
RT_LIB = cw32.lib
!endif
all : gvimext.dll
gvimext.obj : gvimext.cpp gvimext.h
$(CC) -tWD -I$(INCLUDE) -c -DFEAT_GETTEXT $(RT_DEF) -w- gvimext.cpp
gvimext.res : gvimext.rc
$(BRC) -r gvimext.rc
gvimext.dll : gvimext.obj gvimext.res
$(LINK) -L$(LIB) -aa gvimext.obj, gvimext.dll, , c0d32.obj $(RT_LIB) import32.lib, gvimext.def, gvimext.res
clean :
-@del gvimext.obj
-@del gvimext.res
-@del gvimext.dll
| zyz2011-vim | src/GvimExt/Make_bc5.mak | Makefile | gpl2 | 909 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved gvimext by Tianmiao Hu
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
*/
/*
* If you have any questions or any suggestions concerning gvimext, please
* contact Tianmiao Hu: tianmiao@acm.org.
*/
#if !defined(AFX_STDAFX_H__3389658B_AD83_11D3_9C1E_0090278BBD99__INCLUDED_)
#define AFX_STDAFX_H__3389658B_AD83_11D3_9C1E_0090278BBD99__INCLUDED_
#if defined(_MSC_VER) && _MSC_VER > 1000
#pragma once
#endif
// Insert your headers here
// #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
//--------------------------------------------------------------
// common user interface routines
//
//
//--------------------------------------------------------------
#ifndef STRICT
# define STRICT
#endif
#define INC_OLE2 // WIN32, get ole2 from windows.h
/* Visual Studio 2005 has 'deprecated' many of the standard CRT functions */
#if defined(_MSC_VER) && _MSC_VER >= 1400
# define _CRT_SECURE_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
#endif
#include <windows.h>
#include <windowsx.h>
#include <shlobj.h>
/* Accommodate old versions of VC that don't have a modern Platform SDK */
#if (defined(_MSC_VER) && _MSC_VER < 1300) || !defined(MAXULONG_PTR)
# undef UINT_PTR
# define UINT_PTR UINT
#endif
#define ResultFromShort(i) ResultFromScode(MAKE_SCODE(SEVERITY_SUCCESS, 0, (USHORT)(i)))
// Initialize GUIDs (should be done only and at-least once per DLL/EXE)
//
#pragma data_seg(".text")
#define INITGUID
#include <initguid.h>
#include <shlguid.h>
//
// The class ID of this Shell extension class.
//
// class id: {51EEE242-AD87-11d3-9C1E-0090278BBD99}
//
//
// NOTE!!! If you use this shell extension as a starting point,
// you MUST change the GUID below. Simply run UUIDGEN.EXE
// to generate a new GUID.
//
// {51EEE242-AD87-11d3-9C1E-0090278BBD99}
// static const GUID <<name>> =
// { 0x51eee242, 0xad87, 0x11d3, { 0x9c, 0x1e, 0x0, 0x90, 0x27, 0x8b, 0xbd, 0x99 } };
//
//
// {51EEE242-AD87-11d3-9C1E-0090278BBD99}
// IMPLEMENT_OLECREATE(<<class>>, <<external_name>>,
// 0x51eee242, 0xad87, 0x11d3, 0x9c, 0x1e, 0x0, 0x90, 0x27, 0x8b, 0xbd, 0x99);
//
// {51EEE242-AD87-11d3-9C1E-0090278BBD99} -- this is the registry format
DEFINE_GUID(CLSID_ShellExtension, 0x51eee242, 0xad87, 0x11d3, 0x9c, 0x1e, 0x0, 0x90, 0x27, 0x8b, 0xbd, 0x99);
// this class factory object creates context menu handlers for windows 32 shell
class CShellExtClassFactory : public IClassFactory
{
protected:
ULONG m_cRef;
public:
CShellExtClassFactory();
~CShellExtClassFactory();
//IUnknown members
STDMETHODIMP QueryInterface(REFIID, LPVOID FAR *);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
//IClassFactory members
STDMETHODIMP CreateInstance(LPUNKNOWN, REFIID, LPVOID FAR *);
STDMETHODIMP LockServer(BOOL);
};
typedef CShellExtClassFactory *LPCSHELLEXTCLASSFACTORY;
#define MAX_HWND 100
// this is the actual OLE Shell context menu handler
class CShellExt : public IContextMenu,
IShellExtInit
{
protected:
ULONG m_cRef;
LPDATAOBJECT m_pDataObj;
UINT m_edit_existing_off;
// For some reason, this callback must be static
static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);
STDMETHODIMP PushToWindow(HWND hParent,
LPCSTR pszWorkingDir,
LPCSTR pszCmd,
LPCSTR pszParam,
int iShowCmd,
int idHWnd);
STDMETHODIMP InvokeGvim(HWND hParent,
LPCSTR pszWorkingDir,
LPCSTR pszCmd,
LPCSTR pszParam,
int iShowCmd);
STDMETHODIMP InvokeSingleGvim(HWND hParent,
LPCSTR pszWorkingDir,
LPCSTR pszCmd,
LPCSTR pszParam,
int iShowCmd,
int useDiff);
public:
int m_cntOfHWnd;
HWND m_hWnd[MAX_HWND];
CShellExt();
~CShellExt();
//IUnknown members
STDMETHODIMP QueryInterface(REFIID, LPVOID FAR *);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
//IShell members
STDMETHODIMP QueryContextMenu(HMENU hMenu,
UINT indexMenu,
UINT idCmdFirst,
UINT idCmdLast,
UINT uFlags);
STDMETHODIMP InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi);
STDMETHODIMP GetCommandString(UINT_PTR idCmd,
UINT uFlags,
UINT FAR *reserved,
LPSTR pszName,
UINT cchMax);
//IShellExtInit methods
STDMETHODIMP Initialize(LPCITEMIDLIST pIDFolder,
LPDATAOBJECT pDataObj,
HKEY hKeyID);
};
typedef CShellExt *LPCSHELLEXT;
#pragma data_seg()
#endif
| zyz2011-vim | src/GvimExt/gvimext.h | C++ | gpl2 | 4,550 |
# Project: gvimext
# Generates gvimext.dll with gcc.
# To be used with MingW.
#
# Originally, the DLL base address was fixed: -Wl,--image-base=0x1C000000
# Now it is allocated dymanically by the linker by evaluating all DLLs
# already loaded in memory. The binary image contains as well information
# for automatic pseudo-rebasing, if needed by the system. ALV 2004-02-29
# If cross-compiling set this to yes, else set it to no
CROSS = no
#CROSS = yes
# For the old MinGW 2.95 (the one you get e.g. with debian woody)
# set the following variable to yes and check if the executables are
# really named that way.
# If you have a newer MinGW or you are using cygwin set it to no and
# check also the executables
MINGWOLD = no
# Link against the shared versions of libgcc/libstdc++ by default. Set
# STATIC_STDCPLUS to "yes" to link against static versions instead.
STATIC_STDCPLUS=no
#STATIC_STDCPLUS=yes
# Note: -static-libstdc++ is not available until gcc 4.5.x.
LDFLAGS += -shared
ifeq (yes, $(STATIC_STDCPLUS))
LDFLAGS += -static-libgcc -static-libstdc++
endif
ifeq ($(CROSS),yes)
DEL = rm
ifeq ($(MINGWOLD),yes)
CXXFLAGS := -O2 -fvtable-thunks
else
CXXFLAGS := -O2
endif
else
CXXFLAGS := -O2
ifneq (sh.exe, $(SHELL))
DEL = rm
else
DEL = del
endif
endif
CXX := $(CROSS_COMPILE)g++
WINDRES := $(CROSS_COMPILE)windres
WINDRES_CXX = $(CXX)
WINDRES_FLAGS = --preprocessor="$(WINDRES_CXX) -E -xc" -DRC_INVOKED
LIBS := -luuid
RES := gvimext.res
DEFFILE = gvimext_ming.def
OBJ := gvimext.o
DLL := gvimext.dll
.PHONY: all all-before all-after clean clean-custom
all: all-before $(DLL) all-after
$(DLL): $(OBJ) $(RES) $(DEFFILE)
$(CXX) $(LDFLAGS) $(CXXFLAGS) -s -o $@ \
-Wl,--enable-auto-image-base \
-Wl,--enable-auto-import \
-Wl,--whole-archive \
$^ \
-Wl,--no-whole-archive \
$(LIBS)
gvimext.o: gvimext.cpp
$(CXX) $(CXXFLAGS) -DFEAT_GETTEXT -c $? -o $@
$(RES): gvimext_ming.rc
$(WINDRES) $(WINDRES_FLAGS) --input-format=rc --output-format=coff -DMING $? -o $@
clean: clean-custom
-$(DEL) $(OBJ) $(RES) $(DLL)
| zyz2011-vim | src/GvimExt/Make_ming.mak | Makefile | gpl2 | 2,041 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by gvimext.rc
//
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| zyz2011-vim | src/GvimExt/resource.h | C | gpl2 | 365 |
# Makefile for GvimExt, using MSVC
# Options:
# DEBUG=yes Build debug version (for VC7 and maybe later)
#
TARGETOS=BOTH
APPVER=4.0
!if "$(DEBUG)" != "yes"
NODEBUG = 1
!endif
!include <win32.mak>
all: gvimext.dll
gvimext.dll: gvimext.obj \
gvimext.res
# $(implib) /NOLOGO -machine:$(CPU) -def:gvimext.def $** -out:gvimext.lib
# $(link) $(dlllflags) -base:0x1C000000 -out:$*.dll $** $(olelibsdll) shell32.lib gvimext.lib comctl32.lib gvimext.exp
$(link) $(lflags) -dll -def:gvimext.def -base:0x1C000000 -out:$*.dll $** $(olelibsdll) shell32.lib comctl32.lib
if exist $*.dll.manifest mt -nologo -manifest $*.dll.manifest -outputresource:$*.dll;2
gvimext.obj: gvimext.h
.cpp.obj:
$(cc) $(cflags) -DFEAT_GETTEXT $(cvarsmt) $*.cpp
gvimext.res: gvimext.rc
$(rc) $(rcflags) $(rcvars) gvimext.rc
clean:
- if exist gvimext.dll del gvimext.dll
- if exist gvimext.lib del gvimext.lib
- if exist gvimext.exp del gvimext.exp
- if exist gvimext.obj del gvimext.obj
- if exist gvimext.res del gvimext.res
- if exist gvimext.dll.manifest del gvimext.dll.manifest
| zyz2011-vim | src/GvimExt/Makefile | Makefile | gpl2 | 1,100 |
# Project: gvimext
# Generates gvimext.dll with gcc.
# To be used with Cygwin.
#
# Originally, the DLL base address was fixed: -Wl,--image-base=0x1C000000
# Now it is allocated dymanically by the linker by evaluating all DLLs
# already loaded in memory. The binary image contains as well information
# for automatic pseudo-rebasing, if needed by the system. ALV 2004-02-29
# If cross-compiling set this to yes, else set it to no
CROSS = no
#CROSS = yes
# For the old MinGW 2.95 (the one you get e.g. with debian woody)
# set the following variable to yes and check if the executables are
# really named that way.
# If you have a newer MinGW or you are using cygwin set it to no and
# check also the executables
MINGWOLD = no
# Link against the shared versions of libgcc/libstdc++ by default. Set
# STATIC_STDCPLUS to "yes" to link against static versions instead.
STATIC_STDCPLUS=no
#STATIC_STDCPLUS=yes
# Note: -static-libstdc++ is not available until gcc 4.5.x.
LDFLAGS += -shared
ifeq (yes, $(STATIC_STDCPLUS))
LDFLAGS += -static-libgcc -static-libstdc++
endif
ifeq ($(CROSS),yes)
DEL = rm
ifeq ($(MINGWOLD),yes)
CXXFLAGS := -O2 -mno-cygwin -fvtable-thunks
else
CXXFLAGS := -O2 -mno-cygwin
endif
else
CXXFLAGS := -O2 -mno-cygwin
ifneq (sh.exe, $(SHELL))
DEL = rm
else
DEL = del
endif
endif
CXX := $(CROSS_COMPILE)g++
WINDRES := $(CROSS_COMPILE)windres
WINDRES_CXX = $(CXX)
WINDRES_FLAGS = --preprocessor="$(WINDRES_CXX) -E -xc" -DRC_INVOKED
LIBS := -luuid
RES := gvimext.res
DEFFILE = gvimext_ming.def
OBJ := gvimext.o
DLL := gvimext.dll
.PHONY: all all-before all-after clean clean-custom
all: all-before $(DLL) all-after
$(DLL): $(OBJ) $(RES) $(DEFFILE)
$(CXX) $(LDFLAGS) $(CXXFLAGS) -s -o $@ \
-Wl,--enable-auto-image-base \
-Wl,--enable-auto-import \
-Wl,--whole-archive \
$^ \
-Wl,--no-whole-archive \
$(LIBS)
gvimext.o: gvimext.cpp
$(CXX) $(CXXFLAGS) -DFEAT_GETTEXT -c $? -o $@
$(RES): gvimext_ming.rc
$(WINDRES) $(WINDRES_FLAGS) --input-format=rc --output-format=coff -DMING $? -o $@
clean: clean-custom
-$(DEL) $(OBJ) $(RES) $(DLL)
| zyz2011-vim | src/GvimExt/Make_cyg.mak | Makefile | gpl2 | 2,078 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved gvimext by Tianmiao Hu
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
*/
/*
* gvimext is a DLL which is used for the "Edit with Vim" context menu
* extension. It implements a MS defined interface with the Shell.
*
* If you have any questions or any suggestions concerning gvimext, please
* contact Tianmiao Hu: tianmiao@acm.org.
*/
#include "gvimext.h"
#ifdef __BORLANDC__
# include <dir.h>
# ifndef _strnicmp
# define _strnicmp(a, b, c) strnicmp((a), (b), (c))
# endif
#else
static char *searchpath(char *name);
#endif
// Always get an error while putting the following stuff to the
// gvimext.h file as class protected variables, give up and
// declare them as global stuff
FORMATETC fmte = {CF_HDROP,
(DVTARGETDEVICE FAR *)NULL,
DVASPECT_CONTENT,
-1,
TYMED_HGLOBAL
};
STGMEDIUM medium;
HRESULT hres = 0;
UINT cbFiles = 0;
/* The buffers size used to be MAX_PATH (256 bytes), but that's not always
* enough */
#define BUFSIZE 1100
//
// Get the name of the Gvim executable to use, with the path.
// When "runtime" is non-zero, we were called to find the runtime directory.
// Returns the path in name[BUFSIZE]. It's empty when it fails.
//
static void
getGvimName(char *name, int runtime)
{
HKEY keyhandle;
DWORD hlen;
// Get the location of gvim from the registry.
name[0] = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
KEY_READ, &keyhandle) == ERROR_SUCCESS)
{
hlen = BUFSIZE;
if (RegQueryValueEx(keyhandle, "path", 0, NULL, (BYTE *)name, &hlen)
!= ERROR_SUCCESS)
name[0] = 0;
else
name[hlen] = 0;
RegCloseKey(keyhandle);
}
// Registry didn't work, use the search path.
if (name[0] == 0)
strcpy(name, searchpath((char *)"gvim.exe"));
if (!runtime)
{
// Only when looking for the executable, not the runtime dir, we can
// search for the batch file or a name without a path.
if (name[0] == 0)
strcpy(name, searchpath((char *)"gvim.bat"));
if (name[0] == 0)
strcpy(name, "gvim"); // finds gvim.bat or gvim.exe
// avoid that Vim tries to expand wildcards in the file names
strcat(name, " --literal");
}
}
static void
getGvimNameW(wchar_t *nameW)
{
char *name;
name = (char *)malloc(BUFSIZE);
getGvimName(name, 0);
mbstowcs(nameW, name, BUFSIZE);
free(name);
}
//
// Get the Vim runtime directory into buf[BUFSIZE].
// The result is empty when it failed.
// When it works, the path ends in a slash or backslash.
//
static void
getRuntimeDir(char *buf)
{
int idx;
getGvimName(buf, 1);
if (buf[0] != 0)
{
// When no path found, use the search path to expand it.
if (strchr(buf, '/') == NULL && strchr(buf, '\\') == NULL)
strcpy(buf, searchpath(buf));
// remove "gvim.exe" from the end
for (idx = (int)strlen(buf) - 1; idx >= 0; idx--)
if (buf[idx] == '\\' || buf[idx] == '/')
{
buf[idx + 1] = 0;
break;
}
}
}
//
// GETTEXT: translated messages and menu entries
//
#ifndef FEAT_GETTEXT
# define _(x) x
#else
# define _(x) (*dyn_libintl_gettext)(x)
# define VIMPACKAGE "vim"
# ifndef GETTEXT_DLL
# define GETTEXT_DLL "libintl.dll"
# endif
// Dummy functions
static char *null_libintl_gettext(const char *);
static char *null_libintl_textdomain(const char *);
static char *null_libintl_bindtextdomain(const char *, const char *);
static int dyn_libintl_init(char *dir);
static void dyn_libintl_end(void);
static wchar_t *oldenv = NULL;
static HINSTANCE hLibintlDLL = 0;
static char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
static char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
static char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
= null_libintl_bindtextdomain;
//
// Attempt to load libintl.dll. If it doesn't work, use dummy functions.
// "dir" is the directory where the libintl.dll might be.
// Return 1 for success, 0 for failure.
//
static int
dyn_libintl_init(char *dir)
{
int i;
static struct
{
char *name;
FARPROC *ptr;
} libintl_entry[] =
{
{(char *)"gettext", (FARPROC*)&dyn_libintl_gettext},
{(char *)"textdomain", (FARPROC*)&dyn_libintl_textdomain},
{(char *)"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
{NULL, NULL}
};
// No need to initialize twice.
if (hLibintlDLL)
return 1;
// Load gettext library, first try the Vim runtime directory, then search
// the path.
strcat(dir, GETTEXT_DLL);
hLibintlDLL = LoadLibrary(dir);
if (!hLibintlDLL)
{
hLibintlDLL = LoadLibrary(GETTEXT_DLL);
if (!hLibintlDLL)
return 0;
}
// Get the addresses of the functions we need.
for (i = 0; libintl_entry[i].name != NULL
&& libintl_entry[i].ptr != NULL; ++i)
{
if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
libintl_entry[i].name)) == NULL)
{
dyn_libintl_end();
return 0;
}
}
return 1;
}
static void
dyn_libintl_end(void)
{
if (hLibintlDLL)
FreeLibrary(hLibintlDLL);
hLibintlDLL = NULL;
dyn_libintl_gettext = null_libintl_gettext;
dyn_libintl_textdomain = null_libintl_textdomain;
dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
}
static char *
null_libintl_gettext(const char *msgid)
{
return (char *)msgid;
}
static char *
null_libintl_bindtextdomain(const char * /* domainname */, const char * /* dirname */)
{
return NULL;
}
static char *
null_libintl_textdomain(const char* /* domainname */)
{
return NULL;
}
//
// Setup for translating strings.
//
static void
dyn_gettext_load(void)
{
char szBuff[BUFSIZE];
char szLang[BUFSIZE];
DWORD len;
HKEY keyhandle;
int gotlang = 0;
strcpy(szLang, "LANG=");
// First try getting the language from the registry, this can be
// used to overrule the system language.
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
KEY_READ, &keyhandle) == ERROR_SUCCESS)
{
len = BUFSIZE;
if (RegQueryValueEx(keyhandle, "lang", 0, NULL, (BYTE*)szBuff, &len)
== ERROR_SUCCESS)
{
szBuff[len] = 0;
strcat(szLang, szBuff);
gotlang = 1;
}
RegCloseKey(keyhandle);
}
if (!gotlang && getenv("LANG") == NULL)
{
// Get the language from the system.
// Could use LOCALE_SISO639LANGNAME, but it's not in Win95.
// LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use
// only the first two.
len = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME,
(LPTSTR)szBuff, BUFSIZE);
if (len >= 2 && _strnicmp(szBuff, "en", 2) != 0)
{
// There are a few exceptions (probably more)
if (_strnicmp(szBuff, "cht", 3) == 0
|| _strnicmp(szBuff, "zht", 3) == 0)
strcpy(szBuff, "zh_TW");
else if (_strnicmp(szBuff, "chs", 3) == 0
|| _strnicmp(szBuff, "zhc", 3) == 0)
strcpy(szBuff, "zh_CN");
else if (_strnicmp(szBuff, "jp", 2) == 0)
strcpy(szBuff, "ja");
else
szBuff[2] = 0; // truncate to two-letter code
strcat(szLang, szBuff);
gotlang = 1;
}
}
if (gotlang)
putenv(szLang);
// Try to locate the runtime files. The path is used to find libintl.dll
// and the vim.mo files.
getRuntimeDir(szBuff);
if (szBuff[0] != 0)
{
len = (DWORD)strlen(szBuff);
if (dyn_libintl_init(szBuff))
{
strcpy(szBuff + len, "lang");
(*dyn_libintl_bindtextdomain)(VIMPACKAGE, szBuff);
(*dyn_libintl_textdomain)(VIMPACKAGE);
}
}
}
static void
dyn_gettext_free(void)
{
dyn_libintl_end();
}
#endif // FEAT_GETTEXT
//
// Global variables
//
UINT g_cRefThisDll = 0; // Reference count of this DLL.
HINSTANCE g_hmodThisDll = NULL; // Handle to this DLL itself.
//---------------------------------------------------------------------------
// DllMain
//---------------------------------------------------------------------------
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /* lpReserved */)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
// Extension DLL one-time initialization
g_hmodThisDll = hInstance;
break;
case DLL_PROCESS_DETACH:
break;
}
return 1; // ok
}
static void
inc_cRefThisDLL()
{
#ifdef FEAT_GETTEXT
if (g_cRefThisDll == 0) {
dyn_gettext_load();
oldenv = GetEnvironmentStringsW();
}
#endif
InterlockedIncrement((LPLONG)&g_cRefThisDll);
}
static void
dec_cRefThisDLL()
{
#ifdef FEAT_GETTEXT
if (InterlockedDecrement((LPLONG)&g_cRefThisDll) == 0) {
dyn_gettext_free();
if (oldenv != NULL) {
FreeEnvironmentStringsW(oldenv);
oldenv = NULL;
}
}
#else
InterlockedDecrement((LPLONG)&g_cRefThisDll);
#endif
}
//---------------------------------------------------------------------------
// DllCanUnloadNow
//---------------------------------------------------------------------------
STDAPI DllCanUnloadNow(void)
{
return (g_cRefThisDll == 0 ? S_OK : S_FALSE);
}
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvOut)
{
*ppvOut = NULL;
if (IsEqualIID(rclsid, CLSID_ShellExtension))
{
CShellExtClassFactory *pcf = new CShellExtClassFactory;
return pcf->QueryInterface(riid, ppvOut);
}
return CLASS_E_CLASSNOTAVAILABLE;
}
CShellExtClassFactory::CShellExtClassFactory()
{
m_cRef = 0L;
inc_cRefThisDLL();
}
CShellExtClassFactory::~CShellExtClassFactory()
{
dec_cRefThisDLL();
}
STDMETHODIMP CShellExtClassFactory::QueryInterface(REFIID riid,
LPVOID FAR *ppv)
{
*ppv = NULL;
// Any interface on this object is the object pointer
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
{
*ppv = (LPCLASSFACTORY)this;
AddRef();
return NOERROR;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CShellExtClassFactory::AddRef()
{
return InterlockedIncrement((LPLONG)&m_cRef);
}
STDMETHODIMP_(ULONG) CShellExtClassFactory::Release()
{
if (InterlockedDecrement((LPLONG)&m_cRef))
return m_cRef;
delete this;
return 0L;
}
STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter,
REFIID riid,
LPVOID *ppvObj)
{
*ppvObj = NULL;
// Shell extensions typically don't support aggregation (inheritance)
if (pUnkOuter)
return CLASS_E_NOAGGREGATION;
// Create the main shell extension object. The shell will then call
// QueryInterface with IID_IShellExtInit--this is how shell extensions are
// initialized.
LPCSHELLEXT pShellExt = new CShellExt(); //Create the CShellExt object
if (NULL == pShellExt)
return E_OUTOFMEMORY;
return pShellExt->QueryInterface(riid, ppvObj);
}
STDMETHODIMP CShellExtClassFactory::LockServer(BOOL /* fLock */)
{
return NOERROR;
}
// *********************** CShellExt *************************
CShellExt::CShellExt()
{
m_cRef = 0L;
m_pDataObj = NULL;
inc_cRefThisDLL();
}
CShellExt::~CShellExt()
{
if (m_pDataObj)
m_pDataObj->Release();
dec_cRefThisDLL();
}
STDMETHODIMP CShellExt::QueryInterface(REFIID riid, LPVOID FAR *ppv)
{
*ppv = NULL;
if (IsEqualIID(riid, IID_IShellExtInit) || IsEqualIID(riid, IID_IUnknown))
{
*ppv = (LPSHELLEXTINIT)this;
}
else if (IsEqualIID(riid, IID_IContextMenu))
{
*ppv = (LPCONTEXTMENU)this;
}
if (*ppv)
{
AddRef();
return NOERROR;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CShellExt::AddRef()
{
return InterlockedIncrement((LPLONG)&m_cRef);
}
STDMETHODIMP_(ULONG) CShellExt::Release()
{
if (InterlockedDecrement((LPLONG)&m_cRef))
return m_cRef;
delete this;
return 0L;
}
//
// FUNCTION: CShellExt::Initialize(LPCITEMIDLIST, LPDATAOBJECT, HKEY)
//
// PURPOSE: Called by the shell when initializing a context menu or property
// sheet extension.
//
// PARAMETERS:
// pIDFolder - Specifies the parent folder
// pDataObj - Spefifies the set of items selected in that folder.
// hRegKey - Specifies the type of the focused item in the selection.
//
// RETURN VALUE:
//
// NOERROR in all cases.
//
// COMMENTS: Note that at the time this function is called, we don't know
// (or care) what type of shell extension is being initialized.
// It could be a context menu or a property sheet.
//
STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST /* pIDFolder */,
LPDATAOBJECT pDataObj,
HKEY /* hRegKey */)
{
// Initialize can be called more than once
if (m_pDataObj)
m_pDataObj->Release();
// duplicate the object pointer and registry handle
if (pDataObj)
{
m_pDataObj = pDataObj;
pDataObj->AddRef();
}
return NOERROR;
}
//
// FUNCTION: CShellExt::QueryContextMenu(HMENU, UINT, UINT, UINT, UINT)
//
// PURPOSE: Called by the shell just before the context menu is displayed.
// This is where you add your specific menu items.
//
// PARAMETERS:
// hMenu - Handle to the context menu
// indexMenu - Index of where to begin inserting menu items
// idCmdFirst - Lowest value for new menu ID's
// idCmtLast - Highest value for new menu ID's
// uFlags - Specifies the context of the menu event
//
// RETURN VALUE:
//
//
// COMMENTS:
//
STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
UINT indexMenu,
UINT idCmdFirst,
UINT /* idCmdLast */,
UINT /* uFlags */)
{
UINT idCmd = idCmdFirst;
hres = m_pDataObj->GetData(&fmte, &medium);
if (medium.hGlobal)
cbFiles = DragQueryFile((HDROP)medium.hGlobal, (UINT)-1, 0, 0);
// InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
// Initialize m_cntOfHWnd to 0
m_cntOfHWnd = 0;
HKEY keyhandle;
bool showExisting = true;
// Check whether "Edit with existing Vim" entries are disabled.
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
KEY_READ, &keyhandle) == ERROR_SUCCESS)
{
if (RegQueryValueEx(keyhandle, "DisableEditWithExisting", 0, NULL,
NULL, NULL) == ERROR_SUCCESS)
showExisting = false;
RegCloseKey(keyhandle);
}
// Retrieve all the vim instances, unless disabled.
if (showExisting)
EnumWindows(EnumWindowsProc, (LPARAM)this);
if (cbFiles > 1)
{
InsertMenu(hMenu,
indexMenu++,
MF_STRING|MF_BYPOSITION,
idCmd++,
_("Edit with &multiple Vims"));
InsertMenu(hMenu,
indexMenu++,
MF_STRING|MF_BYPOSITION,
idCmd++,
_("Edit with single &Vim"));
if (cbFiles <= 4)
{
// Can edit up to 4 files in diff mode
InsertMenu(hMenu,
indexMenu++,
MF_STRING|MF_BYPOSITION,
idCmd++,
_("Diff with Vim"));
m_edit_existing_off = 3;
}
else
m_edit_existing_off = 2;
}
else
{
InsertMenu(hMenu,
indexMenu++,
MF_STRING|MF_BYPOSITION,
idCmd++,
_("Edit with &Vim"));
m_edit_existing_off = 1;
}
// Now display all the vim instances
for (int i = 0; i < m_cntOfHWnd; i++)
{
char title[BUFSIZE];
char temp[BUFSIZE];
// Obtain window title, continue if can not
if (GetWindowText(m_hWnd[i], title, BUFSIZE - 1) == 0)
continue;
// Truncate the title before the path, keep the file name
char *pos = strchr(title, '(');
if (pos != NULL)
{
if (pos > title && pos[-1] == ' ')
--pos;
*pos = 0;
}
// Now concatenate
strncpy(temp, _("Edit with existing Vim - "), BUFSIZE - 1);
temp[BUFSIZE - 1] = '\0';
strncat(temp, title, BUFSIZE - 1 - strlen(temp));
temp[BUFSIZE - 1] = '\0';
InsertMenu(hMenu,
indexMenu++,
MF_STRING|MF_BYPOSITION,
idCmd++,
temp);
}
// InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
// Must return number of menu items we added.
return ResultFromShort(idCmd-idCmdFirst);
}
//
// FUNCTION: CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO)
//
// PURPOSE: Called by the shell after the user has selected on of the
// menu items that was added in QueryContextMenu().
//
// PARAMETERS:
// lpcmi - Pointer to an CMINVOKECOMMANDINFO structure
//
// RETURN VALUE:
//
//
// COMMENTS:
//
STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
{
HRESULT hr = E_INVALIDARG;
// If HIWORD(lpcmi->lpVerb) then we have been called programmatically
// and lpVerb is a command that should be invoked. Otherwise, the shell
// has called us, and LOWORD(lpcmi->lpVerb) is the menu ID the user has
// selected. Actually, it's (menu ID - idCmdFirst) from QueryContextMenu().
if (!HIWORD(lpcmi->lpVerb))
{
UINT idCmd = LOWORD(lpcmi->lpVerb);
if (idCmd >= m_edit_existing_off)
{
// Existing with vim instance
hr = PushToWindow(lpcmi->hwnd,
lpcmi->lpDirectory,
lpcmi->lpVerb,
lpcmi->lpParameters,
lpcmi->nShow,
idCmd - m_edit_existing_off);
}
else
{
switch (idCmd)
{
case 0:
hr = InvokeGvim(lpcmi->hwnd,
lpcmi->lpDirectory,
lpcmi->lpVerb,
lpcmi->lpParameters,
lpcmi->nShow);
break;
case 1:
hr = InvokeSingleGvim(lpcmi->hwnd,
lpcmi->lpDirectory,
lpcmi->lpVerb,
lpcmi->lpParameters,
lpcmi->nShow,
0);
break;
case 2:
hr = InvokeSingleGvim(lpcmi->hwnd,
lpcmi->lpDirectory,
lpcmi->lpVerb,
lpcmi->lpParameters,
lpcmi->nShow,
1);
break;
}
}
}
return hr;
}
STDMETHODIMP CShellExt::PushToWindow(HWND /* hParent */,
LPCSTR /* pszWorkingDir */,
LPCSTR /* pszCmd */,
LPCSTR /* pszParam */,
int /* iShowCmd */,
int idHWnd)
{
HWND hWnd = m_hWnd[idHWnd];
// Show and bring vim instance to foreground
if (IsIconic(hWnd) != 0)
ShowWindow(hWnd, SW_RESTORE);
else
ShowWindow(hWnd, SW_SHOW);
SetForegroundWindow(hWnd);
// Post the selected files to the vim instance
PostMessage(hWnd, WM_DROPFILES, (WPARAM)medium.hGlobal, 0);
return NOERROR;
}
STDMETHODIMP CShellExt::GetCommandString(UINT_PTR /* idCmd */,
UINT uFlags,
UINT FAR * /* reserved */,
LPSTR pszName,
UINT cchMax)
{
if (uFlags == GCS_HELPTEXT && cchMax > 35)
lstrcpy(pszName, _("Edits the selected file(s) with Vim"));
return NOERROR;
}
BOOL CALLBACK CShellExt::EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
char temp[BUFSIZE];
// First do a bunch of check
// No invisible window
if (!IsWindowVisible(hWnd)) return TRUE;
// No child window ???
// if (GetParent(hWnd)) return TRUE;
// Class name should be Vim, if failed to get class name, return
if (GetClassName(hWnd, temp, sizeof(temp)) == 0)
return TRUE;
// Compare class name to that of vim, if not, return
if (_strnicmp(temp, "vim", sizeof("vim")) != 0)
return TRUE;
// First check if the number of vim instance exceeds MAX_HWND
CShellExt *cs = (CShellExt*) lParam;
if (cs->m_cntOfHWnd >= MAX_HWND) return TRUE;
// Now we get the vim window, put it into some kind of array
cs->m_hWnd[cs->m_cntOfHWnd] = hWnd;
cs->m_cntOfHWnd ++;
return TRUE; // continue enumeration (otherwise this would be false)
}
#ifdef WIN32
// 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
static DWORD g_PlatformId;
//
// Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
// VER_PLATFORM_WIN32_WINDOWS (Win95).
//
static void
PlatformId(void)
{
static int done = FALSE;
if (!done)
{
OSVERSIONINFO ovi;
ovi.dwOSVersionInfoSize = sizeof(ovi);
GetVersionEx(&ovi);
g_PlatformId = ovi.dwPlatformId;
done = TRUE;
}
}
# ifndef __BORLANDC__
static char *
searchpath(char *name)
{
static char widename[2 * BUFSIZE];
static char location[2 * BUFSIZE + 2];
// There appears to be a bug in FindExecutableA() on Windows NT.
// Use FindExecutableW() instead...
PlatformId();
if (g_PlatformId == VER_PLATFORM_WIN32_NT)
{
MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)name, -1,
(LPWSTR)widename, BUFSIZE);
if (FindExecutableW((LPCWSTR)widename, (LPCWSTR)"",
(LPWSTR)location) > (HINSTANCE)32)
{
WideCharToMultiByte(CP_ACP, 0, (LPWSTR)location, -1,
(LPSTR)widename, 2 * BUFSIZE, NULL, NULL);
return widename;
}
}
else
{
if (FindExecutableA((LPCTSTR)name, (LPCTSTR)"",
(LPTSTR)location) > (HINSTANCE)32)
return location;
}
return (char *)"";
}
# endif
#endif
STDMETHODIMP CShellExt::InvokeGvim(HWND hParent,
LPCSTR /* pszWorkingDir */,
LPCSTR /* pszCmd */,
LPCSTR /* pszParam */,
int /* iShowCmd */)
{
wchar_t m_szFileUserClickedOn[BUFSIZE];
wchar_t cmdStrW[BUFSIZE];
UINT i;
for (i = 0; i < cbFiles; i++)
{
DragQueryFileW((HDROP)medium.hGlobal,
i,
m_szFileUserClickedOn,
sizeof(m_szFileUserClickedOn));
getGvimNameW(cmdStrW);
wcscat(cmdStrW, L" \"");
if ((wcslen(cmdStrW) + wcslen(m_szFileUserClickedOn) + 2) < BUFSIZE)
{
wcscat(cmdStrW, m_szFileUserClickedOn);
wcscat(cmdStrW, L"\"");
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
// Start the child process.
if (!CreateProcessW(NULL, // No module name (use command line).
cmdStrW, // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
oldenv == NULL ? 0 : CREATE_UNICODE_ENVIRONMENT,
oldenv, // Use unmodified environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi) // Pointer to PROCESS_INFORMATION structure.
)
{
MessageBox(
hParent,
_("Error creating process: Check if gvim is in your path!"),
_("gvimext.dll error"),
MB_OK);
}
else
{
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
}
else
{
MessageBox(
hParent,
_("Path length too long!"),
_("gvimext.dll error"),
MB_OK);
}
}
return NOERROR;
}
STDMETHODIMP CShellExt::InvokeSingleGvim(HWND hParent,
LPCSTR /* pszWorkingDir */,
LPCSTR /* pszCmd */,
LPCSTR /* pszParam */,
int /* iShowCmd */,
int useDiff)
{
wchar_t m_szFileUserClickedOn[BUFSIZE];
wchar_t *cmdStrW;
size_t cmdlen;
size_t len;
UINT i;
cmdlen = BUFSIZE;
cmdStrW = (wchar_t *) malloc(cmdlen * sizeof(wchar_t));
getGvimNameW(cmdStrW);
if (useDiff)
wcscat(cmdStrW, L" -d");
for (i = 0; i < cbFiles; i++)
{
DragQueryFileW((HDROP)medium.hGlobal,
i,
m_szFileUserClickedOn,
sizeof(m_szFileUserClickedOn));
len = wcslen(cmdStrW) + wcslen(m_szFileUserClickedOn) + 4;
if (len > cmdlen)
{
cmdlen = len + BUFSIZE;
cmdStrW = (wchar_t *)realloc(cmdStrW, cmdlen * sizeof(wchar_t));
}
wcscat(cmdStrW, L" \"");
wcscat(cmdStrW, m_szFileUserClickedOn);
wcscat(cmdStrW, L"\"");
}
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
// Start the child process.
if (!CreateProcessW(NULL, // No module name (use command line).
cmdStrW, // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
oldenv == NULL ? 0 : CREATE_UNICODE_ENVIRONMENT,
oldenv, // Use unmodified environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi) // Pointer to PROCESS_INFORMATION structure.
)
{
MessageBox(
hParent,
_("Error creating process: Check if gvim is in your path!"),
_("gvimext.dll error"),
MB_OK);
}
else
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
free(cmdStrW);
return NOERROR;
}
| zyz2011-vim | src/GvimExt/gvimext.cpp | C++ | gpl2 | 23,997 |
rundll32.exe setupapi,InstallHinfSection DefaultUninstall 128 %1
| zyz2011-vim | src/GvimExt/uninst.bat | Batchfile | gpl2 | 65 |
/* 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.
*/
/*
* dosinst.h: Common code for dosinst.c and uninstal.c
*/
/* Visual Studio 2005 has 'deprecated' many of the standard CRT functions */
#if _MSC_VER >= 1400
# define _CRT_SECURE_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef UNIX_LINT
# include "vimio.h"
# include <ctype.h>
# ifndef __CYGWIN__
# include <direct.h>
# endif
# if defined(_WIN64) || defined(WIN32)
# define WIN3264
# include <windows.h>
# include <shlobj.h>
# else
# include <dir.h>
# include <bios.h>
# include <dos.h>
# endif
#endif
#ifdef UNIX_LINT
/* Running lint on Unix: Some things are missing. */
char *searchpath(char *name);
#endif
#if defined(DJGPP) || defined(UNIX_LINT)
# include <unistd.h>
# include <errno.h>
#endif
#include "version.h"
#if defined(DJGPP) || defined(UNIX_LINT)
# define vim_mkdir(x, y) mkdir((char *)(x), y)
#else
# if defined(WIN3264) && !defined(__BORLANDC__)
# define vim_mkdir(x, y) _mkdir((char *)(x))
# else
# define vim_mkdir(x, y) mkdir((char *)(x))
# endif
#endif
#ifndef DJGPP
# define sleep(n) Sleep((n) * 1000)
#endif
/* ---------------------------------------- */
#define BUFSIZE 512 /* long enough to hold a file name path */
#define NUL 0
#define FAIL 0
#define OK 1
#ifndef FALSE
# define FALSE 0
#endif
#ifndef TRUE
# define TRUE 1
#endif
/*
* Modern way of creating registry entries, also works on 64 bit windows when
* compiled as a 32 bit program.
*/
# ifndef KEY_WOW64_64KEY
# define KEY_WOW64_64KEY 0x0100
# endif
#define VIM_STARTMENU "Programs\\Vim " VIM_VERSION_SHORT
int interactive; /* non-zero when running interactively */
/*
* Call malloc() and exit when out of memory.
*/
static void *
alloc(int len)
{
char *s;
s = malloc(len);
if (s == NULL)
{
printf("ERROR: out of memory\n");
exit(1);
}
return (void *)s;
}
/*
* The toupper() in Bcc 5.5 doesn't work, use our own implementation.
*/
static int
mytoupper(int c)
{
if (c >= 'a' && c <= 'z')
return c - 'a' + 'A';
return c;
}
static void
myexit(int n)
{
if (!interactive)
{
/* Present a prompt, otherwise error messages can't be read. */
printf("Press Enter to continue\n");
rewind(stdin);
(void)getchar();
}
exit(n);
}
#ifdef WIN3264
/* 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
static DWORD g_PlatformId;
/*
* Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
* VER_PLATFORM_WIN32_WINDOWS (Win95).
*/
static void
PlatformId(void)
{
static int done = FALSE;
if (!done)
{
OSVERSIONINFO ovi;
ovi.dwOSVersionInfoSize = sizeof(ovi);
GetVersionEx(&ovi);
g_PlatformId = ovi.dwPlatformId;
done = TRUE;
}
}
# ifdef __BORLANDC__
/* Borland defines its own searchpath() in dir.h */
# include <dir.h>
# else
static char *
searchpath(char *name)
{
static char widename[2 * BUFSIZE];
static char location[2 * BUFSIZE + 2];
/* There appears to be a bug in FindExecutableA() on Windows NT.
* Use FindExecutableW() instead... */
PlatformId();
if (g_PlatformId == VER_PLATFORM_WIN32_NT)
{
MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)name, -1,
(LPWSTR)widename, BUFSIZE);
if (FindExecutableW((LPCWSTR)widename, (LPCWSTR)"",
(LPWSTR)location) > (HINSTANCE)32)
{
WideCharToMultiByte(CP_ACP, 0, (LPWSTR)location, -1,
(LPSTR)widename, 2 * BUFSIZE, NULL, NULL);
return widename;
}
}
else
{
if (FindExecutableA((LPCTSTR)name, (LPCTSTR)"",
(LPTSTR)location) > (HINSTANCE)32)
return location;
}
return NULL;
}
# endif
#endif
/*
* Call searchpath() and save the result in allocated memory, or return NULL.
*/
static char *
searchpath_save(char *name)
{
char *p;
char *s;
p = searchpath(name);
if (p == NULL)
return NULL;
s = alloc(strlen(p) + 1);
strcpy(s, p);
return s;
}
#ifdef WIN3264
#ifndef CSIDL_COMMON_PROGRAMS
# define CSIDL_COMMON_PROGRAMS 0x0017
#endif
#ifndef CSIDL_COMMON_DESKTOPDIRECTORY
# define CSIDL_COMMON_DESKTOPDIRECTORY 0x0019
#endif
/*
* Get the path to a requested Windows shell folder.
*
* Return FAIL on error, OK on success
*/
int
get_shell_folder_path(
char *shell_folder_path,
const char *shell_folder_name)
{
/*
* The following code was successfully built with make_mvc.mak.
* The resulting executable worked on Windows 95, Millennium Edition, and
* 2000 Professional. But it was changed after testing...
*/
LPITEMIDLIST pidl = 0; /* Pointer to an Item ID list allocated below */
LPMALLOC pMalloc; /* Pointer to an IMalloc interface */
int csidl;
int alt_csidl = -1;
static int desktop_csidl = -1;
static int programs_csidl = -1;
int *pcsidl;
int r;
if (strcmp(shell_folder_name, "desktop") == 0)
{
pcsidl = &desktop_csidl;
csidl = CSIDL_COMMON_DESKTOPDIRECTORY;
alt_csidl = CSIDL_DESKTOP;
}
else if (strncmp(shell_folder_name, "Programs", 8) == 0)
{
pcsidl = &programs_csidl;
csidl = CSIDL_COMMON_PROGRAMS;
alt_csidl = CSIDL_PROGRAMS;
}
else
{
printf("\nERROR (internal) unrecognised shell_folder_name: \"%s\"\n\n",
shell_folder_name);
return FAIL;
}
/* Did this stuff before, use the same ID again. */
if (*pcsidl >= 0)
{
csidl = *pcsidl;
alt_csidl = -1;
}
retry:
/* Initialize pointer to IMalloc interface */
if (NOERROR != SHGetMalloc(&pMalloc))
{
printf("\nERROR getting interface for shell_folder_name: \"%s\"\n\n",
shell_folder_name);
return FAIL;
}
/* Get an ITEMIDLIST corresponding to the folder code */
if (NOERROR != SHGetSpecialFolderLocation(0, csidl, &pidl))
{
if (alt_csidl < 0 || NOERROR != SHGetSpecialFolderLocation(0,
alt_csidl, &pidl))
{
printf("\nERROR getting ITEMIDLIST for shell_folder_name: \"%s\"\n\n",
shell_folder_name);
return FAIL;
}
csidl = alt_csidl;
alt_csidl = -1;
}
/* Translate that ITEMIDLIST to a string */
r = SHGetPathFromIDList(pidl, shell_folder_path);
/* Free the data associated with pidl */
pMalloc->lpVtbl->Free(pMalloc, pidl);
/* Release the IMalloc interface */
pMalloc->lpVtbl->Release(pMalloc);
if (!r)
{
if (alt_csidl >= 0)
{
/* We probably get here for Windows 95: the "all users"
* desktop/start menu entry doesn't exist. */
csidl = alt_csidl;
alt_csidl = -1;
goto retry;
}
printf("\nERROR translating ITEMIDLIST for shell_folder_name: \"%s\"\n\n",
shell_folder_name);
return FAIL;
}
/* If there is an alternative: verify we can write in this directory.
* This should cause a retry when the "all users" directory exists but we
* are a normal user and can't write there. */
if (alt_csidl >= 0)
{
char tbuf[BUFSIZE];
FILE *fd;
strcpy(tbuf, shell_folder_path);
strcat(tbuf, "\\vim write test");
fd = fopen(tbuf, "w");
if (fd == NULL)
{
csidl = alt_csidl;
alt_csidl = -1;
goto retry;
}
fclose(fd);
unlink(tbuf);
}
/*
* Keep the found csidl for next time, so that we don't have to do the
* write test every time.
*/
if (*pcsidl < 0)
*pcsidl = csidl;
if (strncmp(shell_folder_name, "Programs\\", 9) == 0)
strcat(shell_folder_path, shell_folder_name + 8);
return OK;
}
#endif
/*
* List of targets. The first one (index zero) is used for the default path
* for the batch files.
*/
#define TARGET_COUNT 9
struct
{
char *name; /* Vim exe name (without .exe) */
char *batname; /* batch file name */
char *lnkname; /* shortcut file name */
char *exename; /* exe file name */
char *exenamearg; /* exe file name when using exearg */
char *exearg; /* argument for vim.exe or gvim.exe */
char *oldbat; /* path to existing xxx.bat or NULL */
char *oldexe; /* path to existing xxx.exe or NULL */
char batpath[BUFSIZE]; /* path of batch file to create; not
created when it's empty */
} targets[TARGET_COUNT] =
{
{"all", "batch files"},
{"vim", "vim.bat", "Vim.lnk",
"vim.exe", "vim.exe", ""},
{"gvim", "gvim.bat", "gVim.lnk",
"gvim.exe", "gvim.exe", ""},
{"evim", "evim.bat", "gVim Easy.lnk",
"evim.exe", "gvim.exe", "-y"},
{"view", "view.bat", "Vim Read-only.lnk",
"view.exe", "vim.exe", "-R"},
{"gview", "gview.bat", "gVim Read-only.lnk",
"gview.exe", "gvim.exe", "-R"},
{"vimdiff", "vimdiff.bat", "Vim Diff.lnk",
"vimdiff.exe","vim.exe", "-d"},
{"gvimdiff","gvimdiff.bat", "gVim Diff.lnk",
"gvimdiff.exe","gvim.exe", "-d"},
{"vimtutor","vimtutor.bat", "Vim tutor.lnk",
"vimtutor.bat", "vimtutor.bat", ""},
};
#define ICON_COUNT 3
char *(icon_names[ICON_COUNT]) =
{"gVim " VIM_VERSION_SHORT,
"gVim Easy " VIM_VERSION_SHORT,
"gVim Read only " VIM_VERSION_SHORT};
char *(icon_link_names[ICON_COUNT]) =
{"gVim " VIM_VERSION_SHORT ".lnk",
"gVim Easy " VIM_VERSION_SHORT ".lnk",
"gVim Read only " VIM_VERSION_SHORT ".lnk"};
/* This is only used for dosinst.c when WIN3264 is defined and for uninstal.c
* when not being able to directly access registry entries. */
#if (defined(DOSINST) && defined(WIN3264)) \
|| (!defined(DOSINST) && !defined(WIN3264))
/*
* Run an external command and wait for it to finish.
*/
static void
run_command(char *cmd)
{
char *cmd_path;
char cmd_buf[BUFSIZE];
char *p;
/* On WinNT, 'start' is a shell built-in for cmd.exe rather than an
* executable (start.exe) like in Win9x. DJGPP, being a DOS program,
* is given the COMSPEC command.com by WinNT, so we have to find
* cmd.exe manually and use it. */
cmd_path = searchpath_save("cmd.exe");
if (cmd_path != NULL)
{
/* There is a cmd.exe, so this might be Windows NT. If it is,
* we need to call cmd.exe explicitly. If it is a later OS,
* calling cmd.exe won't hurt if it is present.
* Also, "start" on NT expects a window title argument.
*/
/* Replace the slashes with backslashes. */
while ((p = strchr(cmd_path, '/')) != NULL)
*p = '\\';
sprintf(cmd_buf, "%s /c start \"vimcmd\" /wait %s", cmd_path, cmd);
free(cmd_path);
}
else
{
/* No cmd.exe, just make the call and let the system handle it. */
sprintf(cmd_buf, "start /w %s", cmd);
}
system(cmd_buf);
}
#endif
/*
* Append a backslash to "name" if there isn't one yet.
*/
static void
add_pathsep(char *name)
{
int len = strlen(name);
if (len > 0 && name[len - 1] != '\\' && name[len - 1] != '/')
strcat(name, "\\");
}
/*
* The normal chdir() does not change the default drive. This one does.
*/
/*ARGSUSED*/
int
change_drive(int drive)
{
#ifdef WIN3264
char temp[3] = "-:";
temp[0] = (char)(drive + 'A' - 1);
return !SetCurrentDirectory(temp);
#else
# ifndef UNIX_LINT
union REGS regs;
regs.h.ah = 0x0e;
regs.h.dl = drive - 1;
intdos(®s, ®s); /* set default drive */
regs.h.ah = 0x19;
intdos(®s, ®s); /* get default drive */
if (regs.h.al == drive - 1)
return 0;
# endif
return -1;
#endif
}
/*
* Change directory to "path".
* Return 0 for success, -1 for failure.
*/
int
mch_chdir(char *path)
{
if (path[0] == NUL) /* just checking... */
return 0;
if (path[1] == ':') /* has a drive name */
{
if (change_drive(mytoupper(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 */
}
/*
* Expand the executable name into a full path name.
*/
#if defined(__BORLANDC__) && !defined(WIN3264)
/* Only Borland C++ has this. */
# define my_fullpath(b, n, l) _fullpath(b, n, l)
#else
static char *
my_fullpath(char *buf, char *fname, int len)
{
# ifdef WIN3264
/* Only GetModuleFileName() will get the long file name path.
* GetFullPathName() may still use the short (FAT) name. */
DWORD len_read = GetModuleFileName(NULL, buf, (size_t)len);
return (len_read > 0 && len_read < (DWORD)len) ? buf : NULL;
# else
char olddir[BUFSIZE];
char *p, *q;
int c;
char *retval = buf;
if (strchr(fname, ':') != NULL) /* already expanded */
{
strncpy(buf, fname, len);
}
else
{
*buf = NUL;
/*
* 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 = strrchr(fname, '/');
q = strrchr(fname, '\\');
if (q != NULL && (p == NULL || q > p))
p = q;
q = strrchr(fname, ':');
if (q != NULL && (p == NULL || q > p))
p = q;
if (p != NULL)
{
if (getcwd(olddir, BUFSIZE) == NULL)
{
p = NULL; /* can't get current dir: don't chdir */
retval = NULL;
}
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;
if (mch_chdir(fname)) /* change to the directory */
retval = NULL;
else
{
fname = q;
if (c == '\\') /* if we cut the name at a */
fname++; /* '\', don't add it again */
}
*q = c;
}
}
if (getcwd(buf, len) == NULL)
{
retval = NULL;
*buf = NUL;
}
/*
* Concatenate the file name to the path.
*/
if (strlen(buf) + strlen(fname) >= len - 1)
{
printf("ERROR: File name too long!\n");
myexit(1);
}
add_pathsep(buf);
strcat(buf, fname);
if (p)
mch_chdir(olddir);
}
/* Replace forward slashes with backslashes, required for the path to a
* command. */
while ((p = strchr(buf, '/')) != NULL)
*p = '\\';
return retval;
# endif
}
#endif
/*
* Remove the tail from a file or directory name.
* Puts a NUL on the last '/' or '\'.
*/
static void
remove_tail(char *path)
{
int i;
for (i = strlen(path) - 1; i > 0; --i)
if (path[i] == '/' || path[i] == '\\')
{
path[i] = NUL;
break;
}
}
char installdir[BUFSIZE]; /* top of the installation dir, where the
install.exe is located, E.g.:
"c:\vim\vim60" */
int runtimeidx; /* index in installdir[] where "vim60" starts */
char *sysdrive; /* system drive or "c:\" */
/*
* Setup for using this program.
* Sets "installdir[]".
*/
static void
do_inits(char **argv)
{
#ifdef DJGPP
/*
* Use Long File Names by default, if $LFN not set.
*/
if (getenv("LFN") == NULL)
putenv("LFN=y");
#endif
/* Find out the full path of our executable. */
if (my_fullpath(installdir, argv[0], BUFSIZE) == NULL)
{
printf("ERROR: Cannot get name of executable\n");
myexit(1);
}
/* remove the tail, the executable name "install.exe" */
remove_tail(installdir);
/* change to the installdir */
mch_chdir(installdir);
/* Find the system drive. Only used for searching the Vim executable, not
* very important. */
sysdrive = getenv("SYSTEMDRIVE");
if (sysdrive == NULL || *sysdrive == NUL)
sysdrive = "C:\\";
}
| zyz2011-vim | src/dosinst.h | C | gpl2 | 15,602 |
#
# Makefile for VIM on Win32, using Cygnus gcc
# Last updated by Dan Sharp. Last Change: 2010 Nov 03
#
# Also read INSTALLpc.txt!
#
# This compiles Vim as a Windows application. If you want Vim to run as a
# Cygwin application use the Makefile (just like on Unix).
#
# GUI no or yes: set to yes if you want the GUI version (yes)
# PERL define to path to Perl dir to get Perl support (not defined)
# PERL_VER define to version of Perl being used (56)
# DYNAMIC_PERL no or yes: set to yes to load the Perl DLL dynamically (yes)
# PYTHON define to path to Python dir to get PYTHON support (not defined)
# PYTHON_VER define to version of Python being used (22)
# DYNAMIC_PYTHON no or yes: use yes to load the Python DLL dynamically (yes)
# PYTHON3 define to path to Python3 dir to get PYTHON3 support (not defined)
# PYTHON3_VER define to version of Python3 being used (22)
# DYNAMIC_PYTHON3 no or yes: use yes to load the Python3 DLL dynamically (yes)
# TCL define to path to TCL dir to get TCL support (not defined)
# TCL_VER define to version of TCL being used (83)
# DYNAMIC_TCL no or yes: use yes to load the TCL DLL dynamically (yes)
# RUBY define to path to Ruby dir to get Ruby support (not defined)
# RUBY_VER define to version of Ruby being used (16)
# DYNAMIC_RUBY no or yes: use yes to load the Ruby DLL dynamically (yes)
# MZSCHEME define to path to MzScheme dir to get MZSCHEME support (not defined)
# MZSCHEME_VER define to version of MzScheme being used (209_000)
# DYNAMIC_MZSCHEME no or yes: use yes to load the MzScheme DLLs dynamically (yes)
# MZSCHEME_DLLS path to MzScheme DLLs (libmzgc and libmzsch), for "static" build.
# MZSCHEME_USE_RACKET define to use "racket" instead of "mzsch".
# LUA define to path to Lua dir to get Lua support (not defined)
# LUA_VER define to version of Lua being used (51)
# DYNAMIC_LUA no or yes: use yes to load the Lua DLL dynamically (yes)
# GETTEXT no or yes: set to yes for dynamic gettext support (yes)
# ICONV no or yes: set to yes for dynamic iconv support (yes)
# MBYTE no or yes: set to yes to include multibyte support (yes)
# IME no or yes: set to yes to include IME support (yes)
# DYNAMIC_IME no or yes: set to yes to load imm32.dll dynamically (yes)
# OLE no or yes: set to yes to make OLE gvim (no)
# DEBUG no or yes: set to yes if you wish a DEBUGging build (no)
# CPUNR No longer supported, use ARCH.
# ARCH i386 through pentium4: select -march argument to compile with
# (i386)
# USEDLL no or yes: set to yes to use the Runtime library DLL (no)
# For USEDLL=yes the cygwin1.dll is required to run Vim.
# "no" does not work with latest version of Cygwin, use
# Make_ming.mak instead. Or set CC to gcc-3 and add
# -L/lib/w32api to EXTRA_LIBS.
# POSTSCRIPT no or yes: set to yes for PostScript printing (no)
# FEATURES TINY, SMALL, NORMAL, BIG or HUGE (BIG)
# WINVER Lowest Win32 version to support. (0x0400)
# CSCOPE no or yes: to include cscope interface support (yes)
# OPTIMIZE SPACE, SPEED, or MAXSPEED: set optimization level (MAXSPEED)
# NETBEANS no or yes: to include netbeans interface support (yes when GUI
# is yes)
# NBDEBUG no or yes: to include netbeans interface debugging support (no)
# XPM define to path to XPM dir to get XPM image support (not defined)
#>>>>> choose options:
ifndef GUI
GUI=yes
endif
ifndef FEATURES
FEATURES = BIG
endif
ifndef GETTEXT
GETTEXT = yes
endif
ifndef ICONV
ICONV = yes
endif
ifndef MBYTE
MBYTE = yes
endif
ifndef IME
IME = yes
endif
ifndef ARCH
ARCH = i386
endif
ifndef WINVER
WINVER = 0x0400
endif
ifndef CSCOPE
CSCOPE = yes
endif
ifndef NETBEANS
ifeq ($(GUI),yes)
NETBEANS = yes
endif
endif
ifndef OPTIMIZE
OPTIMIZE = MAXSPEED
endif
### See feature.h for a list of optionals.
### Any other defines can be included here.
DEFINES = -DWIN32 -DHAVE_PATHDEF -DFEAT_$(FEATURES) \
-DWINVER=$(WINVER) -D_WIN32_WINNT=$(WINVER)
INCLUDES = -march=$(ARCH) -Iproto
#>>>>> name of the compiler and linker, name of lib directory
CROSS_COMPILE =
CC = gcc
RC = windres
##############################
# DYNAMIC_PERL=yes and no both work
##############################
ifdef PERL
DEFINES += -DFEAT_PERL
INCLUDES += -I$(PERL)/lib/CORE
EXTRA_OBJS += $(OUTDIR)/if_perl.o
ifndef DYNAMIC_PERL
DYNAMIC_PERL = yes
endif
ifndef PERL_VER
PERL_VER = 56
endif
ifeq (yes, $(DYNAMIC_PERL))
DEFINES += -DDYNAMIC_PERL -DDYNAMIC_PERL_DLL=\"perl$(PERL_VER).dll\"
else
EXTRA_LIBS += $(PERL)/lib/CORE/perl$(PERL_VER).lib
endif
endif
##############################
# DYNAMIC_PYTHON=yes works.
# DYNAMIC_PYTHON=no does not (unresolved externals on link).
##############################
ifdef PYTHON
DEFINES += -DFEAT_PYTHON
EXTRA_OBJS += $(OUTDIR)/if_python.o
ifndef DYNAMIC_PYTHON
DYNAMIC_PYTHON = yes
endif
ifndef PYTHON_VER
PYTHON_VER = 22
endif
ifeq (yes, $(DYNAMIC_PYTHON))
DEFINES += -DDYNAMIC_PYTHON -DDYNAMIC_PYTHON_DLL=\"python$(PYTHON_VER).dll\"
else
EXTRA_LIBS += $(PYTHON)/libs/python$(PYTHON_VER).lib
endif
endif
##############################
# DYNAMIC_PYTHON3=yes works.
# DYNAMIC_PYTHON3=no does not (unresolved externals on link).
##############################
ifdef PYTHON3
DEFINES += -DFEAT_PYTHON3
EXTRA_OBJS += $(OUTDIR)/if_python3.o
ifndef DYNAMIC_PYTHON3
DYNAMIC_PYTHON3 = yes
endif
ifndef PYTHON3_VER
PYTHON3_VER = 31
endif
ifeq (yes, $(DYNAMIC_PYTHON3))
DEFINES += -DDYNAMIC_PYTHON3 -DDYNAMIC_PYTHON3_DLL=\"python$(PYTHON3_VER).dll\"
else
EXTRA_LIBS += $(PYTHON3)/libs/python$(PYTHON3_VER).lib
endif
endif
##############################
# DYNAMIC_RUBY=yes works.
# DYNAMIC_RUBY=no does not (process exits).
##############################
ifdef RUBY
ifndef RUBY_VER
RUBY_VER=16
endif
ifndef RUBY_VER_LONG
RUBY_VER_LONG=1.6
endif
ifndef DYNAMIC_RUBY
DYNAMIC_RUBY = yes
endif
ifeq ($(RUBY_VER), 16)
ifndef RUBY_PLATFORM
RUBY_PLATFORM = i586-mswin32
endif
ifndef RUBY_INSTALL_NAME
RUBY_INSTALL_NAME = mswin32-ruby$(RUBY_VER)
endif
else
ifndef RUBY_PLATFORM
RUBY_PLATFORM = i386-mswin32
endif
ifndef RUBY_INSTALL_NAME
RUBY_INSTALL_NAME = msvcrt-ruby$(RUBY_VER)
endif
endif
DEFINES += -DFEAT_RUBY
INCLUDES += -I$(RUBY)/lib/ruby/$(RUBY_VER_LONG)/$(RUBY_PLATFORM)
EXTRA_OBJS += $(OUTDIR)/if_ruby.o
ifeq (yes, $(DYNAMIC_RUBY))
DEFINES += -DDYNAMIC_RUBY -DDYNAMIC_RUBY_DLL=\"$(RUBY_INSTALL_NAME).dll\"
DEFINES += -DDYNAMIC_RUBY_VER=$(RUBY_VER)
else
EXTRA_LIBS += $(RUBY)/lib/$(RUBY_INSTALL_NAME).lib
endif
endif
##############################
# DYNAMIC_MZSCHEME=yes works
# DYNAMIC_MZSCHEME=no works too
##############################
ifdef MZSCHEME
DEFINES += -DFEAT_MZSCHEME
INCLUDES += -I$(MZSCHEME)/include
EXTRA_OBJS += $(OUTDIR)/if_mzsch.o
ifndef DYNAMIC_MZSCHEME
DYNAMIC_MZSCHEME = yes
endif
ifndef MZSCHEME_VER
MZSCHEME_VER = 209_000
endif
ifndef MZSCHEME_PRECISE_GC
MZSCHEME_PRECISE_GC=no
endif
# for version 4.x we need to generate byte-code for Scheme base
ifndef MZSCHEME_GENERATE_BASE
MZSCHEME_GENERATE_BASE=no
endif
ifndef MZSCHEME_USE_RACKET
MZSCHEME_MAIN_LIB=mzsch
else
MZSCHEME_MAIN_LIB=racket
endif
ifeq (yes, $(DYNAMIC_MZSCHEME))
DEFINES += -DDYNAMIC_MZSCHEME -DDYNAMIC_MZSCH_DLL=\"lib$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER).dll\" -DDYNAMIC_MZGC_DLL=\"libmzgc$(MZSCHEME_VER).dll\"
else
ifndef MZSCHEME_DLLS
MZSCHEME_DLLS = $(MZSCHEME)
endif
ifeq (yes,$(MZSCHEME_PRECISE_GC))
MZSCHEME_LIB=-l$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER)
else
MZSCHEME_LIB = -l$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER) -lmzgc$(MZSCHEME_VER)
endif
EXTRA_LIBS += -L$(MZSCHEME_DLLS) -L$(MZSCHEME_DLLS)/lib $(MZSCHEME_LIB)
endif
ifeq (yes,$(MZSCHEME_GENERATE_BASE))
DEFINES += -DINCLUDE_MZSCHEME_BASE
MZ_EXTRA_DEP += mzscheme_base.c
endif
ifeq (yes,$(MZSCHEME_PRECISE_GC))
DEFINES += -DMZ_PRECISE_GC
endif
endif
##############################
# DYNAMIC_TCL=yes and no both work.
##############################
ifdef TCL
DEFINES += -DFEAT_TCL
INCLUDES += -I$(TCL)/include
EXTRA_OBJS += $(OUTDIR)/if_tcl.o
ifndef DYNAMIC_TCL
DYNAMIC_TCL = yes
endif
ifndef TCL_VER
TCL_VER = 83
endif
ifeq (yes, $(DYNAMIC_TCL))
DEFINES += -DDYNAMIC_TCL -DDYNAMIC_TCL_DLL=\"tcl$(TCL_VER).dll\"
EXTRA_LIBS += $(TCL)/lib/tclstub$(TCL_VER).lib
else
EXTRA_LIBS += $(TCL)/lib/tcl$(TCL_VER).lib
endif
endif
##############################
# DYNAMIC_LUA=yes works.
# DYNAMIC_LUA=no does not (unresolved externals on link).
##############################
ifdef LUA
DEFINES += -DFEAT_LUA
INCLUDES += -I$(LUA)/include
EXTRA_OBJS += $(OUTDIR)/if_lua.o
ifndef DYNAMIC_LUA
DYNAMIC_LUA = yes
endif
ifndef LUA_VER
LUA_VER = 51
endif
ifeq (yes, $(DYNAMIC_LUA))
DEFINES += -DDYNAMIC_LUA -DDYNAMIC_LUA_DLL=\"lua$(LUA_VER).dll\"
else
EXTRA_LIBS += $(LUA)/lib/lua$(LUA_VER).lib
endif
endif
##############################
ifeq (yes, $(GETTEXT))
DEFINES += -DDYNAMIC_GETTEXT
endif
##############################
ifeq (yes, $(ICONV))
DEFINES += -DDYNAMIC_ICONV
endif
##############################
ifeq (yes, $(MBYTE))
DEFINES += -DFEAT_MBYTE
endif
##############################
ifeq (yes, $(IME))
DEFINES += -DFEAT_MBYTE_IME
ifndef DYNAMIC_IME
DYNAMIC_IME = yes
endif
ifeq (yes, $(DYNAMIC_IME))
DEFINES += -DDYNAMIC_IME
else
EXTRA_LIBS += -limm32
endif
endif
##############################
ifeq (yes, $(DEBUG))
DEFINES += -DDEBUG
INCLUDES += -g -fstack-check
DEBUG_SUFFIX = d
else
ifeq ($(OPTIMIZE), SIZE)
OPTFLAG = -Os
else
ifeq ($(OPTIMIZE), MAXSPEED)
OPTFLAG = -O3 -fomit-frame-pointer -freg-struct-return
else
OPTFLAG = -O2
endif
endif
# A bug in the GCC <= 3.2 optimizer can cause a crash. The
# following option removes the problem optimization.
OPTFLAG += -fno-strength-reduce
INCLUDES += -s
endif
##############################
# USEDLL=yes will build a Cygwin32 executable that relies on cygwin1.dll.
# USEDLL=no will build a Mingw32 executable with no extra dll dependencies.
##############################
ifeq (yes, $(USEDLL))
DEFINES += -D_MAX_PATH=256 -D__CYGWIN__
else
INCLUDES += -mno-cygwin
endif
##############################
ifeq (yes, $(POSTSCRIPT))
DEFINES += -DMSWINPS
endif
##############################
ifeq (yes, $(CSCOPE))
DEFINES += -DFEAT_CSCOPE
EXTRA_OBJS += $(OUTDIR)/if_cscope.o
endif
##############################
ifeq ($(GUI),yes)
##############################
ifeq (yes, $(NETBEANS))
# Only allow NETBEANS for a GUI build.
DEFINES += -DFEAT_NETBEANS_INTG
EXTRA_OBJS += $(OUTDIR)/netbeans.o
EXTRA_LIBS += -lwsock32
ifeq (yes, $(NBDEBUG))
DEFINES += -DNBDEBUG
NBDEBUG_DEP = nbdebug.h nbdebug.c
endif
endif
##############################
ifdef XPM
# Only allow XPM for a GUI build.
DEFINES += -DFEAT_XPM_W32
INCLUDES += -I$(XPM)/include
EXTRA_OBJS += $(OUTDIR)/xpm_w32.o
EXTRA_LIBS += -L$(XPM)/lib -lXpm
endif
##############################
EXE = gvim$(DEBUG_SUFFIX).exe
OUTDIR = gobj$(DEBUG_SUFFIX)
DEFINES += -DFEAT_GUI_W32 -DFEAT_CLIPBOARD
EXTRA_OBJS += $(OUTDIR)/gui.o $(OUTDIR)/gui_w32.o $(OUTDIR)/gui_beval.o $(OUTDIR)/os_w32exe.o
EXTRA_LIBS += -mwindows -lcomctl32 -lversion
else
EXE = vim$(DEBUG_SUFFIX).exe
OUTDIR = obj$(DEBUG_SUFFIX)
LIBS += -luser32 -lgdi32 -lcomdlg32
endif
##############################
ifeq (yes, $(OLE))
DEFINES += -DFEAT_OLE
EXTRA_OBJS += $(OUTDIR)/if_ole.o
EXTRA_LIBS += -loleaut32 -lstdc++
endif
##############################
ifneq (sh.exe, $(SHELL))
DEL = rm
MKDIR = mkdir -p
DIRSLASH = /
else
DEL = del
MKDIR = mkdir
DIRSLASH = \\
endif
#>>>>> end of choices
###########################################################################
INCL = vim.h globals.h option.h keymap.h macros.h ascii.h term.h os_win32.h \
structs.h version.h
CFLAGS = $(OPTFLAG) $(DEFINES) $(INCLUDES)
RCFLAGS = -O coff $(DEFINES)
OBJ = \
$(OUTDIR)/blowfish.o \
$(OUTDIR)/buffer.o \
$(OUTDIR)/charset.o \
$(OUTDIR)/diff.o \
$(OUTDIR)/digraph.o \
$(OUTDIR)/edit.o \
$(OUTDIR)/eval.o \
$(OUTDIR)/ex_cmds.o \
$(OUTDIR)/ex_cmds2.o \
$(OUTDIR)/ex_docmd.o \
$(OUTDIR)/ex_eval.o \
$(OUTDIR)/ex_getln.o \
$(OUTDIR)/fileio.o \
$(OUTDIR)/fold.o \
$(OUTDIR)/getchar.o \
$(OUTDIR)/hardcopy.o \
$(OUTDIR)/hashtab.o \
$(OUTDIR)/main.o \
$(OUTDIR)/mark.o \
$(OUTDIR)/memfile.o \
$(OUTDIR)/memline.o \
$(OUTDIR)/menu.o \
$(OUTDIR)/message.o \
$(OUTDIR)/misc1.o \
$(OUTDIR)/misc2.o \
$(OUTDIR)/move.o \
$(OUTDIR)/mbyte.o \
$(OUTDIR)/normal.o \
$(OUTDIR)/ops.o \
$(OUTDIR)/option.o \
$(OUTDIR)/os_win32.o \
$(OUTDIR)/os_mswin.o \
$(OUTDIR)/pathdef.o \
$(OUTDIR)/popupmnu.o \
$(OUTDIR)/quickfix.o \
$(OUTDIR)/regexp.o \
$(OUTDIR)/screen.o \
$(OUTDIR)/search.o \
$(OUTDIR)/sha256.o \
$(OUTDIR)/spell.o \
$(OUTDIR)/syntax.o \
$(OUTDIR)/tag.o \
$(OUTDIR)/term.o \
$(OUTDIR)/ui.o \
$(OUTDIR)/undo.o \
$(OUTDIR)/version.o \
$(OUTDIR)/vimrc.o \
$(OUTDIR)/window.o \
$(EXTRA_OBJS)
all: $(EXE) xxd/xxd.exe vimrun.exe install.exe uninstal.exe GvimExt/gvimext.dll
# According to the Cygwin doc 1.2 FAQ, kernel32 should not be specified for
# linking unless calling ld directly.
# See /usr/doc/cygwin-doc-1.2/html/faq_toc.html#TOC93 for more information.
$(EXE): $(OUTDIR) $(OBJ)
$(CC) $(CFLAGS) -o $(EXE) $(OBJ) $(LIBS) -luuid -lole32 $(EXTRA_LIBS)
xxd/xxd.exe: xxd/xxd.c
$(MAKE) -C xxd -f Make_cyg.mak CC=$(CC) USEDLL=$(USEDLL)
GvimExt/gvimext.dll: GvimExt/gvimext.cpp GvimExt/gvimext.rc GvimExt/gvimext.h
$(MAKE) -C GvimExt -f Make_cyg.mak CROSS_COMPILE=$(CROSS_COMPILE)
vimrun.exe: vimrun.c
$(CC) $(CFLAGS) -o vimrun.exe vimrun.c $(LIBS)
install.exe: dosinst.c
$(CC) $(CFLAGS) -o install.exe dosinst.c $(LIBS) -luuid -lole32
uninstal.exe: uninstal.c
$(CC) $(CFLAGS) -o uninstal.exe uninstal.c $(LIBS)
$(OUTDIR):
$(MKDIR) $(OUTDIR)
tags:
command /c ctags *.c $(INCL)
clean:
-$(DEL) $(OUTDIR)$(DIRSLASH)*.o
-rmdir $(OUTDIR)
-$(DEL) $(EXE) vimrun.exe install.exe uninstal.exe
ifdef PERL
-$(DEL) if_perl.c
endif
ifdef MZSCHEME
-$(DEL) mzscheme_base.c
endif
-$(DEL) pathdef.c
$(MAKE) -C xxd -f Make_cyg.mak clean
$(MAKE) -C GvimExt -f Make_cyg.mak clean
distclean: clean
-$(DEL) obj$(DIRSLASH)*.o
-rmdir obj
-$(DEL) gobj$(DIRSLASH)*.o
-rmdir gobj
-$(DEL) objd$(DIRSLASH)*.o
-rmdir objd
-$(DEL) gobjd$(DIRSLASH)*.o
-rmdir gobjd
-$(DEL) *.exe
###########################################################################
$(OUTDIR)/%.o : %.c $(INCL)
$(CC) -c $(CFLAGS) $< -o $@
$(OUTDIR)/ex_docmd.o: ex_docmd.c $(INCL) ex_cmds.h
$(CC) -c $(CFLAGS) ex_docmd.c -o $(OUTDIR)/ex_docmd.o
$(OUTDIR)/ex_eval.o: ex_eval.c $(INCL) ex_cmds.h
$(CC) -c $(CFLAGS) ex_eval.c -o $(OUTDIR)/ex_eval.o
$(OUTDIR)/if_cscope.o: if_cscope.c $(INCL) if_cscope.h
$(CC) -c $(CFLAGS) if_cscope.c -o $(OUTDIR)/if_cscope.o
$(OUTDIR)/if_ole.o: if_ole.cpp $(INCL)
$(CC) -c $(CFLAGS) if_ole.cpp -o $(OUTDIR)/if_ole.o
$(OUTDIR)/if_python.o : if_python.c $(INCL)
$(CC) -c $(CFLAGS) -I$(PYTHON)/include $< -o $@
$(OUTDIR)/if_python3.o : if_python3.c $(INCL)
$(CC) -c $(CFLAGS) -I$(PYTHON3)/include $< -o $@
if_perl.c: if_perl.xs typemap
$(PERL)/bin/perl `cygpath -d $(PERL)/lib/ExtUtils/xsubpp` \
-prototypes -typemap \
`cygpath -d $(PERL)/lib/ExtUtils/typemap` if_perl.xs > $@
$(OUTDIR)/if_perl.o: if_perl.c $(INCL)
ifeq (yes, $(USEDLL))
$(CC) -c $(CFLAGS) -I/usr/include/mingw -D__MINGW32__ if_perl.c -o $(OUTDIR)/if_perl.o
endif
$(OUTDIR)/if_ruby.o: if_ruby.c $(INCL)
ifeq (16, $(RUBY_VER))
$(CC) -c $(CFLAGS) -U_WIN32 if_ruby.c -o $(OUTDIR)/if_ruby.o
endif
$(OUTDIR)/netbeans.o: netbeans.c $(INCL) $(NBDEBUG_DEP)
$(CC) -c $(CFLAGS) netbeans.c -o $(OUTDIR)/netbeans.o
$(OUTDIR)/if_mzsch.o: if_mzsch.c $(INCL) if_mzsch.h $(MZ_EXTRA_DEP)
$(CC) -c $(CFLAGS) if_mzsch.c -o $(OUTDIR)/if_mzsch.o
$(OUTDIR)/vimrc.o: vim.rc version.h gui_w32_rc.h
$(RC) $(RCFLAGS) vim.rc -o $(OUTDIR)/vimrc.o
mzscheme_base.c:
$(MZSCHEME)/mzc --c-mods mzscheme_base.c ++lib scheme/base
pathdef.c: $(INCL)
ifneq (sh.exe, $(SHELL))
@echo creating pathdef.c
@echo '/* pathdef.c */' > pathdef.c
@echo '#include "vim.h"' >> pathdef.c
@echo 'char_u *default_vim_dir = (char_u *)"$(VIMRCLOC)";' >> pathdef.c
@echo 'char_u *default_vimruntime_dir = (char_u *)"$(VIMRUNTIMEDIR)";' >> pathdef.c
@echo 'char_u *all_cflags = (char_u *)"$(CC) $(CFLAGS)";' >> pathdef.c
@echo 'char_u *all_lflags = (char_u *)"$(CC) -s -o $(EXE) $(LIBS) -luuid -lole32 $(EXTRA_LIBS)";' >> pathdef.c
@echo 'char_u *compiled_user = (char_u *)"$(USERNAME)";' >> pathdef.c
@echo 'char_u *compiled_sys = (char_u *)"$(USERDOMAIN)";' >> pathdef.c
else
@echo creating pathdef.c
@echo /* pathdef.c */ > pathdef.c
@echo #include "vim.h" >> pathdef.c
@echo char_u *default_vim_dir = (char_u *)"$(VIMRCLOC)"; >> pathdef.c
@echo char_u *default_vimruntime_dir = (char_u *)"$(VIMRUNTIMEDIR)"; >> pathdef.c
@echo char_u *all_cflags = (char_u *)"$(CC) $(CFLAGS)"; >> pathdef.c
@echo char_u *all_lflags = (char_u *)"$(CC) -s -o $(EXE) $(LIBS) -luuid -lole32 $(EXTRA_LIBS)"; >> pathdef.c
@echo char_u *compiled_user = (char_u *)"$(USERNAME)"; >> pathdef.c
@echo char_u *compiled_sys = (char_u *)"$(USERDOMAIN)"; >> pathdef.c
endif
| zyz2011-vim | src/Make_cyg.mak | Makefile | gpl2 | 16,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.
*/
#ifndef __GTK_FORM_H__
#define __GTK_FORM_H__
#include <gdk/gdk.h>
#include <gtk/gtkcontainer.h>
#ifdef __cplusplus
extern "C" {
#endif
#define GTK_TYPE_FORM (gtk_form_get_type ())
#define GTK_FORM(obj) (GTK_CHECK_CAST ((obj), GTK_TYPE_FORM, GtkForm))
#define GTK_FORM_CLASS(klass) (GTK_CHECK_CLASS_CAST ((klass), GTK_TYPE_FORM, GtkFormClass))
#define GTK_IS_FORM(obj) (GTK_CHECK_TYPE ((obj), GTK_TYPE_FORM))
#define GTK_IS_FORM_CLASS(klass) (GTK_CHECK_CLASS_TYPE ((klass), GTK_TYPE_FORM))
typedef struct _GtkForm GtkForm;
typedef struct _GtkFormClass GtkFormClass;
struct _GtkForm
{
GtkContainer container;
GList *children;
guint width;
guint height;
GdkWindow *bin_window;
GdkVisibilityState visibility;
gulong configure_serial;
gint freeze_count;
};
struct _GtkFormClass
{
GtkContainerClass parent_class;
};
GtkType gtk_form_get_type(void);
GtkWidget *gtk_form_new(void);
void gtk_form_put(GtkForm * form, GtkWidget * widget,
gint x, gint y);
void gtk_form_move(GtkForm *form, GtkWidget * widget,
gint x, gint y);
void gtk_form_move_resize(GtkForm * form, GtkWidget * widget,
gint x, gint y,
gint w, gint h);
/* These disable and enable moving and repainting respectively. If you
* want to update the layout's offsets but do not want it to repaint
* itself, you should use these functions.
*/
void gtk_form_freeze(GtkForm *form);
void gtk_form_thaw(GtkForm *form);
#ifdef __cplusplus
}
#endif
#endif /* __GTK_FORM_H__ */
| zyz2011-vim | src/gui_gtk_f.h | C | gpl2 | 1,741 |
/* 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.
*/
/*
* uninstal.c: Minimalistic uninstall program for Vim on MS-Windows
* Removes:
* - the "Edit with Vim" popup menu entry
* - the Vim "Open With..." popup menu entry
* - any Vim Batch files in the path
* - icons for Vim on the Desktop
* - the Vim entry in the Start Menu
*/
/* Include common code for dosinst.c and uninstal.c. */
#include "dosinst.h"
/*
* Return TRUE if the user types a 'y' or 'Y', FALSE otherwise.
*/
static int
confirm(void)
{
char answer[10];
fflush(stdout);
return (scanf(" %c", answer) == 1 && toupper(answer[0]) == 'Y');
}
#ifdef WIN3264
static int
reg_delete_key(HKEY hRootKey, const char *key)
{
static int did_load = FALSE;
static HANDLE advapi_lib = NULL;
static LONG (WINAPI *delete_key_ex)(HKEY, LPCTSTR, REGSAM, DWORD) = NULL;
if (!did_load)
{
/* The RegDeleteKeyEx() function is only available on new systems. It
* is required for 64-bit registry access. For other systems fall
* back to RegDeleteKey(). */
did_load = TRUE;
advapi_lib = LoadLibrary("ADVAPI32.DLL");
if (advapi_lib != NULL)
delete_key_ex = (LONG (WINAPI *)(HKEY, LPCTSTR, REGSAM, DWORD))GetProcAddress(advapi_lib, "RegDeleteKeyExA");
}
if (delete_key_ex != NULL) {
return (*delete_key_ex)(hRootKey, key, KEY_WOW64_64KEY, 0);
}
return RegDeleteKey(hRootKey, key);
}
/*
* Check if the popup menu entry exists and what gvim it refers to.
* Returns non-zero when it's found.
*/
static int
popup_gvim_path(char *buf)
{
HKEY key_handle;
DWORD value_type;
DWORD bufsize = BUFSIZE;
int r;
/* Open the key where the path to gvim.exe is stored. */
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
KEY_WOW64_64KEY | KEY_READ, &key_handle) != ERROR_SUCCESS)
return 0;
/* get the DisplayName out of it to show the user */
r = RegQueryValueEx(key_handle, "path", 0,
&value_type, (LPBYTE)buf, &bufsize);
RegCloseKey(key_handle);
return (r == ERROR_SUCCESS);
}
/*
* Check if the "Open With..." menu entry exists and what gvim it refers to.
* Returns non-zero when it's found.
*/
static int
openwith_gvim_path(char *buf)
{
HKEY key_handle;
DWORD value_type;
DWORD bufsize = BUFSIZE;
int r;
/* Open the key where the path to gvim.exe is stored. */
if (RegOpenKeyEx(HKEY_CLASSES_ROOT,
"Applications\\gvim.exe\\shell\\edit\\command", 0,
KEY_WOW64_64KEY | KEY_READ, &key_handle) != ERROR_SUCCESS)
return 0;
/* get the DisplayName out of it to show the user */
r = RegQueryValueEx(key_handle, "", 0, &value_type, (LPBYTE)buf, &bufsize);
RegCloseKey(key_handle);
return (r == ERROR_SUCCESS);
}
static void
remove_popup(void)
{
int fail = 0;
HKEY kh;
if (reg_delete_key(HKEY_CLASSES_ROOT, "CLSID\\{51EEE242-AD87-11d3-9C1E-0090278BBD99}\\InProcServer32") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "CLSID\\{51EEE242-AD87-11d3-9C1E-0090278BBD99}") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "*\\shellex\\ContextMenuHandlers\\gvim") != ERROR_SUCCESS)
++fail;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved", 0,
KEY_WOW64_64KEY | KEY_ALL_ACCESS, &kh) != ERROR_SUCCESS)
++fail;
else
{
if (RegDeleteValue(kh, "{51EEE242-AD87-11d3-9C1E-0090278BBD99}") != ERROR_SUCCESS)
++fail;
RegCloseKey(kh);
}
if (reg_delete_key(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_LOCAL_MACHINE, "Software\\Vim") != ERROR_SUCCESS)
++fail;
if (fail == 6)
printf("No Vim popup registry entries could be removed\n");
else if (fail > 0)
printf("Some Vim popup registry entries could not be removed\n");
else
printf("The Vim popup registry entries have been removed\n");
}
static void
remove_openwith(void)
{
int fail = 0;
if (reg_delete_key(HKEY_CLASSES_ROOT, "Applications\\gvim.exe\\shell\\edit\\command") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "Applications\\gvim.exe\\shell\\edit") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "Applications\\gvim.exe\\shell") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "Applications\\gvim.exe") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, ".htm\\OpenWithList\\gvim.exe") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, ".vim\\OpenWithList\\gvim.exe") != ERROR_SUCCESS)
++fail;
if (reg_delete_key(HKEY_CLASSES_ROOT, "*\\OpenWithList\\gvim.exe") != ERROR_SUCCESS)
++fail;
if (fail == 7)
printf("No Vim open-with registry entries could be removed\n");
else if (fail > 0)
printf("Some Vim open-with registry entries could not be removed\n");
else
printf("The Vim open-with registry entries have been removed\n");
}
#endif
/*
* Check if a batch file is really for the current version. Don't delete a
* batch file that was written for another (possibly newer) version.
*/
static int
batfile_thisversion(char *path)
{
FILE *fd;
char line[BUFSIZE];
char *p;
int ver_len = strlen(VIM_VERSION_NODOT);
int found = FALSE;
fd = fopen(path, "r");
if (fd != NULL)
{
while (fgets(line, BUFSIZE, fd) != NULL)
{
for (p = line; *p != 0; ++p)
/* don't accept "vim60an" when looking for "vim60". */
if (strnicmp(p, VIM_VERSION_NODOT, ver_len) == 0
&& !isdigit(p[ver_len])
&& !isalpha(p[ver_len]))
{
found = TRUE;
break;
}
if (found)
break;
}
fclose(fd);
}
return found;
}
static int
remove_batfiles(int doit)
{
char *batfile_path;
int i;
int found = 0;
for (i = 1; i < TARGET_COUNT; ++i)
{
batfile_path = searchpath_save(targets[i].batname);
if (batfile_path != NULL && batfile_thisversion(batfile_path))
{
++found;
if (doit)
{
printf("removing %s\n", batfile_path);
remove(batfile_path);
}
else
printf(" - the batch file %s\n", batfile_path);
free(batfile_path);
}
}
return found;
}
#ifdef WIN3264
static void
remove_if_exists(char *path, char *filename)
{
char buf[BUFSIZE];
FILE *fd;
sprintf(buf, "%s\\%s", path, filename);
fd = fopen(buf, "r");
if (fd != NULL)
{
fclose(fd);
printf("removing %s\n", buf);
remove(buf);
}
}
static void
remove_icons(void)
{
char path[BUFSIZE];
int i;
if (get_shell_folder_path(path, "desktop"))
for (i = 0; i < ICON_COUNT; ++i)
remove_if_exists(path, icon_link_names[i]);
}
static void
remove_start_menu(void)
{
char path[BUFSIZE];
int i;
struct stat st;
if (get_shell_folder_path(path, VIM_STARTMENU))
{
for (i = 1; i < TARGET_COUNT; ++i)
remove_if_exists(path, targets[i].lnkname);
remove_if_exists(path, "uninstall.lnk");
remove_if_exists(path, "Help.lnk");
/* Win95 uses .pif, WinNT uses .lnk */
remove_if_exists(path, "Vim tutor.pif");
remove_if_exists(path, "Vim tutor.lnk");
remove_if_exists(path, "Vim online.url");
if (stat(path, &st) == 0)
{
printf("removing %s\n", path);
rmdir(path);
}
}
}
#endif
static void
delete_uninstall_key(void)
{
#ifdef WIN3264
reg_delete_key(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Vim " VIM_VERSION_SHORT);
#else
FILE *fd;
char buf[BUFSIZE];
/*
* On DJGPP we delete registry entries by creating a .inf file and
* installing it.
*/
fd = fopen("vim.inf", "w");
if (fd != NULL)
{
fprintf(fd, "[version]\n");
fprintf(fd, "signature=\"$CHICAGO$\"\n\n");
fprintf(fd, "[DefaultInstall]\n");
fprintf(fd, "DelReg=DeleteMe\n\n");
fprintf(fd, "[DeleteMe]\n");
fprintf(fd, "HKLM,\"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Vim " VIM_VERSION_SHORT "\"\n");
fclose(fd);
/* Don't know how to detect Win NT with DJGPP. Hack: Just try the Win
* 95/98/ME method, since the DJGPP version can't use long filenames
* on Win NT anyway. */
sprintf(buf, "rundll setupx.dll,InstallHinfSection DefaultInstall 132 %s\\vim.inf", installdir);
run_command(buf);
#if 0
/* Windows NT method (untested). */
sprintf(buf, "rundll32 syssetup,SetupInfObjectInstallAction DefaultInstall 128 %s\\vim.inf", installdir);
run_command(buf);
#endif
remove("vim.inf");
}
#endif
}
int
main(int argc, char *argv[])
{
int found = 0;
FILE *fd;
#ifdef WIN3264
int i;
struct stat st;
char icon[BUFSIZE];
char path[BUFSIZE];
char popup_path[BUFSIZE];
/* The nsis uninstaller calls us with a "-nsis" argument. */
if (argc == 2 && stricmp(argv[1], "-nsis") == 0)
interactive = FALSE;
else
#endif
interactive = TRUE;
/* Initialize this program. */
do_inits(argv);
printf("This program will remove the following items:\n");
#ifdef WIN3264
if (popup_gvim_path(popup_path))
{
printf(" - the \"Edit with Vim\" entry in the popup menu\n");
printf(" which uses \"%s\"\n", popup_path);
if (interactive)
printf("\nRemove it (y/n)? ");
if (!interactive || confirm())
{
remove_popup();
/* Assume the "Open With" entry can be removed as well, don't
* bother the user with asking him again. */
remove_openwith();
}
}
else if (openwith_gvim_path(popup_path))
{
printf(" - the Vim \"Open With...\" entry in the popup menu\n");
printf(" which uses \"%s\"\n", popup_path);
printf("\nRemove it (y/n)? ");
if (confirm())
remove_openwith();
}
if (get_shell_folder_path(path, "desktop"))
{
printf("\n");
for (i = 0; i < ICON_COUNT; ++i)
{
sprintf(icon, "%s\\%s", path, icon_link_names[i]);
if (stat(icon, &st) == 0)
{
printf(" - the \"%s\" icon on the desktop\n", icon_names[i]);
++found;
}
}
if (found > 0)
{
if (interactive)
printf("\nRemove %s (y/n)? ", found > 1 ? "them" : "it");
if (!interactive || confirm())
remove_icons();
}
}
if (get_shell_folder_path(path, VIM_STARTMENU)
&& stat(path, &st) == 0)
{
printf("\n - the \"%s\" entry in the Start Menu\n", VIM_STARTMENU);
if (interactive)
printf("\nRemove it (y/n)? ");
if (!interactive || confirm())
remove_start_menu();
}
#endif
printf("\n");
found = remove_batfiles(0);
if (found > 0)
{
if (interactive)
printf("\nRemove %s (y/n)? ", found > 1 ? "them" : "it");
if (!interactive || confirm())
remove_batfiles(1);
}
fd = fopen("gvim.exe", "r");
if (fd != NULL)
{
fclose(fd);
printf("gvim.exe detected. Attempting to unregister gvim with OLE\n");
system("gvim.exe -silent -unregister");
}
delete_uninstall_key();
if (interactive)
{
printf("\nYou may now want to delete the Vim executables and runtime files.\n");
printf("(They are still where you unpacked them.)\n");
}
if (interactive)
{
rewind(stdin);
printf("\nPress Enter to exit...");
(void)getchar();
}
else
sleep(3);
return 0;
}
| zyz2011-vim | src/uninstal.c | C | gpl2 | 11,353 |
/* 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 the defines for the machine dependent escape sequences
* that the editor needs to perform various operations. All of the sequences
* here are optional, except "cm" (cursor motion).
*/
#if defined(SASC) && SASC < 658
/*
* The SAS C compiler has a bug that makes typedefs being forgot in include
* files. Has been fixed in version 6.58.
*/
typedef unsigned char char_u;
#endif
/*
* Index of the termcap codes in the term_strings array.
*/
enum SpecialKey
{
KS_NAME = 0,/* name of this terminal entry */
KS_CE, /* clear to end of line */
KS_AL, /* add new blank line */
KS_CAL, /* add number of blank lines */
KS_DL, /* delete line */
KS_CDL, /* delete number of lines */
KS_CS, /* scroll region */
KS_CL, /* clear screen */
KS_CD, /* clear to end of display */
KS_UT, /* clearing uses current background color */
KS_DA, /* text may be scrolled down from up */
KS_DB, /* text may be scrolled up from down */
KS_VI, /* cursor invisible */
KS_VE, /* cursor visible */
KS_VS, /* cursor very visible */
KS_ME, /* normal mode */
KS_MR, /* reverse mode */
KS_MD, /* bold mode */
KS_SE, /* normal mode */
KS_SO, /* standout mode */
KS_CZH, /* italic mode start */
KS_CZR, /* italic mode end */
KS_UE, /* exit underscore (underline) mode */
KS_US, /* underscore (underline) mode */
KS_UCE, /* exit undercurl mode */
KS_UCS, /* undercurl mode */
KS_MS, /* save to move cur in reverse mode */
KS_CM, /* cursor motion */
KS_SR, /* scroll reverse (backward) */
KS_CRI, /* cursor number of chars right */
KS_VB, /* visual bell */
KS_KS, /* put term in "keypad transmit" mode */
KS_KE, /* out of "keypad transmit" mode */
KS_TI, /* put terminal in termcap mode */
KS_TE, /* out of termcap mode */
KS_BC, /* backspace character (cursor left) */
KS_CCS, /* cur is relative to scroll region */
KS_CCO, /* number of colors */
KS_CSF, /* set foreground color */
KS_CSB, /* set background color */
KS_XS, /* standout not erased by overwriting (hpterm) */
KS_MB, /* blink mode */
KS_CAF, /* set foreground color (ANSI) */
KS_CAB, /* set background color (ANSI) */
KS_LE, /* cursor left (mostly backspace) */
KS_ND, /* cursor right */
KS_CIS, /* set icon text start */
KS_CIE, /* set icon text end */
KS_TS, /* set window title start (to status line)*/
KS_FS, /* set window title end (from status line) */
KS_CWP, /* set window position in pixels */
KS_CWS, /* set window size in characters */
KS_CRV, /* request version string */
KS_CSI, /* start insert mode (bar cursor) */
KS_CEI, /* end insert mode (block cursor) */
#ifdef FEAT_VERTSPLIT
KS_CSV, /* scroll region vertical */
#endif
KS_OP /* original color pair */
};
#define KS_LAST KS_OP
/*
* the terminal capabilities are stored in this array
* IMPORTANT: When making changes, note the following:
* - there should be an entry for each code in the builtin termcaps
* - there should be an option for each code in option.c
* - there should be code in term.c to obtain the value from the termcap
*/
extern char_u *(term_strings[]); /* current terminal strings */
/*
* strings used for terminal
*/
#define T_NAME (term_str(KS_NAME)) /* terminal name */
#define T_CE (term_str(KS_CE)) /* clear to end of line */
#define T_AL (term_str(KS_AL)) /* add new blank line */
#define T_CAL (term_str(KS_CAL)) /* add number of blank lines */
#define T_DL (term_str(KS_DL)) /* delete line */
#define T_CDL (term_str(KS_CDL)) /* delete number of lines */
#define T_CS (term_str(KS_CS)) /* scroll region */
#define T_CSV (term_str(KS_CSV)) /* scroll region vertical */
#define T_CL (term_str(KS_CL)) /* clear screen */
#define T_CD (term_str(KS_CD)) /* clear to end of display */
#define T_UT (term_str(KS_UT)) /* clearing uses background color */
#define T_DA (term_str(KS_DA)) /* text may be scrolled down from up */
#define T_DB (term_str(KS_DB)) /* text may be scrolled up from down */
#define T_VI (term_str(KS_VI)) /* cursor invisible */
#define T_VE (term_str(KS_VE)) /* cursor visible */
#define T_VS (term_str(KS_VS)) /* cursor very visible */
#define T_ME (term_str(KS_ME)) /* normal mode */
#define T_MR (term_str(KS_MR)) /* reverse mode */
#define T_MD (term_str(KS_MD)) /* bold mode */
#define T_SE (term_str(KS_SE)) /* normal mode */
#define T_SO (term_str(KS_SO)) /* standout mode */
#define T_CZH (term_str(KS_CZH)) /* italic mode start */
#define T_CZR (term_str(KS_CZR)) /* italic mode end */
#define T_UE (term_str(KS_UE)) /* exit underscore (underline) mode */
#define T_US (term_str(KS_US)) /* underscore (underline) mode */
#define T_UCE (term_str(KS_UCE)) /* exit undercurl mode */
#define T_UCS (term_str(KS_UCS)) /* undercurl mode */
#define T_MS (term_str(KS_MS)) /* save to move cur in reverse mode */
#define T_CM (term_str(KS_CM)) /* cursor motion */
#define T_SR (term_str(KS_SR)) /* scroll reverse (backward) */
#define T_CRI (term_str(KS_CRI)) /* cursor number of chars right */
#define T_VB (term_str(KS_VB)) /* visual bell */
#define T_KS (term_str(KS_KS)) /* put term in "keypad transmit" mode */
#define T_KE (term_str(KS_KE)) /* out of "keypad transmit" mode */
#define T_TI (term_str(KS_TI)) /* put terminal in termcap mode */
#define T_TE (term_str(KS_TE)) /* out of termcap mode */
#define T_BC (term_str(KS_BC)) /* backspace character */
#define T_CCS (term_str(KS_CCS)) /* cur is relative to scroll region */
#define T_CCO (term_str(KS_CCO)) /* number of colors */
#define T_CSF (term_str(KS_CSF)) /* set foreground color */
#define T_CSB (term_str(KS_CSB)) /* set background color */
#define T_XS (term_str(KS_XS)) /* standout not erased by overwriting */
#define T_MB (term_str(KS_MB)) /* blink mode */
#define T_CAF (term_str(KS_CAF)) /* set foreground color (ANSI) */
#define T_CAB (term_str(KS_CAB)) /* set background color (ANSI) */
#define T_LE (term_str(KS_LE)) /* cursor left */
#define T_ND (term_str(KS_ND)) /* cursor right */
#define T_CIS (term_str(KS_CIS)) /* set icon text start */
#define T_CIE (term_str(KS_CIE)) /* set icon text end */
#define T_TS (term_str(KS_TS)) /* set window title start */
#define T_FS (term_str(KS_FS)) /* set window title end */
#define T_CWP (term_str(KS_CWP)) /* window position */
#define T_CWS (term_str(KS_CWS)) /* window size */
#define T_CSI (term_str(KS_CSI)) /* start insert mode */
#define T_CEI (term_str(KS_CEI)) /* end insert mode */
#define T_CRV (term_str(KS_CRV)) /* request version string */
#define T_OP (term_str(KS_OP)) /* original color pair */
#define TMODE_COOK 0 /* terminal mode for external cmds and Ex mode */
#define TMODE_SLEEP 1 /* terminal mode for sleeping (cooked but no echo) */
#define TMODE_RAW 2 /* terminal mode for Normal and Insert mode */
| zyz2011-vim | src/term.h | C | gpl2 | 7,080 |
/* 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_test.c: Unittests for memfile.c
* Mostly by Ivan Krasilnikov.
*/
#undef NDEBUG
#include <assert.h>
/* Must include main.c because it contains much more than just main() */
#define NO_VIM_MAIN
#include "main.c"
/* This file has to be included because the tested functions are static */
#include "memfile.c"
#define index_to_key(i) ((i) ^ 15167)
#define TEST_COUNT 50000
static void test_mf_hash __ARGS((void));
/*
* Test mf_hash_*() functions.
*/
static void
test_mf_hash()
{
mf_hashtab_T ht;
mf_hashitem_T *item;
blocknr_T key;
long_u i;
long_u num_buckets;
mf_hash_init(&ht);
/* insert some items and check invariants */
for (i = 0; i < TEST_COUNT; i++)
{
assert(ht.mht_count == i);
/* check that number of buckets is a power of 2 */
num_buckets = ht.mht_mask + 1;
assert(num_buckets > 0 && (num_buckets & (num_buckets - 1)) == 0);
/* check load factor */
assert(ht.mht_count <= (num_buckets << MHT_LOG_LOAD_FACTOR));
if (i < (MHT_INIT_SIZE << MHT_LOG_LOAD_FACTOR))
{
/* first expansion shouldn't have occurred yet */
assert(num_buckets == MHT_INIT_SIZE);
assert(ht.mht_buckets == ht.mht_small_buckets);
}
else
{
assert(num_buckets > MHT_INIT_SIZE);
assert(ht.mht_buckets != ht.mht_small_buckets);
}
key = index_to_key(i);
assert(mf_hash_find(&ht, key) == NULL);
/* allocate and add new item */
item = (mf_hashitem_T *)lalloc_clear(sizeof(mf_hashtab_T), FALSE);
assert(item != NULL);
item->mhi_key = key;
mf_hash_add_item(&ht, item);
assert(mf_hash_find(&ht, key) == item);
if (ht.mht_mask + 1 != num_buckets)
{
/* hash table was expanded */
assert(ht.mht_mask + 1 == num_buckets * MHT_GROWTH_FACTOR);
assert(i + 1 == (num_buckets << MHT_LOG_LOAD_FACTOR));
}
}
/* check presence of inserted items */
for (i = 0; i < TEST_COUNT; i++)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
assert(item != NULL);
assert(item->mhi_key == key);
}
/* delete some items */
for (i = 0; i < TEST_COUNT; i++)
{
if (i % 100 < 70)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
assert(item != NULL);
assert(item->mhi_key == key);
mf_hash_rem_item(&ht, item);
assert(mf_hash_find(&ht, key) == NULL);
mf_hash_add_item(&ht, item);
assert(mf_hash_find(&ht, key) == item);
mf_hash_rem_item(&ht, item);
assert(mf_hash_find(&ht, key) == NULL);
vim_free(item);
}
}
/* check again */
for (i = 0; i < TEST_COUNT; i++)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
if (i % 100 < 70)
{
assert(item == NULL);
}
else
{
assert(item != NULL);
assert(item->mhi_key == key);
}
}
/* free hash table and all remaining items */
mf_hash_free_all(&ht);
}
int
main()
{
test_mf_hash();
return 0;
}
| zyz2011-vim | src/memfile_test.c | C | gpl2 | 3,171 |
# Makefile for the Vim message translations for mingw32
#
# Eduardo F. Amatria <eferna1@platea.pntic.mec.es>
#
# Read the README_ming.txt file before using it.
#
# Use at your own risk but with care, it could even kill your canary.
#
# Previous to all you must have the environment variable LANGUAGE set to your
# language (xx) and add it to the next three lines.
#
LANGUAGES = \
af \
ca \
cs \
de \
en_GB \
eo \
es \
fi \
fr \
ga \
it \
ja \
ko \
no \
pl \
pt_BR \
ru \
sk \
sv \
uk \
vi \
zh_CN \
zh_CN.UTF-8\
zh_TW \
zh_TW.UTF-8 \
MOFILES = \
af.mo \
ca.mo \
cs.mo \
de.mo \
en_GB.mo \
eo.mo \
es.mo \
fi.mo \
fr.mo \
ga.mo \
it.mo \
ja.mo \
ko.mo \
no.mo \
pl.mo \
pt_BR.mo \
ru.mo \
sk.mo \
sv.mo \
uk.mo \
vi.mo \
zh_CN.UTF-8.mo \
zh_CN.mo \
zh_TW.UTF-8.mo \
zh_TW.mo \
PACKAGE = vim
# Uncomment one of the lines below or modify it to put the path to your
# gettex binaries; I use the first
#GETTEXT_PATH = C:/gettext.win32/bin/
#GETTEXT_PATH = C:/gettext-0.10.35-w32/win32/Release/
#GETTEXT_PATH = C:/cygwin/bin/
MSGFMT = $(GETTEXT_PATH)msgfmt
XGETTEXT = $(GETTEXT_PATH)xgettext
MSGMERGE = $(GETTEXT_PATH)msgmerge
MV = move
CP = copy
RM = del
MKD = mkdir
.SUFFIXES:
.SUFFIXES: .po .mo .pot
.PHONY: first_time all install clean $(LANGUAGES)
.po.mo:
$(MSGFMT) -o $@ $<
all: $(MOFILES)
first_time:
$(XGETTEXT) --default-domain=$(LANGUAGE) \
--add-comments --keyword=_ --keyword=N_ $(wildcard ../*.c) ../if_perl.xs $(wildcard ../globals.h)
$(LANGUAGES):
$(XGETTEXT) --default-domain=$(PACKAGE) \
--add-comments --keyword=_ --keyword=N_ $(wildcard ../*.c) ../if_perl.xs $(wildcard ../globals.h)
$(MV) $(PACKAGE).po $(PACKAGE).pot
$(CP) $@.po $@.po.orig
$(MV) $@.po $@.po.old
$(MSGMERGE) $@.po.old $(PACKAGE).pot -o $@.po
$(RM) $@.po.old
install:
$(MKD) $(VIMRUNTIME)\lang\$(LANGUAGE)
$(MKD) $(VIMRUNTIME)\lang\$(LANGUAGE)\LC_MESSAGES
$(CP) $(LANGUAGE).mo $(VIMRUNTIME)\lang\$(LANGUAGE)\LC_MESSAGES\$(PACKAGE).mo
clean:
$(RM) *.mo
$(RM) *.pot
| zyz2011-vim | src/po/Make_ming.mak | Makefile | gpl2 | 2,076 |
" Vim script for checking .po files.
"
" Go through the file and verify that:
" - All %...s items in "msgid" are identical to the ones in "msgstr".
" - An error or warning code in "msgid" matches the one in "msgstr".
if 1 " Only execute this if the eval feature is available.
" Function to get a split line at the cursor.
" Used for both msgid and msgstr lines.
" Removes all text except % items and returns the result.
func! GetMline()
let idline = substitute(getline('.'), '"\(.*\)"$', '\1', '')
while line('.') < line('$')
+
let line = getline('.')
if line[0] != '"'
break
endif
let idline .= substitute(line, '"\(.*\)"$', '\1', '')
endwhile
" remove '%', not used for formatting.
let idline = substitute(idline, "'%'", '', 'g')
" remove '%' used for plural forms.
let idline = substitute(idline, '\\nPlural-Forms: .\+;\\n', '', '')
" remove everything but % items.
return substitute(idline, '[^%]*\(%[-+ #''.0-9*]*l\=[dsuxXpoc%]\)\=', '\1', 'g')
endfunc
" This only works when 'wrapscan' is set.
let s:save_wrapscan = &wrapscan
set wrapscan
" Start at the first "msgid" line.
1
/^msgid
let startline = line('.')
let error = 0
while 1
if getline(line('.') - 1) !~ "no-c-format"
let fromline = GetMline()
if getline('.') !~ '^msgstr'
echo 'Missing "msgstr" in line ' . line('.')
let error = 1
endif
let toline = GetMline()
if fromline != toline
echo 'Mismatching % in line ' . (line('.') - 1)
echo 'msgid: ' . fromline
echo 'msgstr: ' . toline
let error = 1
endif
endif
" Find next msgid.
" Wrap around at the end of the file, quit when back at the first one.
/^msgid
if line('.') == startline
break
endif
endwhile
" Check that error code in msgid matches the one in msgstr.
"
" Examples of mismatches found with msgid "E123: ..."
" - msgstr "E321: ..." error code mismatch
" - msgstr "W123: ..." warning instead of error
" - msgstr "E123 ..." missing colon
" - msgstr "..." missing error code
"
1
if search('msgid "\("\n"\)\?\([EW][0-9]\+:\).*\nmsgstr "\("\n"\)\?[^"]\@=\2\@!') > 0
echo 'Mismatching error/warning code in line ' . line('.')
let error = 1
endif
if error == 0
echo "OK"
endif
let &wrapscan = s:save_wrapscan
unlet s:save_wrapscan
endif
| zyz2011-vim | src/po/check.vim | Vim Script | gpl2 | 2,314 |
/*
* Simplistic program to correct SJIS inside strings. When a trail byte is a
* backslash it needs to be doubled.
* Public domain.
*/
#include <stdio.h>
#include <string.h>
int
main(argc, argv)
int argc;
char **argv;
{
char buffer[BUFSIZ];
char *p;
while (fgets(buffer, BUFSIZ, stdin) != NULL)
{
for (p = buffer; *p != 0; p++)
{
if (strncmp(p, "charset=euc-jp", 14) == 0)
{
fputs("charset=cp932", stdout);
p += 13;
}
else if (strncmp(p, "ja.po - Japanese message file", 29) == 0)
{
fputs("ja.sjis.po - Japanese message file for Vim (version 6.x)\n", stdout);
fputs("# generated from ja.po, DO NOT EDIT", stdout);
while (p[1] != '\n')
++p;
}
else if (*(unsigned char *)p == 0x81 && p[1] == '_')
{
putchar('\\');
++p;
}
else
{
if (*p & 0x80)
{
putchar(*p++);
if (*p == '\\')
putchar(*p);
}
putchar(*p);
}
}
}
}
| zyz2011-vim | src/po/sjiscorr.c | C | gpl2 | 932 |
" Vim script to cleanup a .po file:
" - Remove line numbers (avoids that diffs are messy).
" - Comment-out fuzzy and empty messages.
" - Make sure there is a space before the string (required for Solaris).
" Requires Vim 6.0 or later (because of multi-line search patterns).
" Disable diff mode, because it makes this very slow
let s:was_diff = &diff
setl nodiff
silent g/^#: /d
silent g/^#, fuzzy\(, .*\)\=\nmsgid ""\@!/.+1,/^$/-1s/^/#\~ /
silent g/^msgstr"/s//msgstr "/
silent g/^msgid"/s//msgid "/
silent g/^msgstr ""\(\n"\)\@!/?^msgid?,.s/^/#\~ /
if s:was_diff
setl diff
endif
| zyz2011-vim | src/po/cleanup.vim | Vim Script | gpl2 | 586 |
# Makefile for the Vim message translations.
# TODO make this configurable
# Note: ja.sjis, *.cp1250 and zh_CN.cp936 are only for MS-Windows, they are
# not installed on Unix
LANGUAGES = \
af \
ca \
cs \
de \
en_GB \
eo \
es \
fi \
fr \
ga \
it \
ja \
ko \
ko.UTF-8 \
nb \
nl \
no \
pl \
pt_BR \
ru \
sk \
sv \
uk \
vi \
zh_CN \
zh_CN.UTF-8 \
zh_TW \
zh_TW.UTF-8
MOFILES = \
af.mo \
ca.mo \
cs.mo \
de.mo \
en_GB.mo \
eo.mo \
es.mo \
fi.mo \
fr.mo \
ga.mo \
it.mo \
ja.mo \
ko.mo \
ko.UTF-8.mo \
nb.mo \
nl.mo \
no.mo \
pl.mo \
pt_BR.mo \
ru.mo \
sk.mo \
sv.mo \
uk.mo \
vi.mo \
zh_CN.UTF-8.mo \
zh_CN.mo \
zh_TW.UTF-8.mo \
zh_TW.mo
CONVERTED = \
cs.cp1250.mo \
ja.sjis.mo \
pl.cp1250.mo \
pl.UTF-8.mo \
ru.cp1251.mo \
sk.cp1250.mo \
uk.cp1251.mo \
zh_CN.cp936.mo
CHECKFILES = \
af.ck \
ca.ck \
cs.ck \
de.ck \
en_GB.ck \
eo.ck \
es.ck \
fi.ck \
fr.ck \
ga.ck \
it.ck \
ja.ck \
ko.ck \
ko.UTF-8.ck \
nb.ck \
nl.ck \
no.ck \
pl.ck \
pt_BR.ck \
ru.ck \
sk.ck \
sv.ck \
uk.ck \
vi.ck \
zh_CN.UTF-8.ck \
zh_CN.ck \
zh_TW.UTF-8.ck \
zh_TW.ck \
cs.cp1250.ck \
ja.sjis.ck \
pl.cp1250.ck \
pl.UTF-8.ck \
ru.cp1251.ck \
sk.cp1250.ck \
uk.cp1251.ck \
zh_CN.cp936.ck
PACKAGE = vim
SHELL = /bin/sh
VIM = ../vim
# The OLD_PO_FILE_INPUT and OLD_PO_FILE_OUTPUT are for the new GNU gettext
# tools 0.10.37, which use a slightly different .po file format that is not
# compatible with Solaris (and old gettext implementations) unless these are
# set. gettext 0.10.36 will not work!
MSGFMT = OLD_PO_FILE_INPUT=yes msgfmt -v
XGETTEXT = OLD_PO_FILE_INPUT=yes OLD_PO_FILE_OUTPUT=yes xgettext
MSGMERGE = OLD_PO_FILE_INPUT=yes OLD_PO_FILE_OUTPUT=yes msgmerge
.SUFFIXES:
.SUFFIXES: .po .mo .pot .ck
.PHONY: all install uninstall prefixcheck converted check clean checkclean distclean update-po $(LANGUAGES)
.po.mo:
$(MSGFMT) -o $@ $<
.po.ck:
$(VIM) -u NONE -e -X -S check.vim -c "if error == 0 | q | endif" -c cq $<
touch $@
all: $(MOFILES)
check: $(CHECKFILES)
install: $(MOFILES)
@$(MAKE) prefixcheck
for lang in $(LANGUAGES); do \
dir=$(LOCALEDIR)/$$lang/; \
if test ! -x "$$dir"; then \
mkdir $$dir; chmod 755 $$dir; \
fi; \
dir=$(LOCALEDIR)/$$lang/LC_MESSAGES; \
if test ! -x "$$dir"; then \
mkdir $$dir; chmod 755 $$dir; \
fi; \
if test -r $$lang.mo; then \
$(INSTALL_DATA) $$lang.mo $$dir/$(PACKAGE).mo; \
chmod $(FILEMOD) $$dir/$(PACKAGE).mo; \
fi; \
done
uninstall:
@$(MAKE) prefixcheck
for cat in $(MOFILES); do \
cat=`basename $$cat`; \
lang=`echo $$cat | sed 's/\$(CATOBJEXT)$$//'`; \
rm -f $(LOCALEDIR)/$$lang/LC_MESSAGES/$(PACKAGE).mo; \
done
converted: $(CONVERTED)
# Norwegian/Bokmal: "nb" is an alias for "no".
# Copying the file is not efficient, but I don't know of another way to make
# this work.
nb.po: no.po
cp no.po nb.po
# Convert ja.po to create ja.sjis.po. Requires doubling backslashes in the
# second byte. Don't depend on sjiscorr, it should only be compiled when
# ja.sjis.po is outdated.
ja.sjis.po: ja.po
@$(MAKE) sjiscorr
rm -f ja.sjis.po
iconv -f euc-jp -t cp932 ja.po | ./sjiscorr > ja.sjis.po
sjiscorr: sjiscorr.c
$(CC) -o sjiscorr sjiscorr.c
# Convert cs.po to create cs.cp1250.po.
cs.cp1250.po: cs.po
rm -f cs.cp1250.po
iconv -f iso-8859-2 -t cp1250 cs.po | \
sed -e 's/charset=ISO-8859-2/charset=cp1250/' -e 's/# Original translations/# Generated from cs.po, DO NOT EDIT/' > cs.cp1250.po
# Convert pl.po to create pl.cp1250.po.
pl.cp1250.po: pl.po
rm -f pl.cp1250.po
iconv -f iso-8859-2 -t cp1250 pl.po | \
sed -e 's/charset=ISO-8859-2/charset=cp1250/' -e 's/# Original translations/# Generated from pl.po, DO NOT EDIT/' > pl.cp1250.po
# Convert pl.po to create pl.UTF-8.po.
pl.UTF-8.po: pl.po
rm -f pl.UTF-8.po
iconv -f iso-8859-2 -t utf-8 pl.po | \
sed -e 's/charset=ISO-8859-2/charset=utf-8/' -e 's/# Original translations/# Generated from pl.po, DO NOT EDIT/' > pl.UTF-8.po
# Convert sk.po to create sk.cp1250.po.
sk.cp1250.po: sk.po
rm -f sk.cp1250.po
iconv -f iso-8859-2 -t cp1250 sk.po | \
sed -e 's/charset=ISO-8859-2/charset=cp1250/' -e 's/# Original translations/# Generated from sk.po, DO NOT EDIT/' > sk.cp1250.po
# Convert zh_CN.po to create zh_CN.cp936.po.
# set 'charset' to gbk to avoid that msfmt generates a warning
zh_CN.cp936.po: zh_CN.po
rm -f zh_CN.cp936.po
iconv -f gb2312 -t cp936 zh_CN.po | \
sed -e 's/charset=gb2312/charset=gbk/' -e 's/# Original translations/# Generated from zh_CN.po, DO NOT EDIT/' > zh_CN.cp936.po
# Convert ko.UTF-8.po to create ko.po.
ko.po: ko.UTF-8.po
rm -f ko.po
iconv -f UTF-8 -t euc-kr ko.UTF-8.po | \
sed -e 's/charset=UTF-8/charset=euc-kr/' \
-e 's/# Korean translation for Vim/# Generated from ko.UTF-8.po, DO NOT EDIT/' \
> ko.po
# Convert ru.po to create ru.cp1251.po.
ru.cp1251.po: ru.po
rm -f ru.cp1251.po
iconv -f utf-8 -t cp1251 ru.po | \
sed -e 's/charset=utf-8/charset=cp1251/' -e 's/# Original translations/# Generated from ru.po, DO NOT EDIT/' > ru.cp1251.po
# Convert uk.po to create uk.cp1251.po.
uk.cp1251.po: uk.po
rm -f uk.cp1251.po
iconv -f utf-8 -t cp1251 uk.po | \
sed -e 's/charset=utf-8/charset=cp1251/' -e 's/# Original translations/# Generated from uk.po, DO NOT EDIT/' > uk.cp1251.po
prefixcheck:
@if test "x" = "x$(prefix)"; then \
echo "******************************************"; \
echo " please use make from the src directory "; \
echo "******************************************"; \
exit 1; \
fi
clean: checkclean
rm -f core core.* *.old.po *.mo *.pot sjiscorr
distclean: clean
checkclean:
rm -f *.ck
$(PACKAGE).pot: ../*.c ../if_perl.xs ../GvimExt/gvimext.cpp ../globals.h ../if_py_both.h
cd ..; $(XGETTEXT) --default-domain=$(PACKAGE) \
--add-comments --keyword=_ --keyword=N_ \
*.c if_perl.xs GvimExt/gvimext.cpp globals.h if_py_both.h
mv -f ../$(PACKAGE).po $(PACKAGE).pot
update-po: $(LANGUAGES)
# Don't add a dependency here, we only want to update the .po files manually
$(LANGUAGES):
@$(MAKE) $(PACKAGE).pot
if test ! -f $@.po.orig; then cp $@.po $@.po.orig; fi
mv $@.po $@.po.old
if $(MSGMERGE) $@.po.old $(PACKAGE).pot -o $@.po; then \
rm -f $@.po.old; \
else \
echo "msgmerge for $@.po failed!"; mv $@.po.old $@.po; \
fi
| zyz2011-vim | src/po/Makefile | Makefile | gpl2 | 6,422 |
# Makefile for the Vim message translations for Cygwin
# by Tony Mechelynck <antoine.mechelynck@skynet.be>
# after Make_ming.mak by
# Eduardo F. Amatria <eferna1@platea.pntic.mec.es>
#
# Read the README_ming.txt file before using it.
#
# Use at your own risk but with care, it could even kill your canary.
#
ifndef VIMRUNTIME
VIMRUNTIME = ../../runtime
endif
LANGUAGES = af \
ca \
cs \
cs.cp1250 \
de \
en_GB \
eo \
es \
fi \
fr \
ga \
it \
ja \
ja.sjis \
ko \
ko.UTF-8 \
no \
pl \
pl.cp1250 \
pt_BR \
ru \
ru.cp1251 \
sk \
sk.cp1250 \
sv \
uk \
uk.cp1251 \
vi \
zh_CN \
zh_CN.UTF-8 \
zh_CN.cp936 \
zh_TW \
zh_TW.UTF-8 \
MOFILES = af.mo \
ca.mo \
cs.cp1250.mo \
cs.mo \
de.mo \
en_GB.mo \
eo.mo \
es.mo \
fi.mo \
fr.mo \
ga.mo \
it.mo \
ja.mo \
ja.sjis.mo \
ko.mo \
ko.UTF-8.mo \
no.mo \
pl.cp1250.mo \
pl.mo \
pt_BR.mo \
ru.cp1251.mo \
ru.mo \
sk.cp1250.mo \
sk.mo \
sv.mo \
uk.cp1251.mo \
uk.mo \
vi.mo \
zh_CN.UTF-8.mo \
zh_CN.cp936.mo \
zh_CN.mo \
zh_TW.UTF-8.mo \
zh_TW.mo \
PACKAGE = vim
# Uncomment one of the lines below or modify it to put the path to your
# gettext binaries
ifndef GETTEXT_PATH
#GETTEXT_PATH = C:/gettext.win32/bin/
#GETTEXT_PATH = C:/gettext-0.10.35-w32/win32/Release/
GETTEXT_PATH = /bin/
endif
# The OLD_PO_FILE_INPUT and OLD_PO_FILE_OUTPUT are for the new GNU gettext
# tools 0.10.37, which use a slightly different .po file format that is not
# compatible with Solaris (and old gettext implementations) unless these are
# set. gettext 0.10.36 will not work!
MSGFMT = OLD_PO_FILE_INPUT=yes $(GETTEXT_PATH)msgfmt -v
XGETTEXT = OLD_PO_FILE_INPUT=yes OLD_PO_FILE_OUTPUT=yes $(GETTEXT_PATH)xgettext
MSGMERGE = OLD_PO_FILE_INPUT=yes OLD_PO_FILE_OUTPUT=yes $(GETTEXT_PATH)msgmerge
# MV = move
# CP = copy
# RM = del
# MKD = mkdir
MV = mv -f
CP = cp -f
RM = rm -f
MKD = mkdir -p
.SUFFIXES:
.SUFFIXES: .po .mo .pot
.PHONY: first_time all install clean $(LANGUAGES)
.po.mo:
$(MSGFMT) -o $@ $<
all: $(MOFILES)
first_time:
$(XGETTEXT) --default-domain=$(LANGUAGE) \
--add-comments --keyword=_ --keyword=N_ $(wildcard ../*.c) ../if_perl.xs $(wildcard ../globals.h)
$(LANGUAGES):
$(XGETTEXT) --default-domain=$(PACKAGE) \
--add-comments --keyword=_ --keyword=N_ $(wildcard ../*.c) ../if_perl.xs $(wildcard ../globals.h)
$(MV) $(PACKAGE).po $(PACKAGE).pot
$(CP) $@.po $@.po.orig
$(MV) $@.po $@.po.old
$(MSGMERGE) $@.po.old $(PACKAGE).pot -o $@.po
$(RM) $@.po.old
install: $(MOFILES)
for TARGET in $(LANGUAGES); do \
$(MKD) $(VIMRUNTIME)/lang/$$TARGET/LC_MESSAGES ; \
$(CP) $$TARGET.mo $(VIMRUNTIME)/lang/$$TARGET/LC_MESSAGES/$(PACKAGE).mo ; \
done
clean:
$(RM) *.mo
$(RM) *.pot
| zyz2011-vim | src/po/Make_cyg.mak | Makefile | gpl2 | 2,760 |
# Makefile for the Vim message translations for MSVC
# (based on make_ming.mak)
#
# Mike Williams <mrw@eandem.co.uk>
#
# Please read README_mvc.txt before using this file.
#
LANGUAGES = \
af \
ca \
cs \
de \
en_GB \
eo \
es \
fi \
fr \
ga \
it \
ja \
ko \
no \
pl \
pt_BR \
ru \
sk \
sv \
uk \
vi \
zh_CN \
zh_CN.UTF-8 \
zh_TW \
zh_TW.UTF-8 \
MOFILES = \
af.mo \
ca.mo \
cs.mo \
de.mo \
en_GB.mo \
eo.mo \
es.mo \
fi.mo \
fr.mo \
ga.mo \
it.mo \
ja.mo \
ko.mo \
no.mo \
pl.mo \
pt_BR.mo \
ru.mo \
sk.mo \
sv.mo \
uk.mo \
vi.mo \
zh_CN.UTF-8.mo \
zh_CN.mo \
zh_TW.UTF-8.mo \
zh_TW.mo \
PACKAGE = vim
# Correct the following line for the directory where gettext et al is installed
GETTEXT_PATH = H:\gettext.0.14.4\bin
MSGFMT = $(GETTEXT_PATH)\msgfmt
XGETTEXT = $(GETTEXT_PATH)\xgettext
MSGMERGE = $(GETTEXT_PATH)\msgmerge
MV = move
CP = copy
RM = del
MKD = mkdir
LS = dir
LSFLAGS = /b /on /l /s
INSTALLDIR = $(VIMRUNTIME)\lang\$(LANGUAGE)\LC_MESSAGES
.SUFFIXES:
.SUFFIXES: .po .mo .pot
.po.mo:
$(MSGFMT) -o $@ $<
all: $(MOFILES)
files:
$(LS) $(LSFLAGS) ..\*.c ..\if_perl.xs ..\globals.h > .\files
first_time: files
$(XGETTEXT) --default-domain=$(LANGUAGE) --add-comments --keyword=_ --keyword=N_ --files-from=.\files
$(LANGUAGES): files
$(XGETTEXT) --default-domain=$(PACKAGE) --add-comments --keyword=_ --keyword=N_ --files-from=.\files
$(MV) $(PACKAGE).po $(PACKAGE).pot
$(CP) $@.po $@.po.orig
$(MV) $@.po $@.po.old
$(MSGMERGE) $@.po.old $(PACKAGE).pot -o $@.po
$(RM) $@.po.old
install:
if not exist $(INSTALLDIR) $(MKD) $(INSTALLDIR)
$(CP) $(LANGUAGE).mo $(INSTALLDIR)\$(PACKAGE).mo
clean:
$(RM) *.mo
$(RM) *.pot
| zyz2011-vim | src/po/Make_mvc.mak | Makefile | gpl2 | 1,743 |
/* 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.
*/
/*
* normal.c: Contains the main routine for processing characters in command
* mode. Communicates closely with the code in ops.c to handle
* the operators.
*/
#include "vim.h"
#ifdef FEAT_VISUAL
/*
* The Visual area is remembered for reselection.
*/
static int resel_VIsual_mode = NUL; /* 'v', 'V', or Ctrl-V */
static linenr_T resel_VIsual_line_count; /* number of lines */
static colnr_T resel_VIsual_vcol; /* nr of cols or end col */
static int restart_VIsual_select = 0;
#endif
#ifdef FEAT_EVAL
static void set_vcount_ca __ARGS((cmdarg_T *cap, int *set_prevcount));
#endif
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
nv_compare __ARGS((const void *s1, const void *s2));
static int find_command __ARGS((int cmdchar));
static void op_colon __ARGS((oparg_T *oap));
static void op_function __ARGS((oparg_T *oap));
#if defined(FEAT_MOUSE) && defined(FEAT_VISUAL)
static void find_start_of_word __ARGS((pos_T *));
static void find_end_of_word __ARGS((pos_T *));
static int get_mouse_class __ARGS((char_u *p));
#endif
static void prep_redo_cmd __ARGS((cmdarg_T *cap));
static void prep_redo __ARGS((int regname, long, int, int, int, int, int));
static int checkclearop __ARGS((oparg_T *oap));
static int checkclearopq __ARGS((oparg_T *oap));
static void clearop __ARGS((oparg_T *oap));
static void clearopbeep __ARGS((oparg_T *oap));
#ifdef FEAT_VISUAL
static void unshift_special __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_CMDL_INFO
static void del_from_showcmd __ARGS((int));
#endif
/*
* nv_*(): functions called to handle Normal and Visual mode commands.
* n_*(): functions called to handle Normal mode commands.
* v_*(): functions called to handle Visual mode commands.
*/
static void nv_ignore __ARGS((cmdarg_T *cap));
static void nv_nop __ARGS((cmdarg_T *cap));
static void nv_error __ARGS((cmdarg_T *cap));
static void nv_help __ARGS((cmdarg_T *cap));
static void nv_addsub __ARGS((cmdarg_T *cap));
static void nv_page __ARGS((cmdarg_T *cap));
static void nv_gd __ARGS((oparg_T *oap, int nchar, int thisblock));
static int nv_screengo __ARGS((oparg_T *oap, int dir, long dist));
#ifdef FEAT_MOUSE
static void nv_mousescroll __ARGS((cmdarg_T *cap));
static void nv_mouse __ARGS((cmdarg_T *cap));
#endif
static void nv_scroll_line __ARGS((cmdarg_T *cap));
static void nv_zet __ARGS((cmdarg_T *cap));
#ifdef FEAT_GUI
static void nv_ver_scrollbar __ARGS((cmdarg_T *cap));
static void nv_hor_scrollbar __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_GUI_TABLINE
static void nv_tabline __ARGS((cmdarg_T *cap));
static void nv_tabmenu __ARGS((cmdarg_T *cap));
#endif
static void nv_exmode __ARGS((cmdarg_T *cap));
static void nv_colon __ARGS((cmdarg_T *cap));
static void nv_ctrlg __ARGS((cmdarg_T *cap));
static void nv_ctrlh __ARGS((cmdarg_T *cap));
static void nv_clear __ARGS((cmdarg_T *cap));
static void nv_ctrlo __ARGS((cmdarg_T *cap));
static void nv_hat __ARGS((cmdarg_T *cap));
static void nv_Zet __ARGS((cmdarg_T *cap));
static void nv_ident __ARGS((cmdarg_T *cap));
static void nv_tagpop __ARGS((cmdarg_T *cap));
static void nv_scroll __ARGS((cmdarg_T *cap));
static void nv_right __ARGS((cmdarg_T *cap));
static void nv_left __ARGS((cmdarg_T *cap));
static void nv_up __ARGS((cmdarg_T *cap));
static void nv_down __ARGS((cmdarg_T *cap));
#ifdef FEAT_SEARCHPATH
static void nv_gotofile __ARGS((cmdarg_T *cap));
#endif
static void nv_end __ARGS((cmdarg_T *cap));
static void nv_dollar __ARGS((cmdarg_T *cap));
static void nv_search __ARGS((cmdarg_T *cap));
static void nv_next __ARGS((cmdarg_T *cap));
static void normal_search __ARGS((cmdarg_T *cap, int dir, char_u *pat, int opt));
static void nv_csearch __ARGS((cmdarg_T *cap));
static void nv_brackets __ARGS((cmdarg_T *cap));
static void nv_percent __ARGS((cmdarg_T *cap));
static void nv_brace __ARGS((cmdarg_T *cap));
static void nv_mark __ARGS((cmdarg_T *cap));
static void nv_findpar __ARGS((cmdarg_T *cap));
static void nv_undo __ARGS((cmdarg_T *cap));
static void nv_kundo __ARGS((cmdarg_T *cap));
static void nv_Replace __ARGS((cmdarg_T *cap));
#ifdef FEAT_VREPLACE
static void nv_vreplace __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_VISUAL
static void v_swap_corners __ARGS((int cmdchar));
#endif
static void nv_replace __ARGS((cmdarg_T *cap));
static void n_swapchar __ARGS((cmdarg_T *cap));
static void nv_cursormark __ARGS((cmdarg_T *cap, int flag, pos_T *pos));
#ifdef FEAT_VISUAL
static void v_visop __ARGS((cmdarg_T *cap));
#endif
static void nv_subst __ARGS((cmdarg_T *cap));
static void nv_abbrev __ARGS((cmdarg_T *cap));
static void nv_optrans __ARGS((cmdarg_T *cap));
static void nv_gomark __ARGS((cmdarg_T *cap));
static void nv_pcmark __ARGS((cmdarg_T *cap));
static void nv_regname __ARGS((cmdarg_T *cap));
#ifdef FEAT_VISUAL
static void nv_visual __ARGS((cmdarg_T *cap));
static void n_start_visual_mode __ARGS((int c));
#endif
static void nv_window __ARGS((cmdarg_T *cap));
static void nv_suspend __ARGS((cmdarg_T *cap));
static void nv_g_cmd __ARGS((cmdarg_T *cap));
static void n_opencmd __ARGS((cmdarg_T *cap));
static void nv_dot __ARGS((cmdarg_T *cap));
static void nv_redo __ARGS((cmdarg_T *cap));
static void nv_Undo __ARGS((cmdarg_T *cap));
static void nv_tilde __ARGS((cmdarg_T *cap));
static void nv_operator __ARGS((cmdarg_T *cap));
#ifdef FEAT_EVAL
static void set_op_var __ARGS((int optype));
#endif
static void nv_lineop __ARGS((cmdarg_T *cap));
static void nv_home __ARGS((cmdarg_T *cap));
static void nv_pipe __ARGS((cmdarg_T *cap));
static void nv_bck_word __ARGS((cmdarg_T *cap));
static void nv_wordcmd __ARGS((cmdarg_T *cap));
static void nv_beginline __ARGS((cmdarg_T *cap));
static void adjust_cursor __ARGS((oparg_T *oap));
#ifdef FEAT_VISUAL
static void adjust_for_sel __ARGS((cmdarg_T *cap));
static int unadjust_for_sel __ARGS((void));
static void nv_select __ARGS((cmdarg_T *cap));
#endif
static void nv_goto __ARGS((cmdarg_T *cap));
static void nv_normal __ARGS((cmdarg_T *cap));
static void nv_esc __ARGS((cmdarg_T *oap));
static void nv_edit __ARGS((cmdarg_T *cap));
static void invoke_edit __ARGS((cmdarg_T *cap, int repl, int cmd, int startln));
#ifdef FEAT_TEXTOBJ
static void nv_object __ARGS((cmdarg_T *cap));
#endif
static void nv_record __ARGS((cmdarg_T *cap));
static void nv_at __ARGS((cmdarg_T *cap));
static void nv_halfpage __ARGS((cmdarg_T *cap));
static void nv_join __ARGS((cmdarg_T *cap));
static void nv_put __ARGS((cmdarg_T *cap));
static void nv_open __ARGS((cmdarg_T *cap));
#ifdef FEAT_SNIFF
static void nv_sniff __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_NETBEANS_INTG
static void nv_nbcmd __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_DND
static void nv_drop __ARGS((cmdarg_T *cap));
#endif
#ifdef FEAT_AUTOCMD
static void nv_cursorhold __ARGS((cmdarg_T *cap));
#endif
static char *e_noident = N_("E349: No identifier under cursor");
/*
* Function to be called for a Normal or Visual mode command.
* The argument is a cmdarg_T.
*/
typedef void (*nv_func_T) __ARGS((cmdarg_T *cap));
/* Values for cmd_flags. */
#define NV_NCH 0x01 /* may need to get a second char */
#define NV_NCH_NOP (0x02|NV_NCH) /* get second char when no operator pending */
#define NV_NCH_ALW (0x04|NV_NCH) /* always get a second char */
#define NV_LANG 0x08 /* second char needs language adjustment */
#define NV_SS 0x10 /* may start selection */
#define NV_SSS 0x20 /* may start selection with shift modifier */
#define NV_STS 0x40 /* may stop selection without shift modif. */
#define NV_RL 0x80 /* 'rightleft' modifies command */
#define NV_KEEPREG 0x100 /* don't clear regname */
#define NV_NCW 0x200 /* not allowed in command-line window */
/*
* Generally speaking, every Normal mode command should either clear any
* pending operator (with *clearop*()), or set the motion type variable
* oap->motion_type.
*
* When a cursor motion command is made, it is marked as being a character or
* line oriented motion. Then, if an operator is in effect, the operation
* becomes character or line oriented accordingly.
*/
/*
* This table contains one entry for every Normal or Visual mode command.
* The order doesn't matter, init_normal_cmds() will create a sorted index.
* It is faster when all keys from zero to '~' are present.
*/
static const struct nv_cmd
{
int cmd_char; /* (first) command character */
nv_func_T cmd_func; /* function for this command */
short_u cmd_flags; /* NV_ flags */
short cmd_arg; /* value for ca.arg */
} nv_cmds[] =
{
{NUL, nv_error, 0, 0},
{Ctrl_A, nv_addsub, 0, 0},
{Ctrl_B, nv_page, NV_STS, BACKWARD},
{Ctrl_C, nv_esc, 0, TRUE},
{Ctrl_D, nv_halfpage, 0, 0},
{Ctrl_E, nv_scroll_line, 0, TRUE},
{Ctrl_F, nv_page, NV_STS, FORWARD},
{Ctrl_G, nv_ctrlg, 0, 0},
{Ctrl_H, nv_ctrlh, 0, 0},
{Ctrl_I, nv_pcmark, 0, 0},
{NL, nv_down, 0, FALSE},
{Ctrl_K, nv_error, 0, 0},
{Ctrl_L, nv_clear, 0, 0},
{Ctrl_M, nv_down, 0, TRUE},
{Ctrl_N, nv_down, NV_STS, FALSE},
{Ctrl_O, nv_ctrlo, 0, 0},
{Ctrl_P, nv_up, NV_STS, FALSE},
#ifdef FEAT_VISUAL
{Ctrl_Q, nv_visual, 0, FALSE},
#else
{Ctrl_Q, nv_ignore, 0, 0},
#endif
{Ctrl_R, nv_redo, 0, 0},
{Ctrl_S, nv_ignore, 0, 0},
{Ctrl_T, nv_tagpop, NV_NCW, 0},
{Ctrl_U, nv_halfpage, 0, 0},
#ifdef FEAT_VISUAL
{Ctrl_V, nv_visual, 0, FALSE},
{'V', nv_visual, 0, FALSE},
{'v', nv_visual, 0, FALSE},
#else
{Ctrl_V, nv_error, 0, 0},
{'V', nv_error, 0, 0},
{'v', nv_error, 0, 0},
#endif
{Ctrl_W, nv_window, 0, 0},
{Ctrl_X, nv_addsub, 0, 0},
{Ctrl_Y, nv_scroll_line, 0, FALSE},
{Ctrl_Z, nv_suspend, 0, 0},
{ESC, nv_esc, 0, FALSE},
{Ctrl_BSL, nv_normal, NV_NCH_ALW, 0},
{Ctrl_RSB, nv_ident, NV_NCW, 0},
{Ctrl_HAT, nv_hat, NV_NCW, 0},
{Ctrl__, nv_error, 0, 0},
{' ', nv_right, 0, 0},
{'!', nv_operator, 0, 0},
{'"', nv_regname, NV_NCH_NOP|NV_KEEPREG, 0},
{'#', nv_ident, 0, 0},
{'$', nv_dollar, 0, 0},
{'%', nv_percent, 0, 0},
{'&', nv_optrans, 0, 0},
{'\'', nv_gomark, NV_NCH_ALW, TRUE},
{'(', nv_brace, 0, BACKWARD},
{')', nv_brace, 0, FORWARD},
{'*', nv_ident, 0, 0},
{'+', nv_down, 0, TRUE},
{',', nv_csearch, 0, TRUE},
{'-', nv_up, 0, TRUE},
{'.', nv_dot, NV_KEEPREG, 0},
{'/', nv_search, 0, FALSE},
{'0', nv_beginline, 0, 0},
{'1', nv_ignore, 0, 0},
{'2', nv_ignore, 0, 0},
{'3', nv_ignore, 0, 0},
{'4', nv_ignore, 0, 0},
{'5', nv_ignore, 0, 0},
{'6', nv_ignore, 0, 0},
{'7', nv_ignore, 0, 0},
{'8', nv_ignore, 0, 0},
{'9', nv_ignore, 0, 0},
{':', nv_colon, 0, 0},
{';', nv_csearch, 0, FALSE},
{'<', nv_operator, NV_RL, 0},
{'=', nv_operator, 0, 0},
{'>', nv_operator, NV_RL, 0},
{'?', nv_search, 0, FALSE},
{'@', nv_at, NV_NCH_NOP, FALSE},
{'A', nv_edit, 0, 0},
{'B', nv_bck_word, 0, 1},
{'C', nv_abbrev, NV_KEEPREG, 0},
{'D', nv_abbrev, NV_KEEPREG, 0},
{'E', nv_wordcmd, 0, TRUE},
{'F', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD},
{'G', nv_goto, 0, TRUE},
{'H', nv_scroll, 0, 0},
{'I', nv_edit, 0, 0},
{'J', nv_join, 0, 0},
{'K', nv_ident, 0, 0},
{'L', nv_scroll, 0, 0},
{'M', nv_scroll, 0, 0},
{'N', nv_next, 0, SEARCH_REV},
{'O', nv_open, 0, 0},
{'P', nv_put, 0, 0},
{'Q', nv_exmode, NV_NCW, 0},
{'R', nv_Replace, 0, FALSE},
{'S', nv_subst, NV_KEEPREG, 0},
{'T', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD},
{'U', nv_Undo, 0, 0},
{'W', nv_wordcmd, 0, TRUE},
{'X', nv_abbrev, NV_KEEPREG, 0},
{'Y', nv_abbrev, NV_KEEPREG, 0},
{'Z', nv_Zet, NV_NCH_NOP|NV_NCW, 0},
{'[', nv_brackets, NV_NCH_ALW, BACKWARD},
{'\\', nv_error, 0, 0},
{']', nv_brackets, NV_NCH_ALW, FORWARD},
{'^', nv_beginline, 0, BL_WHITE | BL_FIX},
{'_', nv_lineop, 0, 0},
{'`', nv_gomark, NV_NCH_ALW, FALSE},
{'a', nv_edit, NV_NCH, 0},
{'b', nv_bck_word, 0, 0},
{'c', nv_operator, 0, 0},
{'d', nv_operator, 0, 0},
{'e', nv_wordcmd, 0, FALSE},
{'f', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD},
{'g', nv_g_cmd, NV_NCH_ALW, FALSE},
{'h', nv_left, NV_RL, 0},
{'i', nv_edit, NV_NCH, 0},
{'j', nv_down, 0, FALSE},
{'k', nv_up, 0, FALSE},
{'l', nv_right, NV_RL, 0},
{'m', nv_mark, NV_NCH_NOP, 0},
{'n', nv_next, 0, 0},
{'o', nv_open, 0, 0},
{'p', nv_put, 0, 0},
{'q', nv_record, NV_NCH, 0},
{'r', nv_replace, NV_NCH_NOP|NV_LANG, 0},
{'s', nv_subst, NV_KEEPREG, 0},
{'t', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD},
{'u', nv_undo, 0, 0},
{'w', nv_wordcmd, 0, FALSE},
{'x', nv_abbrev, NV_KEEPREG, 0},
{'y', nv_operator, 0, 0},
{'z', nv_zet, NV_NCH_ALW, 0},
{'{', nv_findpar, 0, BACKWARD},
{'|', nv_pipe, 0, 0},
{'}', nv_findpar, 0, FORWARD},
{'~', nv_tilde, 0, 0},
/* pound sign */
{POUND, nv_ident, 0, 0},
#ifdef FEAT_MOUSE
{K_MOUSEUP, nv_mousescroll, 0, MSCR_UP},
{K_MOUSEDOWN, nv_mousescroll, 0, MSCR_DOWN},
{K_MOUSELEFT, nv_mousescroll, 0, MSCR_LEFT},
{K_MOUSERIGHT, nv_mousescroll, 0, MSCR_RIGHT},
{K_LEFTMOUSE, nv_mouse, 0, 0},
{K_LEFTMOUSE_NM, nv_mouse, 0, 0},
{K_LEFTDRAG, nv_mouse, 0, 0},
{K_LEFTRELEASE, nv_mouse, 0, 0},
{K_LEFTRELEASE_NM, nv_mouse, 0, 0},
{K_MIDDLEMOUSE, nv_mouse, 0, 0},
{K_MIDDLEDRAG, nv_mouse, 0, 0},
{K_MIDDLERELEASE, nv_mouse, 0, 0},
{K_RIGHTMOUSE, nv_mouse, 0, 0},
{K_RIGHTDRAG, nv_mouse, 0, 0},
{K_RIGHTRELEASE, nv_mouse, 0, 0},
{K_X1MOUSE, nv_mouse, 0, 0},
{K_X1DRAG, nv_mouse, 0, 0},
{K_X1RELEASE, nv_mouse, 0, 0},
{K_X2MOUSE, nv_mouse, 0, 0},
{K_X2DRAG, nv_mouse, 0, 0},
{K_X2RELEASE, nv_mouse, 0, 0},
#endif
{K_IGNORE, nv_ignore, NV_KEEPREG, 0},
{K_NOP, nv_nop, 0, 0},
{K_INS, nv_edit, 0, 0},
{K_KINS, nv_edit, 0, 0},
{K_BS, nv_ctrlh, 0, 0},
{K_UP, nv_up, NV_SSS|NV_STS, FALSE},
{K_S_UP, nv_page, NV_SS, BACKWARD},
{K_DOWN, nv_down, NV_SSS|NV_STS, FALSE},
{K_S_DOWN, nv_page, NV_SS, FORWARD},
{K_LEFT, nv_left, NV_SSS|NV_STS|NV_RL, 0},
{K_S_LEFT, nv_bck_word, NV_SS|NV_RL, 0},
{K_C_LEFT, nv_bck_word, NV_SSS|NV_RL|NV_STS, 1},
{K_RIGHT, nv_right, NV_SSS|NV_STS|NV_RL, 0},
{K_S_RIGHT, nv_wordcmd, NV_SS|NV_RL, FALSE},
{K_C_RIGHT, nv_wordcmd, NV_SSS|NV_RL|NV_STS, TRUE},
{K_PAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD},
{K_KPAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD},
{K_PAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD},
{K_KPAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD},
{K_END, nv_end, NV_SSS|NV_STS, FALSE},
{K_KEND, nv_end, NV_SSS|NV_STS, FALSE},
{K_S_END, nv_end, NV_SS, FALSE},
{K_C_END, nv_end, NV_SSS|NV_STS, TRUE},
{K_HOME, nv_home, NV_SSS|NV_STS, 0},
{K_KHOME, nv_home, NV_SSS|NV_STS, 0},
{K_S_HOME, nv_home, NV_SS, 0},
{K_C_HOME, nv_goto, NV_SSS|NV_STS, FALSE},
{K_DEL, nv_abbrev, 0, 0},
{K_KDEL, nv_abbrev, 0, 0},
{K_UNDO, nv_kundo, 0, 0},
{K_HELP, nv_help, NV_NCW, 0},
{K_F1, nv_help, NV_NCW, 0},
{K_XF1, nv_help, NV_NCW, 0},
#ifdef FEAT_VISUAL
{K_SELECT, nv_select, 0, 0},
#endif
#ifdef FEAT_GUI
{K_VER_SCROLLBAR, nv_ver_scrollbar, 0, 0},
{K_HOR_SCROLLBAR, nv_hor_scrollbar, 0, 0},
#endif
#ifdef FEAT_GUI_TABLINE
{K_TABLINE, nv_tabline, 0, 0},
{K_TABMENU, nv_tabmenu, 0, 0},
#endif
#ifdef FEAT_FKMAP
{K_F8, farsi_fkey, 0, 0},
{K_F9, farsi_fkey, 0, 0},
#endif
#ifdef FEAT_SNIFF
{K_SNIFF, nv_sniff, 0, 0},
#endif
#ifdef FEAT_NETBEANS_INTG
{K_F21, nv_nbcmd, NV_NCH_ALW, 0},
#endif
#ifdef FEAT_DND
{K_DROP, nv_drop, NV_STS, 0},
#endif
#ifdef FEAT_AUTOCMD
{K_CURSORHOLD, nv_cursorhold, NV_KEEPREG, 0},
#endif
};
/* Number of commands in nv_cmds[]. */
#define NV_CMDS_SIZE (sizeof(nv_cmds) / sizeof(struct nv_cmd))
/* Sorted index of commands in nv_cmds[]. */
static short nv_cmd_idx[NV_CMDS_SIZE];
/* The highest index for which
* nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char] */
static int nv_max_linear;
/*
* Compare functions for qsort() below, that checks the command character
* through the index in nv_cmd_idx[].
*/
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
nv_compare(s1, s2)
const void *s1;
const void *s2;
{
int c1, c2;
/* The commands are sorted on absolute value. */
c1 = nv_cmds[*(const short *)s1].cmd_char;
c2 = nv_cmds[*(const short *)s2].cmd_char;
if (c1 < 0)
c1 = -c1;
if (c2 < 0)
c2 = -c2;
return c1 - c2;
}
/*
* Initialize the nv_cmd_idx[] table.
*/
void
init_normal_cmds()
{
int i;
/* Fill the index table with a one to one relation. */
for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
nv_cmd_idx[i] = i;
/* Sort the commands by the command character. */
qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare);
/* Find the first entry that can't be indexed by the command character. */
for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
if (i != nv_cmds[nv_cmd_idx[i]].cmd_char)
break;
nv_max_linear = i - 1;
}
/*
* Search for a command in the commands table.
* Returns -1 for invalid command.
*/
static int
find_command(cmdchar)
int cmdchar;
{
int i;
int idx;
int top, bot;
int c;
#ifdef FEAT_MBYTE
/* A multi-byte character is never a command. */
if (cmdchar >= 0x100)
return -1;
#endif
/* We use the absolute value of the character. Special keys have a
* negative value, but are sorted on their absolute value. */
if (cmdchar < 0)
cmdchar = -cmdchar;
/* If the character is in the first part: The character is the index into
* nv_cmd_idx[]. */
if (cmdchar <= nv_max_linear)
return nv_cmd_idx[cmdchar];
/* Perform a binary search. */
bot = nv_max_linear + 1;
top = NV_CMDS_SIZE - 1;
idx = -1;
while (bot <= top)
{
i = (top + bot) / 2;
c = nv_cmds[nv_cmd_idx[i]].cmd_char;
if (c < 0)
c = -c;
if (cmdchar == c)
{
idx = nv_cmd_idx[i];
break;
}
if (cmdchar > c)
bot = i + 1;
else
top = i - 1;
}
return idx;
}
/*
* Execute a command in Normal mode.
*/
void
normal_cmd(oap, toplevel)
oparg_T *oap;
int toplevel UNUSED; /* TRUE when called from main() */
{
cmdarg_T ca; /* command arguments */
int c;
int ctrl_w = FALSE; /* got CTRL-W command */
int old_col = curwin->w_curswant;
#ifdef FEAT_CMDL_INFO
int need_flushbuf; /* need to call out_flush() */
#endif
#ifdef FEAT_VISUAL
pos_T old_pos; /* cursor position before command */
int mapped_len;
static int old_mapped_len = 0;
#endif
int idx;
#ifdef FEAT_EVAL
int set_prevcount = FALSE;
#endif
vim_memset(&ca, 0, sizeof(ca)); /* also resets ca.retval */
ca.oap = oap;
/* Use a count remembered from before entering an operator. After typing
* "3d" we return from normal_cmd() and come back here, the "3" is
* remembered in "opcount". */
ca.opcount = opcount;
#ifdef FEAT_SNIFF
want_sniff_request = sniff_connected;
#endif
/*
* If there is an operator pending, then the command we take this time
* will terminate it. Finish_op tells us to finish the operation before
* returning this time (unless the operation was cancelled).
*/
#ifdef CURSOR_SHAPE
c = finish_op;
#endif
finish_op = (oap->op_type != OP_NOP);
#ifdef CURSOR_SHAPE
if (finish_op != c)
{
ui_cursor_shape(); /* may show different cursor shape */
# ifdef FEAT_MOUSESHAPE
update_mouseshape(-1);
# endif
}
#endif
/* When not finishing an operator and no register name typed, reset the
* count. */
if (!finish_op && !oap->regname)
{
ca.opcount = 0;
#ifdef FEAT_EVAL
set_prevcount = TRUE;
#endif
}
#ifdef FEAT_AUTOCMD
/* Restore counts from before receiving K_CURSORHOLD. This means after
* typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not
* "3 * 2". */
if (oap->prev_opcount > 0 || oap->prev_count0 > 0)
{
ca.opcount = oap->prev_opcount;
ca.count0 = oap->prev_count0;
oap->prev_opcount = 0;
oap->prev_count0 = 0;
}
#endif
#ifdef FEAT_VISUAL
mapped_len = typebuf_maplen();
#endif
State = NORMAL_BUSY;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; /* allow scrolling here */
#endif
#ifdef FEAT_EVAL
/* Set v:count here, when called from main() and not a stuffed
* command, so that v:count can be used in an expression mapping
* when there is no count. */
if (toplevel && stuff_empty())
set_vcount_ca(&ca, &set_prevcount);
#endif
/*
* Get the command character from the user.
*/
c = safe_vgetc();
LANGMAP_ADJUST(c, TRUE);
#ifdef FEAT_VISUAL
/*
* If a mapping was started in Visual or Select mode, remember the length
* of the mapping. This is used below to not return to Insert mode for as
* long as the mapping is being executed.
*/
if (restart_edit == 0)
old_mapped_len = 0;
else if (old_mapped_len
|| (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0))
old_mapped_len = typebuf_maplen();
#endif
if (c == NUL)
c = K_ZERO;
#ifdef FEAT_VISUAL
/*
* In Select mode, typed text replaces the selection.
*/
if (VIsual_active
&& VIsual_select
&& (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER))
{
/* Fake a "c"hange command. When "restart_edit" is set (e.g., because
* 'insertmode' is set) fake a "d"elete command, Insert mode will
* restart automatically.
* Insert the typed character in the typeahead buffer, so that it can
* be mapped in Insert mode. Required for ":lmap" to work. */
ins_char_typebuf(c);
if (restart_edit != 0)
c = 'd';
else
c = 'c';
msg_nowait = TRUE; /* don't delay going to insert mode */
}
#endif
#ifdef FEAT_CMDL_INFO
need_flushbuf = add_to_showcmd(c);
#endif
getcount:
#ifdef FEAT_VISUAL
if (!(VIsual_active && VIsual_select))
#endif
{
/*
* Handle a count before a command and compute ca.count0.
* Note that '0' is a command and not the start of a count, but it's
* part of a count after other digits.
*/
while ( (c >= '1' && c <= '9')
|| (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0')))
{
if (c == K_DEL || c == K_KDEL)
{
ca.count0 /= 10;
#ifdef FEAT_CMDL_INFO
del_from_showcmd(4); /* delete the digit and ~@% */
#endif
}
else
ca.count0 = ca.count0 * 10 + (c - '0');
if (ca.count0 < 0) /* got too large! */
ca.count0 = 999999999L;
#ifdef FEAT_EVAL
/* Set v:count here, when called from main() and not a stuffed
* command, so that v:count can be used in an expression mapping
* right after the count. */
if (toplevel && stuff_empty())
set_vcount_ca(&ca, &set_prevcount);
#endif
if (ctrl_w)
{
++no_mapping;
++allow_keys; /* no mapping for nchar, but keys */
}
++no_zero_mapping; /* don't map zero here */
c = plain_vgetc();
LANGMAP_ADJUST(c, TRUE);
--no_zero_mapping;
if (ctrl_w)
{
--no_mapping;
--allow_keys;
}
#ifdef FEAT_CMDL_INFO
need_flushbuf |= add_to_showcmd(c);
#endif
}
/*
* If we got CTRL-W there may be a/another count
*/
if (c == Ctrl_W && !ctrl_w && oap->op_type == OP_NOP)
{
ctrl_w = TRUE;
ca.opcount = ca.count0; /* remember first count */
ca.count0 = 0;
++no_mapping;
++allow_keys; /* no mapping for nchar, but keys */
c = plain_vgetc(); /* get next character */
LANGMAP_ADJUST(c, TRUE);
--no_mapping;
--allow_keys;
#ifdef FEAT_CMDL_INFO
need_flushbuf |= add_to_showcmd(c);
#endif
goto getcount; /* jump back */
}
}
#ifdef FEAT_AUTOCMD
if (c == K_CURSORHOLD)
{
/* Save the count values so that ca.opcount and ca.count0 are exactly
* the same when coming back here after handling K_CURSORHOLD. */
oap->prev_opcount = ca.opcount;
oap->prev_count0 = ca.count0;
}
else
#endif
if (ca.opcount != 0)
{
/*
* If we're in the middle of an operator (including after entering a
* yank buffer with '"') AND we had a count before the operator, then
* that count overrides the current value of ca.count0.
* What this means effectively, is that commands like "3dw" get turned
* into "d3w" which makes things fall into place pretty neatly.
* If you give a count before AND after the operator, they are
* multiplied.
*/
if (ca.count0)
ca.count0 *= ca.opcount;
else
ca.count0 = ca.opcount;
}
/*
* Always remember the count. It will be set to zero (on the next call,
* above) when there is no pending operator.
* When called from main(), save the count for use by the "count" built-in
* variable.
*/
ca.opcount = ca.count0;
ca.count1 = (ca.count0 == 0 ? 1 : ca.count0);
#ifdef FEAT_EVAL
/*
* Only set v:count when called from main() and not a stuffed command.
*/
if (toplevel && stuff_empty())
set_vcount(ca.count0, ca.count1, set_prevcount);
#endif
/*
* Find the command character in the table of commands.
* For CTRL-W we already got nchar when looking for a count.
*/
if (ctrl_w)
{
ca.nchar = c;
ca.cmdchar = Ctrl_W;
}
else
ca.cmdchar = c;
idx = find_command(ca.cmdchar);
if (idx < 0)
{
/* Not a known command: beep. */
clearopbeep(oap);
goto normal_end;
}
if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW))
{
/* This command is not allowed while editing a ccmdline: beep. */
clearopbeep(oap);
text_locked_msg();
goto normal_end;
}
#ifdef FEAT_AUTOCMD
if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked())
goto normal_end;
#endif
#ifdef FEAT_VISUAL
/*
* In Visual/Select mode, a few keys are handled in a special way.
*/
if (VIsual_active)
{
/* when 'keymodel' contains "stopsel" may stop Select/Visual mode */
if (km_stopsel
&& (nv_cmds[idx].cmd_flags & NV_STS)
&& !(mod_mask & MOD_MASK_SHIFT))
{
end_visual_mode();
redraw_curbuf_later(INVERTED);
}
/* Keys that work different when 'keymodel' contains "startsel" */
if (km_startsel)
{
if (nv_cmds[idx].cmd_flags & NV_SS)
{
unshift_special(&ca);
idx = find_command(ca.cmdchar);
if (idx < 0)
{
/* Just in case */
clearopbeep(oap);
goto normal_end;
}
}
else if ((nv_cmds[idx].cmd_flags & NV_SSS)
&& (mod_mask & MOD_MASK_SHIFT))
{
mod_mask &= ~MOD_MASK_SHIFT;
}
}
}
#endif
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl && KeyTyped && !KeyStuffed
&& (nv_cmds[idx].cmd_flags & NV_RL))
{
/* Invert horizontal movements and operations. Only when typed by the
* user directly, not when the result of a mapping or "x" translated
* to "dl". */
switch (ca.cmdchar)
{
case 'l': ca.cmdchar = 'h'; break;
case K_RIGHT: ca.cmdchar = K_LEFT; break;
case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break;
case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break;
case 'h': ca.cmdchar = 'l'; break;
case K_LEFT: ca.cmdchar = K_RIGHT; break;
case K_S_LEFT: ca.cmdchar = K_S_RIGHT; break;
case K_C_LEFT: ca.cmdchar = K_C_RIGHT; break;
case '>': ca.cmdchar = '<'; break;
case '<': ca.cmdchar = '>'; break;
}
idx = find_command(ca.cmdchar);
}
#endif
/*
* Get an additional character if we need one.
*/
if ((nv_cmds[idx].cmd_flags & NV_NCH)
&& (((nv_cmds[idx].cmd_flags & NV_NCH_NOP) == NV_NCH_NOP
&& oap->op_type == OP_NOP)
|| (nv_cmds[idx].cmd_flags & NV_NCH_ALW) == NV_NCH_ALW
|| (ca.cmdchar == 'q'
&& oap->op_type == OP_NOP
&& !Recording
&& !Exec_reg)
|| ((ca.cmdchar == 'a' || ca.cmdchar == 'i')
&& (oap->op_type != OP_NOP
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
))))
{
int *cp;
int repl = FALSE; /* get character for replace mode */
int lit = FALSE; /* get extra character literally */
int langmap_active = FALSE; /* using :lmap mappings */
int lang; /* getting a text character */
#ifdef USE_IM_CONTROL
int save_smd; /* saved value of p_smd */
#endif
++no_mapping;
++allow_keys; /* no mapping for nchar, but allow key codes */
#ifdef FEAT_AUTOCMD
/* Don't generate a CursorHold event here, most commands can't handle
* it, e.g., nv_replace(), nv_csearch(). */
did_cursorhold = TRUE;
#endif
if (ca.cmdchar == 'g')
{
/*
* For 'g' get the next character now, so that we can check for
* "gr", "g'" and "g`".
*/
ca.nchar = plain_vgetc();
LANGMAP_ADJUST(ca.nchar, TRUE);
#ifdef FEAT_CMDL_INFO
need_flushbuf |= add_to_showcmd(ca.nchar);
#endif
if (ca.nchar == 'r' || ca.nchar == '\'' || ca.nchar == '`'
|| ca.nchar == Ctrl_BSL)
{
cp = &ca.extra_char; /* need to get a third character */
if (ca.nchar != 'r')
lit = TRUE; /* get it literally */
else
repl = TRUE; /* get it in replace mode */
}
else
cp = NULL; /* no third character needed */
}
else
{
if (ca.cmdchar == 'r') /* get it in replace mode */
repl = TRUE;
cp = &ca.nchar;
}
lang = (repl || (nv_cmds[idx].cmd_flags & NV_LANG));
/*
* Get a second or third character.
*/
if (cp != NULL)
{
#ifdef CURSOR_SHAPE
if (repl)
{
State = REPLACE; /* pretend Replace mode */
ui_cursor_shape(); /* show different cursor shape */
}
#endif
if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP)
{
/* Allow mappings defined with ":lmap". */
--no_mapping;
--allow_keys;
if (repl)
State = LREPLACE;
else
State = LANGMAP;
langmap_active = TRUE;
}
#ifdef USE_IM_CONTROL
save_smd = p_smd;
p_smd = FALSE; /* Don't let the IM code show the mode here */
if (lang && curbuf->b_p_iminsert == B_IMODE_IM)
im_set_active(TRUE);
#endif
*cp = plain_vgetc();
if (langmap_active)
{
/* Undo the decrement done above */
++no_mapping;
++allow_keys;
State = NORMAL_BUSY;
}
#ifdef USE_IM_CONTROL
if (lang)
{
if (curbuf->b_p_iminsert != B_IMODE_LMAP)
im_save_status(&curbuf->b_p_iminsert);
im_set_active(FALSE);
}
p_smd = save_smd;
#endif
#ifdef CURSOR_SHAPE
State = NORMAL_BUSY;
#endif
#ifdef FEAT_CMDL_INFO
need_flushbuf |= add_to_showcmd(*cp);
#endif
if (!lit)
{
#ifdef FEAT_DIGRAPHS
/* Typing CTRL-K gets a digraph. */
if (*cp == Ctrl_K
&& ((nv_cmds[idx].cmd_flags & NV_LANG)
|| cp == &ca.extra_char)
&& vim_strchr(p_cpo, CPO_DIGRAPH) == NULL)
{
c = get_digraph(FALSE);
if (c > 0)
{
*cp = c;
# ifdef FEAT_CMDL_INFO
/* Guessing how to update showcmd here... */
del_from_showcmd(3);
need_flushbuf |= add_to_showcmd(*cp);
# endif
}
}
#endif
/* adjust chars > 127, except after "tTfFr" commands */
LANGMAP_ADJUST(*cp, !lang);
#ifdef FEAT_RIGHTLEFT
/* adjust Hebrew mapped char */
if (p_hkmap && lang && KeyTyped)
*cp = hkmap(*cp);
# ifdef FEAT_FKMAP
/* adjust Farsi mapped char */
if (p_fkmap && lang && KeyTyped)
*cp = fkmap(*cp);
# endif
#endif
}
/*
* When the next character is CTRL-\ a following CTRL-N means the
* command is aborted and we go to Normal mode.
*/
if (cp == &ca.extra_char
&& ca.nchar == Ctrl_BSL
&& (ca.extra_char == Ctrl_N || ca.extra_char == Ctrl_G))
{
ca.cmdchar = Ctrl_BSL;
ca.nchar = ca.extra_char;
idx = find_command(ca.cmdchar);
}
else if (*cp == Ctrl_BSL)
{
long towait = (p_ttm >= 0 ? p_ttm : p_tm);
/* There is a busy wait here when typing "f<C-\>" and then
* something different from CTRL-N. Can't be avoided. */
while ((c = vpeekc()) <= 0 && towait > 0L)
{
do_sleep(towait > 50L ? 50L : towait);
towait -= 50L;
}
if (c > 0)
{
c = plain_vgetc();
if (c != Ctrl_N && c != Ctrl_G)
vungetc(c);
else
{
ca.cmdchar = Ctrl_BSL;
ca.nchar = c;
idx = find_command(ca.cmdchar);
}
}
}
#ifdef FEAT_MBYTE
/* When getting a text character and the next character is a
* multi-byte character, it could be a composing character.
* However, don't wait for it to arrive. */
while (enc_utf8 && lang && (c = vpeekc()) > 0
&& (c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1))
{
c = plain_vgetc();
if (!utf_iscomposing(c))
{
vungetc(c); /* it wasn't, put it back */
break;
}
else if (ca.ncharC1 == 0)
ca.ncharC1 = c;
else
ca.ncharC2 = c;
}
#endif
}
--no_mapping;
--allow_keys;
}
#ifdef FEAT_CMDL_INFO
/*
* Flush the showcmd characters onto the screen so we can see them while
* the command is being executed. Only do this when the shown command was
* actually displayed, otherwise this will slow down a lot when executing
* mappings.
*/
if (need_flushbuf)
out_flush();
#endif
#ifdef FEAT_AUTOCMD
if (ca.cmdchar != K_IGNORE)
did_cursorhold = FALSE;
#endif
State = NORMAL;
if (ca.nchar == ESC)
{
clearop(oap);
if (restart_edit == 0 && goto_im())
restart_edit = 'a';
goto normal_end;
}
if (ca.cmdchar != K_IGNORE)
{
msg_didout = FALSE; /* don't scroll screen up for normal command */
msg_col = 0;
}
#ifdef FEAT_VISUAL
old_pos = curwin->w_cursor; /* remember where cursor was */
/* When 'keymodel' contains "startsel" some keys start Select/Visual
* mode. */
if (!VIsual_active && km_startsel)
{
if (nv_cmds[idx].cmd_flags & NV_SS)
{
start_selection();
unshift_special(&ca);
idx = find_command(ca.cmdchar);
}
else if ((nv_cmds[idx].cmd_flags & NV_SSS)
&& (mod_mask & MOD_MASK_SHIFT))
{
start_selection();
mod_mask &= ~MOD_MASK_SHIFT;
}
}
#endif
/*
* Execute the command!
* Call the command function found in the commands table.
*/
ca.arg = nv_cmds[idx].cmd_arg;
(nv_cmds[idx].cmd_func)(&ca);
/*
* If we didn't start or finish an operator, reset oap->regname, unless we
* need it later.
*/
if (!finish_op
&& !oap->op_type
&& (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG)))
{
clearop(oap);
#ifdef FEAT_EVAL
{
int regname = 0;
/* Adjust the register according to 'clipboard', so that when
* "unnamed" is present it becomes '*' or '+' instead of '"'. */
# ifdef FEAT_CLIPBOARD
adjust_clip_reg(®name);
# endif
set_reg_var(regname);
}
#endif
}
#ifdef FEAT_VISUAL
/* Get the length of mapped chars again after typing a count, second
* character or "z333<cr>". */
if (old_mapped_len > 0)
old_mapped_len = typebuf_maplen();
#endif
/*
* If an operation is pending, handle it...
*/
do_pending_operator(&ca, old_col, FALSE);
/*
* Wait for a moment when a message is displayed that will be overwritten
* by the mode message.
* In Visual mode and with "^O" in Insert mode, a short message will be
* overwritten by the mode message. Wait a bit, until a key is hit.
* In Visual mode, it's more important to keep the Visual area updated
* than keeping a message (e.g. from a /pat search).
* Only do this if the command was typed, not from a mapping.
* Don't wait when emsg_silent is non-zero.
* Also wait a bit after an error message, e.g. for "^O:".
* Don't redraw the screen, it would remove the message.
*/
if ( ((p_smd
&& msg_silent == 0
&& (restart_edit != 0
#ifdef FEAT_VISUAL
|| (VIsual_active
&& old_pos.lnum == curwin->w_cursor.lnum
&& old_pos.col == curwin->w_cursor.col)
#endif
)
&& (clear_cmdline
|| redraw_cmdline)
&& (msg_didout || (msg_didany && msg_scroll))
&& !msg_nowait
&& KeyTyped)
|| (restart_edit != 0
#ifdef FEAT_VISUAL
&& !VIsual_active
#endif
&& (msg_scroll
|| emsg_on_display)))
&& oap->regname == 0
&& !(ca.retval & CA_COMMAND_BUSY)
&& stuff_empty()
&& typebuf_typed()
&& emsg_silent == 0
&& !did_wait_return
&& oap->op_type == OP_NOP)
{
int save_State = State;
/* Draw the cursor with the right shape here */
if (restart_edit != 0)
State = INSERT;
/* If need to redraw, and there is a "keep_msg", redraw before the
* delay */
if (must_redraw && keep_msg != NULL && !emsg_on_display)
{
char_u *kmsg;
kmsg = keep_msg;
keep_msg = NULL;
/* showmode() will clear keep_msg, but we want to use it anyway */
update_screen(0);
/* now reset it, otherwise it's put in the history again */
keep_msg = kmsg;
msg_attr(kmsg, keep_msg_attr);
vim_free(kmsg);
}
setcursor();
cursor_on();
out_flush();
if (msg_scroll || emsg_on_display)
ui_delay(1000L, TRUE); /* wait at least one second */
ui_delay(3000L, FALSE); /* wait up to three seconds */
State = save_State;
msg_scroll = FALSE;
emsg_on_display = FALSE;
}
/*
* Finish up after executing a Normal mode command.
*/
normal_end:
msg_nowait = FALSE;
/* Reset finish_op, in case it was set */
#ifdef CURSOR_SHAPE
c = finish_op;
#endif
finish_op = FALSE;
#ifdef CURSOR_SHAPE
/* Redraw the cursor with another shape, if we were in Operator-pending
* mode or did a replace command. */
if (c || ca.cmdchar == 'r')
{
ui_cursor_shape(); /* may show different cursor shape */
# ifdef FEAT_MOUSESHAPE
update_mouseshape(-1);
# endif
}
#endif
#ifdef FEAT_CMDL_INFO
if (oap->op_type == OP_NOP && oap->regname == 0
# ifdef FEAT_AUTOCMD
&& ca.cmdchar != K_CURSORHOLD
# endif
)
clear_showcmd();
#endif
checkpcmark(); /* check if we moved since setting pcmark */
vim_free(ca.searchbuf);
#ifdef FEAT_MBYTE
if (has_mbyte)
mb_adjust_cursor();
#endif
#ifdef FEAT_SCROLLBIND
if (curwin->w_p_scb && toplevel)
{
validate_cursor(); /* may need to update w_leftcol */
do_check_scrollbind(TRUE);
}
#endif
#ifdef FEAT_CURSORBIND
if (curwin->w_p_crb && toplevel)
{
validate_cursor(); /* may need to update w_leftcol */
do_check_cursorbind();
}
#endif
/*
* May restart edit(), if we got here with CTRL-O in Insert mode (but not
* if still inside a mapping that started in Visual mode).
* May switch from Visual to Select mode after CTRL-O command.
*/
if ( oap->op_type == OP_NOP
#ifdef FEAT_VISUAL
&& ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0)
|| restart_VIsual_select == 1)
#else
&& restart_edit != 0
#endif
&& !(ca.retval & CA_COMMAND_BUSY)
&& stuff_empty()
&& oap->regname == 0)
{
#ifdef FEAT_VISUAL
if (restart_VIsual_select == 1)
{
VIsual_select = TRUE;
showmode();
restart_VIsual_select = 0;
}
#endif
if (restart_edit != 0
#ifdef FEAT_VISUAL
&& !VIsual_active && old_mapped_len == 0
#endif
)
(void)edit(restart_edit, FALSE, 1L);
}
#ifdef FEAT_VISUAL
if (restart_VIsual_select == 2)
restart_VIsual_select = 1;
#endif
/* Save count before an operator for next time. */
opcount = ca.opcount;
}
#ifdef FEAT_EVAL
/*
* Set v:count and v:count1 according to "cap".
* Set v:prevcount only when "set_prevcount" is TRUE.
*/
static void
set_vcount_ca(cap, set_prevcount)
cmdarg_T *cap;
int *set_prevcount;
{
long count = cap->count0;
/* multiply with cap->opcount the same way as above */
if (cap->opcount != 0)
count = cap->opcount * (count == 0 ? 1 : count);
set_vcount(count, count == 0 ? 1 : count, *set_prevcount);
*set_prevcount = FALSE; /* only set v:prevcount once */
}
#endif
/*
* Handle an operator after visual mode or when the movement is finished
*/
void
do_pending_operator(cap, old_col, gui_yank)
cmdarg_T *cap;
int old_col;
int gui_yank;
{
oparg_T *oap = cap->oap;
pos_T old_cursor;
int empty_region_error;
int restart_edit_save;
#ifdef FEAT_VISUAL
/* The visual area is remembered for redo */
static int redo_VIsual_mode = NUL; /* 'v', 'V', or Ctrl-V */
static linenr_T redo_VIsual_line_count; /* number of lines */
static colnr_T redo_VIsual_vcol; /* number of cols or end column */
static long redo_VIsual_count; /* count for Visual operator */
# ifdef FEAT_VIRTUALEDIT
int include_line_break = FALSE;
# endif
#endif
#if defined(FEAT_CLIPBOARD)
/*
* Yank the visual area into the GUI selection register before we operate
* on it and lose it forever.
* Don't do it if a specific register was specified, so that ""x"*P works.
* This could call do_pending_operator() recursively, but that's OK
* because gui_yank will be TRUE for the nested call.
*/
if (clip_star.available
&& oap->op_type != OP_NOP
&& !gui_yank
# ifdef FEAT_VISUAL
&& VIsual_active
&& !redo_VIsual_busy
# endif
&& oap->regname == 0)
clip_auto_select();
#endif
old_cursor = curwin->w_cursor;
/*
* If an operation is pending, handle it...
*/
if ((finish_op
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
) && oap->op_type != OP_NOP)
{
#ifdef FEAT_VISUAL
oap->is_VIsual = VIsual_active;
if (oap->motion_force == 'V')
oap->motion_type = MLINE;
else if (oap->motion_force == 'v')
{
/* If the motion was linewise, "inclusive" will not have been set.
* Use "exclusive" to be consistent. Makes "dvj" work nice. */
if (oap->motion_type == MLINE)
oap->inclusive = FALSE;
/* If the motion already was characterwise, toggle "inclusive" */
else if (oap->motion_type == MCHAR)
oap->inclusive = !oap->inclusive;
oap->motion_type = MCHAR;
}
else if (oap->motion_force == Ctrl_V)
{
/* Change line- or characterwise motion into Visual block mode. */
VIsual_active = TRUE;
VIsual = oap->start;
VIsual_mode = Ctrl_V;
VIsual_select = FALSE;
VIsual_reselect = FALSE;
}
#endif
/* only redo yank when 'y' flag is in 'cpoptions' */
/* never redo "zf" (define fold) */
if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
#ifdef FEAT_VISUAL
&& (!VIsual_active || oap->motion_force)
#endif
&& cap->cmdchar != 'D'
#ifdef FEAT_FOLDING
&& oap->op_type != OP_FOLD
&& oap->op_type != OP_FOLDOPEN
&& oap->op_type != OP_FOLDOPENREC
&& oap->op_type != OP_FOLDCLOSE
&& oap->op_type != OP_FOLDCLOSEREC
&& oap->op_type != OP_FOLDDEL
&& oap->op_type != OP_FOLDDELREC
#endif
)
{
prep_redo(oap->regname, cap->count0,
get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
oap->motion_force, cap->cmdchar, cap->nchar);
if (cap->cmdchar == '/' || cap->cmdchar == '?') /* was a search */
{
/*
* If 'cpoptions' does not contain 'r', insert the search
* pattern to really repeat the same command.
*/
if (vim_strchr(p_cpo, CPO_REDO) == NULL)
AppendToRedobuffLit(cap->searchbuf, -1);
AppendToRedobuff(NL_STR);
}
else if (cap->cmdchar == ':')
{
/* do_cmdline() has stored the first typed line in
* "repeat_cmdline". When several lines are typed repeating
* won't be possible. */
if (repeat_cmdline == NULL)
ResetRedobuff();
else
{
AppendToRedobuffLit(repeat_cmdline, -1);
AppendToRedobuff(NL_STR);
vim_free(repeat_cmdline);
repeat_cmdline = NULL;
}
}
}
#ifdef FEAT_VISUAL
if (redo_VIsual_busy)
{
/* Redo of an operation on a Visual area. Use the same size from
* redo_VIsual_line_count and redo_VIsual_vcol. */
oap->start = curwin->w_cursor;
curwin->w_cursor.lnum += redo_VIsual_line_count - 1;
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
VIsual_mode = redo_VIsual_mode;
if (redo_VIsual_vcol == MAXCOL || VIsual_mode == 'v')
{
if (VIsual_mode == 'v')
{
if (redo_VIsual_line_count <= 1)
{
validate_virtcol();
curwin->w_curswant =
curwin->w_virtcol + redo_VIsual_vcol - 1;
}
else
curwin->w_curswant = redo_VIsual_vcol;
}
else
{
curwin->w_curswant = MAXCOL;
}
coladvance(curwin->w_curswant);
}
cap->count0 = redo_VIsual_count;
if (redo_VIsual_count != 0)
cap->count1 = redo_VIsual_count;
else
cap->count1 = 1;
}
else if (VIsual_active)
{
if (!gui_yank)
{
/* Save the current VIsual area for '< and '> marks, and "gv" */
curbuf->b_visual.vi_start = VIsual;
curbuf->b_visual.vi_end = curwin->w_cursor;
curbuf->b_visual.vi_mode = VIsual_mode;
curbuf->b_visual.vi_curswant = curwin->w_curswant;
# ifdef FEAT_EVAL
curbuf->b_visual_mode_eval = VIsual_mode;
# endif
}
/* In Select mode, a linewise selection is operated upon like a
* characterwise selection. */
if (VIsual_select && VIsual_mode == 'V')
{
if (lt(VIsual, curwin->w_cursor))
{
VIsual.col = 0;
curwin->w_cursor.col =
(colnr_T)STRLEN(ml_get(curwin->w_cursor.lnum));
}
else
{
curwin->w_cursor.col = 0;
VIsual.col = (colnr_T)STRLEN(ml_get(VIsual.lnum));
}
VIsual_mode = 'v';
}
/* If 'selection' is "exclusive", backup one character for
* charwise selections. */
else if (VIsual_mode == 'v')
{
# ifdef FEAT_VIRTUALEDIT
include_line_break =
# endif
unadjust_for_sel();
}
oap->start = VIsual;
if (VIsual_mode == 'V')
oap->start.col = 0;
}
#endif /* FEAT_VISUAL */
/*
* Set oap->start to the first position of the operated text, oap->end
* to the end of the operated text. w_cursor is equal to oap->start.
*/
if (lt(oap->start, curwin->w_cursor))
{
#ifdef FEAT_FOLDING
/* Include folded lines completely. */
if (!VIsual_active)
{
if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL))
oap->start.col = 0;
if (hasFolding(curwin->w_cursor.lnum, NULL,
&curwin->w_cursor.lnum))
curwin->w_cursor.col = (colnr_T)STRLEN(ml_get_curline());
}
#endif
oap->end = curwin->w_cursor;
curwin->w_cursor = oap->start;
/* w_virtcol may have been updated; if the cursor goes back to its
* previous position w_virtcol becomes invalid and isn't updated
* automatically. */
curwin->w_valid &= ~VALID_VIRTCOL;
}
else
{
#ifdef FEAT_FOLDING
/* Include folded lines completely. */
if (!VIsual_active && oap->motion_type == MLINE)
{
if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum,
NULL))
curwin->w_cursor.col = 0;
if (hasFolding(oap->start.lnum, NULL, &oap->start.lnum))
oap->start.col = (colnr_T)STRLEN(ml_get(oap->start.lnum));
}
#endif
oap->end = oap->start;
oap->start = curwin->w_cursor;
}
oap->line_count = oap->end.lnum - oap->start.lnum + 1;
#ifdef FEAT_VIRTUALEDIT
/* Set "virtual_op" before resetting VIsual_active. */
virtual_op = virtual_active();
#endif
#ifdef FEAT_VISUAL
if (VIsual_active || redo_VIsual_busy)
{
if (VIsual_mode == Ctrl_V) /* block mode */
{
colnr_T start, end;
oap->block_mode = TRUE;
getvvcol(curwin, &(oap->start),
&oap->start_vcol, NULL, &oap->end_vcol);
if (!redo_VIsual_busy)
{
getvvcol(curwin, &(oap->end), &start, NULL, &end);
if (start < oap->start_vcol)
oap->start_vcol = start;
if (end > oap->end_vcol)
{
if (*p_sel == 'e' && start >= 1
&& start - 1 >= oap->end_vcol)
oap->end_vcol = start - 1;
else
oap->end_vcol = end;
}
}
/* if '$' was used, get oap->end_vcol from longest line */
if (curwin->w_curswant == MAXCOL)
{
curwin->w_cursor.col = MAXCOL;
oap->end_vcol = 0;
for (curwin->w_cursor.lnum = oap->start.lnum;
curwin->w_cursor.lnum <= oap->end.lnum;
++curwin->w_cursor.lnum)
{
getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &end);
if (end > oap->end_vcol)
oap->end_vcol = end;
}
}
else if (redo_VIsual_busy)
oap->end_vcol = oap->start_vcol + redo_VIsual_vcol - 1;
/*
* Correct oap->end.col and oap->start.col to be the
* upper-left and lower-right corner of the block area.
*
* (Actually, this does convert column positions into character
* positions)
*/
curwin->w_cursor.lnum = oap->end.lnum;
coladvance(oap->end_vcol);
oap->end = curwin->w_cursor;
curwin->w_cursor = oap->start;
coladvance(oap->start_vcol);
oap->start = curwin->w_cursor;
}
if (!redo_VIsual_busy && !gui_yank)
{
/*
* Prepare to reselect and redo Visual: this is based on the
* size of the Visual text
*/
resel_VIsual_mode = VIsual_mode;
if (curwin->w_curswant == MAXCOL)
resel_VIsual_vcol = MAXCOL;
else
{
if (VIsual_mode != Ctrl_V)
getvvcol(curwin, &(oap->end),
NULL, NULL, &oap->end_vcol);
if (VIsual_mode == Ctrl_V || oap->line_count <= 1)
{
if (VIsual_mode != Ctrl_V)
getvvcol(curwin, &(oap->start),
&oap->start_vcol, NULL, NULL);
resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1;
}
else
resel_VIsual_vcol = oap->end_vcol;
}
resel_VIsual_line_count = oap->line_count;
}
/* can't redo yank (unless 'y' is in 'cpoptions') and ":" */
if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
&& oap->op_type != OP_COLON
#ifdef FEAT_FOLDING
&& oap->op_type != OP_FOLD
&& oap->op_type != OP_FOLDOPEN
&& oap->op_type != OP_FOLDOPENREC
&& oap->op_type != OP_FOLDCLOSE
&& oap->op_type != OP_FOLDCLOSEREC
&& oap->op_type != OP_FOLDDEL
&& oap->op_type != OP_FOLDDELREC
#endif
&& oap->motion_force == NUL
)
{
/* Prepare for redoing. Only use the nchar field for "r",
* otherwise it might be the second char of the operator. */
prep_redo(oap->regname, 0L, NUL, 'v',
get_op_char(oap->op_type),
get_extra_op_char(oap->op_type),
oap->op_type == OP_REPLACE ? cap->nchar : NUL);
if (!redo_VIsual_busy)
{
redo_VIsual_mode = resel_VIsual_mode;
redo_VIsual_vcol = resel_VIsual_vcol;
redo_VIsual_line_count = resel_VIsual_line_count;
redo_VIsual_count = cap->count0;
}
}
/*
* oap->inclusive defaults to TRUE.
* If oap->end is on a NUL (empty line) oap->inclusive becomes
* FALSE. This makes "d}P" and "v}dP" work the same.
*/
if (oap->motion_force == NUL || oap->motion_type == MLINE)
oap->inclusive = TRUE;
if (VIsual_mode == 'V')
oap->motion_type = MLINE;
else
{
oap->motion_type = MCHAR;
if (VIsual_mode != Ctrl_V && *ml_get_pos(&(oap->end)) == NUL
# ifdef FEAT_VIRTUALEDIT
&& (include_line_break || !virtual_op)
# endif
)
{
oap->inclusive = FALSE;
/* Try to include the newline, unless it's an operator
* that works on lines only. */
if (*p_sel != 'o' && !op_on_lines(oap->op_type))
{
if (oap->end.lnum < curbuf->b_ml.ml_line_count)
{
++oap->end.lnum;
oap->end.col = 0;
# ifdef FEAT_VIRTUALEDIT
oap->end.coladd = 0;
# endif
++oap->line_count;
}
else
{
/* Cannot move below the last line, make the op
* inclusive to tell the operation to include the
* line break. */
oap->inclusive = TRUE;
}
}
}
}
redo_VIsual_busy = FALSE;
/*
* Switch Visual off now, so screen updating does
* not show inverted text when the screen is redrawn.
* With OP_YANK and sometimes with OP_COLON and OP_FILTER there is
* no screen redraw, so it is done here to remove the inverted
* part.
*/
if (!gui_yank)
{
VIsual_active = FALSE;
# ifdef FEAT_MOUSE
setmouse();
mouse_dragging = 0;
# endif
if (mode_displayed)
clear_cmdline = TRUE; /* unshow visual mode later */
#ifdef FEAT_CMDL_INFO
else
clear_showcmd();
#endif
if ((oap->op_type == OP_YANK
|| oap->op_type == OP_COLON
|| oap->op_type == OP_FUNCTION
|| oap->op_type == OP_FILTER)
&& oap->motion_force == NUL)
redraw_curbuf_later(INVERTED);
}
}
#endif
#ifdef FEAT_MBYTE
/* Include the trailing byte of a multi-byte char. */
if (has_mbyte && oap->inclusive)
{
int l;
l = (*mb_ptr2len)(ml_get_pos(&oap->end));
if (l > 1)
oap->end.col += l - 1;
}
#endif
curwin->w_set_curswant = TRUE;
/*
* oap->empty is set when start and end are the same. The inclusive
* flag affects this too, unless yanking and the end is on a NUL.
*/
oap->empty = (oap->motion_type == MCHAR
&& (!oap->inclusive
|| (oap->op_type == OP_YANK
&& gchar_pos(&oap->end) == NUL))
&& equalpos(oap->start, oap->end)
#ifdef FEAT_VIRTUALEDIT
&& !(virtual_op && oap->start.coladd != oap->end.coladd)
#endif
);
/*
* For delete, change and yank, it's an error to operate on an
* empty region, when 'E' included in 'cpoptions' (Vi compatible).
*/
empty_region_error = (oap->empty
&& vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL);
#ifdef FEAT_VISUAL
/* Force a redraw when operating on an empty Visual region, when
* 'modifiable is off or creating a fold. */
if (oap->is_VIsual && (oap->empty || !curbuf->b_p_ma
# ifdef FEAT_FOLDING
|| oap->op_type == OP_FOLD
# endif
))
redraw_curbuf_later(INVERTED);
#endif
/*
* If the end of an operator is in column one while oap->motion_type
* is MCHAR and oap->inclusive is FALSE, we put op_end after the last
* character in the previous line. If op_start is on or before the
* first non-blank in the line, the operator becomes linewise
* (strange, but that's the way vi does it).
*/
if ( oap->motion_type == MCHAR
&& oap->inclusive == FALSE
&& !(cap->retval & CA_NO_ADJ_OP_END)
&& oap->end.col == 0
#ifdef FEAT_VISUAL
&& (!oap->is_VIsual || *p_sel == 'o')
&& !oap->block_mode
#endif
&& oap->line_count > 1)
{
oap->end_adjusted = TRUE; /* remember that we did this */
--oap->line_count;
--oap->end.lnum;
if (inindent(0))
oap->motion_type = MLINE;
else
{
oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
if (oap->end.col)
{
--oap->end.col;
oap->inclusive = TRUE;
}
}
}
else
oap->end_adjusted = FALSE;
switch (oap->op_type)
{
case OP_LSHIFT:
case OP_RSHIFT:
op_shift(oap, TRUE,
#ifdef FEAT_VISUAL
oap->is_VIsual ? (int)cap->count1 :
#endif
1);
auto_format(FALSE, TRUE);
break;
case OP_JOIN_NS:
case OP_JOIN:
if (oap->line_count < 2)
oap->line_count = 2;
if (curwin->w_cursor.lnum + oap->line_count - 1 >
curbuf->b_ml.ml_line_count)
beep_flush();
else
{
(void)do_join(oap->line_count, oap->op_type == OP_JOIN, TRUE, TRUE);
auto_format(FALSE, TRUE);
}
break;
case OP_DELETE:
#ifdef FEAT_VISUAL
VIsual_reselect = FALSE; /* don't reselect now */
#endif
if (empty_region_error)
{
vim_beep();
CancelRedo();
}
else
{
(void)op_delete(oap);
if (oap->motion_type == MLINE && has_format_option(FO_AUTO))
u_save_cursor(); /* cursor line wasn't saved yet */
auto_format(FALSE, TRUE);
}
break;
case OP_YANK:
if (empty_region_error)
{
if (!gui_yank)
{
vim_beep();
CancelRedo();
}
}
else
(void)op_yank(oap, FALSE, !gui_yank);
check_cursor_col();
break;
case OP_CHANGE:
#ifdef FEAT_VISUAL
VIsual_reselect = FALSE; /* don't reselect now */
#endif
if (empty_region_error)
{
vim_beep();
CancelRedo();
}
else
{
/* This is a new edit command, not a restart. Need to
* remember it to make 'insertmode' work with mappings for
* Visual mode. But do this only once and not when typed and
* 'insertmode' isn't set. */
if (p_im || !KeyTyped)
restart_edit_save = restart_edit;
else
restart_edit_save = 0;
restart_edit = 0;
/* Reset finish_op now, don't want it set inside edit(). */
finish_op = FALSE;
if (op_change(oap)) /* will call edit() */
cap->retval |= CA_COMMAND_BUSY;
if (restart_edit == 0)
restart_edit = restart_edit_save;
}
break;
case OP_FILTER:
if (vim_strchr(p_cpo, CPO_FILTER) != NULL)
AppendToRedobuff((char_u *)"!\r"); /* use any last used !cmd */
else
bangredo = TRUE; /* do_bang() will put cmd in redo buffer */
case OP_INDENT:
case OP_COLON:
#if defined(FEAT_LISP) || defined(FEAT_CINDENT)
/*
* If 'equalprg' is empty, do the indenting internally.
*/
if (oap->op_type == OP_INDENT && *get_equalprg() == NUL)
{
# ifdef FEAT_LISP
if (curbuf->b_p_lisp)
{
op_reindent(oap, get_lisp_indent);
break;
}
# endif
# ifdef FEAT_CINDENT
op_reindent(oap,
# ifdef FEAT_EVAL
*curbuf->b_p_inde != NUL ? get_expr_indent :
# endif
get_c_indent);
break;
# endif
}
#endif
op_colon(oap);
break;
case OP_TILDE:
case OP_UPPER:
case OP_LOWER:
case OP_ROT13:
if (empty_region_error)
{
vim_beep();
CancelRedo();
}
else
op_tilde(oap);
check_cursor_col();
break;
case OP_FORMAT:
#if defined(FEAT_EVAL)
if (*curbuf->b_p_fex != NUL)
op_formatexpr(oap); /* use expression */
else
#endif
if (*p_fp != NUL)
op_colon(oap); /* use external command */
else
op_format(oap, FALSE); /* use internal function */
break;
case OP_FORMAT2:
op_format(oap, TRUE); /* use internal function */
break;
case OP_FUNCTION:
op_function(oap); /* call 'operatorfunc' */
break;
case OP_INSERT:
case OP_APPEND:
#ifdef FEAT_VISUAL
VIsual_reselect = FALSE; /* don't reselect now */
#endif
#ifdef FEAT_VISUALEXTRA
if (empty_region_error)
{
vim_beep();
CancelRedo();
}
else
{
/* This is a new edit command, not a restart. Need to
* remember it to make 'insertmode' work with mappings for
* Visual mode. But do this only once. */
restart_edit_save = restart_edit;
restart_edit = 0;
op_insert(oap, cap->count1);
/* TODO: when inserting in several lines, should format all
* the lines. */
auto_format(FALSE, TRUE);
if (restart_edit == 0)
restart_edit = restart_edit_save;
}
#else
vim_beep();
#endif
break;
case OP_REPLACE:
#ifdef FEAT_VISUAL
VIsual_reselect = FALSE; /* don't reselect now */
#endif
#ifdef FEAT_VISUALEXTRA
if (empty_region_error)
#endif
{
vim_beep();
CancelRedo();
}
#ifdef FEAT_VISUALEXTRA
else
op_replace(oap, cap->nchar);
#endif
break;
#ifdef FEAT_FOLDING
case OP_FOLD:
VIsual_reselect = FALSE; /* don't reselect now */
foldCreate(oap->start.lnum, oap->end.lnum);
break;
case OP_FOLDOPEN:
case OP_FOLDOPENREC:
case OP_FOLDCLOSE:
case OP_FOLDCLOSEREC:
VIsual_reselect = FALSE; /* don't reselect now */
opFoldRange(oap->start.lnum, oap->end.lnum,
oap->op_type == OP_FOLDOPEN
|| oap->op_type == OP_FOLDOPENREC,
oap->op_type == OP_FOLDOPENREC
|| oap->op_type == OP_FOLDCLOSEREC,
oap->is_VIsual);
break;
case OP_FOLDDEL:
case OP_FOLDDELREC:
VIsual_reselect = FALSE; /* don't reselect now */
deleteFold(oap->start.lnum, oap->end.lnum,
oap->op_type == OP_FOLDDELREC, oap->is_VIsual);
break;
#endif
default:
clearopbeep(oap);
}
#ifdef FEAT_VIRTUALEDIT
virtual_op = MAYBE;
#endif
if (!gui_yank)
{
/*
* if 'sol' not set, go back to old column for some commands
*/
if (!p_sol && oap->motion_type == MLINE && !oap->end_adjusted
&& (oap->op_type == OP_LSHIFT || oap->op_type == OP_RSHIFT
|| oap->op_type == OP_DELETE))
coladvance(curwin->w_curswant = old_col);
}
else
{
curwin->w_cursor = old_cursor;
}
#ifdef FEAT_VISUAL
oap->block_mode = FALSE;
#endif
clearop(oap);
}
}
/*
* Handle indent and format operators and visual mode ":".
*/
static void
op_colon(oap)
oparg_T *oap;
{
stuffcharReadbuff(':');
#ifdef FEAT_VISUAL
if (oap->is_VIsual)
stuffReadbuff((char_u *)"'<,'>");
else
#endif
{
/*
* Make the range look nice, so it can be repeated.
*/
if (oap->start.lnum == curwin->w_cursor.lnum)
stuffcharReadbuff('.');
else
stuffnumReadbuff((long)oap->start.lnum);
if (oap->end.lnum != oap->start.lnum)
{
stuffcharReadbuff(',');
if (oap->end.lnum == curwin->w_cursor.lnum)
stuffcharReadbuff('.');
else if (oap->end.lnum == curbuf->b_ml.ml_line_count)
stuffcharReadbuff('$');
else if (oap->start.lnum == curwin->w_cursor.lnum)
{
stuffReadbuff((char_u *)".+");
stuffnumReadbuff((long)oap->line_count - 1);
}
else
stuffnumReadbuff((long)oap->end.lnum);
}
}
if (oap->op_type != OP_COLON)
stuffReadbuff((char_u *)"!");
if (oap->op_type == OP_INDENT)
{
#ifndef FEAT_CINDENT
if (*get_equalprg() == NUL)
stuffReadbuff((char_u *)"indent");
else
#endif
stuffReadbuff(get_equalprg());
stuffReadbuff((char_u *)"\n");
}
else if (oap->op_type == OP_FORMAT)
{
if (*p_fp == NUL)
stuffReadbuff((char_u *)"fmt");
else
stuffReadbuff(p_fp);
stuffReadbuff((char_u *)"\n']");
}
/*
* do_cmdline() does the rest
*/
}
/*
* Handle the "g@" operator: call 'operatorfunc'.
*/
static void
op_function(oap)
oparg_T *oap UNUSED;
{
#ifdef FEAT_EVAL
char_u *(argv[1]);
int save_virtual_op = virtual_op;
if (*p_opfunc == NUL)
EMSG(_("E774: 'operatorfunc' is empty"));
else
{
/* Set '[ and '] marks to text to be operated on. */
curbuf->b_op_start = oap->start;
curbuf->b_op_end = oap->end;
if (oap->motion_type != MLINE && !oap->inclusive)
/* Exclude the end position. */
decl(&curbuf->b_op_end);
if (oap->block_mode)
argv[0] = (char_u *)"block";
else if (oap->motion_type == MLINE)
argv[0] = (char_u *)"line";
else
argv[0] = (char_u *)"char";
/* Reset virtual_op so that 'virtualedit' can be changed in the
* function. */
virtual_op = MAYBE;
(void)call_func_retnr(p_opfunc, 1, argv, FALSE);
virtual_op = save_virtual_op;
}
#else
EMSG(_("E775: Eval feature not available"));
#endif
}
#if defined(FEAT_MOUSE) || defined(PROTO)
/*
* Do the appropriate action for the current mouse click in the current mode.
* Not used for Command-line mode.
*
* Normal Mode:
* event modi- position visual change action
* fier cursor window
* left press - yes end yes
* left press C yes end yes "^]" (2)
* left press S yes end yes "*" (2)
* left drag - yes start if moved no
* left relse - yes start if moved no
* middle press - yes if not active no put register
* middle press - yes if active no yank and put
* right press - yes start or extend yes
* right press S yes no change yes "#" (2)
* right drag - yes extend no
* right relse - yes extend no
*
* Insert or Replace Mode:
* event modi- position visual change action
* fier cursor window
* left press - yes (cannot be active) yes
* left press C yes (cannot be active) yes "CTRL-O^]" (2)
* left press S yes (cannot be active) yes "CTRL-O*" (2)
* left drag - yes start or extend (1) no CTRL-O (1)
* left relse - yes start or extend (1) no CTRL-O (1)
* middle press - no (cannot be active) no put register
* right press - yes start or extend yes CTRL-O
* right press S yes (cannot be active) yes "CTRL-O#" (2)
*
* (1) only if mouse pointer moved since press
* (2) only if click is in same buffer
*
* Return TRUE if start_arrow() should be called for edit mode.
*/
int
do_mouse(oap, c, dir, count, fixindent)
oparg_T *oap; /* operator argument, can be NULL */
int c; /* K_LEFTMOUSE, etc */
int dir; /* Direction to 'put' if necessary */
long count;
int fixindent; /* PUT_FIXINDENT if fixing indent necessary */
{
static int do_always = FALSE; /* ignore 'mouse' setting next time */
static int got_click = FALSE; /* got a click some time back */
int which_button; /* MOUSE_LEFT, _MIDDLE or _RIGHT */
int is_click; /* If FALSE it's a drag or release event */
int is_drag; /* If TRUE it's a drag event */
int jump_flags = 0; /* flags for jump_to_mouse() */
pos_T start_visual;
int moved; /* Has cursor moved? */
int in_status_line; /* mouse in status line */
#ifdef FEAT_WINDOWS
static int in_tab_line = FALSE; /* mouse clicked in tab line */
#endif
#ifdef FEAT_VERTSPLIT
int in_sep_line; /* mouse in vertical separator line */
#endif
int c1, c2;
#if defined(FEAT_FOLDING)
pos_T save_cursor;
#endif
win_T *old_curwin = curwin;
#ifdef FEAT_VISUAL
static pos_T orig_cursor;
colnr_T leftcol, rightcol;
pos_T end_visual;
int diff;
int old_active = VIsual_active;
int old_mode = VIsual_mode;
#endif
int regname;
#if defined(FEAT_FOLDING)
save_cursor = curwin->w_cursor;
#endif
/*
* When GUI is active, always recognize mouse events, otherwise:
* - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
* - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
* - For command line and insert mode 'mouse' is checked before calling
* do_mouse().
*/
if (do_always)
do_always = FALSE;
else
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
{
#ifdef FEAT_VISUAL
if (VIsual_active)
{
if (!mouse_has(MOUSE_VISUAL))
return FALSE;
}
else
#endif
if (State == NORMAL && !mouse_has(MOUSE_NORMAL))
return FALSE;
}
which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
#ifdef FEAT_MOUSESHAPE
/* May have stopped dragging the status or separator line. The pointer is
* most likely still on the status or separator line. */
if (!is_drag && drag_status_line)
{
drag_status_line = FALSE;
update_mouseshape(SHAPE_IDX_STATUS);
}
# ifdef FEAT_VERTSPLIT
if (!is_drag && drag_sep_line)
{
drag_sep_line = FALSE;
update_mouseshape(SHAPE_IDX_VSEP);
}
# endif
#endif
/*
* Ignore drag and release events if we didn't get a click.
*/
if (is_click)
got_click = TRUE;
else
{
if (!got_click) /* didn't get click, ignore */
return FALSE;
if (!is_drag) /* release, reset got_click */
{
got_click = FALSE;
#ifdef FEAT_WINDOWS
if (in_tab_line)
{
in_tab_line = FALSE;
return FALSE;
}
#endif
}
}
#ifndef FEAT_VISUAL
/*
* ALT is only used for starging/extending Visual mode.
*/
if ((mod_mask & MOD_MASK_ALT))
return FALSE;
#endif
/*
* CTRL right mouse button does CTRL-T
*/
if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
{
if (State & INSERT)
stuffcharReadbuff(Ctrl_O);
if (count > 1)
stuffnumReadbuff(count);
stuffcharReadbuff(Ctrl_T);
got_click = FALSE; /* ignore drag&release now */
return FALSE;
}
/*
* CTRL only works with left mouse button
*/
if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
return FALSE;
/*
* When a modifier is down, ignore drag and release events, as well as
* multiple clicks and the middle mouse button.
* Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
*/
if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
| MOD_MASK_META))
&& (!is_click
|| (mod_mask & MOD_MASK_MULTI_CLICK)
|| which_button == MOUSE_MIDDLE)
&& !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
&& mouse_model_popup()
&& which_button == MOUSE_LEFT)
&& !((mod_mask & MOD_MASK_ALT)
&& !mouse_model_popup()
&& which_button == MOUSE_RIGHT)
)
return FALSE;
/*
* If the button press was used as the movement command for an operator
* (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
* drag/release events.
*/
if (!is_click && which_button == MOUSE_MIDDLE)
return FALSE;
if (oap != NULL)
regname = oap->regname;
else
regname = 0;
/*
* Middle mouse button does a 'put' of the selected text
*/
if (which_button == MOUSE_MIDDLE)
{
if (State == NORMAL)
{
/*
* If an operator was pending, we don't know what the user wanted
* to do. Go back to normal mode: Clear the operator and beep().
*/
if (oap != NULL && oap->op_type != OP_NOP)
{
clearopbeep(oap);
return FALSE;
}
#ifdef FEAT_VISUAL
/*
* If visual was active, yank the highlighted text and put it
* before the mouse pointer position.
* In Select mode replace the highlighted text with the clipboard.
*/
if (VIsual_active)
{
if (VIsual_select)
{
stuffcharReadbuff(Ctrl_G);
stuffReadbuff((char_u *)"\"+p");
}
else
{
stuffcharReadbuff('y');
stuffcharReadbuff(K_MIDDLEMOUSE);
}
do_always = TRUE; /* ignore 'mouse' setting next time */
return FALSE;
}
#endif
/*
* The rest is below jump_to_mouse()
*/
}
else if ((State & INSERT) == 0)
return FALSE;
/*
* Middle click in insert mode doesn't move the mouse, just insert the
* contents of a register. '.' register is special, can't insert that
* with do_put().
* Also paste at the cursor if the current mode isn't in 'mouse' (only
* happens for the GUI).
*/
if ((State & INSERT) || !mouse_has(MOUSE_NORMAL))
{
if (regname == '.')
insert_reg(regname, TRUE);
else
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
insert_reg(regname, TRUE);
else
{
do_put(regname, BACKWARD, 1L, fixindent | PUT_CURSEND);
/* Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r */
AppendCharToRedobuff(Ctrl_R);
AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
AppendCharToRedobuff(regname == 0 ? '"' : regname);
}
}
return FALSE;
}
}
/* When dragging or button-up stay in the same window. */
if (!is_click)
jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
start_visual.lnum = 0;
#ifdef FEAT_WINDOWS
/* Check for clicking in the tab page line. */
if (mouse_row == 0 && firstwin->w_winrow > 0)
{
if (is_drag)
{
if (in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
}
return FALSE;
}
/* click in a tab selects that tab page */
if (is_click
# ifdef FEAT_CMDWIN
&& cmdwin_type == 0
# endif
&& mouse_col < Columns)
{
in_tab_line = TRUE;
c1 = TabPageIdxs[mouse_col];
if (c1 >= 0)
{
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
/* double click opens new page */
end_visual_mode();
tabpage_new();
tabpage_move(c1 == 0 ? 9999 : c1 - 1);
}
else
{
/* Go to specified tab page, or next one if not clicking
* on a label. */
goto_tabpage(c1);
/* It's like clicking on the status line of a window. */
if (curwin != old_curwin)
end_visual_mode();
}
}
else if (c1 < 0)
{
tabpage_T *tp;
/* Close the current or specified tab page. */
if (c1 == -999)
tp = curtab;
else
tp = find_tabpage(-c1);
if (tp == curtab)
{
if (first_tabpage->tp_next != NULL)
tabpage_close(FALSE);
}
else if (tp != NULL)
tabpage_close_other(tp, FALSE);
}
}
return TRUE;
}
else if (is_drag && in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
return FALSE;
}
#endif
/*
* When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
* right button up -> pop-up menu
* shift-left button -> right button
* alt-left button -> alt-right button
*/
if (mouse_model_popup())
{
if (which_button == MOUSE_RIGHT
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
/*
* NOTE: Ignore right button down and drag mouse events.
* Windows only shows the popup menu on the button up event.
*/
#if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
if (!is_click)
return FALSE;
#endif
#if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN)
if (is_click || is_drag)
return FALSE;
#endif
#if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MAC) || defined(FEAT_GUI_PHOTON)
if (gui.in_use)
{
jump_flags = 0;
if (STRCMP(p_mousem, "popup_setpos") == 0)
{
/* First set the cursor position before showing the popup
* menu. */
#ifdef FEAT_VISUAL
if (VIsual_active)
{
pos_T m_pos;
/*
* set MOUSE_MAY_STOP_VIS if we are outside the
* selection or the current window (might have false
* negative here)
*/
if (mouse_row < W_WINROW(curwin)
|| mouse_row
> (W_WINROW(curwin) + curwin->w_height))
jump_flags = MOUSE_MAY_STOP_VIS;
else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
jump_flags = MOUSE_MAY_STOP_VIS;
else
{
if ((lt(curwin->w_cursor, VIsual)
&& (lt(m_pos, curwin->w_cursor)
|| lt(VIsual, m_pos)))
|| (lt(VIsual, curwin->w_cursor)
&& (lt(m_pos, VIsual)
|| lt(curwin->w_cursor, m_pos))))
{
jump_flags = MOUSE_MAY_STOP_VIS;
}
else if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &curwin->w_cursor, &VIsual,
&leftcol, &rightcol);
getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
if (m_pos.col < leftcol || m_pos.col > rightcol)
jump_flags = MOUSE_MAY_STOP_VIS;
}
}
}
else
jump_flags = MOUSE_MAY_STOP_VIS;
#endif
}
if (jump_flags)
{
jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
update_curbuf(
#ifdef FEAT_VISUAL
VIsual_active ? INVERTED :
#endif
VALID);
setcursor();
out_flush(); /* Update before showing popup menu */
}
# ifdef FEAT_MENU
gui_show_popupmenu();
# endif
return (jump_flags & CURSOR_MOVED) != 0;
}
else
return FALSE;
#else
return FALSE;
#endif
}
if (which_button == MOUSE_LEFT
&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
{
which_button = MOUSE_RIGHT;
mod_mask &= ~MOD_MASK_SHIFT;
}
}
#ifdef FEAT_VISUAL
if ((State & (NORMAL | INSERT))
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
if (which_button == MOUSE_LEFT)
{
if (is_click)
{
/* stop Visual mode for a left click in a window, but not when
* on a status line */
if (VIsual_active)
jump_flags |= MOUSE_MAY_STOP_VIS;
}
else if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
else if (which_button == MOUSE_RIGHT)
{
if (is_click && VIsual_active)
{
/*
* Remember the start and end of visual before moving the
* cursor.
*/
if (lt(curwin->w_cursor, VIsual))
{
start_visual = curwin->w_cursor;
end_visual = VIsual;
}
else
{
start_visual = VIsual;
end_visual = curwin->w_cursor;
}
}
jump_flags |= MOUSE_FOCUS;
if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
}
#endif
/*
* If an operator is pending, ignore all drags and releases until the
* next mouse click.
*/
if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
{
got_click = FALSE;
oap->motion_type = MCHAR;
}
/* When releasing the button let jump_to_mouse() know. */
if (!is_click && !is_drag)
jump_flags |= MOUSE_RELEASED;
/*
* JUMP!
*/
jump_flags = jump_to_mouse(jump_flags,
oap == NULL ? NULL : &(oap->inclusive), which_button);
moved = (jump_flags & CURSOR_MOVED);
in_status_line = (jump_flags & IN_STATUS_LINE);
#ifdef FEAT_VERTSPLIT
in_sep_line = (jump_flags & IN_SEP_LINE);
#endif
#ifdef FEAT_NETBEANS_INTG
if (isNetbeansBuffer(curbuf)
&& !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
{
int key = KEY2TERMCAP1(c);
if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
|| key == (int)KE_RIGHTRELEASE)
netbeans_button_release(which_button);
}
#endif
/* When jumping to another window, clear a pending operator. That's a bit
* friendlier than beeping and not jumping to that window. */
if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
clearop(oap);
#ifdef FEAT_FOLDING
if (mod_mask == 0
&& !is_drag
&& (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
&& which_button == MOUSE_LEFT)
{
/* open or close a fold at this line */
if (jump_flags & MOUSE_FOLD_OPEN)
openFold(curwin->w_cursor.lnum, 1L);
else
closeFold(curwin->w_cursor.lnum, 1L);
/* don't move the cursor if still in the same window */
if (curwin == old_curwin)
curwin->w_cursor = save_cursor;
}
#endif
#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
{
clip_modeless(which_button, is_click, is_drag);
return FALSE;
}
#endif
#ifdef FEAT_VISUAL
/* Set global flag that we are extending the Visual area with mouse
* dragging; temporarily minimize 'scrolloff'. */
if (VIsual_active && is_drag && p_so)
{
/* In the very first line, allow scrolling one line */
if (mouse_row == 0)
mouse_dragging = 2;
else
mouse_dragging = 1;
}
/* When dragging the mouse above the window, scroll down. */
if (is_drag && mouse_row < 0 && !in_status_line)
{
scroll_redraw(FALSE, 1L);
mouse_row = 0;
}
if (start_visual.lnum) /* right click in visual mode */
{
/* When ALT is pressed make Visual mode blockwise. */
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
/*
* In Visual-block mode, divide the area in four, pick up the corner
* that is in the quarter that the cursor is in.
*/
if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
if (curwin->w_curswant > (leftcol + rightcol) / 2)
end_visual.col = leftcol;
else
end_visual.col = rightcol;
if (curwin->w_cursor.lnum <
(start_visual.lnum + end_visual.lnum) / 2)
end_visual.lnum = end_visual.lnum;
else
end_visual.lnum = start_visual.lnum;
/* move VIsual to the right column */
start_visual = curwin->w_cursor; /* save the cursor pos */
curwin->w_cursor = end_visual;
coladvance(end_visual.col);
VIsual = curwin->w_cursor;
curwin->w_cursor = start_visual; /* restore the cursor */
}
else
{
/*
* If the click is before the start of visual, change the start.
* If the click is after the end of visual, change the end. If
* the click is inside the visual, change the closest side.
*/
if (lt(curwin->w_cursor, start_visual))
VIsual = end_visual;
else if (lt(end_visual, curwin->w_cursor))
VIsual = start_visual;
else
{
/* In the same line, compare column number */
if (end_visual.lnum == start_visual.lnum)
{
if (curwin->w_cursor.col - start_visual.col >
end_visual.col - curwin->w_cursor.col)
VIsual = start_visual;
else
VIsual = end_visual;
}
/* In different lines, compare line number */
else
{
diff = (curwin->w_cursor.lnum - start_visual.lnum) -
(end_visual.lnum - curwin->w_cursor.lnum);
if (diff > 0) /* closest to end */
VIsual = start_visual;
else if (diff < 0) /* closest to start */
VIsual = end_visual;
else /* in the middle line */
{
if (curwin->w_cursor.col <
(start_visual.col + end_visual.col) / 2)
VIsual = end_visual;
else
VIsual = start_visual;
}
}
}
}
}
/*
* If Visual mode started in insert mode, execute "CTRL-O"
*/
else if ((State & INSERT) && VIsual_active)
stuffcharReadbuff(Ctrl_O);
#endif
/*
* Middle mouse click: Put text before cursor.
*/
if (which_button == MOUSE_MIDDLE)
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if (yank_register_mline(regname))
{
if (mouse_past_bottom)
dir = FORWARD;
}
else if (mouse_past_eol)
dir = FORWARD;
if (fixindent)
{
c1 = (dir == BACKWARD) ? '[' : ']';
c2 = 'p';
}
else
{
c1 = (dir == FORWARD) ? 'p' : 'P';
c2 = NUL;
}
prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
/*
* Remember where the paste started, so in edit() Insstart can be set
* to this position
*/
if (restart_edit != 0)
where_paste_started = curwin->w_cursor;
do_put(regname, dir, count, fixindent | PUT_CURSEND);
}
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
/*
* Ctrl-Mouse click or double click in a quickfix window jumps to the
* error under the mouse pointer.
*/
else if (((mod_mask & MOD_MASK_CTRL)
|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
&& bt_quickfix(curbuf))
{
if (State & INSERT)
stuffcharReadbuff(Ctrl_O);
if (curwin->w_llist_ref == NULL) /* quickfix window */
stuffReadbuff((char_u *)":.cc\n");
else /* location list window */
stuffReadbuff((char_u *)":.ll\n");
got_click = FALSE; /* ignore drag&release now */
}
#endif
/*
* Ctrl-Mouse click (or double click in a help window) jumps to the tag
* under the mouse pointer.
*/
else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
&& (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
{
if (State & INSERT)
stuffcharReadbuff(Ctrl_O);
stuffcharReadbuff(Ctrl_RSB);
got_click = FALSE; /* ignore drag&release now */
}
/*
* Shift-Mouse click searches for the next occurrence of the word under
* the mouse pointer
*/
else if ((mod_mask & MOD_MASK_SHIFT))
{
if (State & INSERT
#ifdef FEAT_VISUAL
|| (VIsual_active && VIsual_select)
#endif
)
stuffcharReadbuff(Ctrl_O);
if (which_button == MOUSE_LEFT)
stuffcharReadbuff('*');
else /* MOUSE_RIGHT */
stuffcharReadbuff('#');
}
/* Handle double clicks, unless on status line */
else if (in_status_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_status_line)
{
drag_status_line = TRUE;
update_mouseshape(-1);
}
#endif
}
#ifdef FEAT_VERTSPLIT
else if (in_sep_line)
{
# ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_sep_line)
{
drag_sep_line = TRUE;
update_mouseshape(-1);
}
# endif
}
#endif
#ifdef FEAT_VISUAL
else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (NORMAL | INSERT))
&& mouse_has(MOUSE_VISUAL))
{
if (is_click || !VIsual_active)
{
if (VIsual_active)
orig_cursor = VIsual;
else
{
check_visual_highlight();
VIsual = curwin->w_cursor;
orig_cursor = VIsual;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
/* start Select mode if 'selectmode' contains "mouse" */
may_start_select('o');
setmouse();
}
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
/* Double click with ALT pressed makes it blockwise. */
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
VIsual_mode = 'V';
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
VIsual_mode = Ctrl_V;
#ifdef FEAT_CLIPBOARD
/* Make sure the clipboard gets updated. Needed because start and
* end may still be the same, and the selection needs to be owned */
clip_star.vmode = NUL;
#endif
}
/*
* A double click selects a word or a block.
*/
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
pos_T *pos = NULL;
int gc;
if (is_click)
{
/* If the character under the cursor (skipping white space) is
* not a word character, try finding a match and select a (),
* {}, [], #if/#endif, etc. block. */
end_visual = curwin->w_cursor;
while (gc = gchar_pos(&end_visual), vim_iswhite(gc))
inc(&end_visual);
if (oap != NULL)
oap->motion_type = MCHAR;
if (oap != NULL
&& VIsual_mode == 'v'
&& !vim_iswordc(gchar_pos(&end_visual))
&& equalpos(curwin->w_cursor, VIsual)
&& (pos = findmatch(oap, NUL)) != NULL)
{
curwin->w_cursor = *pos;
if (oap->motion_type == MLINE)
VIsual_mode = 'V';
else if (*p_sel == 'e')
{
if (lt(curwin->w_cursor, VIsual))
++VIsual.col;
else
++curwin->w_cursor.col;
}
}
}
if (pos == NULL && (is_click || is_drag))
{
/* When not found a match or when dragging: extend to include
* a word. */
if (lt(curwin->w_cursor, orig_cursor))
{
find_start_of_word(&curwin->w_cursor);
find_end_of_word(&VIsual);
}
else
{
find_start_of_word(&VIsual);
if (*p_sel == 'e' && *ml_get_cursor() != NUL)
#ifdef FEAT_MBYTE
curwin->w_cursor.col +=
(*mb_ptr2len)(ml_get_cursor());
#else
++curwin->w_cursor.col;
#endif
find_end_of_word(&curwin->w_cursor);
}
}
curwin->w_set_curswant = TRUE;
}
if (is_click)
redraw_curbuf_later(INVERTED); /* update the inversion */
}
else if (VIsual_active && !old_active)
{
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
/* If Visual mode changed show it later. */
if ((!VIsual_active && old_active && mode_displayed)
|| (VIsual_active && p_smd && msg_silent == 0
&& (!old_active || VIsual_mode != old_mode)))
redraw_cmdline = TRUE;
#endif
return moved;
}
#ifdef FEAT_VISUAL
/*
* Move "pos" back to the start of the word it's in.
*/
static void
find_start_of_word(pos)
pos_T *pos;
{
char_u *line;
int cclass;
int col;
line = ml_get(pos->lnum);
cclass = get_mouse_class(line + pos->col);
while (pos->col > 0)
{
col = pos->col - 1;
#ifdef FEAT_MBYTE
col -= (*mb_head_off)(line, line + col);
#endif
if (get_mouse_class(line + col) != cclass)
break;
pos->col = col;
}
}
/*
* Move "pos" forward to the end of the word it's in.
* When 'selection' is "exclusive", the position is just after the word.
*/
static void
find_end_of_word(pos)
pos_T *pos;
{
char_u *line;
int cclass;
int col;
line = ml_get(pos->lnum);
if (*p_sel == 'e' && pos->col > 0)
{
--pos->col;
#ifdef FEAT_MBYTE
pos->col -= (*mb_head_off)(line, line + pos->col);
#endif
}
cclass = get_mouse_class(line + pos->col);
while (line[pos->col] != NUL)
{
#ifdef FEAT_MBYTE
col = pos->col + (*mb_ptr2len)(line + pos->col);
#else
col = pos->col + 1;
#endif
if (get_mouse_class(line + col) != cclass)
{
if (*p_sel == 'e')
pos->col = col;
break;
}
pos->col = col;
}
}
/*
* Get class of a character for selection: same class means same word.
* 0: blank
* 1: punctuation groups
* 2: normal word character
* >2: multi-byte word character.
*/
static int
get_mouse_class(p)
char_u *p;
{
int c;
#ifdef FEAT_MBYTE
if (has_mbyte && MB_BYTE2LEN(p[0]) > 1)
return mb_get_class(p);
#endif
c = *p;
if (c == ' ' || c == '\t')
return 0;
if (vim_iswordc(c))
return 2;
/*
* There are a few special cases where we want certain combinations of
* characters to be considered as a single word. These are things like
* "->", "/ *", "*=", "+=", "&=", "<=", ">=", "!=" etc. Otherwise, each
* character is in its own class.
*/
if (c != NUL && vim_strchr((char_u *)"-+*/%<>&|^!=", c) != NULL)
return 1;
return c;
}
#endif /* FEAT_VISUAL */
#endif /* FEAT_MOUSE */
#if defined(FEAT_VISUAL) || defined(PROTO)
/*
* Check if highlighting for visual mode is possible, give a warning message
* if not.
*/
void
check_visual_highlight()
{
static int did_check = FALSE;
if (full_screen)
{
if (!did_check && hl_attr(HLF_V) == 0)
MSG(_("Warning: terminal cannot highlight"));
did_check = TRUE;
}
}
/*
* End Visual mode.
* This function should ALWAYS be called to end Visual mode, except from
* do_pending_operator().
*/
void
end_visual_mode()
{
#ifdef FEAT_CLIPBOARD
/*
* If we are using the clipboard, then remember what was selected in case
* we need to paste it somewhere while we still own the selection.
* Only do this when the clipboard is already owned. Don't want to grab
* the selection when hitting ESC.
*/
if (clip_star.available && clip_star.owned)
clip_auto_select();
#endif
VIsual_active = FALSE;
#ifdef FEAT_MOUSE
setmouse();
mouse_dragging = 0;
#endif
/* Save the current VIsual area for '< and '> marks, and "gv" */
curbuf->b_visual.vi_mode = VIsual_mode;
curbuf->b_visual.vi_start = VIsual;
curbuf->b_visual.vi_end = curwin->w_cursor;
curbuf->b_visual.vi_curswant = curwin->w_curswant;
#ifdef FEAT_EVAL
curbuf->b_visual_mode_eval = VIsual_mode;
#endif
#ifdef FEAT_VIRTUALEDIT
if (!virtual_active())
curwin->w_cursor.coladd = 0;
#endif
if (mode_displayed)
clear_cmdline = TRUE; /* unshow visual mode later */
#ifdef FEAT_CMDL_INFO
else
clear_showcmd();
#endif
adjust_cursor_eol();
}
/*
* Reset VIsual_active and VIsual_reselect.
*/
void
reset_VIsual_and_resel()
{
if (VIsual_active)
{
end_visual_mode();
redraw_curbuf_later(INVERTED); /* delete the inversion later */
}
VIsual_reselect = FALSE;
}
/*
* Reset VIsual_active and VIsual_reselect if it's set.
*/
void
reset_VIsual()
{
if (VIsual_active)
{
end_visual_mode();
redraw_curbuf_later(INVERTED); /* delete the inversion later */
VIsual_reselect = FALSE;
}
}
#endif /* FEAT_VISUAL */
#if defined(FEAT_BEVAL)
static int find_is_eval_item __ARGS((char_u *ptr, int *colp, int *nbp, int dir));
/*
* Check for a balloon-eval special item to include when searching for an
* identifier. When "dir" is BACKWARD "ptr[-1]" must be valid!
* Returns TRUE if the character at "*ptr" should be included.
* "dir" is FORWARD or BACKWARD, the direction of searching.
* "*colp" is in/decremented if "ptr[-dir]" should also be included.
* "bnp" points to a counter for square brackets.
*/
static int
find_is_eval_item(ptr, colp, bnp, dir)
char_u *ptr;
int *colp;
int *bnp;
int dir;
{
/* Accept everything inside []. */
if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD))
++*bnp;
if (*bnp > 0)
{
if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD))
--*bnp;
return TRUE;
}
/* skip over "s.var" */
if (*ptr == '.')
return TRUE;
/* two-character item: s->var */
if (ptr[dir == BACKWARD ? 0 : 1] == '>'
&& ptr[dir == BACKWARD ? -1 : 0] == '-')
{
*colp += dir;
return TRUE;
}
return FALSE;
}
#endif
/*
* Find the identifier under or to the right of the cursor.
* "find_type" can have one of three values:
* FIND_IDENT: find an identifier (keyword)
* FIND_STRING: find any non-white string
* FIND_IDENT + FIND_STRING: find any non-white string, identifier preferred.
* FIND_EVAL: find text useful for C program debugging
*
* There are three steps:
* 1. Search forward for the start of an identifier/string. Doesn't move if
* already on one.
* 2. Search backward for the start of this identifier/string.
* This doesn't match the real Vi but I like it a little better and it
* shouldn't bother anyone.
* 3. Search forward to the end of this identifier/string.
* When FIND_IDENT isn't defined, we backup until a blank.
*
* Returns the length of the string, or zero if no string is found.
* If a string is found, a pointer to the string is put in "*string". This
* string is not always NUL terminated.
*/
int
find_ident_under_cursor(string, find_type)
char_u **string;
int find_type;
{
return find_ident_at_pos(curwin, curwin->w_cursor.lnum,
curwin->w_cursor.col, string, find_type);
}
/*
* Like find_ident_under_cursor(), but for any window and any position.
* However: Uses 'iskeyword' from the current window!.
*/
int
find_ident_at_pos(wp, lnum, startcol, string, find_type)
win_T *wp;
linenr_T lnum;
colnr_T startcol;
char_u **string;
int find_type;
{
char_u *ptr;
int col = 0; /* init to shut up GCC */
int i;
#ifdef FEAT_MBYTE
int this_class = 0;
int prev_class;
int prevcol;
#endif
#if defined(FEAT_BEVAL)
int bn = 0; /* bracket nesting */
#endif
/*
* if i == 0: try to find an identifier
* if i == 1: try to find any non-white string
*/
ptr = ml_get_buf(wp->w_buffer, lnum, FALSE);
for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; ++i)
{
/*
* 1. skip to start of identifier/string
*/
col = startcol;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
while (ptr[col] != NUL)
{
# if defined(FEAT_BEVAL)
/* Stop at a ']' to evaluate "a[x]". */
if ((find_type & FIND_EVAL) && ptr[col] == ']')
break;
# endif
this_class = mb_get_class(ptr + col);
if (this_class != 0 && (i == 1 || this_class != 1))
break;
col += (*mb_ptr2len)(ptr + col);
}
}
else
#endif
while (ptr[col] != NUL
&& (i == 0 ? !vim_iswordc(ptr[col]) : vim_iswhite(ptr[col]))
# if defined(FEAT_BEVAL)
&& (!(find_type & FIND_EVAL) || ptr[col] != ']')
# endif
)
++col;
#if defined(FEAT_BEVAL)
/* When starting on a ']' count it, so that we include the '['. */
bn = ptr[col] == ']';
#endif
/*
* 2. Back up to start of identifier/string.
*/
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Remember class of character under cursor. */
# if defined(FEAT_BEVAL)
if ((find_type & FIND_EVAL) && ptr[col] == ']')
this_class = mb_get_class((char_u *)"a");
else
# endif
this_class = mb_get_class(ptr + col);
while (col > 0 && this_class != 0)
{
prevcol = col - 1 - (*mb_head_off)(ptr, ptr + col - 1);
prev_class = mb_get_class(ptr + prevcol);
if (this_class != prev_class
&& (i == 0
|| prev_class == 0
|| (find_type & FIND_IDENT))
# if defined(FEAT_BEVAL)
&& (!(find_type & FIND_EVAL)
|| prevcol == 0
|| !find_is_eval_item(ptr + prevcol, &prevcol,
&bn, BACKWARD))
# endif
)
break;
col = prevcol;
}
/* If we don't want just any old string, or we've found an
* identifier, stop searching. */
if (this_class > 2)
this_class = 2;
if (!(find_type & FIND_STRING) || this_class == 2)
break;
}
else
#endif
{
while (col > 0
&& ((i == 0
? vim_iswordc(ptr[col - 1])
: (!vim_iswhite(ptr[col - 1])
&& (!(find_type & FIND_IDENT)
|| !vim_iswordc(ptr[col - 1]))))
#if defined(FEAT_BEVAL)
|| ((find_type & FIND_EVAL)
&& col > 1
&& find_is_eval_item(ptr + col - 1, &col,
&bn, BACKWARD))
#endif
))
--col;
/* If we don't want just any old string, or we've found an
* identifier, stop searching. */
if (!(find_type & FIND_STRING) || vim_iswordc(ptr[col]))
break;
}
}
if (ptr[col] == NUL || (i == 0 && (
#ifdef FEAT_MBYTE
has_mbyte ? this_class != 2 :
#endif
!vim_iswordc(ptr[col]))))
{
/*
* didn't find an identifier or string
*/
if (find_type & FIND_STRING)
EMSG(_("E348: No string under cursor"));
else
EMSG(_(e_noident));
return 0;
}
ptr += col;
*string = ptr;
/*
* 3. Find the end if the identifier/string.
*/
#if defined(FEAT_BEVAL)
bn = 0;
startcol -= col;
#endif
col = 0;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
/* Search for point of changing multibyte character class. */
this_class = mb_get_class(ptr);
while (ptr[col] != NUL
&& ((i == 0 ? mb_get_class(ptr + col) == this_class
: mb_get_class(ptr + col) != 0)
# if defined(FEAT_BEVAL)
|| ((find_type & FIND_EVAL)
&& col <= (int)startcol
&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
# endif
))
col += (*mb_ptr2len)(ptr + col);
}
else
#endif
while ((i == 0 ? vim_iswordc(ptr[col])
: (ptr[col] != NUL && !vim_iswhite(ptr[col])))
# if defined(FEAT_BEVAL)
|| ((find_type & FIND_EVAL)
&& col <= (int)startcol
&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
# endif
)
{
++col;
}
return col;
}
/*
* Prepare for redo of a normal command.
*/
static void
prep_redo_cmd(cap)
cmdarg_T *cap;
{
prep_redo(cap->oap->regname, cap->count0,
NUL, cap->cmdchar, NUL, NUL, cap->nchar);
}
/*
* Prepare for redo of any command.
* Note that only the last argument can be a multi-byte char.
*/
static void
prep_redo(regname, num, cmd1, cmd2, cmd3, cmd4, cmd5)
int regname;
long num;
int cmd1;
int cmd2;
int cmd3;
int cmd4;
int cmd5;
{
ResetRedobuff();
if (regname != 0) /* yank from specified buffer */
{
AppendCharToRedobuff('"');
AppendCharToRedobuff(regname);
}
if (num)
AppendNumberToRedobuff(num);
if (cmd1 != NUL)
AppendCharToRedobuff(cmd1);
if (cmd2 != NUL)
AppendCharToRedobuff(cmd2);
if (cmd3 != NUL)
AppendCharToRedobuff(cmd3);
if (cmd4 != NUL)
AppendCharToRedobuff(cmd4);
if (cmd5 != NUL)
AppendCharToRedobuff(cmd5);
}
/*
* check for operator active and clear it
*
* return TRUE if operator was active
*/
static int
checkclearop(oap)
oparg_T *oap;
{
if (oap->op_type == OP_NOP)
return FALSE;
clearopbeep(oap);
return TRUE;
}
/*
* Check for operator or Visual active. Clear active operator.
*
* Return TRUE if operator or Visual was active.
*/
static int
checkclearopq(oap)
oparg_T *oap;
{
if (oap->op_type == OP_NOP
#ifdef FEAT_VISUAL
&& !VIsual_active
#endif
)
return FALSE;
clearopbeep(oap);
return TRUE;
}
static void
clearop(oap)
oparg_T *oap;
{
oap->op_type = OP_NOP;
oap->regname = 0;
oap->motion_force = NUL;
oap->use_reg_one = FALSE;
}
static void
clearopbeep(oap)
oparg_T *oap;
{
clearop(oap);
beep_flush();
}
#ifdef FEAT_VISUAL
/*
* Remove the shift modifier from a special key.
*/
static void
unshift_special(cap)
cmdarg_T *cap;
{
switch (cap->cmdchar)
{
case K_S_RIGHT: cap->cmdchar = K_RIGHT; break;
case K_S_LEFT: cap->cmdchar = K_LEFT; break;
case K_S_UP: cap->cmdchar = K_UP; break;
case K_S_DOWN: cap->cmdchar = K_DOWN; break;
case K_S_HOME: cap->cmdchar = K_HOME; break;
case K_S_END: cap->cmdchar = K_END; break;
}
cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask);
}
#endif
#if defined(FEAT_CMDL_INFO) || defined(PROTO)
/*
* Routines for displaying a partly typed command
*/
#ifdef FEAT_VISUAL /* need room for size of Visual area */
# define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30
#else
# define SHOWCMD_BUFLEN SHOWCMD_COLS + 1
#endif
static char_u showcmd_buf[SHOWCMD_BUFLEN];
static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; /* For push_showcmd() */
static int showcmd_is_clear = TRUE;
static int showcmd_visual = FALSE;
static void display_showcmd __ARGS((void));
void
clear_showcmd()
{
if (!p_sc)
return;
#ifdef FEAT_VISUAL
if (VIsual_active && !char_avail())
{
int cursor_bot = lt(VIsual, curwin->w_cursor);
long lines;
colnr_T leftcol, rightcol;
linenr_T top, bot;
/* Show the size of the Visual area. */
if (cursor_bot)
{
top = VIsual.lnum;
bot = curwin->w_cursor.lnum;
}
else
{
top = curwin->w_cursor.lnum;
bot = VIsual.lnum;
}
# ifdef FEAT_FOLDING
/* Include closed folds as a whole. */
hasFolding(top, &top, NULL);
hasFolding(bot, NULL, &bot);
# endif
lines = bot - top + 1;
if (VIsual_mode == Ctrl_V)
{
# ifdef FEAT_LINEBREAK
char_u *saved_sbr = p_sbr;
/* Make 'sbr' empty for a moment to get the correct size. */
p_sbr = empty_option;
# endif
getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol);
# ifdef FEAT_LINEBREAK
p_sbr = saved_sbr;
# endif
sprintf((char *)showcmd_buf, "%ldx%ld", lines,
(long)(rightcol - leftcol + 1));
}
else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum)
sprintf((char *)showcmd_buf, "%ld", lines);
else
{
char_u *s, *e;
int l;
int bytes = 0;
int chars = 0;
if (cursor_bot)
{
s = ml_get_pos(&VIsual);
e = ml_get_cursor();
}
else
{
s = ml_get_cursor();
e = ml_get_pos(&VIsual);
}
while ((*p_sel != 'e') ? s <= e : s < e)
{
# ifdef FEAT_MBYTE
l = (*mb_ptr2len)(s);
# else
l = (*s == NUL) ? 0 : 1;
# endif
if (l == 0)
{
++bytes;
++chars;
break; /* end of line */
}
bytes += l;
++chars;
s += l;
}
if (bytes == chars)
sprintf((char *)showcmd_buf, "%d", chars);
else
sprintf((char *)showcmd_buf, "%d-%d", chars, bytes);
}
showcmd_buf[SHOWCMD_COLS] = NUL; /* truncate */
showcmd_visual = TRUE;
}
else
#endif
{
showcmd_buf[0] = NUL;
showcmd_visual = FALSE;
/* Don't actually display something if there is nothing to clear. */
if (showcmd_is_clear)
return;
}
display_showcmd();
}
/*
* Add 'c' to string of shown command chars.
* Return TRUE if output has been written (and setcursor() has been called).
*/
int
add_to_showcmd(c)
int c;
{
char_u *p;
int old_len;
int extra_len;
int overflow;
#if defined(FEAT_MOUSE)
int i;
static int ignore[] =
{
# ifdef FEAT_GUI
K_VER_SCROLLBAR, K_HOR_SCROLLBAR,
K_LEFTMOUSE_NM, K_LEFTRELEASE_NM,
# endif
K_IGNORE,
K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE,
K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE,
K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE,
K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT,
K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE,
K_CURSORHOLD,
0
};
#endif
if (!p_sc || msg_silent != 0)
return FALSE;
if (showcmd_visual)
{
showcmd_buf[0] = NUL;
showcmd_visual = FALSE;
}
#if defined(FEAT_MOUSE)
/* Ignore keys that are scrollbar updates and mouse clicks */
if (IS_SPECIAL(c))
for (i = 0; ignore[i] != 0; ++i)
if (ignore[i] == c)
return FALSE;
#endif
p = transchar(c);
old_len = (int)STRLEN(showcmd_buf);
extra_len = (int)STRLEN(p);
overflow = old_len + extra_len - SHOWCMD_COLS;
if (overflow > 0)
mch_memmove(showcmd_buf, showcmd_buf + overflow,
old_len - overflow + 1);
STRCAT(showcmd_buf, p);
if (char_avail())
return FALSE;
display_showcmd();
return TRUE;
}
void
add_to_showcmd_c(c)
int c;
{
if (!add_to_showcmd(c))
setcursor();
}
/*
* Delete 'len' characters from the end of the shown command.
*/
static void
del_from_showcmd(len)
int len;
{
int old_len;
if (!p_sc)
return;
old_len = (int)STRLEN(showcmd_buf);
if (len > old_len)
len = old_len;
showcmd_buf[old_len - len] = NUL;
if (!char_avail())
display_showcmd();
}
/*
* push_showcmd() and pop_showcmd() are used when waiting for the user to type
* something and there is a partial mapping.
*/
void
push_showcmd()
{
if (p_sc)
STRCPY(old_showcmd_buf, showcmd_buf);
}
void
pop_showcmd()
{
if (!p_sc)
return;
STRCPY(showcmd_buf, old_showcmd_buf);
display_showcmd();
}
static void
display_showcmd()
{
int len;
cursor_off();
len = (int)STRLEN(showcmd_buf);
if (len == 0)
showcmd_is_clear = TRUE;
else
{
screen_puts(showcmd_buf, (int)Rows - 1, sc_col, 0);
showcmd_is_clear = FALSE;
}
/*
* clear the rest of an old message by outputting up to SHOWCMD_COLS
* spaces
*/
screen_puts((char_u *)" " + len, (int)Rows - 1, sc_col + len, 0);
setcursor(); /* put cursor back where it belongs */
}
#endif
#ifdef FEAT_SCROLLBIND
/*
* When "check" is FALSE, prepare for commands that scroll the window.
* When "check" is TRUE, take care of scroll-binding after the window has
* scrolled. Called from normal_cmd() and edit().
*/
void
do_check_scrollbind(check)
int check;
{
static win_T *old_curwin = NULL;
static linenr_T old_topline = 0;
#ifdef FEAT_DIFF
static int old_topfill = 0;
#endif
static buf_T *old_buf = NULL;
static colnr_T old_leftcol = 0;
if (check && curwin->w_p_scb)
{
/* If a ":syncbind" command was just used, don't scroll, only reset
* the values. */
if (did_syncbind)
did_syncbind = FALSE;
else if (curwin == old_curwin)
{
/*
* Synchronize other windows, as necessary according to
* 'scrollbind'. Don't do this after an ":edit" command, except
* when 'diff' is set.
*/
if ((curwin->w_buffer == old_buf
#ifdef FEAT_DIFF
|| curwin->w_p_diff
#endif
)
&& (curwin->w_topline != old_topline
#ifdef FEAT_DIFF
|| curwin->w_topfill != old_topfill
#endif
|| curwin->w_leftcol != old_leftcol))
{
check_scrollbind(curwin->w_topline - old_topline,
(long)(curwin->w_leftcol - old_leftcol));
}
}
else if (vim_strchr(p_sbo, 'j')) /* jump flag set in 'scrollopt' */
{
/*
* When switching between windows, make sure that the relative
* vertical offset is valid for the new window. The relative
* offset is invalid whenever another 'scrollbind' window has
* scrolled to a point that would force the current window to
* scroll past the beginning or end of its buffer. When the
* resync is performed, some of the other 'scrollbind' windows may
* need to jump so that the current window's relative position is
* visible on-screen.
*/
check_scrollbind(curwin->w_topline - curwin->w_scbind_pos, 0L);
}
curwin->w_scbind_pos = curwin->w_topline;
}
old_curwin = curwin;
old_topline = curwin->w_topline;
#ifdef FEAT_DIFF
old_topfill = curwin->w_topfill;
#endif
old_buf = curwin->w_buffer;
old_leftcol = curwin->w_leftcol;
}
/*
* Synchronize any windows that have "scrollbind" set, based on the
* number of rows by which the current window has changed
* (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
*/
void
check_scrollbind(topline_diff, leftcol_diff)
linenr_T topline_diff;
long leftcol_diff;
{
int want_ver;
int want_hor;
win_T *old_curwin = curwin;
buf_T *old_curbuf = curbuf;
#ifdef FEAT_VISUAL
int old_VIsual_select = VIsual_select;
int old_VIsual_active = VIsual_active;
#endif
colnr_T tgt_leftcol = curwin->w_leftcol;
long topline;
long y;
/*
* check 'scrollopt' string for vertical and horizontal scroll options
*/
want_ver = (vim_strchr(p_sbo, 'v') && topline_diff != 0);
#ifdef FEAT_DIFF
want_ver |= old_curwin->w_p_diff;
#endif
want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || topline_diff != 0));
/*
* loop through the scrollbound windows and scroll accordingly
*/
#ifdef FEAT_VISUAL
VIsual_select = VIsual_active = 0;
#endif
for (curwin = firstwin; curwin; curwin = curwin->w_next)
{
curbuf = curwin->w_buffer;
/* skip original window and windows with 'noscrollbind' */
if (curwin != old_curwin && curwin->w_p_scb)
{
/*
* do the vertical scroll
*/
if (want_ver)
{
#ifdef FEAT_DIFF
if (old_curwin->w_p_diff && curwin->w_p_diff)
{
diff_set_topline(old_curwin, curwin);
}
else
#endif
{
curwin->w_scbind_pos += topline_diff;
topline = curwin->w_scbind_pos;
if (topline > curbuf->b_ml.ml_line_count)
topline = curbuf->b_ml.ml_line_count;
if (topline < 1)
topline = 1;
y = topline - curwin->w_topline;
if (y > 0)
scrollup(y, FALSE);
else
scrolldown(-y, FALSE);
}
redraw_later(VALID);
cursor_correct();
#ifdef FEAT_WINDOWS
curwin->w_redr_status = TRUE;
#endif
}
/*
* do the horizontal scroll
*/
if (want_hor && curwin->w_leftcol != tgt_leftcol)
{
curwin->w_leftcol = tgt_leftcol;
leftcol_changed();
}
}
}
/*
* reset current-window
*/
#ifdef FEAT_VISUAL
VIsual_select = old_VIsual_select;
VIsual_active = old_VIsual_active;
#endif
curwin = old_curwin;
curbuf = old_curbuf;
}
#endif /* #ifdef FEAT_SCROLLBIND */
/*
* Command character that's ignored.
* Used for CTRL-Q and CTRL-S to avoid problems with terminals that use
* xon/xoff.
*/
static void
nv_ignore(cap)
cmdarg_T *cap;
{
cap->retval |= CA_COMMAND_BUSY; /* don't call edit() now */
}
/*
* Command character that doesn't do anything, but unlike nv_ignore() does
* start edit(). Used for "startinsert" executed while starting up.
*/
static void
nv_nop(cap)
cmdarg_T *cap UNUSED;
{
}
/*
* Command character doesn't exist.
*/
static void
nv_error(cap)
cmdarg_T *cap;
{
clearopbeep(cap->oap);
}
/*
* <Help> and <F1> commands.
*/
static void
nv_help(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
ex_help(NULL);
}
/*
* CTRL-A and CTRL-X: Add or subtract from letter or number under cursor.
*/
static void
nv_addsub(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap)
&& do_addsub((int)cap->cmdchar, cap->count1) == OK)
prep_redo_cmd(cap);
}
/*
* CTRL-F, CTRL-B, etc: Scroll page up or down.
*/
static void
nv_page(cap)
cmdarg_T *cap;
{
if (!checkclearop(cap->oap))
{
#ifdef FEAT_WINDOWS
if (mod_mask & MOD_MASK_CTRL)
{
/* <C-PageUp>: tab page back; <C-PageDown>: tab page forward */
if (cap->arg == BACKWARD)
goto_tabpage(-(int)cap->count1);
else
goto_tabpage((int)cap->count0);
}
else
#endif
(void)onepage(cap->arg, cap->count1);
}
}
/*
* Implementation of "gd" and "gD" command.
*/
static void
nv_gd(oap, nchar, thisblock)
oparg_T *oap;
int nchar;
int thisblock; /* 1 for "1gd" and "1gD" */
{
int len;
char_u *ptr;
if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0
|| find_decl(ptr, len, nchar == 'd', thisblock, 0) == FAIL)
clearopbeep(oap);
#ifdef FEAT_FOLDING
else if ((fdo_flags & FDO_SEARCH) && KeyTyped && oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* Search for variable declaration of "ptr[len]".
* When "locally" is TRUE in the current function ("gd"), otherwise in the
* current file ("gD").
* When "thisblock" is TRUE check the {} block scope.
* Return FAIL when not found.
*/
int
find_decl(ptr, len, locally, thisblock, searchflags)
char_u *ptr;
int len;
int locally;
int thisblock;
int searchflags; /* flags passed to searchit() */
{
char_u *pat;
pos_T old_pos;
pos_T par_pos;
pos_T found_pos;
int t;
int save_p_ws;
int save_p_scs;
int retval = OK;
int incll;
if ((pat = alloc(len + 7)) == NULL)
return FAIL;
/* Put "\V" before the pattern to avoid that the special meaning of "."
* and "~" causes trouble. */
sprintf((char *)pat, vim_iswordp(ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s",
len, ptr);
old_pos = curwin->w_cursor;
save_p_ws = p_ws;
save_p_scs = p_scs;
p_ws = FALSE; /* don't wrap around end of file now */
p_scs = FALSE; /* don't switch ignorecase off now */
/*
* With "gD" go to line 1.
* With "gd" Search back for the start of the current function, then go
* back until a blank line. If this fails go to line 1.
*/
if (!locally || !findpar(&incll, BACKWARD, 1L, '{', FALSE))
{
setpcmark(); /* Set in findpar() otherwise */
curwin->w_cursor.lnum = 1;
par_pos = curwin->w_cursor;
}
else
{
par_pos = curwin->w_cursor;
while (curwin->w_cursor.lnum > 1 && *skipwhite(ml_get_curline()) != NUL)
--curwin->w_cursor.lnum;
}
curwin->w_cursor.col = 0;
/* Search forward for the identifier, ignore comment lines. */
clearpos(&found_pos);
for (;;)
{
t = searchit(curwin, curbuf, &curwin->w_cursor, FORWARD,
pat, 1L, searchflags, RE_LAST, (linenr_T)0, NULL);
if (curwin->w_cursor.lnum >= old_pos.lnum)
t = FAIL; /* match after start is failure too */
if (thisblock && t != FAIL)
{
pos_T *pos;
/* Check that the block the match is in doesn't end before the
* position where we started the search from. */
if ((pos = findmatchlimit(NULL, '}', FM_FORWARD,
(int)(old_pos.lnum - curwin->w_cursor.lnum + 1))) != NULL
&& pos->lnum < old_pos.lnum)
continue;
}
if (t == FAIL)
{
/* If we previously found a valid position, use it. */
if (found_pos.lnum != 0)
{
curwin->w_cursor = found_pos;
t = OK;
}
break;
}
#ifdef FEAT_COMMENTS
if (get_leader_len(ml_get_curline(), NULL, FALSE, TRUE) > 0)
{
/* Ignore this line, continue at start of next line. */
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
continue;
}
#endif
if (!locally) /* global search: use first match found */
break;
if (curwin->w_cursor.lnum >= par_pos.lnum)
{
/* If we previously found a valid position, use it. */
if (found_pos.lnum != 0)
curwin->w_cursor = found_pos;
break;
}
/* For finding a local variable and the match is before the "{" search
* to find a later match. For K&R style function declarations this
* skips the function header without types. */
found_pos = curwin->w_cursor;
}
if (t == FAIL)
{
retval = FAIL;
curwin->w_cursor = old_pos;
}
else
{
curwin->w_set_curswant = TRUE;
/* "n" searches forward now */
reset_search_dir();
}
vim_free(pat);
p_ws = save_p_ws;
p_scs = save_p_scs;
return retval;
}
/*
* Move 'dist' lines in direction 'dir', counting lines by *screen*
* lines rather than lines in the file.
* 'dist' must be positive.
*
* Return OK if able to move cursor, FAIL otherwise.
*/
static int
nv_screengo(oap, dir, dist)
oparg_T *oap;
int dir;
long dist;
{
int linelen = linetabsize(ml_get_curline());
int retval = OK;
int atend = FALSE;
int n;
int col_off1; /* margin offset for first screen line */
int col_off2; /* margin offset for wrapped screen line */
int width1; /* text width for first screen line */
int width2; /* test width for wrapped screen line */
oap->motion_type = MCHAR;
oap->inclusive = FALSE;
col_off1 = curwin_col_off();
col_off2 = col_off1 - curwin_col_off2();
width1 = W_WIDTH(curwin) - col_off1;
width2 = W_WIDTH(curwin) - col_off2;
#ifdef FEAT_VERTSPLIT
if (curwin->w_width != 0)
{
#endif
/*
* Instead of sticking at the last character of the buffer line we
* try to stick in the last column of the screen.
*/
if (curwin->w_curswant == MAXCOL)
{
atend = TRUE;
validate_virtcol();
if (width1 <= 0)
curwin->w_curswant = 0;
else
{
curwin->w_curswant = width1 - 1;
if (curwin->w_virtcol > curwin->w_curswant)
curwin->w_curswant += ((curwin->w_virtcol
- curwin->w_curswant - 1) / width2 + 1) * width2;
}
}
else
{
if (linelen > width1)
n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
else
n = width1;
if (curwin->w_curswant > (colnr_T)n + 1)
curwin->w_curswant -= ((curwin->w_curswant - n) / width2 + 1)
* width2;
}
while (dist--)
{
if (dir == BACKWARD)
{
if ((long)curwin->w_curswant >= width2)
/* move back within line */
curwin->w_curswant -= width2;
else
{
/* to previous line */
if (curwin->w_cursor.lnum == 1)
{
retval = FAIL;
break;
}
--curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
/* Move to the start of a closed fold. Don't do that when
* 'foldopen' contains "all": it will open in a moment. */
if (!(fdo_flags & FDO_ALL))
(void)hasFolding(curwin->w_cursor.lnum,
&curwin->w_cursor.lnum, NULL);
#endif
linelen = linetabsize(ml_get_curline());
if (linelen > width1)
curwin->w_curswant += (((linelen - width1 - 1) / width2)
+ 1) * width2;
}
}
else /* dir == FORWARD */
{
if (linelen > width1)
n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
else
n = width1;
if (curwin->w_curswant + width2 < (colnr_T)n)
/* move forward within line */
curwin->w_curswant += width2;
else
{
/* to next line */
#ifdef FEAT_FOLDING
/* Move to the end of a closed fold. */
(void)hasFolding(curwin->w_cursor.lnum, NULL,
&curwin->w_cursor.lnum);
#endif
if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
{
retval = FAIL;
break;
}
curwin->w_cursor.lnum++;
curwin->w_curswant %= width2;
linelen = linetabsize(ml_get_curline());
}
}
}
#ifdef FEAT_VERTSPLIT
}
#endif
coladvance(curwin->w_curswant);
#if defined(FEAT_LINEBREAK) || defined(FEAT_MBYTE)
if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
{
/*
* Check for landing on a character that got split at the end of the
* last line. We want to advance a screenline, not end up in the same
* screenline or move two screenlines.
*/
validate_virtcol();
if (curwin->w_virtcol > curwin->w_curswant
&& (curwin->w_curswant < (colnr_T)width1
? (curwin->w_curswant > (colnr_T)width1 / 2)
: ((curwin->w_curswant - width1) % width2
> (colnr_T)width2 / 2)))
--curwin->w_cursor.col;
}
#endif
if (atend)
curwin->w_curswant = MAXCOL; /* stick in the last column */
return retval;
}
#ifdef FEAT_MOUSE
/*
* Mouse scroll wheel: Default action is to scroll three lines, or one page
* when Shift or Ctrl is used.
* K_MOUSEUP (cap->arg == 1) or K_MOUSEDOWN (cap->arg == 0) or
* K_MOUSELEFT (cap->arg == -1) or K_MOUSERIGHT (cap->arg == -2)
*/
static void
nv_mousescroll(cap)
cmdarg_T *cap;
{
# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
win_T *old_curwin = curwin;
/* Currently we only get the mouse coordinates 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;
}
# endif
if (cap->arg == MSCR_UP || cap->arg == MSCR_DOWN)
{
if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
{
(void)onepage(cap->arg ? FORWARD : BACKWARD, 1L);
}
else
{
cap->count1 = 3;
cap->count0 = 3;
nv_scroll_line(cap);
}
}
# ifdef FEAT_GUI
else
{
/* Horizontal scroll - only allowed when 'wrap' is disabled */
if (!curwin->w_p_wrap)
{
int val, step = 6;
if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
step = W_WIDTH(curwin);
val = curwin->w_leftcol + (cap->arg == MSCR_RIGHT ? -step : +step);
if (val < 0)
val = 0;
gui_do_horiz_scroll(val, TRUE);
}
}
# endif
# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
curwin->w_redr_status = TRUE;
curwin = old_curwin;
curbuf = curwin->w_buffer;
# endif
}
/*
* Mouse clicks and drags.
*/
static void
nv_mouse(cap)
cmdarg_T *cap;
{
(void)do_mouse(cap->oap, cap->cmdchar, BACKWARD, cap->count1, 0);
}
#endif
/*
* Handle CTRL-E and CTRL-Y commands: scroll a line up or down.
* cap->arg must be TRUE for CTRL-E.
*/
static void
nv_scroll_line(cap)
cmdarg_T *cap;
{
if (!checkclearop(cap->oap))
scroll_redraw(cap->arg, cap->count1);
}
/*
* Scroll "count" lines up or down, and redraw.
*/
void
scroll_redraw(up, count)
int up;
long count;
{
linenr_T prev_topline = curwin->w_topline;
#ifdef FEAT_DIFF
int prev_topfill = curwin->w_topfill;
#endif
linenr_T prev_lnum = curwin->w_cursor.lnum;
if (up)
scrollup(count, TRUE);
else
scrolldown(count, TRUE);
if (p_so)
{
/* Adjust the cursor position for 'scrolloff'. Mark w_topline as
* valid, otherwise the screen jumps back at the end of the file. */
cursor_correct();
check_cursor_moved(curwin);
curwin->w_valid |= VALID_TOPLINE;
/* If moved back to where we were, at least move the cursor, otherwise
* we get stuck at one position. Don't move the cursor up if the
* first line of the buffer is already on the screen */
while (curwin->w_topline == prev_topline
#ifdef FEAT_DIFF
&& curwin->w_topfill == prev_topfill
#endif
)
{
if (up)
{
if (curwin->w_cursor.lnum > prev_lnum
|| cursor_down(1L, FALSE) == FAIL)
break;
}
else
{
if (curwin->w_cursor.lnum < prev_lnum
|| prev_topline == 1L
|| cursor_up(1L, FALSE) == FAIL)
break;
}
/* Mark w_topline as valid, otherwise the screen jumps back at the
* end of the file. */
check_cursor_moved(curwin);
curwin->w_valid |= VALID_TOPLINE;
}
}
if (curwin->w_cursor.lnum != prev_lnum)
coladvance(curwin->w_curswant);
redraw_later(VALID);
}
/*
* Commands that start with "z".
*/
static void
nv_zet(cap)
cmdarg_T *cap;
{
long n;
colnr_T col;
int nchar = cap->nchar;
#ifdef FEAT_FOLDING
long old_fdl = curwin->w_p_fdl;
int old_fen = curwin->w_p_fen;
#endif
#ifdef FEAT_SPELL
int undo = FALSE;
#endif
if (VIM_ISDIGIT(nchar))
{
/*
* "z123{nchar}": edit the count before obtaining {nchar}
*/
if (checkclearop(cap->oap))
return;
n = nchar - '0';
for (;;)
{
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; /* disallow scrolling here */
#endif
++no_mapping;
++allow_keys; /* no mapping for nchar, but allow key codes */
nchar = plain_vgetc();
LANGMAP_ADJUST(nchar, TRUE);
--no_mapping;
--allow_keys;
#ifdef FEAT_CMDL_INFO
(void)add_to_showcmd(nchar);
#endif
if (nchar == K_DEL || nchar == K_KDEL)
n /= 10;
else if (VIM_ISDIGIT(nchar))
n = n * 10 + (nchar - '0');
else if (nchar == CAR)
{
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight((int)n);
break;
}
else if (nchar == 'l'
|| nchar == 'h'
|| nchar == K_LEFT
|| nchar == K_RIGHT)
{
cap->count1 = n ? n * cap->count1 : cap->count1;
goto dozet;
}
else
{
clearopbeep(cap->oap);
break;
}
}
cap->oap->op_type = OP_NOP;
return;
}
dozet:
if (
#ifdef FEAT_FOLDING
/* "zf" and "zF" are always an operator, "zd", "zo", "zO", "zc"
* and "zC" only in Visual mode. "zj" and "zk" are motion
* commands. */
cap->nchar != 'f' && cap->nchar != 'F'
&& !(VIsual_active && vim_strchr((char_u *)"dcCoO", cap->nchar))
&& cap->nchar != 'j' && cap->nchar != 'k'
&&
#endif
checkclearop(cap->oap))
return;
/*
* For "z+", "z<CR>", "zt", "z.", "zz", "z^", "z-", "zb":
* If line number given, set cursor.
*/
if ((vim_strchr((char_u *)"+\r\nt.z^-b", nchar) != NULL)
&& cap->count0
&& cap->count0 != curwin->w_cursor.lnum)
{
setpcmark();
if (cap->count0 > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
else
curwin->w_cursor.lnum = cap->count0;
check_cursor_col();
}
switch (nchar)
{
/* "z+", "z<CR>" and "zt": put cursor at top of screen */
case '+':
if (cap->count0 == 0)
{
/* No count given: put cursor at the line below screen */
validate_botline(); /* make sure w_botline is valid */
if (curwin->w_botline > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
else
curwin->w_cursor.lnum = curwin->w_botline;
}
/* FALLTHROUGH */
case NL:
case CAR:
case K_KENTER:
beginline(BL_WHITE | BL_FIX);
/* FALLTHROUGH */
case 't': scroll_cursor_top(0, TRUE);
redraw_later(VALID);
break;
/* "z." and "zz": put cursor in middle of screen */
case '.': beginline(BL_WHITE | BL_FIX);
/* FALLTHROUGH */
case 'z': scroll_cursor_halfway(TRUE);
redraw_later(VALID);
break;
/* "z^", "z-" and "zb": put cursor at bottom of screen */
case '^': /* Strange Vi behavior: <count>z^ finds line at top of window
* when <count> is at bottom of window, and puts that one at
* bottom of window. */
if (cap->count0 != 0)
{
scroll_cursor_bot(0, TRUE);
curwin->w_cursor.lnum = curwin->w_topline;
}
else if (curwin->w_topline == 1)
curwin->w_cursor.lnum = 1;
else
curwin->w_cursor.lnum = curwin->w_topline - 1;
/* FALLTHROUGH */
case '-':
beginline(BL_WHITE | BL_FIX);
/* FALLTHROUGH */
case 'b': scroll_cursor_bot(0, TRUE);
redraw_later(VALID);
break;
/* "zH" - scroll screen right half-page */
case 'H':
cap->count1 *= W_WIDTH(curwin) / 2;
/* FALLTHROUGH */
/* "zh" - scroll screen to the right */
case 'h':
case K_LEFT:
if (!curwin->w_p_wrap)
{
if ((colnr_T)cap->count1 > curwin->w_leftcol)
curwin->w_leftcol = 0;
else
curwin->w_leftcol -= (colnr_T)cap->count1;
leftcol_changed();
}
break;
/* "zL" - scroll screen left half-page */
case 'L': cap->count1 *= W_WIDTH(curwin) / 2;
/* FALLTHROUGH */
/* "zl" - scroll screen to the left */
case 'l':
case K_RIGHT:
if (!curwin->w_p_wrap)
{
/* scroll the window left */
curwin->w_leftcol += (colnr_T)cap->count1;
leftcol_changed();
}
break;
/* "zs" - scroll screen, cursor at the start */
case 's': if (!curwin->w_p_wrap)
{
#ifdef FEAT_FOLDING
if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
col = 0; /* like the cursor is in col 0 */
else
#endif
getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
if ((long)col > p_siso)
col -= p_siso;
else
col = 0;
if (curwin->w_leftcol != col)
{
curwin->w_leftcol = col;
redraw_later(NOT_VALID);
}
}
break;
/* "ze" - scroll screen, cursor at the end */
case 'e': if (!curwin->w_p_wrap)
{
#ifdef FEAT_FOLDING
if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
col = 0; /* like the cursor is in col 0 */
else
#endif
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
n = W_WIDTH(curwin) - curwin_col_off();
if ((long)col + p_siso < n)
col = 0;
else
col = col + p_siso - n + 1;
if (curwin->w_leftcol != col)
{
curwin->w_leftcol = col;
redraw_later(NOT_VALID);
}
}
break;
#ifdef FEAT_FOLDING
/* "zF": create fold command */
/* "zf": create fold operator */
case 'F':
case 'f': if (foldManualAllowed(TRUE))
{
cap->nchar = 'f';
nv_operator(cap);
curwin->w_p_fen = TRUE;
/* "zF" is like "zfzf" */
if (nchar == 'F' && cap->oap->op_type == OP_FOLD)
{
nv_operator(cap);
finish_op = TRUE;
}
}
else
clearopbeep(cap->oap);
break;
/* "zd": delete fold at cursor */
/* "zD": delete fold at cursor recursively */
case 'd':
case 'D': if (foldManualAllowed(FALSE))
{
if (VIsual_active)
nv_operator(cap);
else
deleteFold(curwin->w_cursor.lnum,
curwin->w_cursor.lnum, nchar == 'D', FALSE);
}
break;
/* "zE": erease all folds */
case 'E': if (foldmethodIsManual(curwin))
{
clearFolding(curwin);
changed_window_setting();
}
else if (foldmethodIsMarker(curwin))
deleteFold((linenr_T)1, curbuf->b_ml.ml_line_count,
TRUE, FALSE);
else
EMSG(_("E352: Cannot erase folds with current 'foldmethod'"));
break;
/* "zn": fold none: reset 'foldenable' */
case 'n': curwin->w_p_fen = FALSE;
break;
/* "zN": fold Normal: set 'foldenable' */
case 'N': curwin->w_p_fen = TRUE;
break;
/* "zi": invert folding: toggle 'foldenable' */
case 'i': curwin->w_p_fen = !curwin->w_p_fen;
break;
/* "za": open closed fold or close open fold at cursor */
case 'a': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
openFold(curwin->w_cursor.lnum, cap->count1);
else
{
closeFold(curwin->w_cursor.lnum, cap->count1);
curwin->w_p_fen = TRUE;
}
break;
/* "zA": open fold at cursor recursively */
case 'A': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
openFoldRecurse(curwin->w_cursor.lnum);
else
{
closeFoldRecurse(curwin->w_cursor.lnum);
curwin->w_p_fen = TRUE;
}
break;
/* "zo": open fold at cursor or Visual area */
case 'o': if (VIsual_active)
nv_operator(cap);
else
openFold(curwin->w_cursor.lnum, cap->count1);
break;
/* "zO": open fold recursively */
case 'O': if (VIsual_active)
nv_operator(cap);
else
openFoldRecurse(curwin->w_cursor.lnum);
break;
/* "zc": close fold at cursor or Visual area */
case 'c': if (VIsual_active)
nv_operator(cap);
else
closeFold(curwin->w_cursor.lnum, cap->count1);
curwin->w_p_fen = TRUE;
break;
/* "zC": close fold recursively */
case 'C': if (VIsual_active)
nv_operator(cap);
else
closeFoldRecurse(curwin->w_cursor.lnum);
curwin->w_p_fen = TRUE;
break;
/* "zv": open folds at the cursor */
case 'v': foldOpenCursor();
break;
/* "zx": re-apply 'foldlevel' and open folds at the cursor */
case 'x': curwin->w_p_fen = TRUE;
curwin->w_foldinvalid = TRUE; /* recompute folds */
newFoldLevel(); /* update right now */
foldOpenCursor();
break;
/* "zX": undo manual opens/closes, re-apply 'foldlevel' */
case 'X': curwin->w_p_fen = TRUE;
curwin->w_foldinvalid = TRUE; /* recompute folds */
old_fdl = -1; /* force an update */
break;
/* "zm": fold more */
case 'm': if (curwin->w_p_fdl > 0)
--curwin->w_p_fdl;
old_fdl = -1; /* force an update */
curwin->w_p_fen = TRUE;
break;
/* "zM": close all folds */
case 'M': curwin->w_p_fdl = 0;
old_fdl = -1; /* force an update */
curwin->w_p_fen = TRUE;
break;
/* "zr": reduce folding */
case 'r': ++curwin->w_p_fdl;
break;
/* "zR": open all folds */
case 'R': curwin->w_p_fdl = getDeepestNesting();
old_fdl = -1; /* force an update */
break;
case 'j': /* "zj" move to next fold downwards */
case 'k': /* "zk" move to next fold upwards */
if (foldMoveTo(TRUE, nchar == 'j' ? FORWARD : BACKWARD,
cap->count1) == FAIL)
clearopbeep(cap->oap);
break;
#endif /* FEAT_FOLDING */
#ifdef FEAT_SPELL
case 'u': /* "zug" and "zuw": undo "zg" and "zw" */
++no_mapping;
++allow_keys; /* no mapping for nchar, but allow key codes */
nchar = plain_vgetc();
LANGMAP_ADJUST(nchar, TRUE);
--no_mapping;
--allow_keys;
#ifdef FEAT_CMDL_INFO
(void)add_to_showcmd(nchar);
#endif
if (vim_strchr((char_u *)"gGwW", nchar) == NULL)
{
clearopbeep(cap->oap);
break;
}
undo = TRUE;
/*FALLTHROUGH*/
case 'g': /* "zg": add good word to word list */
case 'w': /* "zw": add wrong word to word list */
case 'G': /* "zG": add good word to temp word list */
case 'W': /* "zW": add wrong word to temp word list */
{
char_u *ptr = NULL;
int len;
if (checkclearop(cap->oap))
break;
# ifdef FEAT_VISUAL
if (VIsual_active && get_visual_text(cap, &ptr, &len)
== FAIL)
return;
# endif
if (ptr == NULL)
{
pos_T pos = curwin->w_cursor;
/* Find bad word under the cursor. */
len = spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL);
if (len != 0 && curwin->w_cursor.col <= pos.col)
ptr = ml_get_pos(&curwin->w_cursor);
curwin->w_cursor = pos;
}
if (ptr == NULL && (len = find_ident_under_cursor(&ptr,
FIND_IDENT)) == 0)
return;
spell_add_word(ptr, len, nchar == 'w' || nchar == 'W',
(nchar == 'G' || nchar == 'W')
? 0 : (int)cap->count1,
undo);
}
break;
case '=': /* "z=": suggestions for a badly spelled word */
if (!checkclearop(cap->oap))
spell_suggest((int)cap->count0);
break;
#endif
default: clearopbeep(cap->oap);
}
#ifdef FEAT_FOLDING
/* Redraw when 'foldenable' changed */
if (old_fen != curwin->w_p_fen)
{
# ifdef FEAT_DIFF
win_T *wp;
if (foldmethodIsDiff(curwin) && curwin->w_p_scb)
{
/* Adjust 'foldenable' in diff-synced windows. */
FOR_ALL_WINDOWS(wp)
{
if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb)
{
wp->w_p_fen = curwin->w_p_fen;
changed_window_setting_win(wp);
}
}
}
# endif
changed_window_setting();
}
/* Redraw when 'foldlevel' changed. */
if (old_fdl != curwin->w_p_fdl)
newFoldLevel();
#endif
}
#ifdef FEAT_GUI
/*
* Vertical scrollbar movement.
*/
static void
nv_ver_scrollbar(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type != OP_NOP)
clearopbeep(cap->oap);
/* Even if an operator was pending, we still want to scroll */
gui_do_scroll();
}
/*
* Horizontal scrollbar movement.
*/
static void
nv_hor_scrollbar(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type != OP_NOP)
clearopbeep(cap->oap);
/* Even if an operator was pending, we still want to scroll */
gui_do_horiz_scroll(scrollbar_value, FALSE);
}
#endif
#if defined(FEAT_GUI_TABLINE) || defined(PROTO)
/*
* Click in GUI tab.
*/
static void
nv_tabline(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type != OP_NOP)
clearopbeep(cap->oap);
/* Even if an operator was pending, we still want to jump tabs. */
goto_tabpage(current_tab);
}
/*
* Selected item in tab line menu.
*/
static void
nv_tabmenu(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type != OP_NOP)
clearopbeep(cap->oap);
/* Even if an operator was pending, we still want to jump tabs. */
handle_tabmenu();
}
/*
* Handle selecting an item of the GUI tab line menu.
* Used in Normal and Insert mode.
*/
void
handle_tabmenu()
{
switch (current_tabmenu)
{
case TABLINE_MENU_CLOSE:
if (current_tab == 0)
do_cmdline_cmd((char_u *)"tabclose");
else
{
vim_snprintf((char *)IObuff, IOSIZE, "tabclose %d",
current_tab);
do_cmdline_cmd(IObuff);
}
break;
case TABLINE_MENU_NEW:
vim_snprintf((char *)IObuff, IOSIZE, "%dtabnew",
current_tab > 0 ? current_tab - 1 : 999);
do_cmdline_cmd(IObuff);
break;
case TABLINE_MENU_OPEN:
vim_snprintf((char *)IObuff, IOSIZE, "browse %dtabnew",
current_tab > 0 ? current_tab - 1 : 999);
do_cmdline_cmd(IObuff);
break;
}
}
#endif
/*
* "Q" command.
*/
static void
nv_exmode(cap)
cmdarg_T *cap;
{
/*
* Ignore 'Q' in Visual mode, just give a beep.
*/
#ifdef FEAT_VISUAL
if (VIsual_active)
vim_beep();
else
#endif
if (!checkclearop(cap->oap))
do_exmode(FALSE);
}
/*
* Handle a ":" command.
*/
static void
nv_colon(cap)
cmdarg_T *cap;
{
int old_p_im;
#ifdef FEAT_VISUAL
if (VIsual_active)
nv_operator(cap);
else
#endif
{
if (cap->oap->op_type != OP_NOP)
{
/* Using ":" as a movement is characterwise exclusive. */
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
}
else if (cap->count0)
{
/* translate "count:" into ":.,.+(count - 1)" */
stuffcharReadbuff('.');
if (cap->count0 > 1)
{
stuffReadbuff((char_u *)",.+");
stuffnumReadbuff((long)cap->count0 - 1L);
}
}
/* When typing, don't type below an old message */
if (KeyTyped)
compute_cmdrow();
old_p_im = p_im;
/* get a command line and execute it */
do_cmdline(NULL, getexline, NULL,
cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
/* If 'insertmode' changed, enter or exit Insert mode */
if (p_im != old_p_im)
{
if (p_im)
restart_edit = 'i';
else
restart_edit = 0;
}
/* The start of the operator may have become invalid by the Ex
* command. */
if (cap->oap->op_type != OP_NOP
&& (cap->oap->start.lnum > curbuf->b_ml.ml_line_count
|| cap->oap->start.col >
(colnr_T)STRLEN(ml_get(cap->oap->start.lnum))))
clearopbeep(cap->oap);
}
}
/*
* Handle CTRL-G command.
*/
static void
nv_ctrlg(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active) /* toggle Selection/Visual mode */
{
VIsual_select = !VIsual_select;
showmode();
}
else
#endif
if (!checkclearop(cap->oap))
/* print full name if count given or :cd used */
fileinfo((int)cap->count0, FALSE, TRUE);
}
/*
* Handle CTRL-H <Backspace> command.
*/
static void
nv_ctrlh(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active && VIsual_select)
{
cap->cmdchar = 'x'; /* BS key behaves like 'x' in Select mode */
v_visop(cap);
}
else
#endif
nv_left(cap);
}
/*
* CTRL-L: clear screen and redraw.
*/
static void
nv_clear(cap)
cmdarg_T *cap;
{
if (!checkclearop(cap->oap))
{
#if defined(__BEOS__) && !USE_THREAD_FOR_INPUT_WITH_TIMEOUT
/*
* Right now, the BeBox doesn't seem to have an easy way to detect
* window resizing, so we cheat and make the user detect it
* manually with CTRL-L instead
*/
ui_get_shellsize();
#endif
#ifdef FEAT_SYN_HL
/* Clear all syntax states to force resyncing. */
syn_stack_free_all(curwin->w_s);
#endif
redraw_later(CLEAR);
}
}
/*
* CTRL-O: In Select mode: switch to Visual mode for one command.
* Otherwise: Go to older pcmark.
*/
static void
nv_ctrlo(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active && VIsual_select)
{
VIsual_select = FALSE;
showmode();
restart_VIsual_select = 2; /* restart Select mode later */
}
else
#endif
{
cap->count1 = -cap->count1;
nv_pcmark(cap);
}
}
/*
* CTRL-^ command, short for ":e #"
*/
static void
nv_hat(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
(void)buflist_getfile((int)cap->count0, (linenr_T)0,
GETF_SETMARK|GETF_ALT, FALSE);
}
/*
* "Z" commands.
*/
static void
nv_Zet(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
{
switch (cap->nchar)
{
/* "ZZ": equivalent to ":x". */
case 'Z': do_cmdline_cmd((char_u *)"x");
break;
/* "ZQ": equivalent to ":q!" (Elvis compatible). */
case 'Q': do_cmdline_cmd((char_u *)"q!");
break;
default: clearopbeep(cap->oap);
}
}
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Call nv_ident() as if "c1" was used, with "c2" as next character.
*/
void
do_nv_ident(c1, c2)
int c1;
int c2;
{
oparg_T oa;
cmdarg_T ca;
clear_oparg(&oa);
vim_memset(&ca, 0, sizeof(ca));
ca.oap = &oa;
ca.cmdchar = c1;
ca.nchar = c2;
nv_ident(&ca);
}
#endif
/*
* Handle the commands that use the word under the cursor.
* [g] CTRL-] :ta to current identifier
* [g] 'K' run program for current identifier
* [g] '*' / to current identifier or string
* [g] '#' ? to current identifier or string
* g ']' :tselect for current identifier
*/
static void
nv_ident(cap)
cmdarg_T *cap;
{
char_u *ptr = NULL;
char_u *buf;
char_u *newbuf;
char_u *p;
char_u *kp; /* value of 'keywordprg' */
int kp_help; /* 'keywordprg' is ":help" */
int n = 0; /* init for GCC */
int cmdchar;
int g_cmd; /* "g" command */
int tag_cmd = FALSE;
char_u *aux_ptr;
int isman;
int isman_s;
if (cap->cmdchar == 'g') /* "g*", "g#", "g]" and "gCTRL-]" */
{
cmdchar = cap->nchar;
g_cmd = TRUE;
}
else
{
cmdchar = cap->cmdchar;
g_cmd = FALSE;
}
if (cmdchar == POUND) /* the pound sign, '#' for English keyboards */
cmdchar = '#';
/*
* The "]", "CTRL-]" and "K" commands accept an argument in Visual mode.
*/
if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K')
{
#ifdef FEAT_VISUAL
if (VIsual_active && get_visual_text(cap, &ptr, &n) == FAIL)
return;
#endif
if (checkclearopq(cap->oap))
return;
}
if (ptr == NULL && (n = find_ident_under_cursor(&ptr,
(cmdchar == '*' || cmdchar == '#')
? FIND_IDENT|FIND_STRING : FIND_IDENT)) == 0)
{
clearop(cap->oap);
return;
}
/* Allocate buffer to put the command in. Inserting backslashes can
* double the length of the word. p_kp / curbuf->b_p_kp could be added
* and some numbers. */
kp = (*curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp);
kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0
|| STRCMP(kp, ":help") == 0);
buf = alloc((unsigned)(n * 2 + 30 + STRLEN(kp)));
if (buf == NULL)
return;
buf[0] = NUL;
switch (cmdchar)
{
case '*':
case '#':
/*
* Put cursor at start of word, makes search skip the word
* under the cursor.
* Call setpcmark() first, so "*``" puts the cursor back where
* it was.
*/
setpcmark();
curwin->w_cursor.col = (colnr_T) (ptr - ml_get_curline());
if (!g_cmd && vim_iswordp(ptr))
STRCPY(buf, "\\<");
no_smartcase = TRUE; /* don't use 'smartcase' now */
break;
case 'K':
if (kp_help)
STRCPY(buf, "he! ");
else
{
/* An external command will probably use an argument starting
* with "-" as an option. To avoid trouble we skip the "-". */
while (*ptr == '-' && n > 0)
{
++ptr;
--n;
}
if (n == 0)
{
EMSG(_(e_noident)); /* found dashes only */
vim_free(buf);
return;
}
/* When a count is given, turn it into a range. Is this
* really what we want? */
isman = (STRCMP(kp, "man") == 0);
isman_s = (STRCMP(kp, "man -s") == 0);
if (cap->count0 != 0 && !(isman || isman_s))
sprintf((char *)buf, ".,.+%ld", cap->count0 - 1);
STRCAT(buf, "! ");
if (cap->count0 == 0 && isman_s)
STRCAT(buf, "man");
else
STRCAT(buf, kp);
STRCAT(buf, " ");
if (cap->count0 != 0 && (isman || isman_s))
{
sprintf((char *)buf + STRLEN(buf), "%ld", cap->count0);
STRCAT(buf, " ");
}
}
break;
case ']':
tag_cmd = TRUE;
#ifdef FEAT_CSCOPE
if (p_cst)
STRCPY(buf, "cstag ");
else
#endif
STRCPY(buf, "ts ");
break;
default:
tag_cmd = TRUE;
if (curbuf->b_help)
STRCPY(buf, "he! ");
else
{
if (g_cmd)
STRCPY(buf, "tj ");
else
sprintf((char *)buf, "%ldta ", cap->count0);
}
}
/*
* Now grab the chars in the identifier
*/
if (cmdchar == 'K' && !kp_help)
{
/* Escape the argument properly for a shell command */
ptr = vim_strnsave(ptr, n);
p = vim_strsave_shellescape(ptr, TRUE);
vim_free(ptr);
if (p == NULL)
{
vim_free(buf);
return;
}
newbuf = (char_u *)vim_realloc(buf, STRLEN(buf) + STRLEN(p) + 1);
if (newbuf == NULL)
{
vim_free(buf);
vim_free(p);
return;
}
buf = newbuf;
STRCAT(buf, p);
vim_free(p);
}
else
{
if (cmdchar == '*')
aux_ptr = (char_u *)(p_magic ? "/.*~[^$\\" : "/^$\\");
else if (cmdchar == '#')
aux_ptr = (char_u *)(p_magic ? "/?.*~[^$\\" : "/?^$\\");
else if (tag_cmd)
{
if (curbuf->b_help)
/* ":help" handles unescaped argument */
aux_ptr = (char_u *)"";
else
aux_ptr = (char_u *)"\\|\"\n[";
}
else
aux_ptr = (char_u *)"\\|\"\n*?[";
p = buf + STRLEN(buf);
while (n-- > 0)
{
/* put a backslash before \ and some others */
if (vim_strchr(aux_ptr, *ptr) != NULL)
*p++ = '\\';
#ifdef FEAT_MBYTE
/* When current byte is a part of multibyte character, copy all
* bytes of that character. */
if (has_mbyte)
{
int i;
int len = (*mb_ptr2len)(ptr) - 1;
for (i = 0; i < len && n >= 1; ++i, --n)
*p++ = *ptr++;
}
#endif
*p++ = *ptr++;
}
*p = NUL;
}
/*
* Execute the command.
*/
if (cmdchar == '*' || cmdchar == '#')
{
if (!g_cmd && (
#ifdef FEAT_MBYTE
has_mbyte ? vim_iswordp(mb_prevptr(ml_get_curline(), ptr)) :
#endif
vim_iswordc(ptr[-1])))
STRCAT(buf, "\\>");
#ifdef FEAT_CMDHIST
/* put pattern in search history */
init_history();
add_to_history(HIST_SEARCH, buf, TRUE, NUL);
#endif
normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0);
}
else
do_cmdline_cmd(buf);
vim_free(buf);
}
#if defined(FEAT_VISUAL) || defined(PROTO)
/*
* Get visually selected text, within one line only.
* Returns FAIL if more than one line selected.
*/
int
get_visual_text(cap, pp, lenp)
cmdarg_T *cap;
char_u **pp; /* return: start of selected text */
int *lenp; /* return: length of selected text */
{
if (VIsual_mode != 'V')
unadjust_for_sel();
if (VIsual.lnum != curwin->w_cursor.lnum)
{
if (cap != NULL)
clearopbeep(cap->oap);
return FAIL;
}
if (VIsual_mode == 'V')
{
*pp = ml_get_curline();
*lenp = (int)STRLEN(*pp);
}
else
{
if (lt(curwin->w_cursor, VIsual))
{
*pp = ml_get_pos(&curwin->w_cursor);
*lenp = VIsual.col - curwin->w_cursor.col + 1;
}
else
{
*pp = ml_get_pos(&VIsual);
*lenp = curwin->w_cursor.col - VIsual.col + 1;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
/* Correct the length to include the whole last character. */
*lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
#endif
}
reset_VIsual_and_resel();
return OK;
}
#endif
/*
* CTRL-T: backwards in tag stack
*/
static void
nv_tagpop(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
do_tag((char_u *)"", DT_POP, (int)cap->count1, FALSE, TRUE);
}
/*
* Handle scrolling command 'H', 'L' and 'M'.
*/
static void
nv_scroll(cap)
cmdarg_T *cap;
{
int used = 0;
long n;
#ifdef FEAT_FOLDING
linenr_T lnum;
#endif
int half;
cap->oap->motion_type = MLINE;
setpcmark();
if (cap->cmdchar == 'L')
{
validate_botline(); /* make sure curwin->w_botline is valid */
curwin->w_cursor.lnum = curwin->w_botline - 1;
if (cap->count1 - 1 >= curwin->w_cursor.lnum)
curwin->w_cursor.lnum = 1;
else
{
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
/* Count a fold for one screen line. */
for (n = cap->count1 - 1; n > 0
&& curwin->w_cursor.lnum > curwin->w_topline; --n)
{
(void)hasFolding(curwin->w_cursor.lnum,
&curwin->w_cursor.lnum, NULL);
--curwin->w_cursor.lnum;
}
}
else
#endif
curwin->w_cursor.lnum -= cap->count1 - 1;
}
}
else
{
if (cap->cmdchar == 'M')
{
#ifdef FEAT_DIFF
/* Don't count filler lines above the window. */
used -= diff_check_fill(curwin, curwin->w_topline)
- curwin->w_topfill;
#endif
validate_botline(); /* make sure w_empty_rows is valid */
half = (curwin->w_height - curwin->w_empty_rows + 1) / 2;
for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; ++n)
{
#ifdef FEAT_DIFF
/* Count half he number of filler lines to be "below this
* line" and half to be "above the next line". */
if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline
+ n) / 2 >= half)
{
--n;
break;
}
#endif
used += plines(curwin->w_topline + n);
if (used >= half)
break;
#ifdef FEAT_FOLDING
if (hasFolding(curwin->w_topline + n, NULL, &lnum))
n = lnum - curwin->w_topline;
#endif
}
if (n > 0 && used > curwin->w_height)
--n;
}
else /* (cap->cmdchar == 'H') */
{
n = cap->count1 - 1;
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
/* Count a fold for one screen line. */
lnum = curwin->w_topline;
while (n-- > 0 && lnum < curwin->w_botline - 1)
{
hasFolding(lnum, NULL, &lnum);
++lnum;
}
n = lnum - curwin->w_topline;
}
#endif
}
curwin->w_cursor.lnum = curwin->w_topline + n;
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
}
cursor_correct(); /* correct for 'so' */
beginline(BL_SOL | BL_FIX);
}
/*
* Cursor right commands.
*/
static void
nv_right(cap)
cmdarg_T *cap;
{
long n;
#ifdef FEAT_VISUAL
int PAST_LINE;
#else
# define PAST_LINE 0
#endif
if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
{
/* <C-Right> and <S-Right> move a word or WORD right */
if (mod_mask & MOD_MASK_CTRL)
cap->arg = TRUE;
nv_wordcmd(cap);
return;
}
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
#ifdef FEAT_VISUAL
PAST_LINE = (VIsual_active && *p_sel != 'o');
# ifdef FEAT_VIRTUALEDIT
/*
* In virtual mode, there's no such thing as "PAST_LINE", as lines are
* (theoretically) infinitely long.
*/
if (virtual_active())
PAST_LINE = 0;
# endif
#endif
for (n = cap->count1; n > 0; --n)
{
if ((!PAST_LINE && oneright() == FAIL)
#ifdef FEAT_VISUAL
|| (PAST_LINE && *ml_get_cursor() == NUL)
#endif
)
{
/*
* <Space> wraps to next line if 'whichwrap' has 's'.
* 'l' wraps to next line if 'whichwrap' has 'l'.
* CURS_RIGHT wraps to next line if 'whichwrap' has '>'.
*/
if ( ((cap->cmdchar == ' '
&& vim_strchr(p_ww, 's') != NULL)
|| (cap->cmdchar == 'l'
&& vim_strchr(p_ww, 'l') != NULL)
|| (cap->cmdchar == K_RIGHT
&& vim_strchr(p_ww, '>') != NULL))
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
/* When deleting we also count the NL as a character.
* Set cap->oap->inclusive when last char in the line is
* included, move to next line after that */
if ( cap->oap->op_type != OP_NOP
&& !cap->oap->inclusive
&& !lineempty(curwin->w_cursor.lnum))
cap->oap->inclusive = TRUE;
else
{
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
curwin->w_set_curswant = TRUE;
cap->oap->inclusive = FALSE;
}
continue;
}
if (cap->oap->op_type == OP_NOP)
{
/* Only beep and flush if not moved at all */
if (n == cap->count1)
beep_flush();
}
else
{
if (!lineempty(curwin->w_cursor.lnum))
cap->oap->inclusive = TRUE;
}
break;
}
#ifdef FEAT_VISUAL
else if (PAST_LINE)
{
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;
}
}
#endif
}
#ifdef FEAT_FOLDING
if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
&& cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* Cursor left commands.
*
* Returns TRUE when operator end should not be adjusted.
*/
static void
nv_left(cap)
cmdarg_T *cap;
{
long n;
if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
{
/* <C-Left> and <S-Left> move a word or WORD left */
if (mod_mask & MOD_MASK_CTRL)
cap->arg = 1;
nv_bck_word(cap);
return;
}
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
for (n = cap->count1; n > 0; --n)
{
if (oneleft() == FAIL)
{
/* <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'.
* 'h' wraps to previous line if 'whichwrap' has 'h'.
* CURS_LEFT wraps to previous line if 'whichwrap' has '<'.
*/
if ( (((cap->cmdchar == K_BS
|| cap->cmdchar == Ctrl_H)
&& vim_strchr(p_ww, 'b') != NULL)
|| (cap->cmdchar == 'h'
&& vim_strchr(p_ww, 'h') != NULL)
|| (cap->cmdchar == K_LEFT
&& vim_strchr(p_ww, '<') != NULL))
&& curwin->w_cursor.lnum > 1)
{
--(curwin->w_cursor.lnum);
coladvance((colnr_T)MAXCOL);
curwin->w_set_curswant = TRUE;
/* When the NL before the first char has to be deleted we
* put the cursor on the NUL after the previous line.
* This is a very special case, be careful!
* Don't adjust op_end now, otherwise it won't work. */
if ( (cap->oap->op_type == OP_DELETE
|| cap->oap->op_type == OP_CHANGE)
&& !lineempty(curwin->w_cursor.lnum))
{
if (*ml_get_cursor() != NUL)
++curwin->w_cursor.col;
cap->retval |= CA_NO_ADJ_OP_END;
}
continue;
}
/* Only beep and flush if not moved at all */
else if (cap->oap->op_type == OP_NOP && n == cap->count1)
beep_flush();
break;
}
}
#ifdef FEAT_FOLDING
if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
&& cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* Cursor up commands.
* cap->arg is TRUE for "-": Move cursor to first non-blank.
*/
static void
nv_up(cap)
cmdarg_T *cap;
{
if (mod_mask & MOD_MASK_SHIFT)
{
/* <S-Up> is page up */
cap->arg = BACKWARD;
nv_page(cap);
}
else
{
cap->oap->motion_type = MLINE;
if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
clearopbeep(cap->oap);
else if (cap->arg)
beginline(BL_WHITE | BL_FIX);
}
}
/*
* Cursor down commands.
* cap->arg is TRUE for CR and "+": Move cursor to first non-blank.
*/
static void
nv_down(cap)
cmdarg_T *cap;
{
if (mod_mask & MOD_MASK_SHIFT)
{
/* <S-Down> is page down */
cap->arg = FORWARD;
nv_page(cap);
}
else
#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
/* In a quickfix window a <CR> jumps to the error under the cursor. */
if (bt_quickfix(curbuf) && cap->cmdchar == CAR)
if (curwin->w_llist_ref == NULL)
do_cmdline_cmd((char_u *)".cc"); /* quickfix window */
else
do_cmdline_cmd((char_u *)".ll"); /* location list window */
else
#endif
{
#ifdef FEAT_CMDWIN
/* In the cmdline window a <CR> executes the command. */
if (cmdwin_type != 0 && cap->cmdchar == CAR)
cmdwin_result = CAR;
else
#endif
{
cap->oap->motion_type = MLINE;
if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
clearopbeep(cap->oap);
else if (cap->arg)
beginline(BL_WHITE | BL_FIX);
}
}
}
#ifdef FEAT_SEARCHPATH
/*
* Grab the file name under the cursor and edit it.
*/
static void
nv_gotofile(cap)
cmdarg_T *cap;
{
char_u *ptr;
linenr_T lnum = -1;
if (text_locked())
{
clearopbeep(cap->oap);
text_locked_msg();
return;
}
#ifdef FEAT_AUTOCMD
if (curbuf_locked())
{
clearop(cap->oap);
return;
}
#endif
ptr = grab_file_name(cap->count1, &lnum);
if (ptr != NULL)
{
/* do autowrite if necessary */
if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !P_HID(curbuf))
autowrite(curbuf, FALSE);
setpcmark();
(void)do_ecmd(0, ptr, NULL, NULL, ECMD_LAST,
P_HID(curbuf) ? ECMD_HIDE : 0, curwin);
if (cap->nchar == 'F' && lnum >= 0)
{
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_SOL | BL_FIX);
}
vim_free(ptr);
}
else
clearop(cap->oap);
}
#endif
/*
* <End> command: to end of current line or last line.
*/
static void
nv_end(cap)
cmdarg_T *cap;
{
if (cap->arg || (mod_mask & MOD_MASK_CTRL)) /* CTRL-END = goto last line */
{
cap->arg = TRUE;
nv_goto(cap);
cap->count1 = 1; /* to end of current line */
}
nv_dollar(cap);
}
/*
* Handle the "$" command.
*/
static void
nv_dollar(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = TRUE;
#ifdef FEAT_VIRTUALEDIT
/* In virtual mode when off the edge of a line and an operator
* is pending (whew!) keep the cursor where it is.
* Otherwise, send it to the end of the line. */
if (!virtual_active() || gchar_cursor() != NUL
|| cap->oap->op_type == OP_NOP)
#endif
curwin->w_curswant = MAXCOL; /* so we stay at the end */
if (cursor_down((long)(cap->count1 - 1),
cap->oap->op_type == OP_NOP) == FAIL)
clearopbeep(cap->oap);
#ifdef FEAT_FOLDING
else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* Implementation of '?' and '/' commands.
* If cap->arg is TRUE don't set PC mark.
*/
static void
nv_search(cap)
cmdarg_T *cap;
{
oparg_T *oap = cap->oap;
if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13)
{
/* Translate "g??" to "g?g?" */
cap->cmdchar = 'g';
cap->nchar = '?';
nv_operator(cap);
return;
}
cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0);
if (cap->searchbuf == NULL)
{
clearop(oap);
return;
}
normal_search(cap, cap->cmdchar, cap->searchbuf,
(cap->arg ? 0 : SEARCH_MARK));
}
/*
* Handle "N" and "n" commands.
* cap->arg is SEARCH_REV for "N", 0 for "n".
*/
static void
nv_next(cap)
cmdarg_T *cap;
{
normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg);
}
/*
* Search for "pat" in direction "dir" ('/' or '?', 0 for repeat).
* Uses only cap->count1 and cap->oap from "cap".
*/
static void
normal_search(cap, dir, pat, opt)
cmdarg_T *cap;
int dir;
char_u *pat;
int opt; /* extra flags for do_search() */
{
int i;
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
cap->oap->use_reg_one = TRUE;
curwin->w_set_curswant = TRUE;
i = do_search(cap->oap, dir, pat, cap->count1,
opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, NULL);
if (i == 0)
clearop(cap->oap);
else
{
if (i == 2)
cap->oap->motion_type = MLINE;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_FOLDING
if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
foldOpenCursor();
#endif
}
/* "/$" will put the cursor after the end of the line, may need to
* correct that here */
check_cursor();
}
/*
* Character search commands.
* cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for
* ',' and FALSE for ';'.
* cap->nchar is NUL for ',' and ';' (repeat the search)
*/
static void
nv_csearch(cap)
cmdarg_T *cap;
{
int t_cmd;
if (cap->cmdchar == 't' || cap->cmdchar == 'T')
t_cmd = TRUE;
else
t_cmd = FALSE;
cap->oap->motion_type = MCHAR;
if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL)
clearopbeep(cap->oap);
else
{
curwin->w_set_curswant = TRUE;
#ifdef FEAT_VIRTUALEDIT
/* Include a Tab for "tx" and for "dfx". */
if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD
&& (t_cmd || cap->oap->op_type != OP_NOP))
{
colnr_T scol, ecol;
getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
curwin->w_cursor.coladd = ecol - scol;
}
else
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_VISUAL
adjust_for_sel(cap);
#endif
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* "[" and "]" commands.
* cap->arg is BACKWARD for "[" and FORWARD for "]".
*/
static void
nv_brackets(cap)
cmdarg_T *cap;
{
pos_T new_pos = INIT_POS_T(0, 0, 0);
pos_T prev_pos;
pos_T *pos = NULL; /* init for GCC */
pos_T old_pos; /* cursor position before command */
int flag;
long n;
int findc;
int c;
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
old_pos = curwin->w_cursor;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0; /* TODO: don't do this for an error. */
#endif
#ifdef FEAT_SEARCHPATH
/*
* "[f" or "]f" : Edit file under the cursor (same as "gf")
*/
if (cap->nchar == 'f')
nv_gotofile(cap);
else
#endif
#ifdef FEAT_FIND_ID
/*
* Find the occurrence(s) of the identifier or define under cursor
* in current and included files or jump to the first occurrence.
*
* search list jump
* fwd bwd fwd bwd fwd bwd
* identifier "]i" "[i" "]I" "[I" "]^I" "[^I"
* define "]d" "[d" "]D" "[D" "]^D" "[^D"
*/
if (vim_strchr((char_u *)
#ifdef EBCDIC
"iI\005dD\067",
#else
"iI\011dD\004",
#endif
cap->nchar) != NULL)
{
char_u *ptr;
int len;
if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
clearop(cap->oap);
else
{
find_pattern_in_path(ptr, 0, len, TRUE,
cap->count0 == 0 ? !isupper(cap->nchar) : FALSE,
((cap->nchar & 0xf) == ('d' & 0xf)) ? FIND_DEFINE : FIND_ANY,
cap->count1,
isupper(cap->nchar) ? ACTION_SHOW_ALL :
islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,
cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,
(linenr_T)MAXLNUM);
curwin->w_set_curswant = TRUE;
}
}
else
#endif
/*
* "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
* "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
* "[/", "[*", "]/", "]*": go to Nth comment start/end.
* "[m" or "]m" search for prev/next start of (Java) method.
* "[M" or "]M" search for prev/next end of (Java) method.
*/
if ( (cap->cmdchar == '['
&& vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL)
|| (cap->cmdchar == ']'
&& vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL))
{
if (cap->nchar == '*')
cap->nchar = '/';
prev_pos.lnum = 0;
if (cap->nchar == 'm' || cap->nchar == 'M')
{
if (cap->cmdchar == '[')
findc = '{';
else
findc = '}';
n = 9999;
}
else
{
findc = cap->nchar;
n = cap->count1;
}
for ( ; n > 0; --n)
{
if ((pos = findmatchlimit(cap->oap, findc,
(cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL)
{
if (new_pos.lnum == 0) /* nothing found */
{
if (cap->nchar != 'm' && cap->nchar != 'M')
clearopbeep(cap->oap);
}
else
pos = &new_pos; /* use last one found */
break;
}
prev_pos = new_pos;
curwin->w_cursor = *pos;
new_pos = *pos;
}
curwin->w_cursor = old_pos;
/*
* Handle "[m", "]m", "[M" and "[M". The findmatchlimit() only
* brought us to the match for "[m" and "]M" when inside a method.
* Try finding the '{' or '}' we want to be at.
* Also repeat for the given count.
*/
if (cap->nchar == 'm' || cap->nchar == 'M')
{
/* norm is TRUE for "]M" and "[m" */
int norm = ((findc == '{') == (cap->nchar == 'm'));
n = cap->count1;
/* found a match: we were inside a method */
if (prev_pos.lnum != 0)
{
pos = &prev_pos;
curwin->w_cursor = prev_pos;
if (norm)
--n;
}
else
pos = NULL;
while (n > 0)
{
for (;;)
{
if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0)
{
/* if not found anything, that's an error */
if (pos == NULL)
clearopbeep(cap->oap);
n = 0;
break;
}
c = gchar_cursor();
if (c == '{' || c == '}')
{
/* Must have found end/start of class: use it.
* Or found the place to be at. */
if ((c == findc && norm) || (n == 1 && !norm))
{
new_pos = curwin->w_cursor;
pos = &new_pos;
n = 0;
}
/* if no match found at all, we started outside of the
* class and we're inside now. Just go on. */
else if (new_pos.lnum == 0)
{
new_pos = curwin->w_cursor;
pos = &new_pos;
}
/* found start/end of other method: go to match */
else if ((pos = findmatchlimit(cap->oap, findc,
(cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD,
0)) == NULL)
n = 0;
else
curwin->w_cursor = *pos;
break;
}
}
--n;
}
curwin->w_cursor = old_pos;
if (pos == NULL && new_pos.lnum != 0)
clearopbeep(cap->oap);
}
if (pos != NULL)
{
setpcmark();
curwin->w_cursor = *pos;
curwin->w_set_curswant = TRUE;
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_BLOCK) && KeyTyped
&& cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* "[[", "[]", "]]" and "][": move to start or end of function
*/
else if (cap->nchar == '[' || cap->nchar == ']')
{
if (cap->nchar == cap->cmdchar) /* "]]" or "[[" */
flag = '{';
else
flag = '}'; /* "][" or "[]" */
curwin->w_set_curswant = TRUE;
/*
* Imitate strange Vi behaviour: When using "]]" with an operator
* we also stop at '}'.
*/
if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,
(cap->oap->op_type != OP_NOP
&& cap->arg == FORWARD && flag == '{')))
clearopbeep(cap->oap);
else
{
if (cap->oap->op_type == OP_NOP)
beginline(BL_WHITE | BL_FIX);
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* "[p", "[P", "]P" and "]p": put with indent adjustment
*/
else if (cap->nchar == 'p' || cap->nchar == 'P')
{
if (!checkclearop(cap->oap))
{
prep_redo_cmd(cap);
do_put(cap->oap->regname,
(cap->cmdchar == ']' && cap->nchar == 'p') ? FORWARD : BACKWARD,
cap->count1, PUT_FIXINDENT);
}
}
/*
* "['", "[`", "]'" and "]`": jump to next mark
*/
else if (cap->nchar == '\'' || cap->nchar == '`')
{
pos = &curwin->w_cursor;
for (n = cap->count1; n > 0; --n)
{
prev_pos = *pos;
pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD,
cap->nchar == '\'');
if (pos == NULL)
break;
}
if (pos == NULL)
pos = &prev_pos;
nv_cursormark(cap, cap->nchar == '\'', pos);
}
#ifdef FEAT_MOUSE
/*
* [ or ] followed by a middle mouse click: put selected text with
* indent adjustment. Any other button just does as usual.
*/
else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE)
{
(void)do_mouse(cap->oap, cap->nchar,
(cap->cmdchar == ']') ? FORWARD : BACKWARD,
cap->count1, PUT_FIXINDENT);
}
#endif /* FEAT_MOUSE */
#ifdef FEAT_FOLDING
/*
* "[z" and "]z": move to start or end of open fold.
*/
else if (cap->nchar == 'z')
{
if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD,
cap->count1) == FAIL)
clearopbeep(cap->oap);
}
#endif
#ifdef FEAT_DIFF
/*
* "[c" and "]c": move to next or previous diff-change.
*/
else if (cap->nchar == 'c')
{
if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,
cap->count1) == FAIL)
clearopbeep(cap->oap);
}
#endif
#ifdef FEAT_SPELL
/*
* "[s", "[S", "]s" and "]S": move to next spell error.
*/
else if (cap->nchar == 's' || cap->nchar == 'S')
{
setpcmark();
for (n = 0; n < cap->count1; ++n)
if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,
cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0)
{
clearopbeep(cap->oap);
break;
}
# ifdef FEAT_FOLDING
if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
foldOpenCursor();
# endif
}
#endif
/* Not a valid cap->nchar. */
else
clearopbeep(cap->oap);
}
/*
* Handle Normal mode "%" command.
*/
static void
nv_percent(cap)
cmdarg_T *cap;
{
pos_T *pos;
#if defined(FEAT_FOLDING)
linenr_T lnum = curwin->w_cursor.lnum;
#endif
cap->oap->inclusive = TRUE;
if (cap->count0) /* {cnt}% : goto {cnt} percentage in file */
{
if (cap->count0 > 100)
clearopbeep(cap->oap);
else
{
cap->oap->motion_type = MLINE;
setpcmark();
/* Round up, so CTRL-G will give same value. Watch out for a
* large line count, the line number must not go negative! */
if (curbuf->b_ml.ml_line_count > 1000000)
curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L)
/ 100L * cap->count0;
else
curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count *
cap->count0 + 99L) / 100L;
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
beginline(BL_SOL | BL_FIX);
}
}
else /* "%" : go to matching paren */
{
cap->oap->motion_type = MCHAR;
cap->oap->use_reg_one = TRUE;
if ((pos = findmatch(cap->oap, NUL)) == NULL)
clearopbeep(cap->oap);
else
{
setpcmark();
curwin->w_cursor = *pos;
curwin->w_set_curswant = TRUE;
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_VISUAL
adjust_for_sel(cap);
#endif
}
}
#ifdef FEAT_FOLDING
if (cap->oap->op_type == OP_NOP
&& lnum != curwin->w_cursor.lnum
&& (fdo_flags & FDO_PERCENT)
&& KeyTyped)
foldOpenCursor();
#endif
}
/*
* Handle "(" and ")" commands.
* cap->arg is BACKWARD for "(" and FORWARD for ")".
*/
static void
nv_brace(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->use_reg_one = TRUE;
/* The motion used to be inclusive for "(", but that is not what Vi does. */
cap->oap->inclusive = FALSE;
curwin->w_set_curswant = TRUE;
if (findsent(cap->arg, cap->count1) == FAIL)
clearopbeep(cap->oap);
else
{
/* Don't leave the cursor on the NUL past end of line. */
adjust_cursor(cap->oap);
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* "m" command: Mark a position.
*/
static void
nv_mark(cap)
cmdarg_T *cap;
{
if (!checkclearop(cap->oap))
{
if (setmark(cap->nchar) == FAIL)
clearopbeep(cap->oap);
}
}
/*
* "{" and "}" commands.
* cmd->arg is BACKWARD for "{" and FORWARD for "}".
*/
static void
nv_findpar(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
cap->oap->use_reg_one = TRUE;
curwin->w_set_curswant = TRUE;
if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE))
clearopbeep(cap->oap);
else
{
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* "u" command: Undo or make lower case.
*/
static void
nv_undo(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type == OP_LOWER
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
)
{
/* translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" */
cap->cmdchar = 'g';
cap->nchar = 'u';
nv_operator(cap);
}
else
nv_kundo(cap);
}
/*
* <Undo> command.
*/
static void
nv_kundo(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
{
u_undo((int)cap->count1);
curwin->w_set_curswant = TRUE;
}
}
/*
* Handle the "r" command.
*/
static void
nv_replace(cap)
cmdarg_T *cap;
{
char_u *ptr;
int had_ctrl_v;
long n;
if (checkclearop(cap->oap))
return;
/* get another character */
if (cap->nchar == Ctrl_V)
{
had_ctrl_v = Ctrl_V;
cap->nchar = get_literal();
/* Don't redo a multibyte character with CTRL-V. */
if (cap->nchar > DEL)
had_ctrl_v = NUL;
}
else
had_ctrl_v = NUL;
/* Abort if the character is a special key. */
if (IS_SPECIAL(cap->nchar))
{
clearopbeep(cap->oap);
return;
}
#ifdef FEAT_VISUAL
/* Visual mode "r" */
if (VIsual_active)
{
if (got_int)
reset_VIsual();
nv_operator(cap);
return;
}
#endif
#ifdef FEAT_VIRTUALEDIT
/* Break tabs, etc. */
if (virtual_active())
{
if (u_save_cursor() == FAIL)
return;
if (gchar_cursor() == NUL)
{
/* Add extra space and put the cursor on the first one. */
coladvance_force((colnr_T)(getviscol() + cap->count1));
curwin->w_cursor.col -= cap->count1;
}
else if (gchar_cursor() == TAB)
coladvance_force(getviscol());
}
#endif
/* Abort if not enough characters to replace. */
ptr = ml_get_cursor();
if (STRLEN(ptr) < (unsigned)cap->count1
#ifdef FEAT_MBYTE
|| (has_mbyte && mb_charlen(ptr) < cap->count1)
#endif
)
{
clearopbeep(cap->oap);
return;
}
/*
* Replacing with a TAB is done by edit() when it is complicated because
* 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB.
* Other characters are done below to avoid problems with things like
* CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).
*/
if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta))
{
stuffnumReadbuff(cap->count1);
stuffcharReadbuff('R');
stuffcharReadbuff('\t');
stuffcharReadbuff(ESC);
return;
}
/* save line for undo */
if (u_save_cursor() == FAIL)
return;
if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n'))
{
/*
* Replace character(s) by a single newline.
* Strange vi behaviour: Only one newline is inserted.
* Delete the characters here.
* Insert the newline with an insert command, takes care of
* autoindent. The insert command depends on being on the last
* character of a line or not.
*/
#ifdef FEAT_MBYTE
(void)del_chars(cap->count1, FALSE); /* delete the characters */
#else
(void)del_bytes(cap->count1, FALSE, FALSE); /* delete the characters */
#endif
stuffcharReadbuff('\r');
stuffcharReadbuff(ESC);
/* Give 'r' to edit(), to get the redo command right. */
invoke_edit(cap, TRUE, 'r', FALSE);
}
else
{
prep_redo(cap->oap->regname, cap->count1,
NUL, 'r', NUL, had_ctrl_v, cap->nchar);
curbuf->b_op_start = curwin->w_cursor;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int old_State = State;
if (cap->ncharC1 != 0)
AppendCharToRedobuff(cap->ncharC1);
if (cap->ncharC2 != 0)
AppendCharToRedobuff(cap->ncharC2);
/* This is slow, but it handles replacing a single-byte with a
* multi-byte and the other way around. Also handles adding
* composing characters for utf-8. */
for (n = cap->count1; n > 0; --n)
{
State = REPLACE;
if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
{
int c = ins_copychar(curwin->w_cursor.lnum
+ (cap->nchar == Ctrl_Y ? -1 : 1));
if (c != NUL)
ins_char(c);
else
/* will be decremented further down */
++curwin->w_cursor.col;
}
else
ins_char(cap->nchar);
State = old_State;
if (cap->ncharC1 != 0)
ins_char(cap->ncharC1);
if (cap->ncharC2 != 0)
ins_char(cap->ncharC2);
}
}
else
#endif
{
/*
* Replace the characters within one line.
*/
for (n = cap->count1; n > 0; --n)
{
/*
* Get ptr again, because u_save and/or showmatch() will have
* released the line. At the same time we let know that the
* line will be changed.
*/
ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);
if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
{
int c = ins_copychar(curwin->w_cursor.lnum
+ (cap->nchar == Ctrl_Y ? -1 : 1));
if (c != NUL)
ptr[curwin->w_cursor.col] = c;
}
else
ptr[curwin->w_cursor.col] = cap->nchar;
if (p_sm && msg_silent == 0)
showmatch(cap->nchar);
++curwin->w_cursor.col;
}
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active())
{
colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1);
netbeans_removed(curbuf, curwin->w_cursor.lnum, start,
(long)cap->count1);
netbeans_inserted(curbuf, curwin->w_cursor.lnum, start,
&ptr[start], (int)cap->count1);
}
#endif
/* mark the buffer as changed and prepare for displaying */
changed_bytes(curwin->w_cursor.lnum,
(colnr_T)(curwin->w_cursor.col - cap->count1));
}
--curwin->w_cursor.col; /* cursor on the last replaced char */
#ifdef FEAT_MBYTE
/* if the character on the left of the current cursor is a multi-byte
* character, move two characters left */
if (has_mbyte)
mb_adjust_cursor();
#endif
curbuf->b_op_end = curwin->w_cursor;
curwin->w_set_curswant = TRUE;
set_last_insert(cap->nchar);
}
}
#ifdef FEAT_VISUAL
/*
* 'o': Exchange start and end of Visual area.
* 'O': same, but in block mode exchange left and right corners.
*/
static void
v_swap_corners(cmdchar)
int cmdchar;
{
pos_T old_cursor;
colnr_T left, right;
if (cmdchar == 'O' && VIsual_mode == Ctrl_V)
{
old_cursor = curwin->w_cursor;
getvcols(curwin, &old_cursor, &VIsual, &left, &right);
curwin->w_cursor.lnum = VIsual.lnum;
coladvance(left);
VIsual = curwin->w_cursor;
curwin->w_cursor.lnum = old_cursor.lnum;
curwin->w_curswant = right;
/* 'selection "exclusive" and cursor at right-bottom corner: move it
* right one column */
if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e')
++curwin->w_curswant;
coladvance(curwin->w_curswant);
if (curwin->w_cursor.col == old_cursor.col
#ifdef FEAT_VIRTUALEDIT
&& (!virtual_active()
|| curwin->w_cursor.coladd == old_cursor.coladd)
#endif
)
{
curwin->w_cursor.lnum = VIsual.lnum;
if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e')
++right;
coladvance(right);
VIsual = curwin->w_cursor;
curwin->w_cursor.lnum = old_cursor.lnum;
coladvance(left);
curwin->w_curswant = left;
}
}
else
{
old_cursor = curwin->w_cursor;
curwin->w_cursor = VIsual;
VIsual = old_cursor;
curwin->w_set_curswant = TRUE;
}
}
#endif /* FEAT_VISUAL */
/*
* "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE).
*/
static void
nv_Replace(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active) /* "R" is replace lines */
{
cap->cmdchar = 'c';
cap->nchar = NUL;
VIsual_mode = 'V';
nv_operator(cap);
}
else
#endif
if (!checkclearopq(cap->oap))
{
if (!curbuf->b_p_ma)
EMSG(_(e_modifiable));
else
{
#ifdef FEAT_VIRTUALEDIT
if (virtual_active())
coladvance(getviscol());
#endif
invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE);
}
}
}
#ifdef FEAT_VREPLACE
/*
* "gr".
*/
static void
nv_vreplace(cap)
cmdarg_T *cap;
{
# ifdef FEAT_VISUAL
if (VIsual_active)
{
cap->cmdchar = 'r';
cap->nchar = cap->extra_char;
nv_replace(cap); /* Do same as "r" in Visual mode for now */
}
else
# endif
if (!checkclearopq(cap->oap))
{
if (!curbuf->b_p_ma)
EMSG(_(e_modifiable));
else
{
if (cap->extra_char == Ctrl_V) /* get another character */
cap->extra_char = get_literal();
stuffcharReadbuff(cap->extra_char);
stuffcharReadbuff(ESC);
# ifdef FEAT_VIRTUALEDIT
if (virtual_active())
coladvance(getviscol());
# endif
invoke_edit(cap, TRUE, 'v', FALSE);
}
}
}
#endif
/*
* Swap case for "~" command, when it does not work like an operator.
*/
static void
n_swapchar(cap)
cmdarg_T *cap;
{
long n;
pos_T startpos;
int did_change = 0;
#ifdef FEAT_NETBEANS_INTG
pos_T pos;
char_u *ptr;
int count;
#endif
if (checkclearopq(cap->oap))
return;
if (lineempty(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL)
{
clearopbeep(cap->oap);
return;
}
prep_redo_cmd(cap);
if (u_save_cursor() == FAIL)
return;
startpos = curwin->w_cursor;
#ifdef FEAT_NETBEANS_INTG
pos = startpos;
#endif
for (n = cap->count1; n > 0; --n)
{
did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor);
inc_cursor();
if (gchar_cursor() == NUL)
{
if (vim_strchr(p_ww, '~') != NULL
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active())
{
if (did_change)
{
ptr = ml_get(pos.lnum);
count = (int)STRLEN(ptr) - pos.col;
netbeans_removed(curbuf, pos.lnum, pos.col,
(long)count);
netbeans_inserted(curbuf, pos.lnum, pos.col,
&ptr[pos.col], count);
}
pos.col = 0;
pos.lnum++;
}
#endif
++curwin->w_cursor.lnum;
curwin->w_cursor.col = 0;
if (n > 1)
{
if (u_savesub(curwin->w_cursor.lnum) == FAIL)
break;
u_clearline();
}
}
else
break;
}
}
#ifdef FEAT_NETBEANS_INTG
if (did_change && netbeans_active())
{
ptr = ml_get(pos.lnum);
count = curwin->w_cursor.col - pos.col;
netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count);
}
#endif
check_cursor();
curwin->w_set_curswant = TRUE;
if (did_change)
{
changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1,
0L);
curbuf->b_op_start = startpos;
curbuf->b_op_end = curwin->w_cursor;
if (curbuf->b_op_end.col > 0)
--curbuf->b_op_end.col;
}
}
/*
* Move cursor to mark.
*/
static void
nv_cursormark(cap, flag, pos)
cmdarg_T *cap;
int flag;
pos_T *pos;
{
if (check_mark(pos) == FAIL)
clearop(cap->oap);
else
{
if (cap->cmdchar == '\''
|| cap->cmdchar == '`'
|| cap->cmdchar == '['
|| cap->cmdchar == ']')
setpcmark();
curwin->w_cursor = *pos;
if (flag)
beginline(BL_WHITE | BL_FIX);
else
check_cursor();
}
cap->oap->motion_type = flag ? MLINE : MCHAR;
if (cap->cmdchar == '`')
cap->oap->use_reg_one = TRUE;
cap->oap->inclusive = FALSE; /* ignored if not MCHAR */
curwin->w_set_curswant = TRUE;
}
#ifdef FEAT_VISUAL
/*
* Handle commands that are operators in Visual mode.
*/
static void
v_visop(cap)
cmdarg_T *cap;
{
static char_u trans[] = "YyDdCcxdXdAAIIrr";
/* Uppercase means linewise, except in block mode, then "D" deletes till
* the end of the line, and "C" replaces til EOL */
if (isupper(cap->cmdchar))
{
if (VIsual_mode != Ctrl_V)
VIsual_mode = 'V';
else if (cap->cmdchar == 'C' || cap->cmdchar == 'D')
curwin->w_curswant = MAXCOL;
}
cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1);
nv_operator(cap);
}
#endif
/*
* "s" and "S" commands.
*/
static void
nv_subst(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active) /* "vs" and "vS" are the same as "vc" */
{
if (cap->cmdchar == 'S')
VIsual_mode = 'V';
cap->cmdchar = 'c';
nv_operator(cap);
}
else
#endif
nv_optrans(cap);
}
/*
* Abbreviated commands.
*/
static void
nv_abbrev(cap)
cmdarg_T *cap;
{
if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL)
cap->cmdchar = 'x'; /* DEL key behaves like 'x' */
#ifdef FEAT_VISUAL
/* in Visual mode these commands are operators */
if (VIsual_active)
v_visop(cap);
else
#endif
nv_optrans(cap);
}
/*
* Translate a command into another command.
*/
static void
nv_optrans(cap)
cmdarg_T *cap;
{
static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh",
(char_u *)"d$", (char_u *)"c$",
(char_u *)"cl", (char_u *)"cc",
(char_u *)"yy", (char_u *)":s\r"};
static char_u *str = (char_u *)"xXDCsSY&";
if (!checkclearopq(cap->oap))
{
/* In Vi "2D" doesn't delete the next line. Can't translate it
* either, because "2." should also not use the count. */
if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL)
{
cap->oap->start = curwin->w_cursor;
cap->oap->op_type = OP_DELETE;
#ifdef FEAT_EVAL
set_op_var(OP_DELETE);
#endif
cap->count1 = 1;
nv_dollar(cap);
finish_op = TRUE;
ResetRedobuff();
AppendCharToRedobuff('D');
}
else
{
if (cap->count0)
stuffnumReadbuff(cap->count0);
stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]);
}
}
cap->opcount = 0;
}
/*
* "'" and "`" commands. Also for "g'" and "g`".
* cap->arg is TRUE for "'" and "g'".
*/
static void
nv_gomark(cap)
cmdarg_T *cap;
{
pos_T *pos;
int c;
#ifdef FEAT_FOLDING
linenr_T lnum = curwin->w_cursor.lnum;
int old_KeyTyped = KeyTyped; /* getting file may reset it */
#endif
if (cap->cmdchar == 'g')
c = cap->extra_char;
else
c = cap->nchar;
pos = getmark(c, (cap->oap->op_type == OP_NOP));
if (pos == (pos_T *)-1) /* jumped to other file */
{
if (cap->arg)
{
check_cursor_lnum();
beginline(BL_WHITE | BL_FIX);
}
else
check_cursor();
}
else
nv_cursormark(cap, cap->arg, pos);
#ifdef FEAT_VIRTUALEDIT
/* May need to clear the coladd that a mark includes. */
if (!virtual_active())
curwin->w_cursor.coladd = 0;
#endif
#ifdef FEAT_FOLDING
if (cap->oap->op_type == OP_NOP
&& (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum)
&& (fdo_flags & FDO_MARK)
&& old_KeyTyped)
foldOpenCursor();
#endif
}
/*
* Handle CTRL-O, CTRL-I, "g;" and "g," commands.
*/
static void
nv_pcmark(cap)
cmdarg_T *cap;
{
#ifdef FEAT_JUMPLIST
pos_T *pos;
# ifdef FEAT_FOLDING
linenr_T lnum = curwin->w_cursor.lnum;
int old_KeyTyped = KeyTyped; /* getting file may reset it */
# endif
if (!checkclearopq(cap->oap))
{
if (cap->cmdchar == 'g')
pos = movechangelist((int)cap->count1);
else
pos = movemark((int)cap->count1);
if (pos == (pos_T *)-1) /* jump to other file */
{
curwin->w_set_curswant = TRUE;
check_cursor();
}
else if (pos != NULL) /* can jump */
nv_cursormark(cap, FALSE, pos);
else if (cap->cmdchar == 'g')
{
if (curbuf->b_changelistlen == 0)
EMSG(_("E664: changelist is empty"));
else if (cap->count1 < 0)
EMSG(_("E662: At start of changelist"));
else
EMSG(_("E663: At end of changelist"));
}
else
clearopbeep(cap->oap);
# ifdef FEAT_FOLDING
if (cap->oap->op_type == OP_NOP
&& (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum)
&& (fdo_flags & FDO_MARK)
&& old_KeyTyped)
foldOpenCursor();
# endif
}
#else
clearopbeep(cap->oap);
#endif
}
/*
* Handle '"' command.
*/
static void
nv_regname(cap)
cmdarg_T *cap;
{
if (checkclearop(cap->oap))
return;
#ifdef FEAT_EVAL
if (cap->nchar == '=')
cap->nchar = get_expr_register();
#endif
if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE))
{
cap->oap->regname = cap->nchar;
cap->opcount = cap->count0; /* remember count before '"' */
#ifdef FEAT_EVAL
set_reg_var(cap->oap->regname);
#endif
}
else
clearopbeep(cap->oap);
}
#ifdef FEAT_VISUAL
/*
* Handle "v", "V" and "CTRL-V" commands.
* Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg
* is TRUE.
* Handle CTRL-Q just like CTRL-V.
*/
static void
nv_visual(cap)
cmdarg_T *cap;
{
if (cap->cmdchar == Ctrl_Q)
cap->cmdchar = Ctrl_V;
/* 'v', 'V' and CTRL-V can be used while an operator is pending to make it
* characterwise, linewise, or blockwise. */
if (cap->oap->op_type != OP_NOP)
{
cap->oap->motion_force = cap->cmdchar;
finish_op = FALSE; /* operator doesn't finish now but later */
return;
}
VIsual_select = cap->arg;
if (VIsual_active) /* change Visual mode */
{
if (VIsual_mode == cap->cmdchar) /* stop visual mode */
end_visual_mode();
else /* toggle char/block mode */
{ /* or char/line mode */
VIsual_mode = cap->cmdchar;
showmode();
}
redraw_curbuf_later(INVERTED); /* update the inversion */
}
else /* start Visual mode */
{
check_visual_highlight();
if (cap->count0 > 0 && resel_VIsual_mode != NUL)
{
/* use previously selected part */
VIsual = curwin->w_cursor;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
if (!cap->arg)
/* start Select mode when 'selectmode' contains "cmd" */
may_start_select('c');
#ifdef FEAT_MOUSE
setmouse();
#endif
if (p_smd && msg_silent == 0)
redraw_cmdline = TRUE; /* show visual mode later */
/*
* For V and ^V, we multiply the number of lines even if there
* was only one -- webb
*/
if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1)
{
curwin->w_cursor.lnum +=
resel_VIsual_line_count * cap->count0 - 1;
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
}
VIsual_mode = resel_VIsual_mode;
if (VIsual_mode == 'v')
{
if (resel_VIsual_line_count <= 1)
{
validate_virtcol();
curwin->w_curswant = curwin->w_virtcol
+ resel_VIsual_vcol * cap->count0 - 1;
}
else
curwin->w_curswant = resel_VIsual_vcol;
coladvance(curwin->w_curswant);
}
if (resel_VIsual_vcol == MAXCOL)
{
curwin->w_curswant = MAXCOL;
coladvance((colnr_T)MAXCOL);
}
else if (VIsual_mode == Ctrl_V)
{
validate_virtcol();
curwin->w_curswant = curwin->w_virtcol
+ resel_VIsual_vcol * cap->count0 - 1;
coladvance(curwin->w_curswant);
}
else
curwin->w_set_curswant = TRUE;
redraw_curbuf_later(INVERTED); /* show the inversion */
}
else
{
if (!cap->arg)
/* start Select mode when 'selectmode' contains "cmd" */
may_start_select('c');
n_start_visual_mode(cap->cmdchar);
if (VIsual_mode != 'V' && *p_sel == 'e')
++cap->count1; /* include one more char */
if (cap->count0 > 0 && --cap->count1 > 0)
{
/* With a count select that many characters or lines. */
if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V)
nv_right(cap);
else if (VIsual_mode == 'V')
nv_down(cap);
}
}
}
}
/*
* Start selection for Shift-movement keys.
*/
void
start_selection()
{
/* if 'selectmode' contains "key", start Select mode */
may_start_select('k');
n_start_visual_mode('v');
}
/*
* Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu.
*/
void
may_start_select(c)
int c;
{
VIsual_select = (stuff_empty() && typebuf_typed()
&& (vim_strchr(p_slm, c) != NULL));
}
/*
* Start Visual mode "c".
* Should set VIsual_select before calling this.
*/
static void
n_start_visual_mode(c)
int c;
{
#ifdef FEAT_CONCEAL
/* Check for redraw before changing the state. */
conceal_check_cursur_line();
#endif
VIsual_mode = c;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
#ifdef FEAT_VIRTUALEDIT
/* Corner case: the 0 position in a tab may change when going into
* virtualedit. Recalculate curwin->w_cursor to avoid bad hilighting.
*/
if (c == Ctrl_V && (ve_flags & VE_BLOCK) && gchar_cursor() == TAB)
coladvance(curwin->w_virtcol);
#endif
VIsual = curwin->w_cursor;
#ifdef FEAT_FOLDING
foldAdjustVisual();
#endif
#ifdef FEAT_MOUSE
setmouse();
#endif
#ifdef FEAT_CONCEAL
/* Check for redraw after changing the state. */
conceal_check_cursur_line();
#endif
if (p_smd && msg_silent == 0)
redraw_cmdline = TRUE; /* show visual mode later */
#ifdef FEAT_CLIPBOARD
/* Make sure the clipboard gets updated. Needed because start and
* end may still be the same, and the selection needs to be owned */
clip_star.vmode = NUL;
#endif
/* Only need to redraw this line, unless still need to redraw an old
* Visual area (when 'lazyredraw' is set). */
if (curwin->w_redr_type < INVERTED)
{
curwin->w_old_cursor_lnum = curwin->w_cursor.lnum;
curwin->w_old_visual_lnum = curwin->w_cursor.lnum;
}
}
#endif /* FEAT_VISUAL */
/*
* CTRL-W: Window commands
*/
static void
nv_window(cap)
cmdarg_T *cap;
{
#ifdef FEAT_WINDOWS
if (!checkclearop(cap->oap))
do_window(cap->nchar, cap->count0, NUL); /* everything is in window.c */
#else
(void)checkclearop(cap->oap);
#endif
}
/*
* CTRL-Z: Suspend
*/
static void
nv_suspend(cap)
cmdarg_T *cap;
{
clearop(cap->oap);
#ifdef FEAT_VISUAL
if (VIsual_active)
end_visual_mode(); /* stop Visual mode */
#endif
do_cmdline_cmd((char_u *)"st");
}
/*
* Commands starting with "g".
*/
static void
nv_g_cmd(cap)
cmdarg_T *cap;
{
oparg_T *oap = cap->oap;
#ifdef FEAT_VISUAL
pos_T tpos;
#endif
int i;
int flag = FALSE;
switch (cap->nchar)
{
#ifdef MEM_PROFILE
/*
* "g^A": dump log of used memory.
*/
case Ctrl_A:
vim_mem_profile_dump();
break;
#endif
#ifdef FEAT_VREPLACE
/*
* "gR": Enter virtual replace mode.
*/
case 'R':
cap->arg = TRUE;
nv_Replace(cap);
break;
case 'r':
nv_vreplace(cap);
break;
#endif
case '&':
do_cmdline_cmd((char_u *)"%s//~/&");
break;
#ifdef FEAT_VISUAL
/*
* "gv": Reselect the previous Visual area. If Visual already active,
* exchange previous and current Visual area.
*/
case 'v':
if (checkclearop(oap))
break;
if ( curbuf->b_visual.vi_start.lnum == 0
|| curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count
|| curbuf->b_visual.vi_end.lnum == 0)
beep_flush();
else
{
/* set w_cursor to the start of the Visual area, tpos to the end */
if (VIsual_active)
{
i = VIsual_mode;
VIsual_mode = curbuf->b_visual.vi_mode;
curbuf->b_visual.vi_mode = i;
# ifdef FEAT_EVAL
curbuf->b_visual_mode_eval = i;
# endif
i = curwin->w_curswant;
curwin->w_curswant = curbuf->b_visual.vi_curswant;
curbuf->b_visual.vi_curswant = i;
tpos = curbuf->b_visual.vi_end;
curbuf->b_visual.vi_end = curwin->w_cursor;
curwin->w_cursor = curbuf->b_visual.vi_start;
curbuf->b_visual.vi_start = VIsual;
}
else
{
VIsual_mode = curbuf->b_visual.vi_mode;
curwin->w_curswant = curbuf->b_visual.vi_curswant;
tpos = curbuf->b_visual.vi_end;
curwin->w_cursor = curbuf->b_visual.vi_start;
}
VIsual_active = TRUE;
VIsual_reselect = TRUE;
/* Set Visual to the start and w_cursor to the end of the Visual
* area. Make sure they are on an existing character. */
check_cursor();
VIsual = curwin->w_cursor;
curwin->w_cursor = tpos;
check_cursor();
update_topline();
/*
* When called from normal "g" command: start Select mode when
* 'selectmode' contains "cmd". When called for K_SELECT, always
* start Select mode.
*/
if (cap->arg)
VIsual_select = TRUE;
else
may_start_select('c');
#ifdef FEAT_MOUSE
setmouse();
#endif
#ifdef FEAT_CLIPBOARD
/* Make sure the clipboard gets updated. Needed because start and
* end are still the same, and the selection needs to be owned */
clip_star.vmode = NUL;
#endif
redraw_curbuf_later(INVERTED);
showmode();
}
break;
/*
* "gV": Don't reselect the previous Visual area after a Select mode
* mapping of menu.
*/
case 'V':
VIsual_reselect = FALSE;
break;
/*
* "gh": start Select mode.
* "gH": start Select line mode.
* "g^H": start Select block mode.
*/
case K_BS:
cap->nchar = Ctrl_H;
/* FALLTHROUGH */
case 'h':
case 'H':
case Ctrl_H:
# ifdef EBCDIC
/* EBCDIC: 'v'-'h' != '^v'-'^h' */
if (cap->nchar == Ctrl_H)
cap->cmdchar = Ctrl_V;
else
# endif
cap->cmdchar = cap->nchar + ('v' - 'h');
cap->arg = TRUE;
nv_visual(cap);
break;
#endif /* FEAT_VISUAL */
/*
* "gj" and "gk" two new funny movement keys -- up and down
* movement based on *screen* line rather than *file* line.
*/
case 'j':
case K_DOWN:
/* with 'nowrap' it works just like the normal "j" command; also when
* in a closed fold */
if (!curwin->w_p_wrap
#ifdef FEAT_FOLDING
|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
#endif
)
{
oap->motion_type = MLINE;
i = cursor_down(cap->count1, oap->op_type == OP_NOP);
}
else
i = nv_screengo(oap, FORWARD, cap->count1);
if (i == FAIL)
clearopbeep(oap);
break;
case 'k':
case K_UP:
/* with 'nowrap' it works just like the normal "k" command; also when
* in a closed fold */
if (!curwin->w_p_wrap
#ifdef FEAT_FOLDING
|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
#endif
)
{
oap->motion_type = MLINE;
i = cursor_up(cap->count1, oap->op_type == OP_NOP);
}
else
i = nv_screengo(oap, BACKWARD, cap->count1);
if (i == FAIL)
clearopbeep(oap);
break;
/*
* "gJ": join two lines without inserting a space.
*/
case 'J':
nv_join(cap);
break;
/*
* "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines.
* "gm": middle of "g0" and "g$".
*/
case '^':
flag = TRUE;
/* FALLTHROUGH */
case '0':
case 'm':
case K_HOME:
case K_KHOME:
oap->motion_type = MCHAR;
oap->inclusive = FALSE;
if (curwin->w_p_wrap
#ifdef FEAT_VERTSPLIT
&& curwin->w_width != 0
#endif
)
{
int width1 = W_WIDTH(curwin) - curwin_col_off();
int width2 = width1 + curwin_col_off2();
validate_virtcol();
i = 0;
if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0)
i = (curwin->w_virtcol - width1) / width2 * width2 + width1;
}
else
i = curwin->w_leftcol;
/* Go to the middle of the screen line. When 'number' or
* 'relativenumber' is on and lines are wrapping the middle can be more
* to the left. */
if (cap->nchar == 'm')
i += (W_WIDTH(curwin) - curwin_col_off()
+ ((curwin->w_p_wrap && i > 0)
? curwin_col_off2() : 0)) / 2;
coladvance((colnr_T)i);
if (flag)
{
do
i = gchar_cursor();
while (vim_iswhite(i) && oneright() == OK);
}
curwin->w_set_curswant = TRUE;
break;
case '_':
/* "g_": to the last non-blank character in the line or <count> lines
* downward. */
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = TRUE;
curwin->w_curswant = MAXCOL;
if (cursor_down((long)(cap->count1 - 1),
cap->oap->op_type == OP_NOP) == FAIL)
clearopbeep(cap->oap);
else
{
char_u *ptr = ml_get_curline();
/* In Visual mode we may end up after the line. */
if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL)
--curwin->w_cursor.col;
/* Decrease the cursor column until it's on a non-blank. */
while (curwin->w_cursor.col > 0
&& vim_iswhite(ptr[curwin->w_cursor.col]))
--curwin->w_cursor.col;
curwin->w_set_curswant = TRUE;
#ifdef FEAT_VISUAL
adjust_for_sel(cap);
#endif
}
break;
case '$':
case K_END:
case K_KEND:
{
int col_off = curwin_col_off();
oap->motion_type = MCHAR;
oap->inclusive = TRUE;
if (curwin->w_p_wrap
#ifdef FEAT_VERTSPLIT
&& curwin->w_width != 0
#endif
)
{
curwin->w_curswant = MAXCOL; /* so we stay at the end */
if (cap->count1 == 1)
{
int width1 = W_WIDTH(curwin) - col_off;
int width2 = width1 + curwin_col_off2();
validate_virtcol();
i = width1 - 1;
if (curwin->w_virtcol >= (colnr_T)width1)
i += ((curwin->w_virtcol - width1) / width2 + 1)
* width2;
coladvance((colnr_T)i);
#if defined(FEAT_LINEBREAK) || defined(FEAT_MBYTE)
if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
{
/*
* Check for landing on a character that got split at
* the end of the line. We do not want to advance to
* the next screen line.
*/
validate_virtcol();
if (curwin->w_virtcol > (colnr_T)i)
--curwin->w_cursor.col;
}
#endif
}
else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL)
clearopbeep(oap);
}
else
{
i = curwin->w_leftcol + W_WIDTH(curwin) - col_off - 1;
coladvance((colnr_T)i);
/* Make sure we stick in this column. */
validate_virtcol();
curwin->w_curswant = curwin->w_virtcol;
curwin->w_set_curswant = FALSE;
}
}
break;
/*
* "g*" and "g#", like "*" and "#" but without using "\<" and "\>"
*/
case '*':
case '#':
#if POUND != '#'
case POUND: /* pound sign (sometimes equal to '#') */
#endif
case Ctrl_RSB: /* :tag or :tselect for current identifier */
case ']': /* :tselect for current identifier */
nv_ident(cap);
break;
/*
* ge and gE: go back to end of word
*/
case 'e':
case 'E':
oap->motion_type = MCHAR;
curwin->w_set_curswant = TRUE;
oap->inclusive = TRUE;
if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL)
clearopbeep(oap);
break;
/*
* "g CTRL-G": display info about cursor position
*/
case Ctrl_G:
cursor_pos_info();
break;
/*
* "gi": start Insert at the last position.
*/
case 'i':
if (curbuf->b_last_insert.lnum != 0)
{
curwin->w_cursor = curbuf->b_last_insert;
check_cursor_lnum();
i = (int)STRLEN(ml_get_curline());
if (curwin->w_cursor.col > (colnr_T)i)
{
#ifdef FEAT_VIRTUALEDIT
if (virtual_active())
curwin->w_cursor.coladd += curwin->w_cursor.col - i;
#endif
curwin->w_cursor.col = i;
}
}
cap->cmdchar = 'i';
nv_edit(cap);
break;
/*
* "gI": Start insert in column 1.
*/
case 'I':
beginline(0);
if (!checkclearopq(oap))
invoke_edit(cap, FALSE, 'g', FALSE);
break;
#ifdef FEAT_SEARCHPATH
/*
* "gf": goto file, edit file under cursor
* "]f" and "[f": can also be used.
*/
case 'f':
case 'F':
nv_gotofile(cap);
break;
#endif
/* "g'm" and "g`m": jump to mark without setting pcmark */
case '\'':
cap->arg = TRUE;
/*FALLTHROUGH*/
case '`':
nv_gomark(cap);
break;
/*
* "gs": Goto sleep.
*/
case 's':
do_sleep(cap->count1 * 1000L);
break;
/*
* "ga": Display the ascii value of the character under the
* cursor. It is displayed in decimal, hex, and octal. -- webb
*/
case 'a':
do_ascii(NULL);
break;
#ifdef FEAT_MBYTE
/*
* "g8": Display the bytes used for the UTF-8 character under the
* cursor. It is displayed in hex.
* "8g8" finds illegal byte sequence.
*/
case '8':
if (cap->count0 == 8)
utf_find_illegal();
else
show_utf8();
break;
#endif
case '<':
show_sb_text();
break;
/*
* "gg": Goto the first line in file. With a count it goes to
* that line number like for "G". -- webb
*/
case 'g':
cap->arg = FALSE;
nv_goto(cap);
break;
/*
* Two-character operators:
* "gq" Format text
* "gw" Format text and keep cursor position
* "g~" Toggle the case of the text.
* "gu" Change text to lower case.
* "gU" Change text to upper case.
* "g?" rot13 encoding
* "g@" call 'operatorfunc'
*/
case 'q':
case 'w':
oap->cursor_start = curwin->w_cursor;
/*FALLTHROUGH*/
case '~':
case 'u':
case 'U':
case '?':
case '@':
nv_operator(cap);
break;
/*
* "gd": Find first occurrence of pattern under the cursor in the
* current function
* "gD": idem, but in the current file.
*/
case 'd':
case 'D':
nv_gd(oap, cap->nchar, (int)cap->count0);
break;
#ifdef FEAT_MOUSE
/*
* g<*Mouse> : <C-*mouse>
*/
case K_MIDDLEMOUSE:
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
case K_LEFTMOUSE:
case K_LEFTDRAG:
case K_LEFTRELEASE:
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:
mod_mask = MOD_MASK_CTRL;
(void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0);
break;
#endif
case K_IGNORE:
break;
/*
* "gP" and "gp": same as "P" and "p" but leave cursor just after new text
*/
case 'p':
case 'P':
nv_put(cap);
break;
#ifdef FEAT_BYTEOFF
/* "go": goto byte count from start of buffer */
case 'o':
goto_byte(cap->count0);
break;
#endif
/* "gQ": improved Ex mode */
case 'Q':
if (text_locked())
{
clearopbeep(cap->oap);
text_locked_msg();
break;
}
if (!checkclearopq(oap))
do_exmode(TRUE);
break;
#ifdef FEAT_JUMPLIST
case ',':
nv_pcmark(cap);
break;
case ';':
cap->count1 = -cap->count1;
nv_pcmark(cap);
break;
#endif
#ifdef FEAT_WINDOWS
case 't':
goto_tabpage((int)cap->count0);
break;
case 'T':
goto_tabpage(-(int)cap->count1);
break;
#endif
case '+':
case '-': /* "g+" and "g-": undo or redo along the timeline */
if (!checkclearopq(oap))
undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1,
FALSE, FALSE, FALSE);
break;
default:
clearopbeep(oap);
break;
}
}
/*
* Handle "o" and "O" commands.
*/
static void
n_opencmd(cap)
cmdarg_T *cap;
{
#ifdef FEAT_CONCEAL
linenr_T oldline = curwin->w_cursor.lnum;
#endif
if (!checkclearopq(cap->oap))
{
#ifdef FEAT_FOLDING
if (cap->cmdchar == 'O')
/* Open above the first line of a folded sequence of lines */
(void)hasFolding(curwin->w_cursor.lnum,
&curwin->w_cursor.lnum, NULL);
else
/* Open below the last line of a folded sequence of lines */
(void)hasFolding(curwin->w_cursor.lnum,
NULL, &curwin->w_cursor.lnum);
#endif
if (u_save((linenr_T)(curwin->w_cursor.lnum -
(cap->cmdchar == 'O' ? 1 : 0)),
(linenr_T)(curwin->w_cursor.lnum +
(cap->cmdchar == 'o' ? 1 : 0))
) == OK
&& open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD,
#ifdef FEAT_COMMENTS
has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM :
#endif
0, 0))
{
#ifdef FEAT_CONCEAL
if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum)
update_single_line(curwin, oldline);
#endif
/* When '#' is in 'cpoptions' ignore the count. */
if (vim_strchr(p_cpo, CPO_HASH) != NULL)
cap->count1 = 1;
invoke_edit(cap, FALSE, cap->cmdchar, TRUE);
}
}
}
/*
* "." command: redo last change.
*/
static void
nv_dot(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
{
/*
* If "restart_edit" 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.
*/
if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL)
clearopbeep(cap->oap);
}
}
/*
* CTRL-R: undo undo
*/
static void
nv_redo(cap)
cmdarg_T *cap;
{
if (!checkclearopq(cap->oap))
{
u_redo((int)cap->count1);
curwin->w_set_curswant = TRUE;
}
}
/*
* Handle "U" command.
*/
static void
nv_Undo(cap)
cmdarg_T *cap;
{
/* In Visual mode and typing "gUU" triggers an operator */
if (cap->oap->op_type == OP_UPPER
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
)
{
/* translate "gUU" to "gUgU" */
cap->cmdchar = 'g';
cap->nchar = 'U';
nv_operator(cap);
}
else if (!checkclearopq(cap->oap))
{
u_undoline();
curwin->w_set_curswant = TRUE;
}
}
/*
* '~' command: If tilde is not an operator and Visual is off: swap case of a
* single character.
*/
static void
nv_tilde(cap)
cmdarg_T *cap;
{
if (!p_to
#ifdef FEAT_VISUAL
&& !VIsual_active
#endif
&& cap->oap->op_type != OP_TILDE)
n_swapchar(cap);
else
nv_operator(cap);
}
/*
* Handle an operator command.
* The actual work is done by do_pending_operator().
*/
static void
nv_operator(cap)
cmdarg_T *cap;
{
int op_type;
op_type = get_op_type(cap->cmdchar, cap->nchar);
if (op_type == cap->oap->op_type) /* double operator works on lines */
nv_lineop(cap);
else if (!checkclearop(cap->oap))
{
cap->oap->start = curwin->w_cursor;
cap->oap->op_type = op_type;
#ifdef FEAT_EVAL
set_op_var(op_type);
#endif
}
}
#ifdef FEAT_EVAL
/*
* Set v:operator to the characters for "optype".
*/
static void
set_op_var(optype)
int optype;
{
char_u opchars[3];
if (optype == OP_NOP)
set_vim_var_string(VV_OP, NULL, 0);
else
{
opchars[0] = get_op_char(optype);
opchars[1] = get_extra_op_char(optype);
opchars[2] = NUL;
set_vim_var_string(VV_OP, opchars, -1);
}
}
#endif
/*
* Handle linewise operator "dd", "yy", etc.
*
* "_" is is a strange motion command that helps make operators more logical.
* It is actually implemented, but not documented in the real Vi. This motion
* command actually refers to "the current line". Commands like "dd" and "yy"
* are really an alternate form of "d_" and "y_". It does accept a count, so
* "d3_" works to delete 3 lines.
*/
static void
nv_lineop(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MLINE;
if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL)
clearopbeep(cap->oap);
else if ( cap->oap->op_type == OP_DELETE
|| cap->oap->op_type == OP_LSHIFT
|| cap->oap->op_type == OP_RSHIFT)
beginline(BL_SOL | BL_FIX);
else if (cap->oap->op_type != OP_YANK) /* 'Y' does not move cursor */
beginline(BL_WHITE | BL_FIX);
}
/*
* <Home> command.
*/
static void
nv_home(cap)
cmdarg_T *cap;
{
/* CTRL-HOME is like "gg" */
if (mod_mask & MOD_MASK_CTRL)
nv_goto(cap);
else
{
cap->count0 = 1;
nv_pipe(cap);
}
ins_at_eol = FALSE; /* Don't move cursor past eol (only necessary in a
one-character line). */
}
/*
* "|" command.
*/
static void
nv_pipe(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
beginline(0);
if (cap->count0 > 0)
{
coladvance((colnr_T)(cap->count0 - 1));
curwin->w_curswant = (colnr_T)(cap->count0 - 1);
}
else
curwin->w_curswant = 0;
/* keep curswant at the column where we wanted to go, not where
* we ended; differs if line is too short */
curwin->w_set_curswant = FALSE;
}
/*
* Handle back-word command "b" and "B".
* cap->arg is 1 for "B"
*/
static void
nv_bck_word(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
curwin->w_set_curswant = TRUE;
if (bck_word(cap->count1, cap->arg, FALSE) == FAIL)
clearopbeep(cap->oap);
#ifdef FEAT_FOLDING
else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* Handle word motion commands "e", "E", "w" and "W".
* cap->arg is TRUE for "E" and "W".
*/
static void
nv_wordcmd(cap)
cmdarg_T *cap;
{
int n;
int word_end;
int flag = FALSE;
pos_T startpos = curwin->w_cursor;
/*
* Set inclusive for the "E" and "e" command.
*/
if (cap->cmdchar == 'e' || cap->cmdchar == 'E')
word_end = TRUE;
else
word_end = FALSE;
cap->oap->inclusive = word_end;
/*
* "cw" and "cW" are a special case.
*/
if (!word_end && cap->oap->op_type == OP_CHANGE)
{
n = gchar_cursor();
if (n != NUL) /* not an empty line */
{
if (vim_iswhite(n))
{
/*
* Reproduce a funny Vi behaviour: "cw" on a blank only
* changes one character, not all blanks until the start of
* the next word. Only do this when the 'w' flag is included
* in 'cpoptions'.
*/
if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL)
{
cap->oap->inclusive = TRUE;
cap->oap->motion_type = MCHAR;
return;
}
}
else
{
/*
* This is a little strange. To match what the real Vi does,
* we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided
* that we are not on a space or a TAB. This seems impolite
* at first, but it's really more what we mean when we say
* 'cw'.
* Another strangeness: When standing on the end of a word
* "ce" will change until the end of the next wordt, but "cw"
* will change only one character! This is done by setting
* flag.
*/
cap->oap->inclusive = TRUE;
word_end = TRUE;
flag = TRUE;
}
}
}
cap->oap->motion_type = MCHAR;
curwin->w_set_curswant = TRUE;
if (word_end)
n = end_word(cap->count1, cap->arg, flag, FALSE);
else
n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP);
/* Don't leave the cursor on the NUL past the end of line. Unless we
* didn't move it forward. */
if (lt(startpos, curwin->w_cursor))
adjust_cursor(cap->oap);
if (n == FAIL && cap->oap->op_type == OP_NOP)
clearopbeep(cap->oap);
else
{
#ifdef FEAT_VISUAL
adjust_for_sel(cap);
#endif
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
}
/*
* Used after a movement command: If the cursor ends up on the NUL after the
* end of the line, may move it back to the last character and make the motion
* inclusive.
*/
static void
adjust_cursor(oap)
oparg_T *oap;
{
/* The cursor cannot remain on the NUL when:
* - the column is > 0
* - not in Visual mode or 'selection' is "o"
* - 'virtualedit' is not "all" and not "onemore".
*/
if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL
#ifdef FEAT_VISUAL
&& (!VIsual_active || *p_sel == 'o')
#endif
#ifdef FEAT_VIRTUALEDIT
&& !virtual_active() && (ve_flags & VE_ONEMORE) == 0
#endif
)
{
--curwin->w_cursor.col;
#ifdef FEAT_MBYTE
/* prevent cursor from moving on the trail byte */
if (has_mbyte)
mb_adjust_cursor();
#endif
oap->inclusive = TRUE;
}
}
/*
* "0" and "^" commands.
* cap->arg is the argument for beginline().
*/
static void
nv_beginline(cap)
cmdarg_T *cap;
{
cap->oap->motion_type = MCHAR;
cap->oap->inclusive = FALSE;
beginline(cap->arg);
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
ins_at_eol = FALSE; /* Don't move cursor past eol (only necessary in a
one-character line). */
}
#ifdef FEAT_VISUAL
/*
* In exclusive Visual mode, may include the last character.
*/
static void
adjust_for_sel(cap)
cmdarg_T *cap;
{
if (VIsual_active && cap->oap->inclusive && *p_sel == 'e'
&& gchar_cursor() != NUL && lt(VIsual, curwin->w_cursor))
{
# ifdef FEAT_MBYTE
if (has_mbyte)
inc_cursor();
else
# endif
++curwin->w_cursor.col;
cap->oap->inclusive = FALSE;
}
}
/*
* Exclude last character at end of Visual area for 'selection' == "exclusive".
* Should check VIsual_mode before calling this.
* Returns TRUE when backed up to the previous line.
*/
static int
unadjust_for_sel()
{
pos_T *pp;
if (*p_sel == 'e' && !equalpos(VIsual, curwin->w_cursor))
{
if (lt(VIsual, curwin->w_cursor))
pp = &curwin->w_cursor;
else
pp = &VIsual;
#ifdef FEAT_VIRTUALEDIT
if (pp->coladd > 0)
--pp->coladd;
else
#endif
if (pp->col > 0)
{
--pp->col;
#ifdef FEAT_MBYTE
mb_adjustpos(curbuf, pp);
#endif
}
else if (pp->lnum > 1)
{
--pp->lnum;
pp->col = (colnr_T)STRLEN(ml_get(pp->lnum));
return TRUE;
}
}
return FALSE;
}
/*
* SELECT key in Normal or Visual mode: end of Select mode mapping.
*/
static void
nv_select(cap)
cmdarg_T *cap;
{
if (VIsual_active)
VIsual_select = TRUE;
else if (VIsual_reselect)
{
cap->nchar = 'v'; /* fake "gv" command */
cap->arg = TRUE;
nv_g_cmd(cap);
}
}
#endif
/*
* "G", "gg", CTRL-END, CTRL-HOME.
* cap->arg is TRUE for "G".
*/
static void
nv_goto(cap)
cmdarg_T *cap;
{
linenr_T lnum;
if (cap->arg)
lnum = curbuf->b_ml.ml_line_count;
else
lnum = 1L;
cap->oap->motion_type = MLINE;
setpcmark();
/* When a count is given, use it instead of the default lnum */
if (cap->count0 != 0)
lnum = cap->count0;
if (lnum < 1L)
lnum = 1L;
else if (lnum > curbuf->b_ml.ml_line_count)
lnum = curbuf->b_ml.ml_line_count;
curwin->w_cursor.lnum = lnum;
beginline(BL_SOL | BL_FIX);
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP)
foldOpenCursor();
#endif
}
/*
* CTRL-\ in Normal mode.
*/
static void
nv_normal(cap)
cmdarg_T *cap;
{
if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G)
{
clearop(cap->oap);
if (restart_edit != 0 && mode_displayed)
clear_cmdline = TRUE; /* unshow mode later */
restart_edit = 0;
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
cmdwin_result = Ctrl_C;
#endif
#ifdef FEAT_VISUAL
if (VIsual_active)
{
end_visual_mode(); /* stop Visual */
redraw_curbuf_later(INVERTED);
}
#endif
/* CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. */
if (cap->nchar == Ctrl_G && p_im)
restart_edit = 'a';
}
else
clearopbeep(cap->oap);
}
/*
* ESC in Normal mode: beep, but don't flush buffers.
* Don't even beep if we are canceling a command.
*/
static void
nv_esc(cap)
cmdarg_T *cap;
{
int no_reason;
no_reason = (cap->oap->op_type == OP_NOP
&& cap->opcount == 0
&& cap->count0 == 0
&& cap->oap->regname == 0
&& !p_im);
if (cap->arg) /* TRUE for CTRL-C */
{
if (restart_edit == 0
#ifdef FEAT_CMDWIN
&& cmdwin_type == 0
#endif
#ifdef FEAT_VISUAL
&& !VIsual_active
#endif
&& no_reason)
MSG(_("Type :quit<Enter> to exit Vim"));
/* Don't reset "restart_edit" when 'insertmode' is set, it won't be
* set again below when halfway a mapping. */
if (!p_im)
restart_edit = 0;
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
{
cmdwin_result = K_IGNORE;
got_int = FALSE; /* don't stop executing autocommands et al. */
return;
}
#endif
}
#ifdef FEAT_VISUAL
if (VIsual_active)
{
end_visual_mode(); /* stop Visual */
check_cursor_col(); /* make sure cursor is not beyond EOL */
curwin->w_set_curswant = TRUE;
redraw_curbuf_later(INVERTED);
}
else
#endif
if (no_reason)
vim_beep();
clearop(cap->oap);
/* A CTRL-C is often used at the start of a menu. When 'insertmode' is
* set return to Insert mode afterwards. */
if (restart_edit == 0 && goto_im()
#ifdef FEAT_EX_EXTRA
&& ex_normal_busy == 0
#endif
)
restart_edit = 'a';
}
/*
* Handle "A", "a", "I", "i" and <Insert> commands.
*/
static void
nv_edit(cap)
cmdarg_T *cap;
{
/* <Insert> is equal to "i" */
if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS)
cap->cmdchar = 'i';
#ifdef FEAT_VISUAL
/* in Visual mode "A" and "I" are an operator */
if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I'))
v_visop(cap);
/* in Visual mode and after an operator "a" and "i" are for text objects */
else
#endif
if ((cap->cmdchar == 'a' || cap->cmdchar == 'i')
&& (cap->oap->op_type != OP_NOP
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
))
{
#ifdef FEAT_TEXTOBJ
nv_object(cap);
#else
clearopbeep(cap->oap);
#endif
}
else if (!curbuf->b_p_ma && !p_im)
{
/* Only give this error when 'insertmode' is off. */
EMSG(_(e_modifiable));
clearop(cap->oap);
}
else if (!checkclearopq(cap->oap))
{
switch (cap->cmdchar)
{
case 'A': /* "A"ppend after the line */
curwin->w_set_curswant = TRUE;
#ifdef FEAT_VIRTUALEDIT
if (ve_flags == VE_ALL)
{
int save_State = State;
/* Pretent Insert mode here to allow the cursor on the
* character past the end of the line */
State = INSERT;
coladvance((colnr_T)MAXCOL);
State = save_State;
}
else
#endif
curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
break;
case 'I': /* "I"nsert before the first non-blank */
if (vim_strchr(p_cpo, CPO_INSEND) == NULL)
beginline(BL_WHITE);
else
beginline(BL_WHITE|BL_FIX);
break;
case 'a': /* "a"ppend is like "i"nsert on the next character. */
#ifdef FEAT_VIRTUALEDIT
/* increment coladd when in virtual space, increment the
* column otherwise, also to append after an unprintable char */
if (virtual_active()
&& (curwin->w_cursor.coladd > 0
|| *ml_get_cursor() == NUL
|| *ml_get_cursor() == TAB))
curwin->w_cursor.coladd++;
else
#endif
if (*ml_get_cursor() != NUL)
inc_cursor();
break;
}
#ifdef FEAT_VIRTUALEDIT
if (curwin->w_cursor.coladd && cap->cmdchar != 'A')
{
int save_State = State;
/* Pretent Insert mode here to allow the cursor on the
* character past the end of the line */
State = INSERT;
coladvance(getviscol());
State = save_State;
}
#endif
invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
}
}
/*
* Invoke edit() and take care of "restart_edit" and the return value.
*/
static void
invoke_edit(cap, repl, cmd, startln)
cmdarg_T *cap;
int repl; /* "r" or "gr" command */
int cmd;
int startln;
{
int restart_edit_save = 0;
/* Complicated: When the user types "a<C-O>a" we don't want to do Insert
* mode recursively. But when doing "a<C-O>." or "a<C-O>rx" we do allow
* it. */
if (repl || !stuff_empty())
restart_edit_save = restart_edit;
else
restart_edit_save = 0;
/* Always reset "restart_edit", this is not a restarted edit. */
restart_edit = 0;
if (edit(cmd, startln, cap->count1))
cap->retval |= CA_COMMAND_BUSY;
if (restart_edit == 0)
restart_edit = restart_edit_save;
}
#ifdef FEAT_TEXTOBJ
/*
* "a" or "i" while an operator is pending or in Visual mode: object motion.
*/
static void
nv_object(cap)
cmdarg_T *cap;
{
int flag;
int include;
char_u *mps_save;
if (cap->cmdchar == 'i')
include = FALSE; /* "ix" = inner object: exclude white space */
else
include = TRUE; /* "ax" = an object: include white space */
/* Make sure (), [], {} and <> are in 'matchpairs' */
mps_save = curbuf->b_p_mps;
curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>";
switch (cap->nchar)
{
case 'w': /* "aw" = a word */
flag = current_word(cap->oap, cap->count1, include, FALSE);
break;
case 'W': /* "aW" = a WORD */
flag = current_word(cap->oap, cap->count1, include, TRUE);
break;
case 'b': /* "ab" = a braces block */
case '(':
case ')':
flag = current_block(cap->oap, cap->count1, include, '(', ')');
break;
case 'B': /* "aB" = a Brackets block */
case '{':
case '}':
flag = current_block(cap->oap, cap->count1, include, '{', '}');
break;
case '[': /* "a[" = a [] block */
case ']':
flag = current_block(cap->oap, cap->count1, include, '[', ']');
break;
case '<': /* "a<" = a <> block */
case '>':
flag = current_block(cap->oap, cap->count1, include, '<', '>');
break;
case 't': /* "at" = a tag block (xml and html) */
flag = current_tagblock(cap->oap, cap->count1, include);
break;
case 'p': /* "ap" = a paragraph */
flag = current_par(cap->oap, cap->count1, include, 'p');
break;
case 's': /* "as" = a sentence */
flag = current_sent(cap->oap, cap->count1, include);
break;
case '"': /* "a"" = a double quoted string */
case '\'': /* "a'" = a single quoted string */
case '`': /* "a`" = a backtick quoted string */
flag = current_quote(cap->oap, cap->count1, include,
cap->nchar);
break;
#if 0 /* TODO */
case 'S': /* "aS" = a section */
case 'f': /* "af" = a filename */
case 'u': /* "au" = a URL */
#endif
default:
flag = FAIL;
break;
}
curbuf->b_p_mps = mps_save;
if (flag == FAIL)
clearopbeep(cap->oap);
adjust_cursor_col();
curwin->w_set_curswant = TRUE;
}
#endif
/*
* "q" command: Start/stop recording.
* "q:", "q/", "q?": edit command-line in command-line window.
*/
static void
nv_record(cap)
cmdarg_T *cap;
{
if (cap->oap->op_type == OP_FORMAT)
{
/* "gqq" is the same as "gqgq": format line */
cap->cmdchar = 'g';
cap->nchar = 'q';
nv_operator(cap);
}
else if (!checkclearop(cap->oap))
{
#ifdef FEAT_CMDWIN
if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?')
{
stuffcharReadbuff(cap->nchar);
stuffcharReadbuff(K_CMDWIN);
}
else
#endif
/* (stop) recording into a named register, unless executing a
* register */
if (!Exec_reg && do_record(cap->nchar) == FAIL)
clearopbeep(cap->oap);
}
}
/*
* Handle the "@r" command.
*/
static void
nv_at(cap)
cmdarg_T *cap;
{
if (checkclearop(cap->oap))
return;
#ifdef FEAT_EVAL
if (cap->nchar == '=')
{
if (get_expr_register() == NUL)
return;
}
#endif
while (cap->count1-- && !got_int)
{
if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL)
{
clearopbeep(cap->oap);
break;
}
line_breakcheck();
}
}
/*
* Handle the CTRL-U and CTRL-D commands.
*/
static void
nv_halfpage(cap)
cmdarg_T *cap;
{
if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1)
|| (cap->cmdchar == Ctrl_D
&& curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count))
clearopbeep(cap->oap);
else if (!checkclearop(cap->oap))
halfpage(cap->cmdchar == Ctrl_D, cap->count0);
}
/*
* Handle "J" or "gJ" command.
*/
static void
nv_join(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
if (VIsual_active) /* join the visual lines */
nv_operator(cap);
else
#endif
if (!checkclearop(cap->oap))
{
if (cap->count0 <= 1)
cap->count0 = 2; /* default for join is two lines! */
if (curwin->w_cursor.lnum + cap->count0 - 1 >
curbuf->b_ml.ml_line_count)
clearopbeep(cap->oap); /* beyond last line */
else
{
prep_redo(cap->oap->regname, cap->count0,
NUL, cap->cmdchar, NUL, NUL, cap->nchar);
(void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE);
}
}
}
/*
* "P", "gP", "p" and "gp" commands.
*/
static void
nv_put(cap)
cmdarg_T *cap;
{
#ifdef FEAT_VISUAL
int regname = 0;
void *reg1 = NULL, *reg2 = NULL;
int empty = FALSE;
int was_visual = FALSE;
#endif
int dir;
int flags = 0;
if (cap->oap->op_type != OP_NOP)
{
#ifdef FEAT_DIFF
/* "dp" is ":diffput" */
if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p')
{
clearop(cap->oap);
nv_diffgetput(TRUE);
}
else
#endif
clearopbeep(cap->oap);
}
else
{
dir = (cap->cmdchar == 'P'
|| (cap->cmdchar == 'g' && cap->nchar == 'P'))
? BACKWARD : FORWARD;
prep_redo_cmd(cap);
if (cap->cmdchar == 'g')
flags |= PUT_CURSEND;
#ifdef FEAT_VISUAL
if (VIsual_active)
{
/* Putting in Visual mode: The put text replaces the selected
* text. First delete the selected text, then put the new text.
* Need to save and restore the registers that the delete
* overwrites if the old contents is being put.
*/
was_visual = TRUE;
regname = cap->oap->regname;
# ifdef FEAT_CLIPBOARD
adjust_clip_reg(®name);
# endif
if (regname == 0 || regname == '"' || VIM_ISDIGIT(regname)
# ifdef FEAT_CLIPBOARD
|| (clip_unnamed && (regname == '*' || regname == '+'))
# endif
)
{
/* the delete is going to overwrite the register we want to
* put, save it first. */
reg1 = get_register(regname, TRUE);
}
/* Now delete the selected text. */
cap->cmdchar = 'd';
cap->nchar = NUL;
cap->oap->regname = NUL;
nv_operator(cap);
do_pending_operator(cap, 0, FALSE);
empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
/* delete PUT_LINE_BACKWARD; */
cap->oap->regname = regname;
if (reg1 != NULL)
{
/* Delete probably changed the register we want to put, save
* it first. Then put back what was there before the delete. */
reg2 = get_register(regname, FALSE);
put_register(regname, reg1);
}
/* When deleted a linewise Visual area, put the register as
* lines to avoid it joined with the next line. When deletion was
* characterwise, split a line when putting lines. */
if (VIsual_mode == 'V')
flags |= PUT_LINE;
else if (VIsual_mode == 'v')
flags |= PUT_LINE_SPLIT;
if (VIsual_mode == Ctrl_V && dir == FORWARD)
flags |= PUT_LINE_FORWARD;
dir = BACKWARD;
if ((VIsual_mode != 'V'
&& curwin->w_cursor.col < curbuf->b_op_start.col)
|| (VIsual_mode == 'V'
&& curwin->w_cursor.lnum < curbuf->b_op_start.lnum))
/* cursor is at the end of the line or end of file, put
* forward. */
dir = FORWARD;
}
#endif
do_put(cap->oap->regname, dir, cap->count1, flags);
#ifdef FEAT_VISUAL
/* If a register was saved, put it back now. */
if (reg2 != NULL)
put_register(regname, reg2);
/* What to reselect with "gv"? Selecting the just put text seems to
* be the most useful, since the original text was removed. */
if (was_visual)
{
curbuf->b_visual.vi_start = curbuf->b_op_start;
curbuf->b_visual.vi_end = curbuf->b_op_end;
}
/* When all lines were selected and deleted do_put() leaves an empty
* line that needs to be deleted now. */
if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL)
{
ml_delete(curbuf->b_ml.ml_line_count, TRUE);
/* If the cursor was in that line, move it to the end of the last
* line. */
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
{
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
coladvance((colnr_T)MAXCOL);
}
}
#endif
auto_format(FALSE, TRUE);
}
}
/*
* "o" and "O" commands.
*/
static void
nv_open(cap)
cmdarg_T *cap;
{
#ifdef FEAT_DIFF
/* "do" is ":diffget" */
if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o')
{
clearop(cap->oap);
nv_diffgetput(FALSE);
}
else
#endif
#ifdef FEAT_VISUAL
if (VIsual_active) /* switch start and end of visual */
v_swap_corners(cap->cmdchar);
else
#endif
n_opencmd(cap);
}
#ifdef FEAT_SNIFF
static void
nv_sniff(cap)
cmdarg_T *cap UNUSED;
{
ProcessSniffRequests();
}
#endif
#ifdef FEAT_NETBEANS_INTG
static void
nv_nbcmd(cap)
cmdarg_T *cap;
{
netbeans_keycommand(cap->nchar);
}
#endif
#ifdef FEAT_DND
static void
nv_drop(cap)
cmdarg_T *cap UNUSED;
{
do_put('~', BACKWARD, 1L, PUT_CURSEND);
}
#endif
#ifdef FEAT_AUTOCMD
/*
* Trigger CursorHold event.
* When waiting for a character for 'updatetime' K_CURSORHOLD is put in the
* input buffer. "did_cursorhold" is set to avoid retriggering.
*/
static void
nv_cursorhold(cap)
cmdarg_T *cap;
{
apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf);
did_cursorhold = TRUE;
cap->retval |= CA_COMMAND_BUSY; /* don't call edit() now */
}
#endif
| zyz2011-vim | src/normal.c | C | gpl2 | 229,257 |
#! /bin/sh
# installml.sh --- install or uninstall manpage links for Vim
#
# arguments:
# 1 what: "install" or "uninstall"
# 2 also do GUI pages: "yes" or ""
# 3 target directory e.g., "/usr/local/man/it/man1"
# 4 vim exe name e.g., "vim"
# 5 vimdiff exe name e.g., "vimdiff"
# 6 evim exe name e.g., "evim"
# 7 ex exe name e.g., "ex"
# 8 view exe name e.g., "view"
# 9 rvim exe name e.g., "rvim"
# 10 rview exe name e.g., "rview"
# 11 gvim exe name e.g., "gvim"
# 12 gview exe name e.g., "gview"
# 13 rgvim exe name e.g., "rgvim"
# 14 rgview exe name e.g., "rgview"
# 15 gvimdiff exe name e.g., "gvimdiff"
# 16 eview exe name e.g., "eview"
errstatus=0
what=$1
gui=$2
destdir=$3
vimname=$4
vimdiffname=$5
evimname=$6
exname=$7
viewname=$8
rvimname=$9
# old shells don't understand ${10}
shift
rviewname=$9
shift
gvimname=$9
shift
gviewname=$9
shift
rgvimname=$9
shift
rgviewname=$9
shift
gvimdiffname=$9
shift
eviewname=$9
if test $what = "install" -a \( -f $destdir/$vimname.1 -o -f $destdir/$vimdiffname.1 -o -f $destdir/$eviewname.1 \); then
if test ! -d $destdir; then
echo creating $destdir
./mkinstalldirs $destdir
fi
# ex
if test ! -f $destdir/$exname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$exname.1
cd $destdir; ln -s $vimname.1 $exname.1
fi
# view
if test ! -f $destdir/$viewname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$viewname.1
cd $destdir; ln -s $vimname.1 $viewname.1
fi
# rvim
if test ! -f $destdir/$rvimname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$rvimname.1
cd $destdir; ln -s $vimname.1 $rvimname.1
fi
# rview
if test ! -f $destdir/$rviewname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$rviewname.1
cd $destdir; ln -s $vimname.1 $rviewname.1
fi
# GUI targets are optional
if test "$gui" = "yes"; then
# gvim
if test ! -f $destdir/$gvimname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$gvimname.1
cd $destdir; ln -s $vimname.1 $gvimname.1
fi
# gview
if test ! -f $destdir/$gviewname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$gviewname.1
cd $destdir; ln -s $vimname.1 $gviewname.1
fi
# rgvim
if test ! -f $destdir/$rgvimname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$rgvimname.1
cd $destdir; ln -s $vimname.1 $rgvimname.1
fi
# rgview
if test ! -f $destdir/$rgviewname.1 -a -f $destdir/$vimname.1; then
echo creating link $destdir/$rgviewname.1
cd $destdir; ln -s $vimname.1 $rgviewname.1
fi
# gvimdiff
if test ! -f $destdir/$gvimdiffname.1 -a -f $destdir/$vimdiffname.1; then
echo creating link $destdir/$gvimdiffname.1
cd $destdir; ln -s $vimdiffname.1 $gvimdiffname.1
fi
# eview
if test ! -f $destdir/$eviewname.1 -a -f $destdir/$evimname.1; then
echo creating link $destdir/$eviewname.1
cd $destdir; ln -s $evimname.1 $eviewname.1
fi
fi
fi
if test $what = "uninstall"; then
echo Checking for Vim manual page links in $destdir...
if test -L $destdir/$exname.1; then
echo deleting $destdir/$exname.1
rm -f $destdir/$exname.1
fi
if test -L $destdir/$viewname.1; then
echo deleting $destdir/$viewname.1
rm -f $destdir/$viewname.1
fi
if test -L $destdir/$rvimname.1; then
echo deleting $destdir/$rvimname.1
rm -f $destdir/$rvimname.1
fi
if test -L $destdir/$rviewname.1; then
echo deleting $destdir/$rviewname.1
rm -f $destdir/$rviewname.1
fi
# GUI targets are optional
if test "$gui" = "yes"; then
if test -L $destdir/$gvimname.1; then
echo deleting $destdir/$gvimname.1
rm -f $destdir/$gvimname.1
fi
if test -L $destdir/$gviewname.1; then
echo deleting $destdir/$gviewname.1
rm -f $destdir/$gviewname.1
fi
if test -L $destdir/$rgvimname.1; then
echo deleting $destdir/$rgvimname.1
rm -f $destdir/$rgvimname.1
fi
if test -L $destdir/$rgviewname.1; then
echo deleting $destdir/$rgviewname.1
rm -f $destdir/$rgviewname.1
fi
if test -L $destdir/$gvimdiffname.1; then
echo deleting $destdir/$gvimdiffname.1
rm -f $destdir/$gvimdiffname.1
fi
if test -L $destdir/$eviewname.1; then
echo deleting $destdir/$eviewname.1
rm -f $destdir/$eviewname.1
fi
fi
fi
exit $errstatus
# vim: set sw=3 :
| zyz2011-vim | src/installml.sh | Shell | gpl2 | 4,580 |
/* 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.
*/
/*
* mark.c: functions for setting marks and jumping to them
*/
#include "vim.h"
/*
* This file contains routines to maintain and manipulate marks.
*/
/*
* If a named file mark's lnum is non-zero, it is valid.
* If a named file mark's fnum is non-zero, it is for an existing buffer,
* otherwise it is from .viminfo and namedfm[n].fname is the file name.
* There are marks 'A - 'Z (set by user) and '0 to '9 (set when writing
* viminfo).
*/
#define EXTRA_MARKS 10 /* marks 0-9 */
static xfmark_T namedfm[NMARKS + EXTRA_MARKS]; /* marks with file nr */
static void fname2fnum __ARGS((xfmark_T *fm));
static void fmarks_check_one __ARGS((xfmark_T *fm, char_u *name, buf_T *buf));
static char_u *mark_line __ARGS((pos_T *mp, int lead_len));
static void show_one_mark __ARGS((int, char_u *, pos_T *, char_u *, int current));
#ifdef FEAT_JUMPLIST
static void cleanup_jumplist __ARGS((void));
#endif
#ifdef FEAT_VIMINFO
static void write_one_filemark __ARGS((FILE *fp, xfmark_T *fm, int c1, int c2));
#endif
/*
* Set named mark "c" at current cursor position.
* Returns OK on success, FAIL if bad name given.
*/
int
setmark(c)
int c;
{
return setmark_pos(c, &curwin->w_cursor, curbuf->b_fnum);
}
/*
* Set named mark "c" to position "pos".
* When "c" is upper case use file "fnum".
* Returns OK on success, FAIL if bad name given.
*/
int
setmark_pos(c, pos, fnum)
int c;
pos_T *pos;
int fnum;
{
int i;
/* Check for a special key (may cause islower() to crash). */
if (c < 0)
return FAIL;
if (c == '\'' || c == '`')
{
if (pos == &curwin->w_cursor)
{
setpcmark();
/* keep it even when the cursor doesn't move */
curwin->w_prev_pcmark = curwin->w_pcmark;
}
else
curwin->w_pcmark = *pos;
return OK;
}
if (c == '"')
{
curbuf->b_last_cursor = *pos;
return OK;
}
/* Allow setting '[ and '] for an autocommand that simulates reading a
* file. */
if (c == '[')
{
curbuf->b_op_start = *pos;
return OK;
}
if (c == ']')
{
curbuf->b_op_end = *pos;
return OK;
}
#ifndef EBCDIC
if (c > 'z') /* some islower() and isupper() cannot handle
characters above 127 */
return FAIL;
#endif
if (islower(c))
{
i = c - 'a';
curbuf->b_namedm[i] = *pos;
return OK;
}
if (isupper(c))
{
i = c - 'A';
namedfm[i].fmark.mark = *pos;
namedfm[i].fmark.fnum = fnum;
vim_free(namedfm[i].fname);
namedfm[i].fname = NULL;
return OK;
}
return FAIL;
}
/*
* Set the previous context mark to the current position and add it to the
* jump list.
*/
void
setpcmark()
{
#ifdef FEAT_JUMPLIST
int i;
xfmark_T *fm;
#endif
#ifdef JUMPLIST_ROTATE
xfmark_T tempmark;
#endif
/* for :global the mark is set only once */
if (global_busy || listcmd_busy || cmdmod.keepjumps)
return;
curwin->w_prev_pcmark = curwin->w_pcmark;
curwin->w_pcmark = curwin->w_cursor;
#ifdef FEAT_JUMPLIST
# ifdef JUMPLIST_ROTATE
/*
* If last used entry is not at the top, put it at the top by rotating
* the stack until it is (the newer entries will be at the bottom).
* Keep one entry (the last used one) at the top.
*/
if (curwin->w_jumplistidx < curwin->w_jumplistlen)
++curwin->w_jumplistidx;
while (curwin->w_jumplistidx < curwin->w_jumplistlen)
{
tempmark = curwin->w_jumplist[curwin->w_jumplistlen - 1];
for (i = curwin->w_jumplistlen - 1; i > 0; --i)
curwin->w_jumplist[i] = curwin->w_jumplist[i - 1];
curwin->w_jumplist[0] = tempmark;
++curwin->w_jumplistidx;
}
# endif
/* If jumplist is full: remove oldest entry */
if (++curwin->w_jumplistlen > JUMPLISTSIZE)
{
curwin->w_jumplistlen = JUMPLISTSIZE;
vim_free(curwin->w_jumplist[0].fname);
for (i = 1; i < JUMPLISTSIZE; ++i)
curwin->w_jumplist[i - 1] = curwin->w_jumplist[i];
}
curwin->w_jumplistidx = curwin->w_jumplistlen;
fm = &curwin->w_jumplist[curwin->w_jumplistlen - 1];
fm->fmark.mark = curwin->w_pcmark;
fm->fmark.fnum = curbuf->b_fnum;
fm->fname = NULL;
#endif
}
/*
* To change context, call setpcmark(), then move the current position to
* where ever, then call checkpcmark(). This ensures that the previous
* context will only be changed if the cursor moved to a different line.
* If pcmark was deleted (with "dG") the previous mark is restored.
*/
void
checkpcmark()
{
if (curwin->w_prev_pcmark.lnum != 0
&& (equalpos(curwin->w_pcmark, curwin->w_cursor)
|| curwin->w_pcmark.lnum == 0))
{
curwin->w_pcmark = curwin->w_prev_pcmark;
curwin->w_prev_pcmark.lnum = 0; /* Show it has been checked */
}
}
#if defined(FEAT_JUMPLIST) || defined(PROTO)
/*
* move "count" positions in the jump list (count may be negative)
*/
pos_T *
movemark(count)
int count;
{
pos_T *pos;
xfmark_T *jmp;
cleanup_jumplist();
if (curwin->w_jumplistlen == 0) /* nothing to jump to */
return (pos_T *)NULL;
for (;;)
{
if (curwin->w_jumplistidx + count < 0
|| curwin->w_jumplistidx + count >= curwin->w_jumplistlen)
return (pos_T *)NULL;
/*
* if first CTRL-O or CTRL-I command after a jump, add cursor position
* to list. Careful: If there are duplicates (CTRL-O immediately after
* starting Vim on a file), another entry may have been removed.
*/
if (curwin->w_jumplistidx == curwin->w_jumplistlen)
{
setpcmark();
--curwin->w_jumplistidx; /* skip the new entry */
if (curwin->w_jumplistidx + count < 0)
return (pos_T *)NULL;
}
curwin->w_jumplistidx += count;
jmp = curwin->w_jumplist + curwin->w_jumplistidx;
if (jmp->fmark.fnum == 0)
fname2fnum(jmp);
if (jmp->fmark.fnum != curbuf->b_fnum)
{
/* jump to other file */
if (buflist_findnr(jmp->fmark.fnum) == NULL)
{ /* Skip this one .. */
count += count < 0 ? -1 : 1;
continue;
}
if (buflist_getfile(jmp->fmark.fnum, jmp->fmark.mark.lnum,
0, FALSE) == FAIL)
return (pos_T *)NULL;
/* Set lnum again, autocommands my have changed it */
curwin->w_cursor = jmp->fmark.mark;
pos = (pos_T *)-1;
}
else
pos = &(jmp->fmark.mark);
return pos;
}
}
/*
* Move "count" positions in the changelist (count may be negative).
*/
pos_T *
movechangelist(count)
int count;
{
int n;
if (curbuf->b_changelistlen == 0) /* nothing to jump to */
return (pos_T *)NULL;
n = curwin->w_changelistidx;
if (n + count < 0)
{
if (n == 0)
return (pos_T *)NULL;
n = 0;
}
else if (n + count >= curbuf->b_changelistlen)
{
if (n == curbuf->b_changelistlen - 1)
return (pos_T *)NULL;
n = curbuf->b_changelistlen - 1;
}
else
n += count;
curwin->w_changelistidx = n;
return curbuf->b_changelist + n;
}
#endif
/*
* Find mark "c".
* If "changefile" is TRUE it's allowed to edit another file for '0, 'A, etc.
* If "fnum" is not NULL store the fnum there for '0, 'A etc., don't edit
* another file.
* Returns:
* - pointer to pos_T if found. lnum is 0 when mark not set, -1 when mark is
* in another file which can't be gotten. (caller needs to check lnum!)
* - NULL if there is no mark called 'c'.
* - -1 if mark is in other file and jumped there (only if changefile is TRUE)
*/
pos_T *
getmark(c, changefile)
int c;
int changefile;
{
return getmark_fnum(c, changefile, NULL);
}
pos_T *
getmark_fnum(c, changefile, fnum)
int c;
int changefile;
int *fnum;
{
pos_T *posp;
#ifdef FEAT_VISUAL
pos_T *startp, *endp;
#endif
static pos_T pos_copy;
posp = NULL;
/* Check for special key, can't be a mark name and might cause islower()
* to crash. */
if (c < 0)
return posp;
#ifndef EBCDIC
if (c > '~') /* check for islower()/isupper() */
;
else
#endif
if (c == '\'' || c == '`') /* previous context mark */
{
pos_copy = curwin->w_pcmark; /* need to make a copy because */
posp = &pos_copy; /* w_pcmark may be changed soon */
}
else if (c == '"') /* to pos when leaving buffer */
posp = &(curbuf->b_last_cursor);
else if (c == '^') /* to where Insert mode stopped */
posp = &(curbuf->b_last_insert);
else if (c == '.') /* to where last change was made */
posp = &(curbuf->b_last_change);
else if (c == '[') /* to start of previous operator */
posp = &(curbuf->b_op_start);
else if (c == ']') /* to end of previous operator */
posp = &(curbuf->b_op_end);
else if (c == '{' || c == '}') /* to previous/next paragraph */
{
pos_T pos;
oparg_T oa;
int slcb = listcmd_busy;
pos = curwin->w_cursor;
listcmd_busy = TRUE; /* avoid that '' is changed */
if (findpar(&oa.inclusive,
c == '}' ? FORWARD : BACKWARD, 1L, NUL, FALSE))
{
pos_copy = curwin->w_cursor;
posp = &pos_copy;
}
curwin->w_cursor = pos;
listcmd_busy = slcb;
}
else if (c == '(' || c == ')') /* to previous/next sentence */
{
pos_T pos;
int slcb = listcmd_busy;
pos = curwin->w_cursor;
listcmd_busy = TRUE; /* avoid that '' is changed */
if (findsent(c == ')' ? FORWARD : BACKWARD, 1L))
{
pos_copy = curwin->w_cursor;
posp = &pos_copy;
}
curwin->w_cursor = pos;
listcmd_busy = slcb;
}
#ifdef FEAT_VISUAL
else if (c == '<' || c == '>') /* start/end of visual area */
{
startp = &curbuf->b_visual.vi_start;
endp = &curbuf->b_visual.vi_end;
if ((c == '<') == lt(*startp, *endp))
posp = startp;
else
posp = endp;
/*
* For Visual line mode, set mark at begin or end of line
*/
if (curbuf->b_visual.vi_mode == 'V')
{
pos_copy = *posp;
posp = &pos_copy;
if (c == '<')
pos_copy.col = 0;
else
pos_copy.col = MAXCOL;
#ifdef FEAT_VIRTUALEDIT
pos_copy.coladd = 0;
#endif
}
}
#endif
else if (ASCII_ISLOWER(c)) /* normal named mark */
{
posp = &(curbuf->b_namedm[c - 'a']);
}
else if (ASCII_ISUPPER(c) || VIM_ISDIGIT(c)) /* named file mark */
{
if (VIM_ISDIGIT(c))
c = c - '0' + NMARKS;
else
c -= 'A';
posp = &(namedfm[c].fmark.mark);
if (namedfm[c].fmark.fnum == 0)
fname2fnum(&namedfm[c]);
if (fnum != NULL)
*fnum = namedfm[c].fmark.fnum;
else if (namedfm[c].fmark.fnum != curbuf->b_fnum)
{
/* mark is in another file */
posp = &pos_copy;
if (namedfm[c].fmark.mark.lnum != 0
&& changefile && namedfm[c].fmark.fnum)
{
if (buflist_getfile(namedfm[c].fmark.fnum,
(linenr_T)1, GETF_SETMARK, FALSE) == OK)
{
/* Set the lnum now, autocommands could have changed it */
curwin->w_cursor = namedfm[c].fmark.mark;
return (pos_T *)-1;
}
pos_copy.lnum = -1; /* can't get file */
}
else
pos_copy.lnum = 0; /* mark exists, but is not valid in
current buffer */
}
}
return posp;
}
/*
* Search for the next named mark in the current file.
*
* Returns pointer to pos_T of the next mark or NULL if no mark is found.
*/
pos_T *
getnextmark(startpos, dir, begin_line)
pos_T *startpos; /* where to start */
int dir; /* direction for search */
int begin_line;
{
int i;
pos_T *result = NULL;
pos_T pos;
pos = *startpos;
/* When searching backward and leaving the cursor on the first non-blank,
* position must be in a previous line.
* When searching forward and leaving the cursor on the first non-blank,
* position must be in a next line. */
if (dir == BACKWARD && begin_line)
pos.col = 0;
else if (dir == FORWARD && begin_line)
pos.col = MAXCOL;
for (i = 0; i < NMARKS; i++)
{
if (curbuf->b_namedm[i].lnum > 0)
{
if (dir == FORWARD)
{
if ((result == NULL || lt(curbuf->b_namedm[i], *result))
&& lt(pos, curbuf->b_namedm[i]))
result = &curbuf->b_namedm[i];
}
else
{
if ((result == NULL || lt(*result, curbuf->b_namedm[i]))
&& lt(curbuf->b_namedm[i], pos))
result = &curbuf->b_namedm[i];
}
}
}
return result;
}
/*
* For an xtended filemark: set the fnum from the fname.
* This is used for marks obtained from the .viminfo file. It's postponed
* until the mark is used to avoid a long startup delay.
*/
static void
fname2fnum(fm)
xfmark_T *fm;
{
char_u *p;
if (fm->fname != NULL)
{
/*
* First expand "~/" in the file name to the home directory.
* Don't expand the whole name, it may contain other '~' chars.
*/
if (fm->fname[0] == '~' && (fm->fname[1] == '/'
#ifdef BACKSLASH_IN_FILENAME
|| fm->fname[1] == '\\'
#endif
))
{
int len;
expand_env((char_u *)"~/", NameBuff, MAXPATHL);
len = (int)STRLEN(NameBuff);
vim_strncpy(NameBuff + len, fm->fname + 2, MAXPATHL - len - 1);
}
else
vim_strncpy(NameBuff, fm->fname, MAXPATHL - 1);
/* Try to shorten the file name. */
mch_dirname(IObuff, IOSIZE);
p = shorten_fname(NameBuff, IObuff);
/* buflist_new() will call fmarks_check_names() */
(void)buflist_new(NameBuff, p, (linenr_T)1, 0);
}
}
/*
* Check all file marks for a name that matches the file name in buf.
* May replace the name with an fnum.
* Used for marks that come from the .viminfo file.
*/
void
fmarks_check_names(buf)
buf_T *buf;
{
char_u *name;
int i;
#ifdef FEAT_JUMPLIST
win_T *wp;
#endif
if (buf->b_ffname == NULL)
return;
name = home_replace_save(buf, buf->b_ffname);
if (name == NULL)
return;
for (i = 0; i < NMARKS + EXTRA_MARKS; ++i)
fmarks_check_one(&namedfm[i], name, buf);
#ifdef FEAT_JUMPLIST
FOR_ALL_WINDOWS(wp)
{
for (i = 0; i < wp->w_jumplistlen; ++i)
fmarks_check_one(&wp->w_jumplist[i], name, buf);
}
#endif
vim_free(name);
}
static void
fmarks_check_one(fm, name, buf)
xfmark_T *fm;
char_u *name;
buf_T *buf;
{
if (fm->fmark.fnum == 0
&& fm->fname != NULL
&& fnamecmp(name, fm->fname) == 0)
{
fm->fmark.fnum = buf->b_fnum;
vim_free(fm->fname);
fm->fname = NULL;
}
}
/*
* Check a if a position from a mark is valid.
* Give and error message and return FAIL if not.
*/
int
check_mark(pos)
pos_T *pos;
{
if (pos == NULL)
{
EMSG(_(e_umark));
return FAIL;
}
if (pos->lnum <= 0)
{
/* lnum is negative if mark is in another file can can't get that
* file, error message already give then. */
if (pos->lnum == 0)
EMSG(_(e_marknotset));
return FAIL;
}
if (pos->lnum > curbuf->b_ml.ml_line_count)
{
EMSG(_(e_markinval));
return FAIL;
}
return OK;
}
/*
* clrallmarks() - clear all marks in the buffer 'buf'
*
* Used mainly when trashing the entire buffer during ":e" type commands
*/
void
clrallmarks(buf)
buf_T *buf;
{
static int i = -1;
if (i == -1) /* first call ever: initialize */
for (i = 0; i < NMARKS + 1; i++)
{
namedfm[i].fmark.mark.lnum = 0;
namedfm[i].fname = NULL;
}
for (i = 0; i < NMARKS; i++)
buf->b_namedm[i].lnum = 0;
buf->b_op_start.lnum = 0; /* start/end op mark cleared */
buf->b_op_end.lnum = 0;
buf->b_last_cursor.lnum = 1; /* '" mark cleared */
buf->b_last_cursor.col = 0;
#ifdef FEAT_VIRTUALEDIT
buf->b_last_cursor.coladd = 0;
#endif
buf->b_last_insert.lnum = 0; /* '^ mark cleared */
buf->b_last_change.lnum = 0; /* '. mark cleared */
#ifdef FEAT_JUMPLIST
buf->b_changelistlen = 0;
#endif
}
/*
* Get name of file from a filemark.
* When it's in the current buffer, return the text at the mark.
* Returns an allocated string.
*/
char_u *
fm_getname(fmark, lead_len)
fmark_T *fmark;
int lead_len;
{
if (fmark->fnum == curbuf->b_fnum) /* current buffer */
return mark_line(&(fmark->mark), lead_len);
return buflist_nr2name(fmark->fnum, FALSE, TRUE);
}
/*
* Return the line at mark "mp". Truncate to fit in window.
* The returned string has been allocated.
*/
static char_u *
mark_line(mp, lead_len)
pos_T *mp;
int lead_len;
{
char_u *s, *p;
int len;
if (mp->lnum == 0 || mp->lnum > curbuf->b_ml.ml_line_count)
return vim_strsave((char_u *)"-invalid-");
s = vim_strnsave(skipwhite(ml_get(mp->lnum)), (int)Columns);
if (s == NULL)
return NULL;
/* Truncate the line to fit it in the window */
len = 0;
for (p = s; *p != NUL; mb_ptr_adv(p))
{
len += ptr2cells(p);
if (len >= Columns - lead_len)
break;
}
*p = NUL;
return s;
}
/*
* print the marks
*/
void
do_marks(eap)
exarg_T *eap;
{
char_u *arg = eap->arg;
int i;
char_u *name;
if (arg != NULL && *arg == NUL)
arg = NULL;
show_one_mark('\'', arg, &curwin->w_pcmark, NULL, TRUE);
for (i = 0; i < NMARKS; ++i)
show_one_mark(i + 'a', arg, &curbuf->b_namedm[i], NULL, TRUE);
for (i = 0; i < NMARKS + EXTRA_MARKS; ++i)
{
if (namedfm[i].fmark.fnum != 0)
name = fm_getname(&namedfm[i].fmark, 15);
else
name = namedfm[i].fname;
if (name != NULL)
{
show_one_mark(i >= NMARKS ? i - NMARKS + '0' : i + 'A',
arg, &namedfm[i].fmark.mark, name,
namedfm[i].fmark.fnum == curbuf->b_fnum);
if (namedfm[i].fmark.fnum != 0)
vim_free(name);
}
}
show_one_mark('"', arg, &curbuf->b_last_cursor, NULL, TRUE);
show_one_mark('[', arg, &curbuf->b_op_start, NULL, TRUE);
show_one_mark(']', arg, &curbuf->b_op_end, NULL, TRUE);
show_one_mark('^', arg, &curbuf->b_last_insert, NULL, TRUE);
show_one_mark('.', arg, &curbuf->b_last_change, NULL, TRUE);
#ifdef FEAT_VISUAL
show_one_mark('<', arg, &curbuf->b_visual.vi_start, NULL, TRUE);
show_one_mark('>', arg, &curbuf->b_visual.vi_end, NULL, TRUE);
#endif
show_one_mark(-1, arg, NULL, NULL, FALSE);
}
static void
show_one_mark(c, arg, p, name, current)
int c;
char_u *arg;
pos_T *p;
char_u *name;
int current; /* in current file */
{
static int did_title = FALSE;
int mustfree = FALSE;
if (c == -1) /* finish up */
{
if (did_title)
did_title = FALSE;
else
{
if (arg == NULL)
MSG(_("No marks set"));
else
EMSG2(_("E283: No marks matching \"%s\""), arg);
}
}
/* don't output anything if 'q' typed at --more-- prompt */
else if (!got_int
&& (arg == NULL || vim_strchr(arg, c) != NULL)
&& p->lnum != 0)
{
if (!did_title)
{
/* Highlight title */
MSG_PUTS_TITLE(_("\nmark line col file/text"));
did_title = TRUE;
}
msg_putchar('\n');
if (!got_int)
{
sprintf((char *)IObuff, " %c %6ld %4d ", c, p->lnum, p->col);
msg_outtrans(IObuff);
if (name == NULL && current)
{
name = mark_line(p, 15);
mustfree = TRUE;
}
if (name != NULL)
{
msg_outtrans_attr(name, current ? hl_attr(HLF_D) : 0);
if (mustfree)
vim_free(name);
}
}
out_flush(); /* show one line at a time */
}
}
/*
* ":delmarks[!] [marks]"
*/
void
ex_delmarks(eap)
exarg_T *eap;
{
char_u *p;
int from, to;
int i;
int lower;
int digit;
int n;
if (*eap->arg == NUL && eap->forceit)
/* clear all marks */
clrallmarks(curbuf);
else if (eap->forceit)
EMSG(_(e_invarg));
else if (*eap->arg == NUL)
EMSG(_(e_argreq));
else
{
/* clear specified marks only */
for (p = eap->arg; *p != NUL; ++p)
{
lower = ASCII_ISLOWER(*p);
digit = VIM_ISDIGIT(*p);
if (lower || digit || ASCII_ISUPPER(*p))
{
if (p[1] == '-')
{
/* clear range of marks */
from = *p;
to = p[2];
if (!(lower ? ASCII_ISLOWER(p[2])
: (digit ? VIM_ISDIGIT(p[2])
: ASCII_ISUPPER(p[2])))
|| to < from)
{
EMSG2(_(e_invarg2), p);
return;
}
p += 2;
}
else
/* clear one lower case mark */
from = to = *p;
for (i = from; i <= to; ++i)
{
if (lower)
curbuf->b_namedm[i - 'a'].lnum = 0;
else
{
if (digit)
n = i - '0' + NMARKS;
else
n = i - 'A';
namedfm[n].fmark.mark.lnum = 0;
vim_free(namedfm[n].fname);
namedfm[n].fname = NULL;
}
}
}
else
switch (*p)
{
case '"': curbuf->b_last_cursor.lnum = 0; break;
case '^': curbuf->b_last_insert.lnum = 0; break;
case '.': curbuf->b_last_change.lnum = 0; break;
case '[': curbuf->b_op_start.lnum = 0; break;
case ']': curbuf->b_op_end.lnum = 0; break;
#ifdef FEAT_VISUAL
case '<': curbuf->b_visual.vi_start.lnum = 0; break;
case '>': curbuf->b_visual.vi_end.lnum = 0; break;
#endif
case ' ': break;
default: EMSG2(_(e_invarg2), p);
return;
}
}
}
}
#if defined(FEAT_JUMPLIST) || defined(PROTO)
/*
* print the jumplist
*/
void
ex_jumps(eap)
exarg_T *eap UNUSED;
{
int i;
char_u *name;
cleanup_jumplist();
/* Highlight title */
MSG_PUTS_TITLE(_("\n jump line col file/text"));
for (i = 0; i < curwin->w_jumplistlen && !got_int; ++i)
{
if (curwin->w_jumplist[i].fmark.mark.lnum != 0)
{
if (curwin->w_jumplist[i].fmark.fnum == 0)
fname2fnum(&curwin->w_jumplist[i]);
name = fm_getname(&curwin->w_jumplist[i].fmark, 16);
if (name == NULL) /* file name not available */
continue;
msg_putchar('\n');
if (got_int)
{
vim_free(name);
break;
}
sprintf((char *)IObuff, "%c %2d %5ld %4d ",
i == curwin->w_jumplistidx ? '>' : ' ',
i > curwin->w_jumplistidx ? i - curwin->w_jumplistidx
: curwin->w_jumplistidx - i,
curwin->w_jumplist[i].fmark.mark.lnum,
curwin->w_jumplist[i].fmark.mark.col);
msg_outtrans(IObuff);
msg_outtrans_attr(name,
curwin->w_jumplist[i].fmark.fnum == curbuf->b_fnum
? hl_attr(HLF_D) : 0);
vim_free(name);
ui_breakcheck();
}
out_flush();
}
if (curwin->w_jumplistidx == curwin->w_jumplistlen)
MSG_PUTS("\n>");
}
/*
* print the changelist
*/
void
ex_changes(eap)
exarg_T *eap UNUSED;
{
int i;
char_u *name;
/* Highlight title */
MSG_PUTS_TITLE(_("\nchange line col text"));
for (i = 0; i < curbuf->b_changelistlen && !got_int; ++i)
{
if (curbuf->b_changelist[i].lnum != 0)
{
msg_putchar('\n');
if (got_int)
break;
sprintf((char *)IObuff, "%c %3d %5ld %4d ",
i == curwin->w_changelistidx ? '>' : ' ',
i > curwin->w_changelistidx ? i - curwin->w_changelistidx
: curwin->w_changelistidx - i,
(long)curbuf->b_changelist[i].lnum,
curbuf->b_changelist[i].col);
msg_outtrans(IObuff);
name = mark_line(&curbuf->b_changelist[i], 17);
if (name == NULL)
break;
msg_outtrans_attr(name, hl_attr(HLF_D));
vim_free(name);
ui_breakcheck();
}
out_flush();
}
if (curwin->w_changelistidx == curbuf->b_changelistlen)
MSG_PUTS("\n>");
}
#endif
#define one_adjust(add) \
{ \
lp = add; \
if (*lp >= line1 && *lp <= line2) \
{ \
if (amount == MAXLNUM) \
*lp = 0; \
else \
*lp += amount; \
} \
else if (amount_after && *lp > line2) \
*lp += amount_after; \
}
/* don't delete the line, just put at first deleted line */
#define one_adjust_nodel(add) \
{ \
lp = add; \
if (*lp >= line1 && *lp <= line2) \
{ \
if (amount == MAXLNUM) \
*lp = line1; \
else \
*lp += amount; \
} \
else if (amount_after && *lp > line2) \
*lp += amount_after; \
}
/*
* Adjust marks between line1 and line2 (inclusive) to move 'amount' lines.
* Must be called before changed_*(), appended_lines() or deleted_lines().
* May be called before or after changing the text.
* When deleting lines line1 to line2, use an 'amount' of MAXLNUM: The marks
* within this range are made invalid.
* If 'amount_after' is non-zero adjust marks after line2.
* Example: Delete lines 34 and 35: mark_adjust(34, 35, MAXLNUM, -2);
* Example: Insert two lines below 55: mark_adjust(56, MAXLNUM, 2, 0);
* or: mark_adjust(56, 55, MAXLNUM, 2);
*/
void
mark_adjust(line1, line2, amount, amount_after)
linenr_T line1;
linenr_T line2;
long amount;
long amount_after;
{
int i;
int fnum = curbuf->b_fnum;
linenr_T *lp;
win_T *win;
#ifdef FEAT_WINDOWS
tabpage_T *tab;
#endif
if (line2 < line1 && amount_after == 0L) /* nothing to do */
return;
if (!cmdmod.lockmarks)
{
/* named marks, lower case and upper case */
for (i = 0; i < NMARKS; i++)
{
one_adjust(&(curbuf->b_namedm[i].lnum));
if (namedfm[i].fmark.fnum == fnum)
one_adjust_nodel(&(namedfm[i].fmark.mark.lnum));
}
for (i = NMARKS; i < NMARKS + EXTRA_MARKS; i++)
{
if (namedfm[i].fmark.fnum == fnum)
one_adjust_nodel(&(namedfm[i].fmark.mark.lnum));
}
/* last Insert position */
one_adjust(&(curbuf->b_last_insert.lnum));
/* last change position */
one_adjust(&(curbuf->b_last_change.lnum));
#ifdef FEAT_JUMPLIST
/* list of change positions */
for (i = 0; i < curbuf->b_changelistlen; ++i)
one_adjust_nodel(&(curbuf->b_changelist[i].lnum));
#endif
#ifdef FEAT_VISUAL
/* Visual area */
one_adjust_nodel(&(curbuf->b_visual.vi_start.lnum));
one_adjust_nodel(&(curbuf->b_visual.vi_end.lnum));
#endif
#ifdef FEAT_QUICKFIX
/* quickfix marks */
qf_mark_adjust(NULL, line1, line2, amount, amount_after);
/* location lists */
FOR_ALL_TAB_WINDOWS(tab, win)
qf_mark_adjust(win, line1, line2, amount, amount_after);
#endif
#ifdef FEAT_SIGNS
sign_mark_adjust(line1, line2, amount, amount_after);
#endif
}
/* previous context mark */
one_adjust(&(curwin->w_pcmark.lnum));
/* previous pcmark */
one_adjust(&(curwin->w_prev_pcmark.lnum));
/* saved cursor for formatting */
if (saved_cursor.lnum != 0)
one_adjust_nodel(&(saved_cursor.lnum));
/*
* Adjust items in all windows related to the current buffer.
*/
FOR_ALL_TAB_WINDOWS(tab, win)
{
#ifdef FEAT_JUMPLIST
if (!cmdmod.lockmarks)
/* Marks in the jumplist. When deleting lines, this may create
* duplicate marks in the jumplist, they will be removed later. */
for (i = 0; i < win->w_jumplistlen; ++i)
if (win->w_jumplist[i].fmark.fnum == fnum)
one_adjust_nodel(&(win->w_jumplist[i].fmark.mark.lnum));
#endif
if (win->w_buffer == curbuf)
{
if (!cmdmod.lockmarks)
/* marks in the tag stack */
for (i = 0; i < win->w_tagstacklen; i++)
if (win->w_tagstack[i].fmark.fnum == fnum)
one_adjust_nodel(&(win->w_tagstack[i].fmark.mark.lnum));
#ifdef FEAT_VISUAL
/* the displayed Visual area */
if (win->w_old_cursor_lnum != 0)
{
one_adjust_nodel(&(win->w_old_cursor_lnum));
one_adjust_nodel(&(win->w_old_visual_lnum));
}
#endif
/* topline and cursor position for windows with the same buffer
* other than the current window */
if (win != curwin)
{
if (win->w_topline >= line1 && win->w_topline <= line2)
{
if (amount == MAXLNUM) /* topline is deleted */
{
if (line1 <= 1)
win->w_topline = 1;
else
win->w_topline = line1 - 1;
}
else /* keep topline on the same line */
win->w_topline += amount;
#ifdef FEAT_DIFF
win->w_topfill = 0;
#endif
}
else if (amount_after && win->w_topline > line2)
{
win->w_topline += amount_after;
#ifdef FEAT_DIFF
win->w_topfill = 0;
#endif
}
if (win->w_cursor.lnum >= line1 && win->w_cursor.lnum <= line2)
{
if (amount == MAXLNUM) /* line with cursor is deleted */
{
if (line1 <= 1)
win->w_cursor.lnum = 1;
else
win->w_cursor.lnum = line1 - 1;
win->w_cursor.col = 0;
}
else /* keep cursor on the same line */
win->w_cursor.lnum += amount;
}
else if (amount_after && win->w_cursor.lnum > line2)
win->w_cursor.lnum += amount_after;
}
#ifdef FEAT_FOLDING
/* adjust folds */
foldMarkAdjust(win, line1, line2, amount, amount_after);
#endif
}
}
#ifdef FEAT_DIFF
/* adjust diffs */
diff_mark_adjust(line1, line2, amount, amount_after);
#endif
}
/* This code is used often, needs to be fast. */
#define col_adjust(pp) \
{ \
posp = pp; \
if (posp->lnum == lnum && posp->col >= mincol) \
{ \
posp->lnum += lnum_amount; \
if (col_amount < 0 && posp->col <= (colnr_T)-col_amount) \
posp->col = 0; \
else \
posp->col += col_amount; \
} \
}
/*
* Adjust marks in line "lnum" at column "mincol" and further: add
* "lnum_amount" to the line number and add "col_amount" to the column
* position.
*/
void
mark_col_adjust(lnum, mincol, lnum_amount, col_amount)
linenr_T lnum;
colnr_T mincol;
long lnum_amount;
long col_amount;
{
int i;
int fnum = curbuf->b_fnum;
win_T *win;
pos_T *posp;
if ((col_amount == 0L && lnum_amount == 0L) || cmdmod.lockmarks)
return; /* nothing to do */
/* named marks, lower case and upper case */
for (i = 0; i < NMARKS; i++)
{
col_adjust(&(curbuf->b_namedm[i]));
if (namedfm[i].fmark.fnum == fnum)
col_adjust(&(namedfm[i].fmark.mark));
}
for (i = NMARKS; i < NMARKS + EXTRA_MARKS; i++)
{
if (namedfm[i].fmark.fnum == fnum)
col_adjust(&(namedfm[i].fmark.mark));
}
/* last Insert position */
col_adjust(&(curbuf->b_last_insert));
/* last change position */
col_adjust(&(curbuf->b_last_change));
#ifdef FEAT_JUMPLIST
/* list of change positions */
for (i = 0; i < curbuf->b_changelistlen; ++i)
col_adjust(&(curbuf->b_changelist[i]));
#endif
#ifdef FEAT_VISUAL
/* Visual area */
col_adjust(&(curbuf->b_visual.vi_start));
col_adjust(&(curbuf->b_visual.vi_end));
#endif
/* previous context mark */
col_adjust(&(curwin->w_pcmark));
/* previous pcmark */
col_adjust(&(curwin->w_prev_pcmark));
/* saved cursor for formatting */
col_adjust(&saved_cursor);
/*
* Adjust items in all windows related to the current buffer.
*/
FOR_ALL_WINDOWS(win)
{
#ifdef FEAT_JUMPLIST
/* marks in the jumplist */
for (i = 0; i < win->w_jumplistlen; ++i)
if (win->w_jumplist[i].fmark.fnum == fnum)
col_adjust(&(win->w_jumplist[i].fmark.mark));
#endif
if (win->w_buffer == curbuf)
{
/* marks in the tag stack */
for (i = 0; i < win->w_tagstacklen; i++)
if (win->w_tagstack[i].fmark.fnum == fnum)
col_adjust(&(win->w_tagstack[i].fmark.mark));
/* cursor position for other windows with the same buffer */
if (win != curwin)
col_adjust(&win->w_cursor);
}
}
}
#ifdef FEAT_JUMPLIST
/*
* When deleting lines, this may create duplicate marks in the
* jumplist. They will be removed here for the current window.
*/
static void
cleanup_jumplist()
{
int i;
int from, to;
to = 0;
for (from = 0; from < curwin->w_jumplistlen; ++from)
{
if (curwin->w_jumplistidx == from)
curwin->w_jumplistidx = to;
for (i = from + 1; i < curwin->w_jumplistlen; ++i)
if (curwin->w_jumplist[i].fmark.fnum
== curwin->w_jumplist[from].fmark.fnum
&& curwin->w_jumplist[from].fmark.fnum != 0
&& curwin->w_jumplist[i].fmark.mark.lnum
== curwin->w_jumplist[from].fmark.mark.lnum)
break;
if (i >= curwin->w_jumplistlen) /* no duplicate */
curwin->w_jumplist[to++] = curwin->w_jumplist[from];
else
vim_free(curwin->w_jumplist[from].fname);
}
if (curwin->w_jumplistidx == curwin->w_jumplistlen)
curwin->w_jumplistidx = to;
curwin->w_jumplistlen = to;
}
# if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Copy the jumplist from window "from" to window "to".
*/
void
copy_jumplist(from, to)
win_T *from;
win_T *to;
{
int i;
for (i = 0; i < from->w_jumplistlen; ++i)
{
to->w_jumplist[i] = from->w_jumplist[i];
if (from->w_jumplist[i].fname != NULL)
to->w_jumplist[i].fname = vim_strsave(from->w_jumplist[i].fname);
}
to->w_jumplistlen = from->w_jumplistlen;
to->w_jumplistidx = from->w_jumplistidx;
}
/*
* Free items in the jumplist of window "wp".
*/
void
free_jumplist(wp)
win_T *wp;
{
int i;
for (i = 0; i < wp->w_jumplistlen; ++i)
vim_free(wp->w_jumplist[i].fname);
}
# endif
#endif /* FEAT_JUMPLIST */
void
set_last_cursor(win)
win_T *win;
{
win->w_buffer->b_last_cursor = win->w_cursor;
}
#if defined(EXITFREE) || defined(PROTO)
void
free_all_marks()
{
int i;
for (i = 0; i < NMARKS + EXTRA_MARKS; i++)
if (namedfm[i].fmark.mark.lnum != 0)
vim_free(namedfm[i].fname);
}
#endif
#if defined(FEAT_VIMINFO) || defined(PROTO)
int
read_viminfo_filemark(virp, force)
vir_T *virp;
int force;
{
char_u *str;
xfmark_T *fm;
int i;
/* We only get here if line[0] == '\'' or '-'.
* Illegal mark names are ignored (for future expansion). */
str = virp->vir_line + 1;
if (
#ifndef EBCDIC
*str <= 127 &&
#endif
((*virp->vir_line == '\'' && (VIM_ISDIGIT(*str) || isupper(*str)))
|| (*virp->vir_line == '-' && *str == '\'')))
{
if (*str == '\'')
{
#ifdef FEAT_JUMPLIST
/* If the jumplist isn't full insert fmark as oldest entry */
if (curwin->w_jumplistlen == JUMPLISTSIZE)
fm = NULL;
else
{
for (i = curwin->w_jumplistlen; i > 0; --i)
curwin->w_jumplist[i] = curwin->w_jumplist[i - 1];
++curwin->w_jumplistidx;
++curwin->w_jumplistlen;
fm = &curwin->w_jumplist[0];
fm->fmark.mark.lnum = 0;
fm->fname = NULL;
}
#else
fm = NULL;
#endif
}
else if (VIM_ISDIGIT(*str))
fm = &namedfm[*str - '0' + NMARKS];
else
fm = &namedfm[*str - 'A'];
if (fm != NULL && (fm->fmark.mark.lnum == 0 || force))
{
str = skipwhite(str + 1);
fm->fmark.mark.lnum = getdigits(&str);
str = skipwhite(str);
fm->fmark.mark.col = getdigits(&str);
#ifdef FEAT_VIRTUALEDIT
fm->fmark.mark.coladd = 0;
#endif
fm->fmark.fnum = 0;
str = skipwhite(str);
vim_free(fm->fname);
fm->fname = viminfo_readstring(virp, (int)(str - virp->vir_line),
FALSE);
}
}
return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
}
void
write_viminfo_filemarks(fp)
FILE *fp;
{
int i;
char_u *name;
buf_T *buf;
xfmark_T *fm;
if (get_viminfo_parameter('f') == 0)
return;
fputs(_("\n# File marks:\n"), fp);
/*
* Find a mark that is the same file and position as the cursor.
* That one, or else the last one is deleted.
* Move '0 to '1, '1 to '2, etc. until the matching one or '9
* Set '0 mark to current cursor position.
*/
if (curbuf->b_ffname != NULL && !removable(curbuf->b_ffname))
{
name = buflist_nr2name(curbuf->b_fnum, TRUE, FALSE);
for (i = NMARKS; i < NMARKS + EXTRA_MARKS - 1; ++i)
if (namedfm[i].fmark.mark.lnum == curwin->w_cursor.lnum
&& (namedfm[i].fname == NULL
? namedfm[i].fmark.fnum == curbuf->b_fnum
: (name != NULL
&& STRCMP(name, namedfm[i].fname) == 0)))
break;
vim_free(name);
vim_free(namedfm[i].fname);
for ( ; i > NMARKS; --i)
namedfm[i] = namedfm[i - 1];
namedfm[NMARKS].fmark.mark = curwin->w_cursor;
namedfm[NMARKS].fmark.fnum = curbuf->b_fnum;
namedfm[NMARKS].fname = NULL;
}
/* Write the filemarks '0 - '9 and 'A - 'Z */
for (i = 0; i < NMARKS + EXTRA_MARKS; i++)
write_one_filemark(fp, &namedfm[i], '\'',
i < NMARKS ? i + 'A' : i - NMARKS + '0');
#ifdef FEAT_JUMPLIST
/* Write the jumplist with -' */
fputs(_("\n# Jumplist (newest first):\n"), fp);
setpcmark(); /* add current cursor position */
cleanup_jumplist();
for (fm = &curwin->w_jumplist[curwin->w_jumplistlen - 1];
fm >= &curwin->w_jumplist[0]; --fm)
{
if (fm->fmark.fnum == 0
|| ((buf = buflist_findnr(fm->fmark.fnum)) != NULL
&& !removable(buf->b_ffname)))
write_one_filemark(fp, fm, '-', '\'');
}
#endif
}
static void
write_one_filemark(fp, fm, c1, c2)
FILE *fp;
xfmark_T *fm;
int c1;
int c2;
{
char_u *name;
if (fm->fmark.mark.lnum == 0) /* not set */
return;
if (fm->fmark.fnum != 0) /* there is a buffer */
name = buflist_nr2name(fm->fmark.fnum, TRUE, FALSE);
else
name = fm->fname; /* use name from .viminfo */
if (name != NULL && *name != NUL)
{
fprintf(fp, "%c%c %ld %ld ", c1, c2, (long)fm->fmark.mark.lnum,
(long)fm->fmark.mark.col);
viminfo_writestring(fp, name);
}
if (fm->fmark.fnum != 0)
vim_free(name);
}
/*
* Return TRUE if "name" is on removable media (depending on 'viminfo').
*/
int
removable(name)
char_u *name;
{
char_u *p;
char_u part[51];
int retval = FALSE;
size_t n;
name = home_replace_save(NULL, name);
if (name != NULL)
{
for (p = p_viminfo; *p; )
{
copy_option_part(&p, part, 51, ", ");
if (part[0] == 'r')
{
n = STRLEN(part + 1);
if (MB_STRNICMP(part + 1, name, n) == 0)
{
retval = TRUE;
break;
}
}
}
vim_free(name);
}
return retval;
}
static void write_one_mark __ARGS((FILE *fp_out, int c, pos_T *pos));
/*
* Write all the named marks for all buffers.
* Return the number of buffers for which marks have been written.
*/
int
write_viminfo_marks(fp_out)
FILE *fp_out;
{
int count;
buf_T *buf;
int is_mark_set;
int i;
#ifdef FEAT_WINDOWS
win_T *win;
tabpage_T *tp;
/*
* Set b_last_cursor for the all buffers that have a window.
*/
FOR_ALL_TAB_WINDOWS(tp, win)
set_last_cursor(win);
#else
set_last_cursor(curwin);
#endif
fputs(_("\n# History of marks within files (newest to oldest):\n"), fp_out);
count = 0;
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
{
/*
* Only write something if buffer has been loaded and at least one
* mark is set.
*/
if (buf->b_marks_read)
{
if (buf->b_last_cursor.lnum != 0)
is_mark_set = TRUE;
else
{
is_mark_set = FALSE;
for (i = 0; i < NMARKS; i++)
if (buf->b_namedm[i].lnum != 0)
{
is_mark_set = TRUE;
break;
}
}
if (is_mark_set && buf->b_ffname != NULL
&& buf->b_ffname[0] != NUL && !removable(buf->b_ffname))
{
home_replace(NULL, buf->b_ffname, IObuff, IOSIZE, TRUE);
fprintf(fp_out, "\n> ");
viminfo_writestring(fp_out, IObuff);
write_one_mark(fp_out, '"', &buf->b_last_cursor);
write_one_mark(fp_out, '^', &buf->b_last_insert);
write_one_mark(fp_out, '.', &buf->b_last_change);
#ifdef FEAT_JUMPLIST
/* changelist positions are stored oldest first */
for (i = 0; i < buf->b_changelistlen; ++i)
write_one_mark(fp_out, '+', &buf->b_changelist[i]);
#endif
for (i = 0; i < NMARKS; i++)
write_one_mark(fp_out, 'a' + i, &buf->b_namedm[i]);
count++;
}
}
}
return count;
}
static void
write_one_mark(fp_out, c, pos)
FILE *fp_out;
int c;
pos_T *pos;
{
if (pos->lnum != 0)
fprintf(fp_out, "\t%c\t%ld\t%d\n", c, (long)pos->lnum, (int)pos->col);
}
/*
* Handle marks in the viminfo file:
* fp_out != NULL: copy marks for buffers not in buffer list
* fp_out == NULL && (flags & VIF_WANT_MARKS): read marks for curbuf only
* fp_out == NULL && (flags & VIF_GET_OLDFILES | VIF_FORCEIT): fill v:oldfiles
*/
void
copy_viminfo_marks(virp, fp_out, count, eof, flags)
vir_T *virp;
FILE *fp_out;
int count;
int eof;
int flags;
{
char_u *line = virp->vir_line;
buf_T *buf;
int num_marked_files;
int load_marks;
int copy_marks_out;
char_u *str;
int i;
char_u *p;
char_u *name_buf;
pos_T pos;
#ifdef FEAT_EVAL
list_T *list = NULL;
#endif
if ((name_buf = alloc(LSIZE)) == NULL)
return;
*name_buf = NUL;
#ifdef FEAT_EVAL
if (fp_out == NULL && (flags & (VIF_GET_OLDFILES | VIF_FORCEIT)))
{
list = list_alloc();
if (list != NULL)
set_vim_var_list(VV_OLDFILES, list);
}
#endif
num_marked_files = get_viminfo_parameter('\'');
while (!eof && (count < num_marked_files || fp_out == NULL))
{
if (line[0] != '>')
{
if (line[0] != '\n' && line[0] != '\r' && line[0] != '#')
{
if (viminfo_error("E576: ", _("Missing '>'"), line))
break; /* too many errors, return now */
}
eof = vim_fgets(line, LSIZE, virp->vir_fd);
continue; /* Skip this dud line */
}
/*
* Handle long line and translate escaped characters.
* Find file name, set str to start.
* Ignore leading and trailing white space.
*/
str = skipwhite(line + 1);
str = viminfo_readstring(virp, (int)(str - virp->vir_line), FALSE);
if (str == NULL)
continue;
p = str + STRLEN(str);
while (p != str && (*p == NUL || vim_isspace(*p)))
p--;
if (*p)
p++;
*p = NUL;
#ifdef FEAT_EVAL
if (list != NULL)
list_append_string(list, str, -1);
#endif
/*
* If fp_out == NULL, load marks for current buffer.
* If fp_out != NULL, copy marks for buffers not in buflist.
*/
load_marks = copy_marks_out = FALSE;
if (fp_out == NULL)
{
if ((flags & VIF_WANT_MARKS) && curbuf->b_ffname != NULL)
{
if (*name_buf == NUL) /* only need to do this once */
home_replace(NULL, curbuf->b_ffname, name_buf, LSIZE, TRUE);
if (fnamecmp(str, name_buf) == 0)
load_marks = TRUE;
}
}
else /* fp_out != NULL */
{
/* This is slow if there are many buffers!! */
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if (buf->b_ffname != NULL)
{
home_replace(NULL, buf->b_ffname, name_buf, LSIZE, TRUE);
if (fnamecmp(str, name_buf) == 0)
break;
}
/*
* copy marks if the buffer has not been loaded
*/
if (buf == NULL || !buf->b_marks_read)
{
copy_marks_out = TRUE;
fputs("\n> ", fp_out);
viminfo_writestring(fp_out, str);
count++;
}
}
vim_free(str);
#ifdef FEAT_VIRTUALEDIT
pos.coladd = 0;
#endif
while (!(eof = viminfo_readline(virp)) && line[0] == TAB)
{
if (load_marks)
{
if (line[1] != NUL)
{
unsigned u;
sscanf((char *)line + 2, "%ld %u", &pos.lnum, &u);
pos.col = u;
switch (line[1])
{
case '"': curbuf->b_last_cursor = pos; break;
case '^': curbuf->b_last_insert = pos; break;
case '.': curbuf->b_last_change = pos; break;
case '+':
#ifdef FEAT_JUMPLIST
/* changelist positions are stored oldest
* first */
if (curbuf->b_changelistlen == JUMPLISTSIZE)
/* list is full, remove oldest entry */
mch_memmove(curbuf->b_changelist,
curbuf->b_changelist + 1,
sizeof(pos_T) * (JUMPLISTSIZE - 1));
else
++curbuf->b_changelistlen;
curbuf->b_changelist[
curbuf->b_changelistlen - 1] = pos;
#endif
break;
default: if ((i = line[1] - 'a') >= 0 && i < NMARKS)
curbuf->b_namedm[i] = pos;
}
}
}
else if (copy_marks_out)
fputs((char *)line, fp_out);
}
if (load_marks)
{
#ifdef FEAT_JUMPLIST
win_T *wp;
FOR_ALL_WINDOWS(wp)
{
if (wp->w_buffer == curbuf)
wp->w_changelistidx = curbuf->b_changelistlen;
}
#endif
break;
}
}
vim_free(name_buf);
}
#endif /* FEAT_VIMINFO */
| zyz2011-vim | src/mark.c | C | gpl2 | 43,230 |
/* 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.
*/
/*
* Define the version number, name, etc.
* The patchlevel is in included_patches[], in version.c.
*
* This doesn't use string concatenation, some compilers don't support it.
*/
#define VIM_VERSION_MAJOR 7
#define VIM_VERSION_MAJOR_STR "7"
#define VIM_VERSION_MINOR 3
#define VIM_VERSION_MINOR_STR "3"
#define VIM_VERSION_100 (VIM_VERSION_MAJOR * 100 + VIM_VERSION_MINOR)
#define VIM_VERSION_BUILD 277
#define VIM_VERSION_BUILD_BCD 0x115
#define VIM_VERSION_BUILD_STR "277"
#define VIM_VERSION_PATCHLEVEL 0
#define VIM_VERSION_PATCHLEVEL_STR "0"
/* Used by MacOS port should be one of: development, alpha, beta, final */
#define VIM_VERSION_RELEASE final
/*
* VIM_VERSION_NODOT is used for the runtime directory name.
* VIM_VERSION_SHORT is copied into the swap file (max. length is 6 chars).
* VIM_VERSION_MEDIUM is used for the startup-screen.
* VIM_VERSION_LONG is used for the ":version" command and "Vim -h".
*/
#define VIM_VERSION_NODOT "vim73"
#define VIM_VERSION_SHORT "7.3"
#define VIM_VERSION_MEDIUM "7.3"
#define VIM_VERSION_LONG "VIM - Vi IMproved 7.3 (2010 Aug 15)"
#define VIM_VERSION_LONG_DATE "VIM - Vi IMproved 7.3 (2010 Aug 15, compiled "
| zyz2011-vim | src/version.h | C | gpl2 | 1,403 |
# Python script to get both the data and resource fork from a BinHex encoded
# file.
# Author: Taro Muraoka
# Last Change: 2003 Oct 25
import sys
import binhex
input = sys.argv[1]
conv = binhex.HexBin(input)
info = conv.FInfo
out = conv.FName
out_data = out
out_rsrc = out + '.rsrcfork'
#print 'out_rsrc=' + out_rsrc
print 'In file: ' + input
outfile = open(out_data, 'wb')
print ' Out data fork: ' + out_data
while 1:
d = conv.read(128000)
if not d: break
outfile.write(d)
outfile.close()
conv.close_data()
d = conv.read_rsrc(128000)
if d:
print ' Out rsrc fork: ' + out_rsrc
outfile = open(out_rsrc, 'wb')
outfile.write(d)
while 1:
d = conv.read_rsrc(128000)
if not d: break
outfile.write(d)
outfile.close()
conv.close()
# vim:set ts=8 sts=4 sw=4 et:
| zyz2011-vim | src/dehqx.py | Python | gpl2 | 817 |
/* 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.
*/
/*
* Porting to GTK+ was done by:
*
* (C) 1998,1999,2000 by Marcin Dalecki <martin@dalecki.de>
*
* With GREAT support and continuous encouragements by Andy Kahn and of
* course Bram Moolenaar!
*
* Support for GTK+ 2 was added by:
*
* (C) 2002,2003 Jason Hildebrand <jason@peaceworks.ca>
* Daniel Elstner <daniel.elstner@gmx.net>
*/
#include "vim.h"
#ifdef FEAT_GUI_GNOME
/* Gnome redefines _() and N_(). Grrr... */
# ifdef _
# undef _
# endif
# ifdef N_
# undef N_
# endif
# ifdef textdomain
# undef textdomain
# endif
# ifdef bindtextdomain
# undef bindtextdomain
# endif
# ifdef bind_textdomain_codeset
# undef bind_textdomain_codeset
# endif
# if defined(FEAT_GETTEXT) && !defined(ENABLE_NLS)
# define ENABLE_NLS /* so the texts in the dialog boxes are translated */
# endif
# include <gnome.h>
# include "version.h"
/* missing prototype in bonobo-dock-item.h */
extern void bonobo_dock_item_set_behavior(BonoboDockItem *dock_item, BonoboDockItemBehavior beh);
#endif
#if !defined(FEAT_GUI_GTK) && defined(PROTO)
/* When generating prototypes we don't want syntax errors. */
# define GdkAtom int
# define GdkEventExpose int
# define GdkEventFocus int
# define GdkEventVisibility int
# define GdkEventProperty int
# define GtkContainer int
# define GtkTargetEntry int
# define GtkType int
# define GtkWidget int
# define gint int
# define gpointer int
# define guint int
# define GdkEventKey int
# define GdkEventSelection int
# define GtkSelectionData int
# define GdkEventMotion int
# define GdkEventButton int
# define GdkDragContext int
# define GdkEventConfigure int
# define GdkEventClient int
#else
# include <gdk/gdkkeysyms.h>
# include <gdk/gdk.h>
# ifdef WIN3264
# include <gdk/gdkwin32.h>
# else
# include <gdk/gdkx.h>
# endif
# include <gtk/gtk.h>
# include "gui_gtk_f.h"
#endif
#ifdef HAVE_X11_SUNKEYSYM_H
# include <X11/Sunkeysym.h>
#endif
/*
* Easy-to-use macro for multihead support.
*/
#ifdef HAVE_GTK_MULTIHEAD
# define GET_X_ATOM(atom) gdk_x11_atom_to_xatom_for_display( \
gtk_widget_get_display(gui.mainwin), atom)
#else
# define GET_X_ATOM(atom) ((Atom)(atom))
#endif
/* Selection type distinguishers */
enum
{
TARGET_TYPE_NONE,
TARGET_UTF8_STRING,
TARGET_STRING,
TARGET_COMPOUND_TEXT,
TARGET_HTML,
TARGET_TEXT,
TARGET_TEXT_URI_LIST,
TARGET_TEXT_PLAIN,
TARGET_VIM,
TARGET_VIMENC
};
/*
* Table of selection targets supported by Vim.
* Note: Order matters, preferred types should come first.
*/
static const GtkTargetEntry selection_targets[] =
{
{VIMENC_ATOM_NAME, 0, TARGET_VIMENC},
{VIM_ATOM_NAME, 0, TARGET_VIM},
{"text/html", 0, TARGET_HTML},
{"UTF8_STRING", 0, TARGET_UTF8_STRING},
{"COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT},
{"TEXT", 0, TARGET_TEXT},
{"STRING", 0, TARGET_STRING}
};
#define N_SELECTION_TARGETS (sizeof(selection_targets) / sizeof(selection_targets[0]))
#ifdef FEAT_DND
/*
* Table of DnD targets supported by Vim.
* Note: Order matters, preferred types should come first.
*/
static const GtkTargetEntry dnd_targets[] =
{
{"text/uri-list", 0, TARGET_TEXT_URI_LIST},
{"text/html", 0, TARGET_HTML},
{"UTF8_STRING", 0, TARGET_UTF8_STRING},
{"STRING", 0, TARGET_STRING},
{"text/plain", 0, TARGET_TEXT_PLAIN}
};
# define N_DND_TARGETS (sizeof(dnd_targets) / sizeof(dnd_targets[0]))
#endif
/*
* "Monospace" is a standard font alias that should be present
* on all proper Pango/fontconfig installations.
*/
# define DEFAULT_FONT "Monospace 10"
#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
/*
* Atoms used to communicate save-yourself from the X11 session manager. There
* is no need to move them into the GUI struct, since they should be constant.
*/
static GdkAtom wm_protocols_atom = GDK_NONE;
static GdkAtom save_yourself_atom = GDK_NONE;
#endif
/*
* Atoms used to control/reference X11 selections.
*/
static GdkAtom html_atom = GDK_NONE;
static GdkAtom utf8_string_atom = GDK_NONE;
static GdkAtom vim_atom = GDK_NONE; /* Vim's own special selection format */
static GdkAtom vimenc_atom = GDK_NONE; /* Vim's extended selection format */
/*
* Keycodes recognized by vim.
* NOTE: when changing this, the table in gui_x11.c probably needs the same
* change!
*/
static struct special_key
{
guint key_sym;
char_u code0;
char_u code1;
}
const special_keys[] =
{
{GDK_Up, 'k', 'u'},
{GDK_Down, 'k', 'd'},
{GDK_Left, 'k', 'l'},
{GDK_Right, 'k', 'r'},
{GDK_F1, 'k', '1'},
{GDK_F2, 'k', '2'},
{GDK_F3, 'k', '3'},
{GDK_F4, 'k', '4'},
{GDK_F5, 'k', '5'},
{GDK_F6, 'k', '6'},
{GDK_F7, 'k', '7'},
{GDK_F8, 'k', '8'},
{GDK_F9, 'k', '9'},
{GDK_F10, 'k', ';'},
{GDK_F11, 'F', '1'},
{GDK_F12, 'F', '2'},
{GDK_F13, 'F', '3'},
{GDK_F14, 'F', '4'},
{GDK_F15, 'F', '5'},
{GDK_F16, 'F', '6'},
{GDK_F17, 'F', '7'},
{GDK_F18, 'F', '8'},
{GDK_F19, 'F', '9'},
{GDK_F20, 'F', 'A'},
{GDK_F21, 'F', 'B'},
{GDK_Pause, 'F', 'B'}, /* Pause == F21 according to netbeans.txt */
{GDK_F22, 'F', 'C'},
{GDK_F23, 'F', 'D'},
{GDK_F24, 'F', 'E'},
{GDK_F25, 'F', 'F'},
{GDK_F26, 'F', 'G'},
{GDK_F27, 'F', 'H'},
{GDK_F28, 'F', 'I'},
{GDK_F29, 'F', 'J'},
{GDK_F30, 'F', 'K'},
{GDK_F31, 'F', 'L'},
{GDK_F32, 'F', 'M'},
{GDK_F33, 'F', 'N'},
{GDK_F34, 'F', 'O'},
{GDK_F35, 'F', 'P'},
#ifdef SunXK_F36
{SunXK_F36, 'F', 'Q'},
{SunXK_F37, 'F', 'R'},
#endif
{GDK_Help, '%', '1'},
{GDK_Undo, '&', '8'},
{GDK_BackSpace, 'k', 'b'},
{GDK_Insert, 'k', 'I'},
{GDK_Delete, 'k', 'D'},
{GDK_3270_BackTab, 'k', 'B'},
{GDK_Clear, 'k', 'C'},
{GDK_Home, 'k', 'h'},
{GDK_End, '@', '7'},
{GDK_Prior, 'k', 'P'},
{GDK_Next, 'k', 'N'},
{GDK_Print, '%', '9'},
/* Keypad keys: */
{GDK_KP_Left, 'k', 'l'},
{GDK_KP_Right, 'k', 'r'},
{GDK_KP_Up, 'k', 'u'},
{GDK_KP_Down, 'k', 'd'},
{GDK_KP_Insert, KS_EXTRA, (char_u)KE_KINS},
{GDK_KP_Delete, KS_EXTRA, (char_u)KE_KDEL},
{GDK_KP_Home, 'K', '1'},
{GDK_KP_End, 'K', '4'},
{GDK_KP_Prior, 'K', '3'}, /* page up */
{GDK_KP_Next, 'K', '5'}, /* page down */
{GDK_KP_Add, 'K', '6'},
{GDK_KP_Subtract, 'K', '7'},
{GDK_KP_Divide, 'K', '8'},
{GDK_KP_Multiply, 'K', '9'},
{GDK_KP_Enter, 'K', 'A'},
{GDK_KP_Decimal, 'K', 'B'},
{GDK_KP_0, 'K', 'C'},
{GDK_KP_1, 'K', 'D'},
{GDK_KP_2, 'K', 'E'},
{GDK_KP_3, 'K', 'F'},
{GDK_KP_4, 'K', 'G'},
{GDK_KP_5, 'K', 'H'},
{GDK_KP_6, 'K', 'I'},
{GDK_KP_7, 'K', 'J'},
{GDK_KP_8, 'K', 'K'},
{GDK_KP_9, 'K', 'L'},
/* End of list marker: */
{0, 0, 0}
};
/*
* Flags for command line options table below.
*/
#define ARG_FONT 1
#define ARG_GEOMETRY 2
#define ARG_REVERSE 3
#define ARG_NOREVERSE 4
#define ARG_BACKGROUND 5
#define ARG_FOREGROUND 6
#define ARG_ICONIC 7
#define ARG_ROLE 8
#define ARG_NETBEANS 9
#define ARG_XRM 10 /* ignored */
#define ARG_MENUFONT 11 /* ignored */
#define ARG_INDEX_MASK 0x00ff
#define ARG_HAS_VALUE 0x0100 /* a value is expected after the argument */
#define ARG_NEEDS_GUI 0x0200 /* need to initialize the GUI for this */
#define ARG_FOR_GTK 0x0400 /* argument is handled by GTK+ or GNOME */
#define ARG_COMPAT_LONG 0x0800 /* accept -foo but substitute with --foo */
#define ARG_KEEP 0x1000 /* don't remove argument from argv[] */
/*
* This table holds all the X GUI command line options allowed. This includes
* the standard ones so that we can skip them when Vim is started without the
* GUI (but the GUI might start up later).
*
* When changing this, also update doc/gui_x11.txt and the usage message!!!
*/
typedef struct
{
const char *name;
unsigned int flags;
}
cmdline_option_T;
static const cmdline_option_T cmdline_options[] =
{
/* We handle these options ourselves */
{"-fn", ARG_FONT|ARG_HAS_VALUE},
{"-font", ARG_FONT|ARG_HAS_VALUE},
{"-geom", ARG_GEOMETRY|ARG_HAS_VALUE},
{"-geometry", ARG_GEOMETRY|ARG_HAS_VALUE},
{"-rv", ARG_REVERSE},
{"-reverse", ARG_REVERSE},
{"+rv", ARG_NOREVERSE},
{"+reverse", ARG_NOREVERSE},
{"-bg", ARG_BACKGROUND|ARG_HAS_VALUE},
{"-background", ARG_BACKGROUND|ARG_HAS_VALUE},
{"-fg", ARG_FOREGROUND|ARG_HAS_VALUE},
{"-foreground", ARG_FOREGROUND|ARG_HAS_VALUE},
{"-iconic", ARG_ICONIC},
{"--role", ARG_ROLE|ARG_HAS_VALUE},
#ifdef FEAT_NETBEANS_INTG
{"-nb", ARG_NETBEANS}, /* non-standard value format */
{"-xrm", ARG_XRM|ARG_HAS_VALUE}, /* not implemented */
{"-mf", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
{"-menufont", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
#endif
/* Arguments handled by GTK (and GNOME) internally. */
{"--g-fatal-warnings", ARG_FOR_GTK},
{"--gdk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gdk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gtk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gtk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gtk-module", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--sync", ARG_FOR_GTK},
{"--display", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
{"--name", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
{"--class", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
{"--screen", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gxid-host", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--gxid-port", ARG_FOR_GTK|ARG_HAS_VALUE},
#ifdef FEAT_GUI_GNOME
{"--load-modules", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--sm-client-id", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--sm-config-prefix", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--sm-disable", ARG_FOR_GTK},
{"--oaf-ior-fd", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--oaf-activate-iid", ARG_FOR_GTK|ARG_HAS_VALUE},
{"--oaf-private", ARG_FOR_GTK},
{"--enable-sound", ARG_FOR_GTK},
{"--disable-sound", ARG_FOR_GTK},
{"--espeaker", ARG_FOR_GTK|ARG_HAS_VALUE},
{"-?", ARG_FOR_GTK|ARG_NEEDS_GUI},
{"--help", ARG_FOR_GTK|ARG_NEEDS_GUI|ARG_KEEP},
{"--usage", ARG_FOR_GTK|ARG_NEEDS_GUI},
# if 0 /* conflicts with Vim's own --version argument */
{"--version", ARG_FOR_GTK|ARG_NEEDS_GUI},
# endif
{"--disable-crash-dialog", ARG_FOR_GTK},
#endif
{NULL, 0}
};
static int gui_argc = 0;
static char **gui_argv = NULL;
static const char *role_argument = NULL;
#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
static const char *restart_command = NULL;
static char *abs_restart_command = NULL;
#endif
static int found_iconic_arg = FALSE;
#ifdef FEAT_GUI_GNOME
/*
* Can't use Gnome if --socketid given
*/
static int using_gnome = 0;
#else
# define using_gnome 0
#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)
{
const cmdline_option_T *option;
int i = 0;
int len = 0;
#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
/*
* Determine the command used to invoke Vim, to be passed as restart
* command to the session manager. If argv[0] contains any directory
* components try building an absolute path, otherwise leave it as is.
*/
restart_command = argv[0];
if (strchr(argv[0], G_DIR_SEPARATOR) != NULL)
{
char_u buf[MAXPATHL];
if (mch_FullName((char_u *)argv[0], buf, (int)sizeof(buf), TRUE) == OK)
{
abs_restart_command = (char *)vim_strsave(buf);
restart_command = abs_restart_command;
}
}
#endif
/*
* Move all the entries in argv which are relevant to GTK+ and GNOME
* into gui_argv. Freed later in gui_mch_init().
*/
gui_argc = 0;
gui_argv = (char **)alloc((unsigned)((*argc + 1) * sizeof(char *)));
g_return_if_fail(gui_argv != NULL);
gui_argv[gui_argc++] = argv[i++];
while (i < *argc)
{
/* Don't waste CPU cycles on non-option arguments. */
if (argv[i][0] != '-' && argv[i][0] != '+')
{
++i;
continue;
}
/* Look for argv[i] in cmdline_options[] table. */
for (option = &cmdline_options[0]; option->name != NULL; ++option)
{
len = strlen(option->name);
if (strncmp(argv[i], option->name, len) == 0)
{
if (argv[i][len] == '\0')
break;
/* allow --foo=bar style */
if (argv[i][len] == '=' && (option->flags & ARG_HAS_VALUE))
break;
#ifdef FEAT_NETBEANS_INTG
/* darn, -nb has non-standard syntax */
if (vim_strchr((char_u *)":=", argv[i][len]) != NULL
&& (option->flags & ARG_INDEX_MASK) == ARG_NETBEANS)
break;
#endif
}
else if ((option->flags & ARG_COMPAT_LONG)
&& strcmp(argv[i], option->name + 1) == 0)
{
/* Replace the standard X arguments "-name" and "-display"
* with their GNU-style long option counterparts. */
argv[i] = (char *)option->name;
break;
}
}
if (option->name == NULL) /* no match */
{
++i;
continue;
}
if (option->flags & ARG_FOR_GTK)
{
/* Move the argument into gui_argv, which
* will later be passed to gtk_init_check() */
gui_argv[gui_argc++] = argv[i];
}
else
{
char *value = NULL;
/* Extract the option's value if there is one.
* Accept both "--foo bar" and "--foo=bar" style. */
if (option->flags & ARG_HAS_VALUE)
{
if (argv[i][len] == '=')
value = &argv[i][len + 1];
else if (i + 1 < *argc && strcmp(argv[i + 1], "--") != 0)
value = argv[i + 1];
}
/* Check for options handled by Vim itself */
switch (option->flags & ARG_INDEX_MASK)
{
case ARG_REVERSE:
found_reverse_arg = TRUE;
break;
case ARG_NOREVERSE:
found_reverse_arg = FALSE;
break;
case ARG_FONT:
font_argument = value;
break;
case ARG_GEOMETRY:
if (value != NULL)
gui.geom = vim_strsave((char_u *)value);
break;
case ARG_BACKGROUND:
background_argument = value;
break;
case ARG_FOREGROUND:
foreground_argument = value;
break;
case ARG_ICONIC:
found_iconic_arg = TRUE;
break;
case ARG_ROLE:
role_argument = value; /* used later in gui_mch_open() */
break;
#ifdef FEAT_NETBEANS_INTG
case ARG_NETBEANS:
gui.dofork = FALSE; /* don't fork() when starting GUI */
netbeansArg = argv[i];
break;
#endif
default:
break;
}
}
/* These arguments make gnome_program_init() print a message and exit.
* Must start the GUI for this, otherwise ":gui" will exit later! */
if (option->flags & ARG_NEEDS_GUI)
gui.starting = TRUE;
if (option->flags & ARG_KEEP)
++i;
else
{
/* Remove the flag from the argument vector. */
if (--*argc > i)
{
int n_strip = 1;
/* Move the argument's value as well, if there is one. */
if ((option->flags & ARG_HAS_VALUE)
&& argv[i][len] != '='
&& strcmp(argv[i + 1], "--") != 0)
{
++n_strip;
--*argc;
if (option->flags & ARG_FOR_GTK)
gui_argv[gui_argc++] = argv[i + 1];
}
if (*argc > i)
mch_memmove(&argv[i], &argv[i + n_strip],
(*argc - i) * sizeof(char *));
}
argv[*argc] = NULL;
}
}
gui_argv[gui_argc] = NULL;
}
#if defined(EXITFREE) || defined(PROTO)
void
gui_mch_free_all()
{
vim_free(gui_argv);
#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
vim_free(abs_restart_command);
#endif
}
#endif
/*
* This should be maybe completely removed.
* Doesn't seem possible, since check_copy_area() relies on
* this information. --danielk
*/
static gint
visibility_event(GtkWidget *widget UNUSED,
GdkEventVisibility *event,
gpointer data UNUSED)
{
gui.visibility = event->state;
/*
* When we do an gdk_window_copy_area(), and the window is partially
* obscured, we want to receive an event to tell us whether it worked
* or not.
*/
if (gui.text_gc != NULL)
gdk_gc_set_exposures(gui.text_gc,
gui.visibility != GDK_VISIBILITY_UNOBSCURED);
return FALSE;
}
/*
* Redraw the corresponding portions of the screen.
*/
static gint
expose_event(GtkWidget *widget UNUSED,
GdkEventExpose *event,
gpointer data UNUSED)
{
/* Skip this when the GUI isn't set up yet, will redraw later. */
if (gui.starting)
return FALSE;
out_flush(); /* make sure all output has been processed */
gui_redraw(event->area.x, event->area.y,
event->area.width, event->area.height);
/* Clear the border areas if needed */
if (event->area.x < FILL_X(0))
gdk_window_clear_area(gui.drawarea->window, 0, 0, FILL_X(0), 0);
if (event->area.y < FILL_Y(0))
gdk_window_clear_area(gui.drawarea->window, 0, 0, 0, FILL_Y(0));
if (event->area.x > FILL_X(Columns))
gdk_window_clear_area(gui.drawarea->window,
FILL_X((int)Columns), 0, 0, 0);
if (event->area.y > FILL_Y(Rows))
gdk_window_clear_area(gui.drawarea->window, 0, FILL_Y((int)Rows), 0, 0);
return FALSE;
}
#ifdef FEAT_CLIENTSERVER
/*
* Handle changes to the "Comm" property
*/
static gint
property_event(GtkWidget *widget,
GdkEventProperty *event,
gpointer data UNUSED)
{
if (event->type == GDK_PROPERTY_NOTIFY
&& event->state == (int)GDK_PROPERTY_NEW_VALUE
&& GDK_WINDOW_XWINDOW(event->window) == commWindow
&& GET_X_ATOM(event->atom) == commProperty)
{
XEvent xev;
/* Translate to XLib */
xev.xproperty.type = PropertyNotify;
xev.xproperty.atom = commProperty;
xev.xproperty.window = commWindow;
xev.xproperty.state = PropertyNewValue;
serverEventProc(GDK_WINDOW_XDISPLAY(widget->window), &xev);
}
return FALSE;
}
#endif
/****************************************************************************
* Focus handlers:
*/
/*
* 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 guint blink_timer = 0;
void
gui_mch_set_blinking(long waittime, long on, long off)
{
blink_waittime = waittime;
blink_ontime = on;
blink_offtime = off;
}
/*
* Stop the cursor blinking. Show the cursor if it wasn't shown.
*/
void
gui_mch_stop_blink(void)
{
if (blink_timer)
{
gtk_timeout_remove(blink_timer);
blink_timer = 0;
}
if (blink_state == BLINK_OFF)
gui_update_cursor(TRUE, FALSE);
blink_state = BLINK_NONE;
}
static gint
blink_cb(gpointer data UNUSED)
{
if (blink_state == BLINK_ON)
{
gui_undraw_cursor();
blink_state = BLINK_OFF;
blink_timer = gtk_timeout_add((guint32)blink_offtime,
(GtkFunction) blink_cb, NULL);
}
else
{
gui_update_cursor(TRUE, FALSE);
blink_state = BLINK_ON;
blink_timer = gtk_timeout_add((guint32)blink_ontime,
(GtkFunction) blink_cb, NULL);
}
return FALSE; /* don't happen again */
}
/*
* Start the cursor blinking. If it was already blinking, this restarts the
* waiting time and shows the cursor.
*/
void
gui_mch_start_blink(void)
{
if (blink_timer)
gtk_timeout_remove(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 = gtk_timeout_add((guint32)blink_waittime,
(GtkFunction) blink_cb, NULL);
blink_state = BLINK_ON;
gui_update_cursor(TRUE, FALSE);
}
}
static gint
enter_notify_event(GtkWidget *widget UNUSED,
GdkEventCrossing *event UNUSED,
gpointer data UNUSED)
{
if (blink_state == BLINK_NONE)
gui_mch_start_blink();
/* make sure keyboard input goes there */
if (gtk_socket_id == 0 || !GTK_WIDGET_HAS_FOCUS(gui.drawarea))
gtk_widget_grab_focus(gui.drawarea);
return FALSE;
}
static gint
leave_notify_event(GtkWidget *widget UNUSED,
GdkEventCrossing *event UNUSED,
gpointer data UNUSED)
{
if (blink_state != BLINK_NONE)
gui_mch_stop_blink();
return FALSE;
}
static gint
focus_in_event(GtkWidget *widget,
GdkEventFocus *event UNUSED,
gpointer data UNUSED)
{
gui_focus_change(TRUE);
if (blink_state == BLINK_NONE)
gui_mch_start_blink();
/* make sure keyboard input goes to the draw area (if this is focus for a
* window) */
if (widget != gui.drawarea)
gtk_widget_grab_focus(gui.drawarea);
return TRUE;
}
static gint
focus_out_event(GtkWidget *widget UNUSED,
GdkEventFocus *event UNUSED,
gpointer data UNUSED)
{
gui_focus_change(FALSE);
if (blink_state != BLINK_NONE)
gui_mch_stop_blink();
return TRUE;
}
/*
* Translate a GDK key value to UTF-8 independently of the current locale.
* The output is written to string, which must have room for at least 6 bytes
* plus the NUL terminator. Returns the length in bytes.
*
* This function is used in the GTK+ 2 GUI only. The GTK+ 1 code makes use
* of GdkEventKey::string instead. But event->string is evil; see here why:
* http://developer.gnome.org/doc/API/2.0/gdk/gdk-Event-Structures.html#GdkEventKey
*/
static int
keyval_to_string(unsigned int keyval, unsigned int state, char_u *string)
{
int len;
guint32 uc;
uc = gdk_keyval_to_unicode(keyval);
if (uc != 0)
{
/* Check for CTRL-foo */
if ((state & GDK_CONTROL_MASK) && uc >= 0x20 && uc < 0x80)
{
/* These mappings look arbitrary at the first glance, but in fact
* resemble quite exactly the behaviour of the GTK+ 1.2 GUI on my
* machine. The only difference is BS vs. DEL for CTRL-8 (makes
* more sense and is consistent with usual terminal behaviour). */
if (uc >= '@')
string[0] = uc & 0x1F;
else if (uc == '2')
string[0] = NUL;
else if (uc >= '3' && uc <= '7')
string[0] = uc ^ 0x28;
else if (uc == '8')
string[0] = BS;
else if (uc == '?')
string[0] = DEL;
else
string[0] = uc;
len = 1;
}
else
{
/* Translate a normal key to UTF-8. This doesn't work for dead
* keys of course, you _have_ to use an input method for that. */
len = utf_char2bytes((int)uc, string);
}
}
else
{
/* Translate keys which are represented by ASCII control codes in Vim.
* There are only a few of those; most control keys are translated to
* special terminal-like control sequences. */
len = 1;
switch (keyval)
{
case GDK_Tab: case GDK_KP_Tab: case GDK_ISO_Left_Tab:
string[0] = TAB;
break;
case GDK_Linefeed:
string[0] = NL;
break;
case GDK_Return: case GDK_ISO_Enter: case GDK_3270_Enter:
string[0] = CAR;
break;
case GDK_Escape:
string[0] = ESC;
break;
default:
len = 0;
break;
}
}
string[len] = NUL;
return len;
}
static int
modifiers_gdk2vim(guint state)
{
int modifiers = 0;
if (state & GDK_SHIFT_MASK)
modifiers |= MOD_MASK_SHIFT;
if (state & GDK_CONTROL_MASK)
modifiers |= MOD_MASK_CTRL;
if (state & GDK_MOD1_MASK)
modifiers |= MOD_MASK_ALT;
#if GTK_CHECK_VERSION(2,10,0)
if (state & GDK_SUPER_MASK)
modifiers |= MOD_MASK_META;
#endif
if (state & GDK_MOD4_MASK)
modifiers |= MOD_MASK_META;
return modifiers;
}
static int
modifiers_gdk2mouse(guint state)
{
int modifiers = 0;
if (state & GDK_SHIFT_MASK)
modifiers |= MOUSE_SHIFT;
if (state & GDK_CONTROL_MASK)
modifiers |= MOUSE_CTRL;
if (state & GDK_MOD1_MASK)
modifiers |= MOUSE_ALT;
return modifiers;
}
/*
* Main keyboard handler:
*/
static gint
key_press_event(GtkWidget *widget UNUSED,
GdkEventKey *event,
gpointer data UNUSED)
{
/* For GTK+ 2 we know for sure how large the string might get.
* (That is, up to 6 bytes + NUL + CSI escapes + safety measure.) */
char_u string[32], string2[32];
guint key_sym;
int len;
int i;
int modifiers;
int key;
guint state;
char_u *s, *d;
gui.event_time = event->time;
key_sym = event->keyval;
state = event->state;
#ifdef FEAT_XIM
if (xim_queue_key_press_event(event, TRUE))
return TRUE;
#endif
#ifdef FEAT_HANGULIN
if (key_sym == GDK_space && (state & GDK_SHIFT_MASK))
{
hangul_input_state_toggle();
return TRUE;
}
#endif
#ifdef SunXK_F36
/*
* These keys have bogus lookup strings, and trapping them here is
* easier than trying to XRebindKeysym() on them with every possible
* combination of modifiers.
*/
if (key_sym == SunXK_F36 || key_sym == SunXK_F37)
len = 0;
else
#endif
{
len = keyval_to_string(key_sym, state, string2);
/* Careful: convert_input() doesn't handle the NUL character.
* No need to convert pure ASCII anyway, thus the len > 1 check. */
if (len > 1 && input_conv.vc_type != CONV_NONE)
len = convert_input(string2, len, sizeof(string2));
s = string2;
d = string;
for (i = 0; i < len; ++i)
{
*d++ = s[i];
if (d[-1] == CSI && d + 2 < string + sizeof(string))
{
/* Turn CSI into K_CSI. */
*d++ = KS_EXTRA;
*d++ = (int)KE_CSI;
}
}
len = d - string;
}
/* Shift-Tab results in Left_Tab, but we want <S-Tab> */
if (key_sym == GDK_ISO_Left_Tab)
{
key_sym = GDK_Tab;
state |= GDK_SHIFT_MASK;
}
#ifdef FEAT_MENU
/* If there is a menu and 'wak' is "yes", or 'wak' is "menu" and the key
* is a menu shortcut, we ignore everything with the ALT modifier. */
if ((state & GDK_MOD1_MASK)
&& gui.menu_is_active
&& (*p_wak == 'y'
|| (*p_wak == 'm'
&& len == 1
&& gui_is_menu_shortcut(string[0]))))
/* For GTK2 we return false to signify that we haven't handled the
* keypress, so that gtk will handle the mnemonic or accelerator. */
return FALSE;
#endif
/* Check for Alt/Meta key (Mod1Mask), but not for a BS, DEL or character
* that already has the 8th bit set.
* Don't do this for <S-M-Tab>, that should become K_S_TAB with ALT.
* Don't do this for double-byte encodings, it turns the char into a lead
* byte. */
if (len == 1
&& ((state & GDK_MOD1_MASK)
#if GTK_CHECK_VERSION(2,10,0)
|| (state & GDK_SUPER_MASK)
#endif
)
&& !(key_sym == GDK_BackSpace || key_sym == GDK_Delete)
&& (string[0] & 0x80) == 0
&& !(key_sym == GDK_Tab && (state & GDK_SHIFT_MASK))
&& !enc_dbcs
)
{
string[0] |= 0x80;
state &= ~GDK_MOD1_MASK; /* don't use it again */
if (enc_utf8) /* convert to utf-8 */
{
string[1] = string[0] & 0xbf;
string[0] = ((unsigned)string[0] >> 6) + 0xc0;
if (string[1] == CSI)
{
string[2] = KS_EXTRA;
string[3] = (int)KE_CSI;
len = 4;
}
else
len = 2;
}
}
/* Check for special keys. Also do this when len == 1 (key has an ASCII
* value) to detect backspace, delete and keypad keys. */
if (len == 0 || len == 1)
{
for (i = 0; special_keys[i].key_sym != 0; i++)
{
if (special_keys[i].key_sym == key_sym)
{
string[0] = CSI;
string[1] = special_keys[i].code0;
string[2] = special_keys[i].code1;
len = -3;
break;
}
}
}
if (len == 0) /* Unrecognized key */
return TRUE;
/* Special keys (and a few others) may have modifiers. Also when using a
* double-byte encoding (can't set the 8th bit). */
if (len == -3 || key_sym == GDK_space || key_sym == GDK_Tab
|| key_sym == GDK_Return || key_sym == GDK_Linefeed
|| key_sym == GDK_Escape || key_sym == GDK_KP_Tab
|| key_sym == GDK_ISO_Enter || key_sym == GDK_3270_Enter
|| (enc_dbcs && len == 1 && ((state & GDK_MOD1_MASK)
#if GTK_CHECK_VERSION(2,10,0)
|| (state & GDK_SUPER_MASK)
#endif
)))
{
modifiers = modifiers_gdk2vim(state);
/*
* For some keys a shift modifier is translated into another key
* code.
*/
if (len == -3)
key = TO_SPECIAL(string[1], string[2]);
else
key = string[0];
key = simplify_key(key, &modifiers);
if (key == CSI)
key = K_CSI;
if (IS_SPECIAL(key))
{
string[0] = CSI;
string[1] = K_SECOND(key);
string[2] = K_THIRD(key);
len = 3;
}
else
{
string[0] = key;
len = 1;
}
if (modifiers != 0)
{
string2[0] = CSI;
string2[1] = KS_MODIFIER;
string2[2] = modifiers;
add_to_input_buf(string2, 3);
}
}
if (len == 1 && ((string[0] == Ctrl_C && ctrl_c_interrupts)
|| (string[0] == intr_char && intr_char != Ctrl_C)))
{
trash_input_buf();
got_int = TRUE;
}
add_to_input_buf(string, len);
/* blank out the pointer if necessary */
if (p_mh)
gui_mch_mousehide(TRUE);
return TRUE;
}
#if defined(FEAT_XIM)
static gboolean
key_release_event(GtkWidget *widget UNUSED,
GdkEventKey *event,
gpointer data UNUSED)
{
gui.event_time = event->time;
/*
* GTK+ 2 input methods may do fancy stuff on key release events too.
* With the default IM for instance, you can enter any UCS code point
* by holding down CTRL-SHIFT and typing hexadecimal digits.
*/
return xim_queue_key_press_event(event, FALSE);
}
#endif
/****************************************************************************
* Selection handlers:
*/
static gint
selection_clear_event(GtkWidget *widget UNUSED,
GdkEventSelection *event,
gpointer user_data UNUSED)
{
if (event->selection == clip_plus.gtk_sel_atom)
clip_lose_selection(&clip_plus);
else
clip_lose_selection(&clip_star);
return TRUE;
}
#define RS_NONE 0 /* selection_received_cb() not called yet */
#define RS_OK 1 /* selection_received_cb() called and OK */
#define RS_FAIL 2 /* selection_received_cb() called and failed */
static int received_selection = RS_NONE;
static void
selection_received_cb(GtkWidget *widget UNUSED,
GtkSelectionData *data,
guint time_ UNUSED,
gpointer user_data UNUSED)
{
VimClipboard *cbd;
char_u *text;
char_u *tmpbuf = NULL;
guchar *tmpbuf_utf8 = NULL;
int len;
int motion_type = MAUTO;
if (data->selection == clip_plus.gtk_sel_atom)
cbd = &clip_plus;
else
cbd = &clip_star;
text = (char_u *)data->data;
len = data->length;
if (text == NULL || len <= 0)
{
received_selection = RS_FAIL;
/* clip_free_selection(cbd); ??? */
return;
}
if (data->type == vim_atom)
{
motion_type = *text++;
--len;
}
else if (data->type == vimenc_atom)
{
char_u *enc;
vimconv_T conv;
motion_type = *text++;
--len;
enc = text;
text += STRLEN(text) + 1;
len -= text - enc;
/* If the encoding of the text is different from 'encoding', attempt
* converting it. */
conv.vc_type = CONV_NONE;
convert_setup(&conv, enc, p_enc);
if (conv.vc_type != CONV_NONE)
{
tmpbuf = string_convert(&conv, text, &len);
if (tmpbuf != NULL)
text = tmpbuf;
convert_setup(&conv, NULL, NULL);
}
}
/* gtk_selection_data_get_text() handles all the nasty details
* and targets and encodings etc. This rocks so hard. */
else
{
tmpbuf_utf8 = gtk_selection_data_get_text(data);
if (tmpbuf_utf8 != NULL)
{
len = STRLEN(tmpbuf_utf8);
if (input_conv.vc_type != CONV_NONE)
{
tmpbuf = string_convert(&input_conv, tmpbuf_utf8, &len);
if (tmpbuf != NULL)
text = tmpbuf;
}
else
text = tmpbuf_utf8;
}
else if (len >= 2 && text[0] == 0xff && text[1] == 0xfe)
{
vimconv_T conv;
/* UTF-16, we get this for HTML */
conv.vc_type = CONV_NONE;
convert_setup_ext(&conv, (char_u *)"utf-16le", FALSE, p_enc, TRUE);
if (conv.vc_type != CONV_NONE)
{
text += 2;
len -= 2;
tmpbuf = string_convert(&conv, text, &len);
convert_setup(&conv, NULL, NULL);
}
if (tmpbuf != NULL)
text = tmpbuf;
}
}
/* Chop off any traiing NUL bytes. OpenOffice sends these. */
while (len > 0 && text[len - 1] == NUL)
--len;
clip_yank_selection(motion_type, text, (long)len, cbd);
received_selection = RS_OK;
vim_free(tmpbuf);
g_free(tmpbuf_utf8);
}
/*
* Prepare our selection data for passing it to the external selection
* client.
*/
static void
selection_get_cb(GtkWidget *widget UNUSED,
GtkSelectionData *selection_data,
guint info,
guint time_ UNUSED,
gpointer user_data UNUSED)
{
char_u *string;
char_u *tmpbuf;
long_u tmplen;
int length;
int motion_type;
GdkAtom type;
VimClipboard *cbd;
if (selection_data->selection == clip_plus.gtk_sel_atom)
cbd = &clip_plus;
else
cbd = &clip_star;
if (!cbd->owned)
return; /* Shouldn't ever happen */
if (info != (guint)TARGET_STRING
&& (!clip_html || info != (guint)TARGET_HTML)
&& info != (guint)TARGET_UTF8_STRING
&& info != (guint)TARGET_VIMENC
&& info != (guint)TARGET_VIM
&& info != (guint)TARGET_COMPOUND_TEXT
&& info != (guint)TARGET_TEXT)
return;
/* get the selection from the '*'/'+' register */
clip_get_selection(cbd);
motion_type = clip_convert_selection(&string, &tmplen, cbd);
if (motion_type < 0 || string == NULL)
return;
/* Due to int arguments we can't handle more than G_MAXINT. Also
* reserve one extra byte for NUL or the motion type; just in case.
* (Not that pasting 2G of text is ever going to work, but... ;-) */
length = MIN(tmplen, (long_u)(G_MAXINT - 1));
if (info == (guint)TARGET_VIM)
{
tmpbuf = alloc((unsigned)length + 1);
if (tmpbuf != NULL)
{
tmpbuf[0] = motion_type;
mch_memmove(tmpbuf + 1, string, (size_t)length);
}
/* For our own format, the first byte contains the motion type */
++length;
vim_free(string);
string = tmpbuf;
type = vim_atom;
}
else if (info == (guint)TARGET_HTML)
{
vimconv_T conv;
/* Since we get utf-16, we probably should set it as well. */
conv.vc_type = CONV_NONE;
convert_setup_ext(&conv, p_enc, TRUE, (char_u *)"utf-16le", FALSE);
if (conv.vc_type != CONV_NONE)
{
tmpbuf = string_convert(&conv, string, &length);
convert_setup(&conv, NULL, NULL);
vim_free(string);
string = tmpbuf;
}
/* Prepend the BOM: "fffe" */
if (string != NULL)
{
tmpbuf = alloc(length + 2);
tmpbuf[0] = 0xff;
tmpbuf[1] = 0xfe;
mch_memmove(tmpbuf + 2, string, (size_t)length);
vim_free(string);
string = tmpbuf;
length += 2;
selection_data->type = selection_data->target;
selection_data->format = 16; /* 16 bits per char */
gtk_selection_data_set(selection_data, html_atom, 16,
string, length);
vim_free(string);
}
return;
}
else if (info == (guint)TARGET_VIMENC)
{
int l = STRLEN(p_enc);
/* contents: motion_type 'encoding' NUL text */
tmpbuf = alloc((unsigned)length + l + 2);
if (tmpbuf != NULL)
{
tmpbuf[0] = motion_type;
STRCPY(tmpbuf + 1, p_enc);
mch_memmove(tmpbuf + l + 2, string, (size_t)length);
}
length += l + 2;
vim_free(string);
string = tmpbuf;
type = vimenc_atom;
}
/* gtk_selection_data_set_text() handles everything for us. This is
* so easy and simple and cool, it'd be insane not to use it. */
else
{
if (output_conv.vc_type != CONV_NONE)
{
tmpbuf = string_convert(&output_conv, string, &length);
vim_free(string);
if (tmpbuf == NULL)
return;
string = tmpbuf;
}
/* Validate the string to avoid runtime warnings */
if (g_utf8_validate((const char *)string, (gssize)length, NULL))
{
gtk_selection_data_set_text(selection_data,
(const char *)string, length);
}
vim_free(string);
return;
}
if (string != NULL)
{
selection_data->type = selection_data->target;
selection_data->format = 8; /* 8 bits per char */
gtk_selection_data_set(selection_data, type, 8, string, length);
vim_free(string);
}
}
/*
* Check if the GUI can be started. Called before gvimrc is sourced and
* before fork().
* Return OK or FAIL.
*/
int
gui_mch_early_init_check(void)
{
char_u *p;
/* Guess that when $DISPLAY isn't set the GUI can't start. */
p = mch_getenv((char_u *)"DISPLAY");
if (p == NULL || *p == NUL)
{
gui.dying = TRUE;
EMSG(_((char *)e_opendisp));
return FAIL;
}
return OK;
}
/*
* Check if the GUI can be started. Called before gvimrc is sourced but after
* fork().
* Return OK or FAIL.
*/
int
gui_mch_init_check(void)
{
#ifdef FEAT_GUI_GNOME
if (gtk_socket_id == 0)
using_gnome = 1;
#endif
/* Don't use gtk_init() or gnome_init(), it exits on failure. */
if (!gtk_init_check(&gui_argc, &gui_argv))
{
gui.dying = TRUE;
EMSG(_((char *)e_opendisp));
return FAIL;
}
return OK;
}
/****************************************************************************
* Mouse handling callbacks
*/
static guint mouse_click_timer = 0;
static int mouse_timed_out = TRUE;
/*
* Timer used to recognize multiple clicks of the mouse button
*/
static gint
mouse_click_timer_cb(gpointer data)
{
/* we don't use this information currently */
int *timed_out = (int *) data;
*timed_out = TRUE;
return FALSE; /* don't happen again */
}
static guint motion_repeat_timer = 0;
static int motion_repeat_offset = FALSE;
static gint motion_repeat_timer_cb(gpointer);
static void
process_motion_notify(int x, int y, GdkModifierType state)
{
int button;
int_u vim_modifiers;
button = (state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
GDK_BUTTON5_MASK))
? MOUSE_DRAG : ' ';
/* If our pointer is currently hidden, then we should show it. */
gui_mch_mousehide(FALSE);
/* Just moving the rodent above the drawing area without any button
* being pressed. */
if (button != MOUSE_DRAG)
{
gui_mouse_moved(x, y);
return;
}
/* translate modifier coding between the main engine and GTK */
vim_modifiers = modifiers_gdk2mouse(state);
/* inform the editor engine about the occurrence of this event */
gui_send_mouse_event(button, x, y, FALSE, vim_modifiers);
/*
* Auto repeat timer handling.
*/
if (x < 0 || y < 0
|| x >= gui.drawarea->allocation.width
|| y >= gui.drawarea->allocation.height)
{
int dx;
int dy;
int offshoot;
int delay = 10;
/* Calculate the maximal distance of the cursor from the drawing area.
* (offshoot can't become negative here!).
*/
dx = x < 0 ? -x : x - gui.drawarea->allocation.width;
dy = y < 0 ? -y : y - gui.drawarea->allocation.height;
offshoot = dx > dy ? dx : dy;
/* Make a linearly decaying timer delay with a threshold of 5 at a
* distance of 127 pixels from the main window.
*
* One could think endlessly about the most ergonomic variant here.
* For example it could make sense to calculate the distance from the
* drags start instead...
*
* Maybe a parabolic interpolation would suite us better here too...
*/
if (offshoot > 127)
{
/* 5 appears to be somehow near to my perceptual limits :-). */
delay = 5;
}
else
{
delay = (130 * (127 - offshoot)) / 127 + 5;
}
/* shoot again */
if (!motion_repeat_timer)
motion_repeat_timer = gtk_timeout_add((guint32)delay,
motion_repeat_timer_cb, NULL);
}
}
/*
* Timer used to recognize multiple clicks of the mouse button.
*/
static gint
motion_repeat_timer_cb(gpointer data UNUSED)
{
int x;
int y;
GdkModifierType state;
gdk_window_get_pointer(gui.drawarea->window, &x, &y, &state);
if (!(state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
GDK_BUTTON5_MASK)))
{
motion_repeat_timer = 0;
return FALSE;
}
/* If there already is a mouse click in the input buffer, wait another
* time (otherwise we would create a backlog of clicks) */
if (vim_used_in_input_buf() > 10)
return TRUE;
motion_repeat_timer = 0;
/*
* Fake a motion event.
* Trick: Pretend the mouse moved to the next character on every other
* event, otherwise drag events will be discarded, because they are still
* in the same character.
*/
if (motion_repeat_offset)
x += gui.char_width;
motion_repeat_offset = !motion_repeat_offset;
process_motion_notify(x, y, state);
/* Don't happen again. We will get reinstalled in the synthetic event
* if needed -- thus repeating should still work. */
return FALSE;
}
static gint
motion_notify_event(GtkWidget *widget,
GdkEventMotion *event,
gpointer data UNUSED)
{
if (event->is_hint)
{
int x;
int y;
GdkModifierType state;
gdk_window_get_pointer(widget->window, &x, &y, &state);
process_motion_notify(x, y, state);
}
else
{
process_motion_notify((int)event->x, (int)event->y,
(GdkModifierType)event->state);
}
return TRUE; /* handled */
}
/*
* Mouse button handling. Note please that we are capturing multiple click's
* by our own timeout mechanism instead of the one provided by GTK+ itself.
* This is due to the way the generic VIM code is recognizing multiple clicks.
*/
static gint
button_press_event(GtkWidget *widget,
GdkEventButton *event,
gpointer data UNUSED)
{
int button;
int repeated_click = FALSE;
int x, y;
int_u vim_modifiers;
gui.event_time = event->time;
/* Make sure we have focus now we've been selected */
if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
gtk_widget_grab_focus(widget);
/*
* Don't let additional events about multiple clicks send by GTK to us
* after the initial button press event confuse us.
*/
if (event->type != GDK_BUTTON_PRESS)
return FALSE;
x = event->x;
y = event->y;
/* Handle multiple clicks */
if (!mouse_timed_out && mouse_click_timer)
{
gtk_timeout_remove(mouse_click_timer);
mouse_click_timer = 0;
repeated_click = TRUE;
}
mouse_timed_out = FALSE;
mouse_click_timer = gtk_timeout_add((guint32)p_mouset,
mouse_click_timer_cb, &mouse_timed_out);
switch (event->button)
{
case 1:
button = MOUSE_LEFT;
break;
case 2:
button = MOUSE_MIDDLE;
break;
case 3:
button = MOUSE_RIGHT;
break;
default:
return FALSE; /* Unknown button */
}
#ifdef FEAT_XIM
/* cancel any preediting */
if (im_is_preediting())
xim_reset();
#endif
vim_modifiers = modifiers_gdk2mouse(event->state);
gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers);
return TRUE;
}
/*
* GTK+ 2 abstracts scrolling via the GdkEventScroll.
*/
static gboolean
scroll_event(GtkWidget *widget,
GdkEventScroll *event,
gpointer data UNUSED)
{
int button;
int_u vim_modifiers;
if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
gtk_widget_grab_focus(widget);
switch (event->direction)
{
case GDK_SCROLL_UP:
button = MOUSE_4;
break;
case GDK_SCROLL_DOWN:
button = MOUSE_5;
break;
case GDK_SCROLL_LEFT:
button = MOUSE_7;
break;
case GDK_SCROLL_RIGHT:
button = MOUSE_6;
break;
default: /* This shouldn't happen */
return FALSE;
}
# ifdef FEAT_XIM
/* cancel any preediting */
if (im_is_preediting())
xim_reset();
# endif
vim_modifiers = modifiers_gdk2mouse(event->state);
gui_send_mouse_event(button, (int)event->x, (int)event->y,
FALSE, vim_modifiers);
return TRUE;
}
static gint
button_release_event(GtkWidget *widget UNUSED,
GdkEventButton *event,
gpointer data UNUSED)
{
int x, y;
int_u vim_modifiers;
gui.event_time = event->time;
/* Remove any motion "machine gun" timers used for automatic further
extension of allocation areas if outside of the applications window
area .*/
if (motion_repeat_timer)
{
gtk_timeout_remove(motion_repeat_timer);
motion_repeat_timer = 0;
}
x = event->x;
y = event->y;
vim_modifiers = modifiers_gdk2mouse(event->state);
gui_send_mouse_event(MOUSE_RELEASE, x, y, FALSE, vim_modifiers);
return TRUE;
}
#ifdef FEAT_DND
/****************************************************************************
* Drag aNd Drop support handlers.
*/
/*
* Count how many items there may be and separate them with a NUL.
* Apparently the items are separated with \r\n. This is not documented,
* thus be careful not to go past the end. Also allow separation with
* NUL characters.
*/
static int
count_and_decode_uri_list(char_u *out, char_u *raw, int len)
{
int i;
char_u *p = out;
int count = 0;
for (i = 0; i < len; ++i)
{
if (raw[i] == NUL || raw[i] == '\n' || raw[i] == '\r')
{
if (p > out && p[-1] != NUL)
{
++count;
*p++ = NUL;
}
}
else if (raw[i] == '%' && i + 2 < len && hexhex2nr(raw + i + 1) > 0)
{
*p++ = hexhex2nr(raw + i + 1);
i += 2;
}
else
*p++ = raw[i];
}
if (p > out && p[-1] != NUL)
{
*p = NUL; /* last item didn't have \r or \n */
++count;
}
return count;
}
/*
* Parse NUL separated "src" strings. Make it an array "outlist" form. On
* this process, URI which protocol is not "file:" are removed. Return
* length of array (less than "max").
*/
static int
filter_uri_list(char_u **outlist, int max, char_u *src)
{
int i, j;
for (i = j = 0; i < max; ++i)
{
outlist[i] = NULL;
if (STRNCMP(src, "file:", 5) == 0)
{
src += 5;
if (STRNCMP(src, "//localhost", 11) == 0)
src += 11;
while (src[0] == '/' && src[1] == '/')
++src;
outlist[j++] = vim_strsave(src);
}
src += STRLEN(src) + 1;
}
return j;
}
static char_u **
parse_uri_list(int *count, char_u *data, int len)
{
int n = 0;
char_u *tmp = NULL;
char_u **array = NULL;;
if (data != NULL && len > 0 && (tmp = (char_u *)alloc(len + 1)) != NULL)
{
n = count_and_decode_uri_list(tmp, data, len);
if (n > 0 && (array = (char_u **)alloc(n * sizeof(char_u *))) != NULL)
n = filter_uri_list(array, n, tmp);
}
vim_free(tmp);
*count = n;
return array;
}
static void
drag_handle_uri_list(GdkDragContext *context,
GtkSelectionData *data,
guint time_,
GdkModifierType state,
gint x,
gint y)
{
char_u **fnames;
int nfiles = 0;
fnames = parse_uri_list(&nfiles, data->data, data->length);
if (fnames != NULL && nfiles > 0)
{
int_u modifiers;
gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
modifiers = modifiers_gdk2mouse(state);
gui_handle_drop(x, y, modifiers, fnames, nfiles);
}
else
vim_free(fnames);
}
static void
drag_handle_text(GdkDragContext *context,
GtkSelectionData *data,
guint time_,
GdkModifierType state)
{
char_u dropkey[6] = {CSI, KS_MODIFIER, 0, CSI, KS_EXTRA, (char_u)KE_DROP};
char_u *text;
int len;
char_u *tmpbuf = NULL;
text = data->data;
len = data->length;
if (data->type == utf8_string_atom)
{
if (input_conv.vc_type != CONV_NONE)
tmpbuf = string_convert(&input_conv, text, &len);
if (tmpbuf != NULL)
text = tmpbuf;
}
dnd_yank_drag_data(text, (long)len);
gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
vim_free(tmpbuf);
dropkey[2] = modifiers_gdk2vim(state);
if (dropkey[2] != 0)
add_to_input_buf(dropkey, (int)sizeof(dropkey));
else
add_to_input_buf(dropkey + 3, (int)(sizeof(dropkey) - 3));
}
/*
* DND receiver.
*/
static void
drag_data_received_cb(GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
GtkSelectionData *data,
guint info,
guint time_,
gpointer user_data UNUSED)
{
GdkModifierType state;
/* Guard against trash */
if (data->data == NULL
|| data->length <= 0
|| data->format != 8
|| data->data[data->length] != '\0')
{
gtk_drag_finish(context, FALSE, FALSE, time_);
return;
}
/* Get the current modifier state for proper distinguishment between
* different operations later. */
gdk_window_get_pointer(widget->window, NULL, NULL, &state);
/* Not sure about the role of "text/plain" here... */
if (info == (guint)TARGET_TEXT_URI_LIST)
drag_handle_uri_list(context, data, time_, state, x, y);
else
drag_handle_text(context, data, time_, state);
}
#endif /* FEAT_DND */
#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
/*
* GnomeClient interact callback. Check for unsaved buffers that cannot
* be abandoned and pop up a dialog asking the user for confirmation if
* necessary.
*/
static void
sm_client_check_changed_any(GnomeClient *client UNUSED,
gint key,
GnomeDialogType type UNUSED,
gpointer data UNUSED)
{
cmdmod_T save_cmdmod;
gboolean shutdown_cancelled;
save_cmdmod = cmdmod;
# ifdef FEAT_BROWSE
cmdmod.browse = TRUE;
# endif
# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmdmod.confirm = TRUE;
# endif
/*
* If there are changed buffers, present the user with
* a dialog if possible, otherwise give an error message.
*/
shutdown_cancelled = check_changed_any(FALSE);
exiting = FALSE;
cmdmod = save_cmdmod;
setcursor(); /* position the cursor */
out_flush();
/*
* If the user hit the [Cancel] button the whole shutdown
* will be cancelled. Wow, quite powerful feature (:
*/
gnome_interaction_key_return(key, shutdown_cancelled);
}
/*
* Generate a script that can be used to restore the current editing session.
* Save the value of v:this_session before running :mksession in order to make
* automagic session save fully transparent. Return TRUE on success.
*/
static int
write_session_file(char_u *filename)
{
char_u *escaped_filename;
char *mksession_cmdline;
unsigned int save_ssop_flags;
int failed;
/*
* Build an ex command line to create a script that restores the current
* session if executed. Escape the filename to avoid nasty surprises.
*/
escaped_filename = vim_strsave_escaped(filename, escape_chars);
if (escaped_filename == NULL)
return FALSE;
mksession_cmdline = g_strconcat("mksession ", (char *)escaped_filename,
NULL);
vim_free(escaped_filename);
/*
* Use a reasonable hardcoded set of 'sessionoptions' flags to avoid
* unpredictable effects when the session is saved automatically. Also,
* we definitely need SSOP_GLOBALS to be able to restore v:this_session.
* Don't use SSOP_BUFFERS to prevent the buffer list from becoming
* enormously large if the GNOME session feature is used regularly.
*/
save_ssop_flags = ssop_flags;
ssop_flags = (SSOP_BLANK|SSOP_CURDIR|SSOP_FOLDS|SSOP_GLOBALS
|SSOP_HELP|SSOP_OPTIONS|SSOP_WINSIZE|SSOP_TABPAGES);
do_cmdline_cmd((char_u *)"let Save_VV_this_session = v:this_session");
failed = (do_cmdline_cmd((char_u *)mksession_cmdline) == FAIL);
do_cmdline_cmd((char_u *)"let v:this_session = Save_VV_this_session");
do_unlet((char_u *)"Save_VV_this_session", TRUE);
ssop_flags = save_ssop_flags;
g_free(mksession_cmdline);
/*
* Reopen the file and append a command to restore v:this_session,
* as if this save never happened. This is to avoid conflicts with
* the user's own sessions. FIXME: It's probably less hackish to add
* a "stealth" flag to 'sessionoptions' -- gotta ask Bram.
*/
if (!failed)
{
FILE *fd;
fd = open_exfile(filename, TRUE, APPENDBIN);
failed = (fd == NULL
|| put_line(fd, "let v:this_session = Save_VV_this_session") == FAIL
|| put_line(fd, "unlet Save_VV_this_session") == FAIL);
if (fd != NULL && fclose(fd) != 0)
failed = TRUE;
if (failed)
mch_remove(filename);
}
return !failed;
}
/*
* "save_yourself" signal handler. Initiate an interaction to ask the user
* for confirmation if necessary. Save the current editing session and tell
* the session manager how to restart Vim.
*/
static gboolean
sm_client_save_yourself(GnomeClient *client,
gint phase UNUSED,
GnomeSaveStyle save_style UNUSED,
gboolean shutdown UNUSED,
GnomeInteractStyle interact_style,
gboolean fast UNUSED,
gpointer data UNUSED)
{
static const char suffix[] = "-session.vim";
char *session_file;
unsigned int len;
gboolean success;
/* Always request an interaction if possible. check_changed_any()
* won't actually show a dialog unless any buffers have been modified.
* There doesn't seem to be an obvious way to check that without
* automatically firing the dialog. Anyway, it works just fine. */
if (interact_style == GNOME_INTERACT_ANY)
gnome_client_request_interaction(client, GNOME_DIALOG_NORMAL,
&sm_client_check_changed_any,
NULL);
out_flush();
ml_sync_all(FALSE, FALSE); /* preserve all swap files */
/* The path is unique for each session save. We do neither know nor care
* which session script will actually be used later. This decision is in
* the domain of the session manager. */
session_file = gnome_config_get_real_path(
gnome_client_get_config_prefix(client));
len = strlen(session_file);
if (len > 0 && session_file[len-1] == G_DIR_SEPARATOR)
--len; /* get rid of the superfluous trailing '/' */
session_file = g_renew(char, session_file, len + sizeof(suffix));
memcpy(session_file + len, suffix, sizeof(suffix));
success = write_session_file((char_u *)session_file);
if (success)
{
const char *argv[8];
int i;
/* Tell the session manager how to wipe out the stored session data.
* This isn't as dangerous as it looks, don't worry :) session_file
* is a unique absolute filename. Usually it'll be something like
* `/home/user/.gnome2/vim-XXXXXX-session.vim'. */
i = 0;
argv[i++] = "rm";
argv[i++] = session_file;
argv[i] = NULL;
gnome_client_set_discard_command(client, i, (char **)argv);
/* Tell the session manager how to restore the just saved session.
* This is easily done thanks to Vim's -S option. Pass the -f flag
* since there's no need to fork -- it might even cause confusion.
* Also pass the window role to give the WM something to match on.
* The role is set in gui_mch_open(), thus should _never_ be NULL. */
i = 0;
argv[i++] = restart_command;
argv[i++] = "-f";
argv[i++] = "-g";
argv[i++] = "--role";
argv[i++] = gtk_window_get_role(GTK_WINDOW(gui.mainwin));
argv[i++] = "-S";
argv[i++] = session_file;
argv[i] = NULL;
gnome_client_set_restart_command(client, i, (char **)argv);
gnome_client_set_clone_command(client, 0, NULL);
}
g_free(session_file);
return success;
}
/*
* Called when the session manager wants us to die. There isn't much to save
* here since "save_yourself" has been emitted before (unless serious trouble
* is happening).
*/
static void
sm_client_die(GnomeClient *client UNUSED, gpointer data UNUSED)
{
/* Don't write messages to the GUI anymore */
full_screen = FALSE;
vim_strncpy(IObuff, (char_u *)
_("Vim: Received \"die\" request from session manager\n"),
IOSIZE - 1);
preserve_exit();
}
/*
* Connect our signal handlers to be notified on session save and shutdown.
*/
static void
setup_save_yourself(void)
{
GnomeClient *client;
client = gnome_master_client();
if (client != NULL)
{
/* Must use the deprecated gtk_signal_connect() for compatibility
* with GNOME 1. Arrgh, zombies! */
gtk_signal_connect(GTK_OBJECT(client), "save_yourself",
GTK_SIGNAL_FUNC(&sm_client_save_yourself), NULL);
gtk_signal_connect(GTK_OBJECT(client), "die",
GTK_SIGNAL_FUNC(&sm_client_die), NULL);
}
}
#else /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
# ifdef USE_XSMP
/*
* GTK tells us that XSMP needs attention
*/
static gboolean
local_xsmp_handle_requests(source, condition, data)
GIOChannel *source UNUSED;
GIOCondition condition;
gpointer data;
{
if (condition == G_IO_IN)
{
/* Do stuff; maybe close connection */
if (xsmp_handle_requests() == FAIL)
g_io_channel_unref((GIOChannel *)data);
return TRUE;
}
/* Error */
g_io_channel_unref((GIOChannel *)data);
xsmp_close();
return TRUE;
}
# endif /* USE_XSMP */
/*
* Setup the WM_PROTOCOLS to indicate we want the WM_SAVE_YOURSELF event.
* This is an ugly use of X functions. GTK doesn't offer an alternative.
*/
static void
setup_save_yourself(void)
{
Atom *existing_atoms = NULL;
int count = 0;
#ifdef USE_XSMP
if (xsmp_icefd != -1)
{
/*
* Use XSMP is preference to legacy WM_SAVE_YOURSELF;
* set up GTK IO monitor
*/
GIOChannel *g_io = g_io_channel_unix_new(xsmp_icefd);
g_io_add_watch(g_io, G_IO_IN | G_IO_ERR | G_IO_HUP,
local_xsmp_handle_requests, (gpointer)g_io);
}
else
#endif
{
/* Fall back to old method */
/* first get the existing value */
if (XGetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
GDK_WINDOW_XWINDOW(gui.mainwin->window),
&existing_atoms, &count))
{
Atom *new_atoms;
Atom save_yourself_xatom;
int i;
save_yourself_xatom = GET_X_ATOM(save_yourself_atom);
/* check if WM_SAVE_YOURSELF isn't there yet */
for (i = 0; i < count; ++i)
if (existing_atoms[i] == save_yourself_xatom)
break;
if (i == count)
{
/* allocate an Atoms array which is one item longer */
new_atoms = (Atom *)alloc((unsigned)((count + 1)
* sizeof(Atom)));
if (new_atoms != NULL)
{
memcpy(new_atoms, existing_atoms, count * sizeof(Atom));
new_atoms[count] = save_yourself_xatom;
XSetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
GDK_WINDOW_XWINDOW(gui.mainwin->window),
new_atoms, count + 1);
vim_free(new_atoms);
}
}
XFree(existing_atoms);
}
}
}
/*
* Installing a global event filter seems to be the only way to catch
* client messages of type WM_PROTOCOLS without overriding GDK's own
* client message event filter. Well, that's still better than trying
* to guess what the GDK filter had done if it had been invoked instead
*
* GTK2_FIXME: This doesn't seem to work. For some reason we never
* receive WM_SAVE_YOURSELF even though everything is set up correctly.
* I have the nasty feeling modern session managers just don't send this
* deprecated message anymore. Addition: confirmed by several people.
*
* The GNOME session support is much cooler anyway. Unlike this ugly
* WM_SAVE_YOURSELF hack it actually stores the session... And yes,
* it should work with KDE as well.
*/
static GdkFilterReturn
global_event_filter(GdkXEvent *xev,
GdkEvent *event UNUSED,
gpointer data UNUSED)
{
XEvent *xevent = (XEvent *)xev;
if (xevent != NULL
&& xevent->type == ClientMessage
&& xevent->xclient.message_type == GET_X_ATOM(wm_protocols_atom)
&& (long_u)xevent->xclient.data.l[0]
== GET_X_ATOM(save_yourself_atom))
{
out_flush();
ml_sync_all(FALSE, FALSE); /* preserve all swap files */
/*
* Set the window's WM_COMMAND property, to let the window manager
* know we are done saving ourselves. We don't want to be
* restarted, thus set argv to NULL.
*/
XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
GDK_WINDOW_XWINDOW(gui.mainwin->window),
NULL, 0);
return GDK_FILTER_REMOVE;
}
return GDK_FILTER_CONTINUE;
}
#endif /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
/*
* Setup the window icon & xcmdsrv comm after the main window has been realized.
*/
static void
mainwin_realize(GtkWidget *widget UNUSED, gpointer data UNUSED)
{
/* If you get an error message here, you still need to unpack the runtime
* archive! */
#ifdef magick
# undef magick
#endif
/* A bit hackish, but avoids casting later and allows optimization */
# define static static const
#define magick vim32x32
#include "../runtime/vim32x32.xpm"
#undef magick
#define magick vim16x16
#include "../runtime/vim16x16.xpm"
#undef magick
#define magick vim48x48
#include "../runtime/vim48x48.xpm"
#undef magick
# undef static
/* When started with "--echo-wid" argument, write window ID on stdout. */
if (echo_wid_arg)
{
printf("WID: %ld\n", (long)GDK_WINDOW_XWINDOW(gui.mainwin->window));
fflush(stdout);
}
if (vim_strchr(p_go, GO_ICON) != NULL)
{
/*
* Add an icon to the main window. For fun and convenience of the user.
*/
GList *icons = NULL;
icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim16x16));
icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim32x32));
icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim48x48));
gtk_window_set_icon_list(GTK_WINDOW(gui.mainwin), icons);
g_list_foreach(icons, (GFunc)&g_object_unref, NULL);
g_list_free(icons);
}
#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
/* Register a handler for WM_SAVE_YOURSELF with GDK's low-level X I/F */
gdk_window_add_filter(NULL, &global_event_filter, NULL);
#endif
/* Setup to indicate to the window manager that we want to catch the
* WM_SAVE_YOURSELF event. For GNOME, this connects to the session
* manager instead. */
#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
if (using_gnome)
#endif
setup_save_yourself();
#ifdef FEAT_CLIENTSERVER
if (serverName == NULL && serverDelayedStartName != NULL)
{
/* This is a :gui command in a plain vim with no previous server */
commWindow = GDK_WINDOW_XWINDOW(gui.mainwin->window);
(void)serverRegisterName(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
serverDelayedStartName);
}
else
{
/*
* Cannot handle "XLib-only" windows with gtk event routines, we'll
* have to change the "server" registration to that of the main window
* If we have not registered a name yet, remember the window
*/
serverChangeRegisteredWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
GDK_WINDOW_XWINDOW(gui.mainwin->window));
}
gtk_widget_add_events(gui.mainwin, GDK_PROPERTY_CHANGE_MASK);
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "property_notify_event",
GTK_SIGNAL_FUNC(property_event), NULL);
#endif
}
static GdkCursor *
create_blank_pointer(void)
{
GdkWindow *root_window = NULL;
GdkPixmap *blank_mask;
GdkCursor *cursor;
GdkColor color = { 0, 0, 0, 0 };
char blank_data[] = { 0x0 };
#ifdef HAVE_GTK_MULTIHEAD
root_window = gtk_widget_get_root_window(gui.mainwin);
#endif
/* Create a pseudo blank pointer, which is in fact one pixel by one pixel
* in size. */
blank_mask = gdk_bitmap_create_from_data(root_window, blank_data, 1, 1);
cursor = gdk_cursor_new_from_pixmap(blank_mask, blank_mask,
&color, &color, 0, 0);
gdk_bitmap_unref(blank_mask);
return cursor;
}
#ifdef HAVE_GTK_MULTIHEAD
static void
mainwin_screen_changed_cb(GtkWidget *widget,
GdkScreen *previous_screen UNUSED,
gpointer data UNUSED)
{
if (!gtk_widget_has_screen(widget))
return;
/*
* Recreate the invisible mouse cursor.
*/
if (gui.blank_pointer != NULL)
gdk_cursor_unref(gui.blank_pointer);
gui.blank_pointer = create_blank_pointer();
if (gui.pointer_hidden && gui.drawarea->window != NULL)
gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
/*
* Create a new PangoContext for this screen, and initialize it
* with the current font if necessary.
*/
if (gui.text_context != NULL)
g_object_unref(gui.text_context);
gui.text_context = gtk_widget_create_pango_context(widget);
pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
if (gui.norm_font != NULL)
{
gui_mch_init_font(p_guifont, FALSE);
gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
}
}
#endif /* HAVE_GTK_MULTIHEAD */
/*
* After the drawing area comes up, we calculate all colors and create the
* dummy blank cursor.
*
* Don't try to set any VIM scrollbar sizes anywhere here. I'm relying on the
* fact that the main VIM engine doesn't take them into account anywhere.
*/
static void
drawarea_realize_cb(GtkWidget *widget, gpointer data UNUSED)
{
GtkWidget *sbar;
#ifdef FEAT_XIM
xim_init();
#endif
gui_mch_new_colors();
gui.text_gc = gdk_gc_new(gui.drawarea->window);
gui.blank_pointer = create_blank_pointer();
if (gui.pointer_hidden)
gdk_window_set_cursor(widget->window, gui.blank_pointer);
/* get the actual size of the scrollbars, if they are realized */
sbar = firstwin->w_scrollbars[SBAR_LEFT].id;
if (!sbar || (!gui.which_scrollbars[SBAR_LEFT]
&& firstwin->w_scrollbars[SBAR_RIGHT].id))
sbar = firstwin->w_scrollbars[SBAR_RIGHT].id;
if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.width)
gui.scrollbar_width = sbar->allocation.width;
sbar = gui.bottom_sbar.id;
if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.height)
gui.scrollbar_height = sbar->allocation.height;
}
/*
* Properly clean up on shutdown.
*/
static void
drawarea_unrealize_cb(GtkWidget *widget UNUSED, gpointer data UNUSED)
{
/* Don't write messages to the GUI anymore */
full_screen = FALSE;
#ifdef FEAT_XIM
im_shutdown();
#endif
if (gui.ascii_glyphs != NULL)
{
pango_glyph_string_free(gui.ascii_glyphs);
gui.ascii_glyphs = NULL;
}
if (gui.ascii_font != NULL)
{
g_object_unref(gui.ascii_font);
gui.ascii_font = NULL;
}
g_object_unref(gui.text_context);
gui.text_context = NULL;
g_object_unref(gui.text_gc);
gui.text_gc = NULL;
gdk_cursor_unref(gui.blank_pointer);
gui.blank_pointer = NULL;
}
static void
drawarea_style_set_cb(GtkWidget *widget UNUSED,
GtkStyle *previous_style UNUSED,
gpointer data UNUSED)
{
gui_mch_new_colors();
}
/*
* Callback routine for the "delete_event" signal on the toplevel window.
* Tries to vim gracefully, or refuses to exit with changed buffers.
*/
static gint
delete_event_cb(GtkWidget *widget UNUSED,
GdkEventAny *event UNUSED,
gpointer data UNUSED)
{
gui_shell_closed();
return TRUE;
}
#if defined(FEAT_MENU) || defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE)
static int
get_item_dimensions(GtkWidget *widget, GtkOrientation orientation)
{
GtkOrientation item_orientation = GTK_ORIENTATION_HORIZONTAL;
#ifdef FEAT_GUI_GNOME
if (using_gnome && widget != NULL)
{
GtkWidget *parent;
BonoboDockItem *dockitem;
parent = gtk_widget_get_parent(widget);
if (G_TYPE_FROM_INSTANCE(parent) == BONOBO_TYPE_DOCK_ITEM)
{
/* Only menu & toolbar are dock items. Could tabline be?
* Seem to be only the 2 defined in GNOME */
widget = parent;
dockitem = BONOBO_DOCK_ITEM(widget);
if (dockitem == NULL || dockitem->is_floating)
return 0;
item_orientation = bonobo_dock_item_get_orientation(dockitem);
}
}
#endif
if (widget != NULL
&& item_orientation == orientation
&& GTK_WIDGET_REALIZED(widget)
&& GTK_WIDGET_VISIBLE(widget))
{
if (orientation == GTK_ORIENTATION_HORIZONTAL)
return widget->allocation.height;
else
return widget->allocation.width;
}
return 0;
}
#endif
static int
get_menu_tool_width(void)
{
int width = 0;
#ifdef FEAT_GUI_GNOME /* these are never vertical without GNOME */
# ifdef FEAT_MENU
width += get_item_dimensions(gui.menubar, GTK_ORIENTATION_VERTICAL);
# endif
# ifdef FEAT_TOOLBAR
width += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_VERTICAL);
# endif
# ifdef FEAT_GUI_TABLINE
if (gui.tabline != NULL)
width += get_item_dimensions(gui.tabline, GTK_ORIENTATION_VERTICAL);
# endif
#endif
return width;
}
static int
get_menu_tool_height(void)
{
int height = 0;
#ifdef FEAT_MENU
height += get_item_dimensions(gui.menubar, GTK_ORIENTATION_HORIZONTAL);
#endif
#ifdef FEAT_TOOLBAR
height += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_HORIZONTAL);
#endif
#ifdef FEAT_GUI_TABLINE
if (gui.tabline != NULL)
height += get_item_dimensions(gui.tabline, GTK_ORIENTATION_HORIZONTAL);
#endif
return height;
}
/* This controls whether we can set the real window hints at
* start-up when in a GtkPlug.
* 0 = normal processing (default)
* 1 = init. hints set, no-one's tried to reset since last check
* 2 = init. hints set, attempt made to change hints
*/
static int init_window_hints_state = 0;
static void
update_window_manager_hints(int force_width, int force_height)
{
static int old_width = 0;
static int old_height = 0;
static int old_min_width = 0;
static int old_min_height = 0;
static int old_char_width = 0;
static int old_char_height = 0;
int width;
int height;
int min_width;
int min_height;
/* At start-up, don't try to set the hints until the initial
* values have been used (those that dictate our initial size)
* Let forced (i.e., correct) values through always.
*/
if (!(force_width && force_height) && init_window_hints_state > 0)
{
/* Don't do it! */
init_window_hints_state = 2;
return;
}
/* This also needs to be done when the main window isn't there yet,
* otherwise the hints don't work. */
width = gui_get_base_width();
height = gui_get_base_height();
# ifdef FEAT_MENU
height += tabline_height() * gui.char_height;
# endif
width += get_menu_tool_width();
height += get_menu_tool_height();
/* GtkSockets use GtkPlug's [gui,mainwin] min-size hints to determine
* their actual widget size. When we set our size ourselves (e.g.,
* 'set columns=' or init. -geom) we briefly set the min. to the size
* we wish to be instead of the legitimate minimum so that we actually
* resize correctly.
*/
if (force_width && force_height)
{
min_width = force_width;
min_height = force_height;
}
else
{
min_width = width + MIN_COLUMNS * gui.char_width;
min_height = height + MIN_LINES * gui.char_height;
}
/* Avoid an expose event when the size didn't change. */
if (width != old_width
|| height != old_height
|| min_width != old_min_width
|| min_height != old_min_height
|| gui.char_width != old_char_width
|| gui.char_height != old_char_height)
{
GdkGeometry geometry;
GdkWindowHints geometry_mask;
geometry.width_inc = gui.char_width;
geometry.height_inc = gui.char_height;
geometry.base_width = width;
geometry.base_height = height;
geometry.min_width = min_width;
geometry.min_height = min_height;
geometry_mask = GDK_HINT_BASE_SIZE|GDK_HINT_RESIZE_INC
|GDK_HINT_MIN_SIZE;
/* Using gui.formwin as geometry widget doesn't work as expected
* with GTK+ 2 -- dunno why. Presumably all the resizing hacks
* in Vim confuse GTK+. */
gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.mainwin,
&geometry, geometry_mask);
old_width = width;
old_height = height;
old_min_width = min_width;
old_min_height = min_height;
old_char_width = gui.char_width;
old_char_height = gui.char_height;
}
}
#ifdef FEAT_TOOLBAR
/*
* This extra effort wouldn't be necessary if we only used stock icons in the
* toolbar, as we do for all builtin icons. But user-defined toolbar icons
* shouldn't be treated differently, thus we do need this.
*/
static void
icon_size_changed_foreach(GtkWidget *widget, gpointer user_data)
{
if (GTK_IS_IMAGE(widget))
{
GtkImage *image = (GtkImage *)widget;
/* User-defined icons are stored in a GtkIconSet */
if (gtk_image_get_storage_type(image) == GTK_IMAGE_ICON_SET)
{
GtkIconSet *icon_set;
GtkIconSize icon_size;
gtk_image_get_icon_set(image, &icon_set, &icon_size);
icon_size = (GtkIconSize)(long)user_data;
gtk_icon_set_ref(icon_set);
gtk_image_set_from_icon_set(image, icon_set, icon_size);
gtk_icon_set_unref(icon_set);
}
}
else if (GTK_IS_CONTAINER(widget))
{
gtk_container_foreach((GtkContainer *)widget,
&icon_size_changed_foreach,
user_data);
}
}
static void
set_toolbar_style(GtkToolbar *toolbar)
{
GtkToolbarStyle style;
GtkIconSize size;
GtkIconSize oldsize;
if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
== (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
style = GTK_TOOLBAR_BOTH_HORIZ;
else if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS))
== (TOOLBAR_TEXT | TOOLBAR_ICONS))
style = GTK_TOOLBAR_BOTH;
else if (toolbar_flags & TOOLBAR_TEXT)
style = GTK_TOOLBAR_TEXT;
else
style = GTK_TOOLBAR_ICONS;
gtk_toolbar_set_style(toolbar, style);
gtk_toolbar_set_tooltips(toolbar, (toolbar_flags & TOOLBAR_TOOLTIPS) != 0);
switch (tbis_flags)
{
case TBIS_TINY: size = GTK_ICON_SIZE_MENU; break;
case TBIS_SMALL: size = GTK_ICON_SIZE_SMALL_TOOLBAR; break;
case TBIS_MEDIUM: size = GTK_ICON_SIZE_BUTTON; break;
case TBIS_LARGE: size = GTK_ICON_SIZE_LARGE_TOOLBAR; break;
default: size = GTK_ICON_SIZE_INVALID; break;
}
oldsize = gtk_toolbar_get_icon_size(toolbar);
if (size == GTK_ICON_SIZE_INVALID)
{
/* Let global user preferences decide the icon size. */
gtk_toolbar_unset_icon_size(toolbar);
size = gtk_toolbar_get_icon_size(toolbar);
}
if (size != oldsize)
{
gtk_container_foreach(GTK_CONTAINER(toolbar),
&icon_size_changed_foreach,
GINT_TO_POINTER((int)size));
}
gtk_toolbar_set_icon_size(toolbar, size);
}
#endif /* FEAT_TOOLBAR */
#if defined(FEAT_GUI_TABLINE) || defined(PROTO)
static int ignore_tabline_evt = FALSE;
static GtkWidget *tabline_menu;
static GtkTooltips *tabline_tooltip;
static int clicked_page; /* page clicked in tab line */
/*
* Handle selecting an item in the tab line popup menu.
*/
static void
tabline_menu_handler(GtkMenuItem *item UNUSED, gpointer user_data)
{
/* Add the string cmd into input buffer */
send_tabline_menu_event(clicked_page, (int)(long)user_data);
}
static void
add_tabline_menu_item(GtkWidget *menu, char_u *text, int resp)
{
GtkWidget *item;
char_u *utf_text;
utf_text = CONVERT_TO_UTF8(text);
item = gtk_menu_item_new_with_label((const char *)utf_text);
gtk_widget_show(item);
CONVERT_TO_UTF8_FREE(utf_text);
gtk_container_add(GTK_CONTAINER(menu), item);
gtk_signal_connect(GTK_OBJECT(item), "activate",
GTK_SIGNAL_FUNC(tabline_menu_handler),
(gpointer)(long)resp);
}
/*
* Create a menu for the tab line.
*/
static GtkWidget *
create_tabline_menu(void)
{
GtkWidget *menu;
menu = gtk_menu_new();
add_tabline_menu_item(menu, (char_u *)_("Close"), TABLINE_MENU_CLOSE);
add_tabline_menu_item(menu, (char_u *)_("New tab"), TABLINE_MENU_NEW);
add_tabline_menu_item(menu, (char_u *)_("Open Tab..."), TABLINE_MENU_OPEN);
return menu;
}
static gboolean
on_tabline_menu(GtkWidget *widget, GdkEvent *event)
{
/* Was this button press event ? */
if (event->type == GDK_BUTTON_PRESS)
{
GdkEventButton *bevent = (GdkEventButton *)event;
int x = bevent->x;
int y = bevent->y;
GtkWidget *tabwidget;
GdkWindow *tabwin;
/* When ignoring events return TRUE so that the selected page doesn't
* change. */
if (hold_gui_events
# ifdef FEAT_CMDWIN
|| cmdwin_type != 0
# endif
)
return TRUE;
tabwin = gdk_window_at_pointer(&x, &y);
gdk_window_get_user_data(tabwin, (gpointer)&tabwidget);
clicked_page = (int)(long)gtk_object_get_user_data(
GTK_OBJECT(tabwidget));
/* If the event was generated for 3rd button popup the menu. */
if (bevent->button == 3)
{
gtk_menu_popup(GTK_MENU(widget), NULL, NULL, NULL, NULL,
bevent->button, bevent->time);
/* We handled the event. */
return TRUE;
}
else if (bevent->button == 1)
{
if (clicked_page == 0)
{
/* Click after all tabs moves to next tab page. When "x" is
* small guess it's the left button. */
send_tabline_event(x < 50 ? -1 : 0);
}
}
}
/* We didn't handle the event. */
return FALSE;
}
/*
* Handle selecting one of the tabs.
*/
static void
on_select_tab(
GtkNotebook *notebook UNUSED,
GtkNotebookPage *page UNUSED,
gint idx,
gpointer data UNUSED)
{
if (!ignore_tabline_evt)
{
send_tabline_event(idx + 1);
}
}
/*
* Show or hide the tabline.
*/
void
gui_mch_show_tabline(int showit)
{
if (gui.tabline == NULL)
return;
if (!showit != !gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline)))
{
/* Note: this may cause a resize event */
gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), showit);
update_window_manager_hints(0, 0);
if (showit)
GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(gui.tabline), GTK_CAN_FOCUS);
}
gui_mch_update();
}
/*
* Return TRUE when tabline is displayed.
*/
int
gui_mch_showing_tabline(void)
{
return gui.tabline != NULL
&& gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline));
}
/*
* Update the labels of the tabline.
*/
void
gui_mch_update_tabline(void)
{
GtkWidget *page;
GtkWidget *event_box;
GtkWidget *label;
tabpage_T *tp;
int nr = 0;
int tab_num;
int curtabidx = 0;
char_u *labeltext;
if (gui.tabline == NULL)
return;
ignore_tabline_evt = TRUE;
/* 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;
tab_num = nr + 1;
page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr);
if (page == NULL)
{
/* Add notebook page */
page = gtk_vbox_new(FALSE, 0);
gtk_widget_show(page);
event_box = gtk_event_box_new();
gtk_widget_show(event_box);
label = gtk_label_new("-Empty-");
gtk_misc_set_padding(GTK_MISC(label), 2, 2);
gtk_container_add(GTK_CONTAINER(event_box), label);
gtk_widget_show(label);
gtk_notebook_insert_page(GTK_NOTEBOOK(gui.tabline),
page,
event_box,
nr++);
}
event_box = gtk_notebook_get_tab_label(GTK_NOTEBOOK(gui.tabline), page);
gtk_object_set_user_data(GTK_OBJECT(event_box),
(gpointer)(long)tab_num);
label = GTK_BIN(event_box)->child;
get_tabline_label(tp, FALSE);
labeltext = CONVERT_TO_UTF8(NameBuff);
gtk_label_set_text(GTK_LABEL(label), (const char *)labeltext);
CONVERT_TO_UTF8_FREE(labeltext);
get_tabline_label(tp, TRUE);
labeltext = CONVERT_TO_UTF8(NameBuff);
gtk_tooltips_set_tip(GTK_TOOLTIPS(tabline_tooltip), event_box,
(const char *)labeltext, NULL);
CONVERT_TO_UTF8_FREE(labeltext);
}
/* Remove any old labels. */
while (gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr) != NULL)
gtk_notebook_remove_page(GTK_NOTEBOOK(gui.tabline), nr);
if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != curtabidx)
gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), curtabidx);
/* Make sure everything is in place before drawing text. */
gui_mch_update();
ignore_tabline_evt = FALSE;
}
/*
* Set the current tab to "nr". First tab is 1.
*/
void
gui_mch_set_curtab(nr)
int nr;
{
if (gui.tabline == NULL)
return;
ignore_tabline_evt = TRUE;
if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != nr - 1)
gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), nr - 1);
ignore_tabline_evt = FALSE;
}
#endif /* FEAT_GUI_TABLINE */
/*
* Add selection targets for PRIMARY and CLIPBOARD selections.
*/
void
gui_gtk_set_selection_targets(void)
{
int i, j = 0;
int n_targets = N_SELECTION_TARGETS;
GtkTargetEntry targets[N_SELECTION_TARGETS];
for (i = 0; i < (int)N_SELECTION_TARGETS; ++i)
{
/* OpenOffice tries to use TARGET_HTML and fails when we don't
* return something, instead of trying another target. Therefore only
* offer TARGET_HTML when it works. */
if (!clip_html && selection_targets[i].info == TARGET_HTML)
n_targets--;
else
targets[j++] = selection_targets[i];
}
gtk_selection_clear_targets(gui.drawarea, (GdkAtom)GDK_SELECTION_PRIMARY);
gtk_selection_clear_targets(gui.drawarea, (GdkAtom)clip_plus.gtk_sel_atom);
gtk_selection_add_targets(gui.drawarea,
(GdkAtom)GDK_SELECTION_PRIMARY,
targets, n_targets);
gtk_selection_add_targets(gui.drawarea,
(GdkAtom)clip_plus.gtk_sel_atom,
targets, n_targets);
}
/*
* Set up for receiving DND items.
*/
void
gui_gtk_set_dnd_targets(void)
{
int i, j = 0;
int n_targets = N_DND_TARGETS;
GtkTargetEntry targets[N_DND_TARGETS];
for (i = 0; i < (int)N_DND_TARGETS; ++i)
{
if (!clip_html && dnd_targets[i].info == TARGET_HTML)
n_targets--;
else
targets[j++] = dnd_targets[i];
}
gtk_drag_dest_unset(gui.drawarea);
gtk_drag_dest_set(gui.drawarea,
GTK_DEST_DEFAULT_ALL,
targets, n_targets,
GDK_ACTION_COPY | GDK_ACTION_MOVE);
}
/*
* Initialize the GUI. Create all the windows, set up all the callbacks etc.
* Returns OK for success, FAIL when the GUI can't be started.
*/
int
gui_mch_init(void)
{
GtkWidget *vbox;
#ifdef FEAT_GUI_GNOME
/* Initialize the GNOME libraries. gnome_program_init()/gnome_init()
* exits on failure, but that's a non-issue because we already called
* gtk_init_check() in gui_mch_init_check(). */
if (using_gnome)
gnome_program_init(VIMPACKAGE, VIM_VERSION_SHORT,
LIBGNOMEUI_MODULE, gui_argc, gui_argv, NULL);
#endif
vim_free(gui_argv);
gui_argv = NULL;
#if GLIB_CHECK_VERSION(2,1,3)
/* Set the human-readable application name */
g_set_application_name("Vim");
#endif
/*
* Force UTF-8 output no matter what the value of 'encoding' is.
* did_set_string_option() in option.c prohibits changing 'termencoding'
* to something else than UTF-8 if the GUI is in use.
*/
set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
#ifdef FEAT_TOOLBAR
gui_gtk_register_stock_icons();
#endif
/* FIXME: Need to install the classic icons and a gtkrc.classic file.
* The hard part is deciding install locations and the Makefile magic. */
#if 0
gtk_rc_parse("gtkrc");
#endif
/* Initialize values */
gui.border_width = 2;
gui.scrollbar_width = SB_DEFAULT_WIDTH;
gui.scrollbar_height = SB_DEFAULT_WIDTH;
/* LINTED: avoid warning: conversion to 'unsigned long' */
gui.fgcolor = g_new0(GdkColor, 1);
/* LINTED: avoid warning: conversion to 'unsigned long' */
gui.bgcolor = g_new0(GdkColor, 1);
/* LINTED: avoid warning: conversion to 'unsigned long' */
gui.spcolor = g_new0(GdkColor, 1);
/* Initialise atoms */
html_atom = gdk_atom_intern("text/html", FALSE);
utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
/* Set default foreground and background colors. */
gui.norm_pixel = gui.def_norm_pixel;
gui.back_pixel = gui.def_back_pixel;
if (gtk_socket_id != 0)
{
GtkWidget *plug;
/* Use GtkSocket from another app. */
#ifdef HAVE_GTK_MULTIHEAD
plug = gtk_plug_new_for_display(gdk_display_get_default(),
gtk_socket_id);
#else
plug = gtk_plug_new(gtk_socket_id);
#endif
if (plug != NULL && GTK_PLUG(plug)->socket_window != NULL)
{
gui.mainwin = plug;
}
else
{
g_warning("Connection to GTK+ socket (ID %u) failed",
(unsigned int)gtk_socket_id);
/* Pretend we never wanted it if it failed (get own window) */
gtk_socket_id = 0;
}
}
if (gtk_socket_id == 0)
{
#ifdef FEAT_GUI_GNOME
if (using_gnome)
{
gui.mainwin = gnome_app_new("Vim", NULL);
# ifdef USE_XSMP
/* Use the GNOME save-yourself functionality now. */
xsmp_close();
# endif
}
else
#endif
gui.mainwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
}
gtk_widget_set_name(gui.mainwin, "vim-main-window");
/* Create the PangoContext used for drawing all text. */
gui.text_context = gtk_widget_create_pango_context(gui.mainwin);
pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
gtk_container_border_width(GTK_CONTAINER(gui.mainwin), 0);
gtk_widget_add_events(gui.mainwin, GDK_VISIBILITY_NOTIFY_MASK);
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "delete_event",
GTK_SIGNAL_FUNC(&delete_event_cb), NULL);
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "realize",
GTK_SIGNAL_FUNC(&mainwin_realize), NULL);
#ifdef HAVE_GTK_MULTIHEAD
g_signal_connect(G_OBJECT(gui.mainwin), "screen_changed",
G_CALLBACK(&mainwin_screen_changed_cb), NULL);
#endif
gui.accel_group = gtk_accel_group_new();
gtk_window_add_accel_group(GTK_WINDOW(gui.mainwin), gui.accel_group);
/* A vertical box holds the menubar, toolbar and main text window. */
vbox = gtk_vbox_new(FALSE, 0);
#ifdef FEAT_GUI_GNOME
if (using_gnome)
{
# if defined(FEAT_MENU)
/* automagically restore menubar/toolbar placement */
gnome_app_enable_layout_config(GNOME_APP(gui.mainwin), TRUE);
# endif
gnome_app_set_contents(GNOME_APP(gui.mainwin), vbox);
}
else
#endif
{
gtk_container_add(GTK_CONTAINER(gui.mainwin), vbox);
gtk_widget_show(vbox);
}
#ifdef FEAT_MENU
/*
* Create the menubar and handle
*/
gui.menubar = gtk_menu_bar_new();
gtk_widget_set_name(gui.menubar, "vim-menubar");
/* Avoid that GTK takes <F10> away from us. */
{
GtkSettings *gtk_settings;
gtk_settings = gtk_settings_get_for_screen(gdk_screen_get_default());
g_object_set(gtk_settings, "gtk-menu-bar-accel", NULL, NULL);
}
# ifdef FEAT_GUI_GNOME
if (using_gnome)
{
BonoboDockItem *dockitem;
gnome_app_set_menus(GNOME_APP(gui.mainwin), GTK_MENU_BAR(gui.menubar));
dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
GNOME_APP_MENUBAR_NAME);
/* We don't want the menu to float. */
bonobo_dock_item_set_behavior(dockitem,
bonobo_dock_item_get_behavior(dockitem)
| BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
gui.menubar_h = GTK_WIDGET(dockitem);
}
else
# endif /* FEAT_GUI_GNOME */
{
/* Always show the menubar, otherwise <F10> doesn't work. It may be
* disabled in gui_init() later. */
gtk_widget_show(gui.menubar);
gtk_box_pack_start(GTK_BOX(vbox), gui.menubar, FALSE, FALSE, 0);
}
#endif /* FEAT_MENU */
#ifdef FEAT_TOOLBAR
/*
* Create the toolbar and handle
*/
/* some aesthetics on the toolbar */
gtk_rc_parse_string(
"style \"vim-toolbar-style\" {\n"
" GtkToolbar::button_relief = GTK_RELIEF_NONE\n"
"}\n"
"widget \"*.vim-toolbar\" style \"vim-toolbar-style\"\n");
gui.toolbar = gtk_toolbar_new();
gtk_widget_set_name(gui.toolbar, "vim-toolbar");
set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
# ifdef FEAT_GUI_GNOME
if (using_gnome)
{
BonoboDockItem *dockitem;
gnome_app_set_toolbar(GNOME_APP(gui.mainwin), GTK_TOOLBAR(gui.toolbar));
dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
GNOME_APP_TOOLBAR_NAME);
gui.toolbar_h = GTK_WIDGET(dockitem);
/* When the toolbar is floating it gets stuck. So long as that isn't
* fixed let's disallow floating. */
bonobo_dock_item_set_behavior(dockitem,
bonobo_dock_item_get_behavior(dockitem)
| BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
gtk_container_set_border_width(GTK_CONTAINER(gui.toolbar), 0);
}
else
# endif /* FEAT_GUI_GNOME */
{
if (vim_strchr(p_go, GO_TOOLBAR) != NULL
&& (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
gtk_widget_show(gui.toolbar);
gtk_box_pack_start(GTK_BOX(vbox), gui.toolbar, FALSE, FALSE, 0);
}
#endif /* FEAT_TOOLBAR */
#ifdef FEAT_GUI_TABLINE
/*
* Use a Notebook for the tab pages labels. The labels are hidden by
* default.
*/
gui.tabline = gtk_notebook_new();
gtk_widget_show(gui.tabline);
gtk_box_pack_start(GTK_BOX(vbox), gui.tabline, FALSE, FALSE, 0);
gtk_notebook_set_show_border(GTK_NOTEBOOK(gui.tabline), FALSE);
gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), FALSE);
gtk_notebook_set_scrollable(GTK_NOTEBOOK(gui.tabline), TRUE);
gtk_notebook_set_tab_border(GTK_NOTEBOOK(gui.tabline), FALSE);
tabline_tooltip = gtk_tooltips_new();
gtk_tooltips_enable(GTK_TOOLTIPS(tabline_tooltip));
{
GtkWidget *page, *label, *event_box;
/* Add the first tab. */
page = gtk_vbox_new(FALSE, 0);
gtk_widget_show(page);
gtk_container_add(GTK_CONTAINER(gui.tabline), page);
label = gtk_label_new("-Empty-");
gtk_widget_show(label);
event_box = gtk_event_box_new();
gtk_widget_show(event_box);
gtk_object_set_user_data(GTK_OBJECT(event_box), (gpointer)1L);
gtk_misc_set_padding(GTK_MISC(label), 2, 2);
gtk_container_add(GTK_CONTAINER(event_box), label);
gtk_notebook_set_tab_label(GTK_NOTEBOOK(gui.tabline), page, event_box);
}
gtk_signal_connect(GTK_OBJECT(gui.tabline), "switch_page",
GTK_SIGNAL_FUNC(on_select_tab), NULL);
/* Create a popup menu for the tab line and connect it. */
tabline_menu = create_tabline_menu();
gtk_signal_connect_object(GTK_OBJECT(gui.tabline), "button_press_event",
GTK_SIGNAL_FUNC(on_tabline_menu), GTK_OBJECT(tabline_menu));
#endif
gui.formwin = gtk_form_new();
gtk_container_border_width(GTK_CONTAINER(gui.formwin), 0);
gtk_widget_set_events(gui.formwin, GDK_EXPOSURE_MASK);
gui.drawarea = gtk_drawing_area_new();
/* Determine which events we will filter. */
gtk_widget_set_events(gui.drawarea,
GDK_EXPOSURE_MASK |
GDK_ENTER_NOTIFY_MASK |
GDK_LEAVE_NOTIFY_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_SCROLL_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_POINTER_MOTION_HINT_MASK);
gtk_widget_show(gui.drawarea);
gtk_form_put(GTK_FORM(gui.formwin), gui.drawarea, 0, 0);
gtk_widget_show(gui.formwin);
gtk_box_pack_start(GTK_BOX(vbox), gui.formwin, TRUE, TRUE, 0);
/* For GtkSockets, key-presses must go to the focus widget (drawarea)
* and not the window. */
gtk_signal_connect((gtk_socket_id == 0) ? GTK_OBJECT(gui.mainwin)
: GTK_OBJECT(gui.drawarea),
"key_press_event",
GTK_SIGNAL_FUNC(key_press_event), NULL);
#if defined(FEAT_XIM)
/* Also forward key release events for the benefit of GTK+ 2 input
* modules. Try CTRL-SHIFT-xdigits to enter a Unicode code point. */
g_signal_connect((gtk_socket_id == 0) ? G_OBJECT(gui.mainwin)
: G_OBJECT(gui.drawarea),
"key_release_event",
G_CALLBACK(&key_release_event), NULL);
#endif
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "realize",
GTK_SIGNAL_FUNC(drawarea_realize_cb), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "unrealize",
GTK_SIGNAL_FUNC(drawarea_unrealize_cb), NULL);
gtk_signal_connect_after(GTK_OBJECT(gui.drawarea), "style_set",
GTK_SIGNAL_FUNC(&drawarea_style_set_cb), NULL);
gui.visibility = GDK_VISIBILITY_UNOBSCURED;
#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
wm_protocols_atom = gdk_atom_intern("WM_PROTOCOLS", FALSE);
save_yourself_atom = gdk_atom_intern("WM_SAVE_YOURSELF", FALSE);
#endif
if (gtk_socket_id != 0)
/* make sure keyboard input can go to the drawarea */
GTK_WIDGET_SET_FLAGS(gui.drawarea, GTK_CAN_FOCUS);
/*
* Set clipboard specific atoms
*/
vim_atom = gdk_atom_intern(VIM_ATOM_NAME, FALSE);
vimenc_atom = gdk_atom_intern(VIMENC_ATOM_NAME, FALSE);
clip_star.gtk_sel_atom = GDK_SELECTION_PRIMARY;
clip_plus.gtk_sel_atom = gdk_atom_intern("CLIPBOARD", FALSE);
/*
* Start out by adding the configured border width into the border offset.
*/
gui.border_offset = gui.border_width;
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "visibility_notify_event",
GTK_SIGNAL_FUNC(visibility_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "expose_event",
GTK_SIGNAL_FUNC(expose_event), NULL);
/*
* Only install these enter/leave callbacks when 'p' in 'guioptions'.
* Only needed for some window managers.
*/
if (vim_strchr(p_go, GO_POINTER) != NULL)
{
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "leave_notify_event",
GTK_SIGNAL_FUNC(leave_notify_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "enter_notify_event",
GTK_SIGNAL_FUNC(enter_notify_event), NULL);
}
/* Real windows can get focus ... GtkPlug, being a mere container can't,
* only its widgets. Arguably, this could be common code and we not use
* the window focus at all, but let's be safe.
*/
if (gtk_socket_id == 0)
{
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_out_event",
GTK_SIGNAL_FUNC(focus_out_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_in_event",
GTK_SIGNAL_FUNC(focus_in_event), NULL);
}
else
{
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_out_event",
GTK_SIGNAL_FUNC(focus_out_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_in_event",
GTK_SIGNAL_FUNC(focus_in_event), NULL);
#ifdef FEAT_GUI_TABLINE
gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_out_event",
GTK_SIGNAL_FUNC(focus_out_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_in_event",
GTK_SIGNAL_FUNC(focus_in_event), NULL);
#endif /* FEAT_GUI_TABLINE */
}
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "motion_notify_event",
GTK_SIGNAL_FUNC(motion_notify_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_press_event",
GTK_SIGNAL_FUNC(button_press_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_release_event",
GTK_SIGNAL_FUNC(button_release_event), NULL);
g_signal_connect(G_OBJECT(gui.drawarea), "scroll_event",
G_CALLBACK(&scroll_event), NULL);
/*
* Add selection handler functions.
*/
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_clear_event",
GTK_SIGNAL_FUNC(selection_clear_event), NULL);
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_received",
GTK_SIGNAL_FUNC(selection_received_cb), NULL);
gui_gtk_set_selection_targets();
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_get",
GTK_SIGNAL_FUNC(selection_get_cb), NULL);
/* Pretend we don't have input focus, we will get an event if we do. */
gui.in_focus = FALSE;
return OK;
}
#if (defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)) || defined(PROTO)
/*
* This is called from gui_start() after a fork() has been done.
* We have to tell the session manager our new PID.
*/
void
gui_mch_forked(void)
{
if (using_gnome)
{
GnomeClient *client;
client = gnome_master_client();
if (client != NULL)
gnome_client_set_process_id(client, getpid());
}
}
#endif /* FEAT_GUI_GNOME && FEAT_SESSION */
/*
* Called when the foreground or background color has been changed.
* This used to change the graphics contexts directly but we are
* currently manipulating them where desired.
*/
void
gui_mch_new_colors(void)
{
if (gui.drawarea != NULL && gui.drawarea->window != NULL)
{
GdkColor color = { 0, 0, 0, 0 };
color.pixel = gui.back_pixel;
gdk_window_set_background(gui.drawarea->window, &color);
}
}
/*
* This signal informs us about the need to rearrange our sub-widgets.
*/
static gint
form_configure_event(GtkWidget *widget UNUSED,
GdkEventConfigure *event,
gpointer data UNUSED)
{
int usable_height = event->height;
/* When in a GtkPlug, we can't guarantee valid heights (as a round
* no. of char-heights), so we have to manually sanitise them.
* Widths seem to sort themselves out, don't ask me why.
*/
if (gtk_socket_id != 0)
usable_height -= (gui.char_height - (gui.char_height/2)); /* sic. */
gtk_form_freeze(GTK_FORM(gui.formwin));
gui_resize_shell(event->width, usable_height);
gtk_form_thaw(GTK_FORM(gui.formwin));
return TRUE;
}
/*
* Function called when window already closed.
* We can't do much more here than to trying to preserve what had been done,
* since the window is already inevitably going away.
*/
static void
mainwin_destroy_cb(GtkObject *object UNUSED, gpointer data UNUSED)
{
/* Don't write messages to the GUI anymore */
full_screen = FALSE;
gui.mainwin = NULL;
gui.drawarea = NULL;
if (!exiting) /* only do anything if the destroy was unexpected */
{
vim_strncpy(IObuff,
(char_u *)_("Vim: Main window unexpectedly destroyed\n"),
IOSIZE - 1);
preserve_exit();
}
}
/*
* Bit of a hack to ensure we start GtkPlug windows with the correct window
* hints (and thus the required size from -geom), but that after that we
* put the hints back to normal (the actual minimum size) so we may
* subsequently be resized smaller. GtkSocket (the parent end) uses the
* plug's window 'min hints to set *it's* minimum size, but that's also the
* only way we have of making ourselves bigger (by set lines/columns).
* Thus set hints at start-up to ensure correct init. size, then a
* second after the final attempt to reset the real minimum hinst (done by
* scrollbar init.), actually do the standard hinst and stop the timer.
* We'll not let the default hints be set while this timer's active.
*/
static gboolean
check_startup_plug_hints(gpointer data UNUSED)
{
if (init_window_hints_state == 1)
{
/* Safe to use normal hints now */
init_window_hints_state = 0;
update_window_manager_hints(0, 0);
return FALSE; /* stop timer */
}
/* Keep on trying */
init_window_hints_state = 1;
return TRUE;
}
/*
* Open the GUI window which was created by a call to gui_mch_init().
*/
int
gui_mch_open(void)
{
guicolor_T fg_pixel = INVALCOLOR;
guicolor_T bg_pixel = INVALCOLOR;
guint pixel_width;
guint pixel_height;
/*
* Allow setting a window role on the command line, or invent one
* if none was specified. This is mainly useful for GNOME session
* support; allowing the WM to restore window placement.
*/
if (role_argument != NULL)
{
gtk_window_set_role(GTK_WINDOW(gui.mainwin), role_argument);
}
else
{
char *role;
/* Invent a unique-enough ID string for the role */
role = g_strdup_printf("vim-%u-%u-%u",
(unsigned)mch_get_pid(),
(unsigned)g_random_int(),
(unsigned)time(NULL));
gtk_window_set_role(GTK_WINDOW(gui.mainwin), role);
g_free(role);
}
if (gui_win_x != -1 && gui_win_y != -1)
gtk_window_move(GTK_WINDOW(gui.mainwin), gui_win_x, gui_win_y);
/* Determine user specified geometry, if present. */
if (gui.geom != NULL)
{
int mask;
unsigned int w, h;
int x = 0;
int y = 0;
mask = XParseGeometry((char *)gui.geom, &x, &y, &w, &h);
if (mask & WidthValue)
Columns = w;
if (mask & HeightValue)
{
if (p_window > (long)h - 1 || !option_was_set((char_u *)"window"))
p_window = h - 1;
Rows = h;
}
pixel_width = (guint)(gui_get_base_width() + Columns * gui.char_width);
pixel_height = (guint)(gui_get_base_height() + Rows * gui.char_height);
pixel_width += get_menu_tool_width();
pixel_height += get_menu_tool_height();
if (mask & (XValue | YValue))
{
int ww, hh;
gui_mch_get_screen_dimensions(&ww, &hh);
hh += p_ghr + get_menu_tool_height();
ww += get_menu_tool_width();
if (mask & XNegative)
x += ww - pixel_width;
if (mask & YNegative)
y += hh - pixel_height;
gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
}
vim_free(gui.geom);
gui.geom = NULL;
/* From now until everyone's stopped trying to set the window hints
* to their correct minimum values, stop them being set as we need
* them to remain at our required size for the parent GtkSocket to
* give us the right initial size.
*/
if (gtk_socket_id != 0 && (mask & WidthValue || mask & HeightValue))
{
update_window_manager_hints(pixel_width, pixel_height);
init_window_hints_state = 1;
g_timeout_add(1000, check_startup_plug_hints, NULL);
}
}
pixel_width = (guint)(gui_get_base_width() + Columns * gui.char_width);
pixel_height = (guint)(gui_get_base_height() + Rows * gui.char_height);
/* For GTK2 changing the size of the form widget doesn't cause window
* resizing. */
if (gtk_socket_id == 0)
gtk_window_resize(GTK_WINDOW(gui.mainwin), pixel_width, pixel_height);
update_window_manager_hints(0, 0);
if (foreground_argument != NULL)
fg_pixel = gui_get_color((char_u *)foreground_argument);
if (fg_pixel == INVALCOLOR)
fg_pixel = gui_get_color((char_u *)"Black");
if (background_argument != NULL)
bg_pixel = gui_get_color((char_u *)background_argument);
if (bg_pixel == INVALCOLOR)
bg_pixel = gui_get_color((char_u *)"White");
if (found_reverse_arg)
{
gui.def_norm_pixel = bg_pixel;
gui.def_back_pixel = fg_pixel;
}
else
{
gui.def_norm_pixel = fg_pixel;
gui.def_back_pixel = bg_pixel;
}
/* Get the colors from the "Normal" and "Menu" 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 */
gui_check_colors();
/* Get the colors for the highlight groups (gui_check_colors() might have
* changed them). */
highlight_gui_started(); /* re-init colors and fonts */
gtk_signal_connect(GTK_OBJECT(gui.mainwin), "destroy",
GTK_SIGNAL_FUNC(mainwin_destroy_cb), NULL);
#ifdef FEAT_HANGULIN
hangul_keyboard_set();
#endif
/*
* Notify the fixed area about the need to resize the contents of the
* gui.formwin, which we use for random positioning of the included
* components.
*
* We connect this signal deferred finally after anything is in place,
* since this is intended to handle resizements coming from the window
* manager upon us and should not interfere with what VIM is requesting
* upon startup.
*/
gtk_signal_connect(GTK_OBJECT(gui.formwin), "configure_event",
GTK_SIGNAL_FUNC(form_configure_event), NULL);
#ifdef FEAT_DND
/* Set up for receiving DND items. */
gui_gtk_set_dnd_targets();
gtk_signal_connect(GTK_OBJECT(gui.drawarea), "drag_data_received",
GTK_SIGNAL_FUNC(drag_data_received_cb), NULL);
#endif
/* With GTK+ 2, we need to iconify the window before calling show()
* to avoid mapping the window for a short time. */
if (found_iconic_arg && gtk_socket_id == 0)
gui_mch_iconify();
{
#if defined(FEAT_GUI_GNOME) && defined(FEAT_MENU)
unsigned long menu_handler = 0;
# ifdef FEAT_TOOLBAR
unsigned long tool_handler = 0;
# endif
/*
* Urgh hackish :/ For some reason BonoboDockLayout always forces a
* show when restoring the saved layout configuration. We can't just
* hide the widgets again after gtk_widget_show(gui.mainwin) since it's
* a toplevel window and thus will be realized immediately. Instead,
* connect signal handlers to hide the widgets just after they've been
* marked visible, but before the main window is realized.
*/
if (using_gnome && vim_strchr(p_go, GO_MENUS) == NULL)
menu_handler = g_signal_connect_after(gui.menubar_h, "show",
G_CALLBACK(>k_widget_hide),
NULL);
# ifdef FEAT_TOOLBAR
if (using_gnome && vim_strchr(p_go, GO_TOOLBAR) == NULL
&& (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
tool_handler = g_signal_connect_after(gui.toolbar_h, "show",
G_CALLBACK(>k_widget_hide),
NULL);
# endif
#endif
gtk_widget_show(gui.mainwin);
#if defined(FEAT_GUI_GNOME) && defined(FEAT_MENU)
if (menu_handler != 0)
g_signal_handler_disconnect(gui.menubar_h, menu_handler);
# ifdef FEAT_TOOLBAR
if (tool_handler != 0)
g_signal_handler_disconnect(gui.toolbar_h, tool_handler);
# endif
#endif
}
return OK;
}
void
gui_mch_exit(int rc UNUSED)
{
if (gui.mainwin != NULL)
gtk_widget_destroy(gui.mainwin);
}
/*
* Get the position of the top left corner of the window.
*/
int
gui_mch_get_winpos(int *x, int *y)
{
gtk_window_get_position(GTK_WINDOW(gui.mainwin), x, y);
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)
{
gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
}
#if 0
static int resize_idle_installed = FALSE;
/*
* Idle handler to force resize. Used by gui_mch_set_shellsize() to ensure
* the shell size doesn't exceed the window size, i.e. if the window manager
* ignored our size request. Usually this happens if the window is maximized.
*
* FIXME: It'd be nice if we could find a little more orthodox solution.
* See also the remark below in gui_mch_set_shellsize().
*
* DISABLED: When doing ":set lines+=1" this function would first invoke
* gui_resize_shell() with the old size, then the normal callback would
* report the new size through form_configure_event(). That caused the window
* layout to be messed up.
*/
static gboolean
force_shell_resize_idle(gpointer data)
{
if (gui.mainwin != NULL
&& GTK_WIDGET_REALIZED(gui.mainwin)
&& GTK_WIDGET_VISIBLE(gui.mainwin))
{
int width;
int height;
gtk_window_get_size(GTK_WINDOW(gui.mainwin), &width, &height);
width -= get_menu_tool_width();
height -= get_menu_tool_height();
gui_resize_shell(width, height);
}
resize_idle_installed = FALSE;
return FALSE; /* don't call me again */
}
#endif
/*
* Return TRUE if the main window is maximized.
*/
int
gui_mch_maximized()
{
return (gui.mainwin != NULL && gui.mainwin->window != NULL
&& (gdk_window_get_state(gui.mainwin->window)
& GDK_WINDOW_STATE_MAXIMIZED));
}
/*
* Unmaximize the main window
*/
void
gui_mch_unmaximize()
{
if (gui.mainwin != NULL)
gtk_window_unmaximize(GTK_WINDOW(gui.mainwin));
}
/*
* 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()
{
int w, h;
gtk_window_get_size(GTK_WINDOW(gui.mainwin), &w, &h);
w -= get_menu_tool_width();
h -= get_menu_tool_height();
gui_resize_shell(w, h);
}
/*
* Set the windows size.
*/
void
gui_mch_set_shellsize(int width, int height,
int min_width UNUSED, int min_height UNUSED,
int base_width UNUSED, int base_height UNUSED,
int direction UNUSED)
{
/* give GTK+ a chance to put all widget's into place */
gui_mch_update();
/* this will cause the proper resizement to happen too */
if (gtk_socket_id == 0)
update_window_manager_hints(0, 0);
/* With GTK+ 2, changing the size of the form widget doesn't resize
* the window. So let's do it the other way around and resize the
* main window instead. */
width += get_menu_tool_width();
height += get_menu_tool_height();
if (gtk_socket_id == 0)
gtk_window_resize(GTK_WINDOW(gui.mainwin), width, height);
else
update_window_manager_hints(width, height);
# if 0
if (!resize_idle_installed)
{
g_idle_add_full(GDK_PRIORITY_EVENTS + 10,
&force_shell_resize_idle, NULL, NULL);
resize_idle_installed = TRUE;
}
# endif
/*
* Wait until all events are processed to prevent a crash because the
* real size of the drawing area doesn't reflect Vim's internal ideas.
*
* This is a bit of a hack, since Vim is a terminal application with a GUI
* on top, while the GUI expects to be the boss.
*/
gui_mch_update();
}
/*
* The screen size is used to make sure the initial window doesn't get bigger
* than the screen. This subtracts some room for menubar, toolbar and window
* decorations.
*/
void
gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
{
#ifdef HAVE_GTK_MULTIHEAD
GdkScreen* screen;
if (gui.mainwin != NULL && gtk_widget_has_screen(gui.mainwin))
screen = gtk_widget_get_screen(gui.mainwin);
else
screen = gdk_screen_get_default();
*screen_w = gdk_screen_get_width(screen);
*screen_h = gdk_screen_get_height(screen) - p_ghr;
#else
*screen_w = gdk_screen_width();
/* Subtract 'guiheadroom' from the height to allow some room for the
* window manager (task list and window title bar). */
*screen_h = gdk_screen_height() - p_ghr;
#endif
/*
* FIXME: dirty trick: Because the gui_get_base_height() doesn't include
* the toolbar and menubar for GTK, we subtract them from the screen
* height, so that the window size can be made to fit on the screen.
* This should be completely changed later.
*/
*screen_w -= get_menu_tool_width();
*screen_h -= get_menu_tool_height();
}
#if defined(FEAT_TITLE) || defined(PROTO)
void
gui_mch_settitle(char_u *title, char_u *icon UNUSED)
{
if (title != NULL && output_conv.vc_type != CONV_NONE)
title = string_convert(&output_conv, title, NULL);
gtk_window_set_title(GTK_WINDOW(gui.mainwin), (const char *)title);
if (output_conv.vc_type != CONV_NONE)
vim_free(title);
}
#endif /* FEAT_TITLE */
#if defined(FEAT_MENU) || defined(PROTO)
void
gui_mch_enable_menu(int showit)
{
GtkWidget *widget;
# ifdef FEAT_GUI_GNOME
if (using_gnome)
widget = gui.menubar_h;
else
# endif
widget = gui.menubar;
/* Do not disable the menu while starting up, otherwise F10 doesn't work. */
if (!showit != !GTK_WIDGET_VISIBLE(widget) && !gui.starting)
{
if (showit)
gtk_widget_show(widget);
else
gtk_widget_hide(widget);
update_window_manager_hints(0, 0);
}
}
#endif /* FEAT_MENU */
#if defined(FEAT_TOOLBAR) || defined(PROTO)
void
gui_mch_show_toolbar(int showit)
{
GtkWidget *widget;
if (gui.toolbar == NULL)
return;
# ifdef FEAT_GUI_GNOME
if (using_gnome)
widget = gui.toolbar_h;
else
# endif
widget = gui.toolbar;
if (showit)
set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
if (!showit != !GTK_WIDGET_VISIBLE(widget))
{
if (showit)
gtk_widget_show(widget);
else
gtk_widget_hide(widget);
update_window_manager_hints(0, 0);
}
}
#endif /* FEAT_TOOLBAR */
/*
* Check if a given font is a CJK font. This is done in a very crude manner. It
* just see if U+04E00 for zh and ja and U+AC00 for ko are covered in a given
* font. Consequently, this function cannot be used as a general purpose check
* for CJK-ness for which fontconfig APIs should be used. This is only used by
* gui_mch_init_font() to deal with 'CJK fixed width fonts'.
*/
static int
is_cjk_font(PangoFontDescription *font_desc)
{
static const char * const cjk_langs[] =
{"zh_CN", "zh_TW", "zh_HK", "ja", "ko"};
PangoFont *font;
unsigned i;
int is_cjk = FALSE;
font = pango_context_load_font(gui.text_context, font_desc);
if (font == NULL)
return FALSE;
for (i = 0; !is_cjk && i < G_N_ELEMENTS(cjk_langs); ++i)
{
PangoCoverage *coverage;
gunichar uc;
coverage = pango_font_get_coverage(
font, pango_language_from_string(cjk_langs[i]));
if (coverage != NULL)
{
uc = (cjk_langs[i][0] == 'k') ? 0xAC00 : 0x4E00;
is_cjk = (pango_coverage_get(coverage, uc) == PANGO_COVERAGE_EXACT);
pango_coverage_unref(coverage);
}
}
g_object_unref(font);
return is_cjk;
}
/*
* Adjust gui.char_height (after 'linespace' was changed).
*/
int
gui_mch_adjust_charheight(void)
{
PangoFontMetrics *metrics;
int ascent;
int descent;
metrics = pango_context_get_metrics(gui.text_context, gui.norm_font,
pango_context_get_language(gui.text_context));
ascent = pango_font_metrics_get_ascent(metrics);
descent = pango_font_metrics_get_descent(metrics);
pango_font_metrics_unref(metrics);
gui.char_height = (ascent + descent + PANGO_SCALE - 1) / PANGO_SCALE
+ p_linespace;
/* LINTED: avoid warning: bitwise operation on signed value */
gui.char_ascent = PANGO_PIXELS(ascent + p_linespace * PANGO_SCALE / 2);
/* A not-positive value of char_height may crash Vim. Only happens
* if 'linespace' is negative (which does make sense sometimes). */
gui.char_ascent = MAX(gui.char_ascent, 0);
gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
return OK;
}
/*
* Put up a font dialog and return the selected font name in allocated memory.
* "oldval" is the previous value. Return NULL when cancelled.
* This should probably go into gui_gtk.c. Hmm.
* FIXME:
* The GTK2 font selection dialog has no filtering API. So we could either
* a) implement our own (possibly copying the code from somewhere else) or
* b) just live with it.
*/
char_u *
gui_mch_font_dialog(char_u *oldval)
{
GtkWidget *dialog;
int response;
char_u *fontname = NULL;
char_u *oldname;
dialog = gtk_font_selection_dialog_new(NULL);
gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(gui.mainwin));
gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE);
if (oldval != NULL && oldval[0] != NUL)
{
if (output_conv.vc_type != CONV_NONE)
oldname = string_convert(&output_conv, oldval, NULL);
else
oldname = oldval;
/* Annoying bug in GTK (or Pango): if the font name does not include a
* size, zero is used. Use default point size ten. */
if (!vim_isdigit(oldname[STRLEN(oldname) - 1]))
{
char_u *p = vim_strnsave(oldname, STRLEN(oldname) + 3);
if (p != NULL)
{
STRCPY(p + STRLEN(p), " 10");
if (oldname != oldval)
vim_free(oldname);
oldname = p;
}
}
gtk_font_selection_dialog_set_font_name(
GTK_FONT_SELECTION_DIALOG(dialog), (const char *)oldname);
if (oldname != oldval)
vim_free(oldname);
}
else
gtk_font_selection_dialog_set_font_name(
GTK_FONT_SELECTION_DIALOG(dialog), DEFAULT_FONT);
response = gtk_dialog_run(GTK_DIALOG(dialog));
if (response == GTK_RESPONSE_OK)
{
char *name;
name = gtk_font_selection_dialog_get_font_name(
GTK_FONT_SELECTION_DIALOG(dialog));
if (name != NULL)
{
char_u *p;
/* Apparently some font names include a comma, need to escape
* that, because in 'guifont' it separates names. */
p = vim_strsave_escaped((char_u *)name, (char_u *)",");
g_free(name);
if (p != NULL && input_conv.vc_type != CONV_NONE)
{
fontname = string_convert(&input_conv, p, NULL);
vim_free(p);
}
else
fontname = p;
}
}
if (response != GTK_RESPONSE_NONE)
gtk_widget_destroy(dialog);
return fontname;
}
/*
* Some monospace fonts don't support a bold weight, and fall back
* silently to the regular weight. But this is no good since our text
* drawing function can emulate bold by overstriking. So let's try
* to detect whether bold weight is actually available and emulate it
* otherwise.
*
* Note that we don't need to check for italic style since Xft can
* emulate italic on its own, provided you have a proper fontconfig
* setup. We wouldn't be able to emulate it in Vim anyway.
*/
static void
get_styled_font_variants(void)
{
PangoFontDescription *bold_font_desc;
PangoFont *plain_font;
PangoFont *bold_font;
gui.font_can_bold = FALSE;
plain_font = pango_context_load_font(gui.text_context, gui.norm_font);
if (plain_font == NULL)
return;
bold_font_desc = pango_font_description_copy_static(gui.norm_font);
pango_font_description_set_weight(bold_font_desc, PANGO_WEIGHT_BOLD);
bold_font = pango_context_load_font(gui.text_context, bold_font_desc);
/*
* The comparison relies on the unique handle nature of a PangoFont*,
* i.e. it's assumed that a different PangoFont* won't refer to the
* same font. Seems to work, and failing here isn't critical anyway.
*/
if (bold_font != NULL)
{
gui.font_can_bold = (bold_font != plain_font);
g_object_unref(bold_font);
}
pango_font_description_free(bold_font_desc);
g_object_unref(plain_font);
}
static PangoEngineShape *default_shape_engine = NULL;
/*
* Create a map from ASCII characters in the range [32,126] to glyphs
* of the current font. This is used by gui_gtk2_draw_string() to skip
* the itemize and shaping process for the most common case.
*/
static void
ascii_glyph_table_init(void)
{
char_u ascii_chars[128];
PangoAttrList *attr_list;
GList *item_list;
int i;
if (gui.ascii_glyphs != NULL)
pango_glyph_string_free(gui.ascii_glyphs);
if (gui.ascii_font != NULL)
g_object_unref(gui.ascii_font);
gui.ascii_glyphs = NULL;
gui.ascii_font = NULL;
/* For safety, fill in question marks for the control characters. */
for (i = 0; i < 32; ++i)
ascii_chars[i] = '?';
for (; i < 127; ++i)
ascii_chars[i] = i;
ascii_chars[i] = '?';
attr_list = pango_attr_list_new();
item_list = pango_itemize(gui.text_context, (const char *)ascii_chars,
0, sizeof(ascii_chars), attr_list, NULL);
if (item_list != NULL && item_list->next == NULL) /* play safe */
{
PangoItem *item;
int width;
item = (PangoItem *)item_list->data;
width = gui.char_width * PANGO_SCALE;
/* Remember the shape engine used for ASCII. */
default_shape_engine = item->analysis.shape_engine;
gui.ascii_font = item->analysis.font;
g_object_ref(gui.ascii_font);
gui.ascii_glyphs = pango_glyph_string_new();
pango_shape((const char *)ascii_chars, sizeof(ascii_chars),
&item->analysis, gui.ascii_glyphs);
g_return_if_fail(gui.ascii_glyphs->num_glyphs == sizeof(ascii_chars));
for (i = 0; i < gui.ascii_glyphs->num_glyphs; ++i)
{
PangoGlyphGeometry *geom;
geom = &gui.ascii_glyphs->glyphs[i].geometry;
geom->x_offset += MAX(0, width - geom->width) / 2;
geom->width = width;
}
}
g_list_foreach(item_list, (GFunc)&pango_item_free, NULL);
g_list_free(item_list);
pango_attr_list_unref(attr_list);
}
/*
* Initialize Vim to use the font or fontset with the given name.
* Return FAIL if the font could not be loaded, OK otherwise.
*/
int
gui_mch_init_font(char_u *font_name, int fontset UNUSED)
{
PangoFontDescription *font_desc;
PangoLayout *layout;
int width;
/* If font_name is NULL, this means to use the default, which should
* be present on all proper Pango/fontconfig installations. */
if (font_name == NULL)
font_name = (char_u *)DEFAULT_FONT;
font_desc = gui_mch_get_font(font_name, FALSE);
if (font_desc == NULL)
return FAIL;
gui_mch_free_font(gui.norm_font);
gui.norm_font = font_desc;
pango_context_set_font_description(gui.text_context, font_desc);
layout = pango_layout_new(gui.text_context);
pango_layout_set_text(layout, "MW", 2);
pango_layout_get_size(layout, &width, NULL);
/*
* Set char_width to half the width obtained from pango_layout_get_size()
* for CJK fixed_width/bi-width fonts. An unpatched version of Xft leads
* Pango to use the same width for both non-CJK characters (e.g. Latin
* letters and numbers) and CJK characters. This results in 's p a c e d
* o u t' rendering when a CJK 'fixed width' font is used. To work around
* that, divide the width returned by Pango by 2 if cjk_width is equal to
* width for CJK fonts.
*
* For related bugs, see:
* http://bugzilla.gnome.org/show_bug.cgi?id=106618
* http://bugzilla.gnome.org/show_bug.cgi?id=106624
*
* With this, for all four of the following cases, Vim works fine:
* guifont=CJK_fixed_width_font
* guifont=Non_CJK_fixed_font
* guifont=Non_CJK_fixed_font,CJK_Fixed_font
* guifont=Non_CJK_fixed_font guifontwide=CJK_fixed_font
*/
if (is_cjk_font(gui.norm_font))
{
int cjk_width;
/* Measure the text extent of U+4E00 and U+4E8C */
pango_layout_set_text(layout, "\344\270\200\344\272\214", -1);
pango_layout_get_size(layout, &cjk_width, NULL);
if (width == cjk_width) /* Xft not patched */
width /= 2;
}
g_object_unref(layout);
gui.char_width = (width / 2 + PANGO_SCALE - 1) / PANGO_SCALE;
/* A zero width may cause a crash. Happens for semi-invalid fontsets. */
if (gui.char_width <= 0)
gui.char_width = 8;
gui_mch_adjust_charheight();
/* Set the fontname, which will be used for information purposes */
hl_set_font_name(font_name);
get_styled_font_variants();
ascii_glyph_table_init();
/* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
if (gui.wide_font != NULL
&& pango_font_description_equal(gui.norm_font, gui.wide_font))
{
pango_font_description_free(gui.wide_font);
gui.wide_font = NULL;
}
if (gui_mch_maximized())
{
/* Update lines and columns in accordance with the new font, keep the
* window maximized. */
gui_mch_newfont();
}
else
{
/* Preserve the logical dimensions of the screen. */
update_window_manager_hints(0, 0);
}
return OK;
}
/*
* Get a reference to the font "name".
* Return zero for failure.
*/
GuiFont
gui_mch_get_font(char_u *name, int report_error)
{
PangoFontDescription *font;
/* can't do this when GUI is not running */
if (!gui.in_use || name == NULL)
return NULL;
if (output_conv.vc_type != CONV_NONE)
{
char_u *buf;
buf = string_convert(&output_conv, name, NULL);
if (buf != NULL)
{
font = pango_font_description_from_string((const char *)buf);
vim_free(buf);
}
else
font = NULL;
}
else
font = pango_font_description_from_string((const char *)name);
if (font != NULL)
{
PangoFont *real_font;
/* pango_context_load_font() bails out if no font size is set */
if (pango_font_description_get_size(font) <= 0)
pango_font_description_set_size(font, 10 * PANGO_SCALE);
real_font = pango_context_load_font(gui.text_context, font);
if (real_font == NULL)
{
pango_font_description_free(font);
font = NULL;
}
else
g_object_unref(real_font);
}
if (font == NULL)
{
if (report_error)
EMSG2(_((char *)e_font), name);
return NULL;
}
return font;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return the name of font "font" in allocated memory.
*/
char_u *
gui_mch_get_fontname(GuiFont font, char_u *name UNUSED)
{
if (font != NOFONT)
{
char *pangoname = pango_font_description_to_string(font);
if (pangoname != NULL)
{
char_u *s = vim_strsave((char_u *)pangoname);
g_free(pangoname);
return s;
}
}
return NULL;
}
#endif
/*
* If a font is not going to be used, free its structure.
*/
void
gui_mch_free_font(GuiFont font)
{
if (font != NOFONT)
pango_font_description_free(font);
}
/*
* Return the Pixel value (color) for the given color name. This routine was
* pretty much taken from example code in the Silicon Graphics OSF/Motif
* Programmer's Guide.
* Return INVALCOLOR for error.
*/
guicolor_T
gui_mch_get_color(char_u *name)
{
/* A number of colors that some X11 systems don't have */
static const char *const vimnames[][2] =
{
{"LightRed", "#FFBBBB"},
{"LightGreen", "#88FF88"},
{"LightMagenta","#FFBBFF"},
{"DarkCyan", "#008888"},
{"DarkBlue", "#0000BB"},
{"DarkRed", "#BB0000"},
{"DarkMagenta", "#BB00BB"},
{"DarkGrey", "#BBBBBB"},
{"DarkYellow", "#BBBB00"},
{"Gray10", "#1A1A1A"},
{"Grey10", "#1A1A1A"},
{"Gray20", "#333333"},
{"Grey20", "#333333"},
{"Gray30", "#4D4D4D"},
{"Grey30", "#4D4D4D"},
{"Gray40", "#666666"},
{"Grey40", "#666666"},
{"Gray50", "#7F7F7F"},
{"Grey50", "#7F7F7F"},
{"Gray60", "#999999"},
{"Grey60", "#999999"},
{"Gray70", "#B3B3B3"},
{"Grey70", "#B3B3B3"},
{"Gray80", "#CCCCCC"},
{"Grey80", "#CCCCCC"},
{"Gray90", "#E5E5E5"},
{"Grey90", "#E5E5E5"},
{NULL, NULL}
};
if (!gui.in_use) /* can't do this when GUI not running */
return INVALCOLOR;
while (name != NULL)
{
GdkColor color;
int parsed;
int i;
parsed = gdk_color_parse((const char *)name, &color);
if (parsed)
{
gdk_colormap_alloc_color(gtk_widget_get_colormap(gui.drawarea),
&color, FALSE, TRUE);
return (guicolor_T)color.pixel;
}
/* add a few builtin names and try again */
for (i = 0; ; ++i)
{
if (vimnames[i][0] == NULL)
{
name = NULL;
break;
}
if (STRICMP(name, vimnames[i][0]) == 0)
{
name = (char_u *)vimnames[i][1];
break;
}
}
}
return INVALCOLOR;
}
/*
* Set the current text foreground color.
*/
void
gui_mch_set_fg_color(guicolor_T color)
{
gui.fgcolor->pixel = (unsigned long)color;
}
/*
* Set the current text background color.
*/
void
gui_mch_set_bg_color(guicolor_T color)
{
gui.bgcolor->pixel = (unsigned long)color;
}
/*
* Set the current text special color.
*/
void
gui_mch_set_sp_color(guicolor_T color)
{
gui.spcolor->pixel = (unsigned long)color;
}
/*
* Function-like convenience macro for the sake of efficiency.
*/
#define INSERT_PANGO_ATTR(Attribute, AttrList, Start, End) \
G_STMT_START{ \
PangoAttribute *tmp_attr_; \
tmp_attr_ = (Attribute); \
tmp_attr_->start_index = (Start); \
tmp_attr_->end_index = (End); \
pango_attr_list_insert((AttrList), tmp_attr_); \
}G_STMT_END
static void
apply_wide_font_attr(char_u *s, int len, PangoAttrList *attr_list)
{
char_u *start = NULL;
char_u *p;
int uc;
for (p = s; p < s + len; p += utf_byte2len(*p))
{
uc = utf_ptr2char(p);
if (start == NULL)
{
if (uc >= 0x80 && utf_char2cells(uc) == 2)
start = p;
}
else if (uc < 0x80 /* optimization shortcut */
|| (utf_char2cells(uc) != 2 && !utf_iscomposing(uc)))
{
INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
attr_list, start - s, p - s);
start = NULL;
}
}
if (start != NULL)
INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
attr_list, start - s, len);
}
static int
count_cluster_cells(char_u *s, PangoItem *item,
PangoGlyphString* glyphs, int i,
int *cluster_width,
int *last_glyph_rbearing)
{
char_u *p;
int next; /* glyph start index of next cluster */
int start, end; /* string segment of current cluster */
int width; /* real cluster width in Pango units */
int uc;
int cellcount = 0;
width = glyphs->glyphs[i].geometry.width;
for (next = i + 1; next < glyphs->num_glyphs; ++next)
{
if (glyphs->glyphs[next].attr.is_cluster_start)
break;
else if (glyphs->glyphs[next].geometry.width > width)
width = glyphs->glyphs[next].geometry.width;
}
start = item->offset + glyphs->log_clusters[i];
end = item->offset + ((next < glyphs->num_glyphs) ?
glyphs->log_clusters[next] : item->length);
for (p = s + start; p < s + end; p += utf_byte2len(*p))
{
uc = utf_ptr2char(p);
if (uc < 0x80)
++cellcount;
else if (!utf_iscomposing(uc))
cellcount += utf_char2cells(uc);
}
if (last_glyph_rbearing != NULL
&& cellcount > 0 && next == glyphs->num_glyphs)
{
PangoRectangle ink_rect;
/*
* If a certain combining mark had to be taken from a non-monospace
* font, we have to compensate manually by adapting x_offset according
* to the ink extents of the previous glyph.
*/
pango_font_get_glyph_extents(item->analysis.font,
glyphs->glyphs[i].glyph,
&ink_rect, NULL);
if (PANGO_RBEARING(ink_rect) > 0)
*last_glyph_rbearing = PANGO_RBEARING(ink_rect);
}
if (cellcount > 0)
*cluster_width = width;
return cellcount;
}
/*
* If there are only combining characters in the cluster, we cannot just
* change the width of the previous glyph since there is none. Therefore
* some guesswork is needed.
*
* If ink_rect.x is negative Pango apparently has taken care of the composing
* by itself. Actually setting x_offset = 0 should be sufficient then, but due
* to problems with composing from different fonts we still need to fine-tune
* x_offset to avoid ugliness.
*
* If ink_rect.x is not negative, force overstriking by pointing x_offset to
* the position of the previous glyph. Apparently this happens only with old
* X fonts which don't provide the special combining information needed by
* Pango.
*/
static void
setup_zero_width_cluster(PangoItem *item, PangoGlyphInfo *glyph,
int last_cellcount, int last_cluster_width,
int last_glyph_rbearing)
{
PangoRectangle ink_rect;
PangoRectangle logical_rect;
int width;
width = last_cellcount * gui.char_width * PANGO_SCALE;
glyph->geometry.x_offset = -width + MAX(0, width - last_cluster_width) / 2;
glyph->geometry.width = 0;
pango_font_get_glyph_extents(item->analysis.font,
glyph->glyph,
&ink_rect, &logical_rect);
if (ink_rect.x < 0)
{
glyph->geometry.x_offset += last_glyph_rbearing;
glyph->geometry.y_offset = logical_rect.height
- (gui.char_height - p_linespace) * PANGO_SCALE;
}
else
/* If the accent width is smaller than the cluster width, position it
* in the middle. */
glyph->geometry.x_offset = -width + MAX(0, width - ink_rect.width) / 2;
}
static void
draw_glyph_string(int row, int col, int num_cells, int flags,
PangoFont *font, PangoGlyphString *glyphs)
{
if (!(flags & DRAW_TRANSP))
{
gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
gdk_draw_rectangle(gui.drawarea->window,
gui.text_gc,
TRUE,
FILL_X(col),
FILL_Y(row),
num_cells * gui.char_width,
gui.char_height);
}
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
gdk_draw_glyphs(gui.drawarea->window,
gui.text_gc,
font,
TEXT_X(col),
TEXT_Y(row),
glyphs);
/* redraw the contents with an offset of 1 to emulate bold */
if ((flags & DRAW_BOLD) && !gui.font_can_bold)
gdk_draw_glyphs(gui.drawarea->window,
gui.text_gc,
font,
TEXT_X(col) + 1,
TEXT_Y(row),
glyphs);
}
/*
* Draw underline and undercurl at the bottom of the character cell.
*/
static void
draw_under(int flags, int row, int col, int cells)
{
int i;
int offset;
static const int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 };
int y = FILL_Y(row + 1) - 1;
/* Undercurl: draw curl at the bottom of the character cell. */
if (flags & DRAW_UNDERC)
{
gdk_gc_set_foreground(gui.text_gc, gui.spcolor);
for (i = FILL_X(col); i < FILL_X(col + cells); ++i)
{
offset = val[i % 8];
gdk_draw_point(gui.drawarea->window, gui.text_gc, i, y - offset);
}
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
}
/* Underline: draw a line at the bottom of the character cell. */
if (flags & DRAW_UNDERL)
{
/* When p_linespace is 0, overwrite the bottom row of pixels.
* Otherwise put the line just below the character. */
if (p_linespace > 1)
y -= p_linespace - 1;
gdk_draw_line(gui.drawarea->window, gui.text_gc,
FILL_X(col), y,
FILL_X(col + cells) - 1, y);
}
}
int
gui_gtk2_draw_string(int row, int col, char_u *s, int len, int flags)
{
GdkRectangle area; /* area for clip mask */
PangoGlyphString *glyphs; /* glyphs of current item */
int column_offset = 0; /* column offset in cells */
int i;
char_u *conv_buf = NULL; /* result of UTF-8 conversion */
char_u *new_conv_buf;
int convlen;
char_u *sp, *bp;
int plen;
if (gui.text_context == NULL || gui.drawarea->window == NULL)
return len;
if (output_conv.vc_type != CONV_NONE)
{
/*
* Convert characters from 'encoding' to 'termencoding', which is set
* to UTF-8 by gui_mch_init(). did_set_string_option() in option.c
* prohibits changing this to something else than UTF-8 if the GUI is
* in use.
*/
convlen = len;
conv_buf = string_convert(&output_conv, s, &convlen);
g_return_val_if_fail(conv_buf != NULL, len);
/* Correct for differences in char width: some chars are
* double-wide in 'encoding' but single-wide in utf-8. Add a space to
* compensate for that. */
for (sp = s, bp = conv_buf; sp < s + len && bp < conv_buf + convlen; )
{
plen = utf_ptr2len(bp);
if ((*mb_ptr2cells)(sp) == 2 && utf_ptr2cells(bp) == 1)
{
new_conv_buf = alloc(convlen + 2);
if (new_conv_buf == NULL)
return len;
plen += bp - conv_buf;
mch_memmove(new_conv_buf, conv_buf, plen);
new_conv_buf[plen] = ' ';
mch_memmove(new_conv_buf + plen + 1, conv_buf + plen,
convlen - plen + 1);
vim_free(conv_buf);
conv_buf = new_conv_buf;
++convlen;
bp = conv_buf + plen;
plen = 1;
}
sp += (*mb_ptr2len)(sp);
bp += plen;
}
s = conv_buf;
len = convlen;
}
/*
* Restrict all drawing to the current screen line in order to prevent
* fuzzy font lookups from messing up the screen.
*/
area.x = gui.border_offset;
area.y = FILL_Y(row);
area.width = gui.num_cols * gui.char_width;
area.height = gui.char_height;
gdk_gc_set_clip_origin(gui.text_gc, 0, 0);
gdk_gc_set_clip_rectangle(gui.text_gc, &area);
glyphs = pango_glyph_string_new();
/*
* Optimization hack: If possible, skip the itemize and shaping process
* for pure ASCII strings. This optimization is particularly effective
* because Vim draws space characters to clear parts of the screen.
*/
if (!(flags & DRAW_ITALIC)
&& !((flags & DRAW_BOLD) && gui.font_can_bold)
&& gui.ascii_glyphs != NULL)
{
char_u *p;
for (p = s; p < s + len; ++p)
if (*p & 0x80)
goto not_ascii;
pango_glyph_string_set_size(glyphs, len);
for (i = 0; i < len; ++i)
{
glyphs->glyphs[i] = gui.ascii_glyphs->glyphs[s[i]];
glyphs->log_clusters[i] = i;
}
draw_glyph_string(row, col, len, flags, gui.ascii_font, glyphs);
column_offset = len;
}
else
not_ascii:
{
PangoAttrList *attr_list;
GList *item_list;
int cluster_width;
int last_glyph_rbearing;
int cells = 0; /* cells occupied by current cluster */
/* Safety check: pango crashes when invoked with invalid utf-8
* characters. */
if (!utf_valid_string(s, s + len))
{
column_offset = len;
goto skipitall;
}
/* original width of the current cluster */
cluster_width = PANGO_SCALE * gui.char_width;
/* right bearing of the last non-composing glyph */
last_glyph_rbearing = PANGO_SCALE * gui.char_width;
attr_list = pango_attr_list_new();
/* If 'guifontwide' is set then use that for double-width characters.
* Otherwise just go with 'guifont' and let Pango do its thing. */
if (gui.wide_font != NULL)
apply_wide_font_attr(s, len, attr_list);
if ((flags & DRAW_BOLD) && gui.font_can_bold)
INSERT_PANGO_ATTR(pango_attr_weight_new(PANGO_WEIGHT_BOLD),
attr_list, 0, len);
if (flags & DRAW_ITALIC)
INSERT_PANGO_ATTR(pango_attr_style_new(PANGO_STYLE_ITALIC),
attr_list, 0, len);
/*
* Break the text into segments with consistent directional level
* and shaping engine. Pure Latin text needs only a single segment,
* so there's no need to worry about the loop's efficiency. Better
* try to optimize elsewhere, e.g. reducing exposes and stuff :)
*/
item_list = pango_itemize(gui.text_context,
(const char *)s, 0, len, attr_list, NULL);
while (item_list != NULL)
{
PangoItem *item;
int item_cells = 0; /* item length in cells */
item = (PangoItem *)item_list->data;
item_list = g_list_delete_link(item_list, item_list);
/*
* Increment the bidirectional embedding level by 1 if it is not
* even. An odd number means the output will be RTL, but we don't
* want that since Vim handles right-to-left text on its own. It
* would probably be sufficient to just set level = 0, but you can
* never know :)
*
* Unfortunately we can't take advantage of Pango's ability to
* render both LTR and RTL at the same time. In order to support
* that, Vim's main screen engine would have to make use of Pango
* functionality.
*/
item->analysis.level = (item->analysis.level + 1) & (~1U);
/* HACK: Overrule the shape engine, we don't want shaping to be
* done, because drawing the cursor would change the display. */
item->analysis.shape_engine = default_shape_engine;
pango_shape((const char *)s + item->offset, item->length,
&item->analysis, glyphs);
/*
* Fixed-width hack: iterate over the array and assign a fixed
* width to each glyph, thus overriding the choice made by the
* shaping engine. We use utf_char2cells() to determine the
* number of cells needed.
*
* Also perform all kind of dark magic to get composing
* characters right (and pretty too of course).
*/
for (i = 0; i < glyphs->num_glyphs; ++i)
{
PangoGlyphInfo *glyph;
glyph = &glyphs->glyphs[i];
if (glyph->attr.is_cluster_start)
{
int cellcount;
cellcount = count_cluster_cells(
s, item, glyphs, i, &cluster_width,
(item_list != NULL) ? &last_glyph_rbearing : NULL);
if (cellcount > 0)
{
int width;
width = cellcount * gui.char_width * PANGO_SCALE;
glyph->geometry.x_offset +=
MAX(0, width - cluster_width) / 2;
glyph->geometry.width = width;
}
else
{
/* If there are only combining characters in the
* cluster, we cannot just change the width of the
* previous glyph since there is none. Therefore
* some guesswork is needed. */
setup_zero_width_cluster(item, glyph, cells,
cluster_width,
last_glyph_rbearing);
}
item_cells += cellcount;
cells = cellcount;
}
else if (i > 0)
{
int width;
/* There is a previous glyph, so we deal with combining
* characters the canonical way.
* In some circumstances Pango uses a positive x_offset,
* then use the width of the previous glyph for this one
* and set the previous width to zero.
* Otherwise we get a negative x_offset, Pango has already
* positioned the combining char, keep the widths as they
* are.
* For both adjust the x_offset to position the glyph in
* the middle. */
if (glyph->geometry.x_offset >= 0)
{
glyphs->glyphs[i].geometry.width =
glyphs->glyphs[i - 1].geometry.width;
glyphs->glyphs[i - 1].geometry.width = 0;
}
width = cells * gui.char_width * PANGO_SCALE;
glyph->geometry.x_offset +=
MAX(0, width - cluster_width) / 2;
}
else /* i == 0 "cannot happen" */
{
glyph->geometry.width = 0;
}
}
/*** Aaaaand action! ***/
draw_glyph_string(row, col + column_offset, item_cells,
flags, item->analysis.font, glyphs);
pango_item_free(item);
column_offset += item_cells;
}
pango_attr_list_unref(attr_list);
}
skipitall:
/* Draw underline and undercurl. */
draw_under(flags, row, col, column_offset);
pango_glyph_string_free(glyphs);
vim_free(conv_buf);
gdk_gc_set_clip_rectangle(gui.text_gc, NULL);
return column_offset;
}
/*
* 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].key_sym != 0; i++)
if (name[0] == special_keys[i].code0
&& name[1] == special_keys[i].code1)
return OK;
return FAIL;
}
#if defined(FEAT_TITLE) \
|| defined(PROTO)
/*
* Return the text window-id and display. Only required for X-based GUI's
*/
int
gui_get_x11_windis(Window *win, Display **dis)
{
if (gui.mainwin != NULL && gui.mainwin->window != NULL)
{
*dis = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
*win = GDK_WINDOW_XWINDOW(gui.mainwin->window);
return OK;
}
*dis = NULL;
*win = 0;
return FAIL;
}
#endif
#if defined(FEAT_CLIENTSERVER) \
|| (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
Display *
gui_mch_get_display(void)
{
if (gui.mainwin != NULL && gui.mainwin->window != NULL)
return GDK_WINDOW_XDISPLAY(gui.mainwin->window);
else
return NULL;
}
#endif
void
gui_mch_beep(void)
{
#ifdef HAVE_GTK_MULTIHEAD
GdkDisplay *display;
if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
display = gtk_widget_get_display(gui.mainwin);
else
display = gdk_display_get_default();
if (display != NULL)
gdk_display_beep(display);
#else
gdk_beep();
#endif
}
void
gui_mch_flash(int msec)
{
GdkGCValues values;
GdkGC *invert_gc;
if (gui.drawarea->window == NULL)
return;
values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
values.function = GDK_XOR;
invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
&values,
GDK_GC_FOREGROUND |
GDK_GC_BACKGROUND |
GDK_GC_FUNCTION);
gdk_gc_set_exposures(invert_gc,
gui.visibility != GDK_VISIBILITY_UNOBSCURED);
/*
* Do a visual beep by changing back and forth in some undetermined way,
* the foreground and background colors. This is due to the fact that
* there can't be really any prediction about the effects of XOR on
* arbitrary X11 servers. However this seems to be enough for what we
* intend it to do.
*/
gdk_draw_rectangle(gui.drawarea->window, invert_gc,
TRUE,
0, 0,
FILL_X((int)Columns) + gui.border_offset,
FILL_Y((int)Rows) + gui.border_offset);
gui_mch_flush();
ui_delay((long)msec, TRUE); /* wait so many msec */
gdk_draw_rectangle(gui.drawarea->window, invert_gc,
TRUE,
0, 0,
FILL_X((int)Columns) + gui.border_offset,
FILL_Y((int)Rows) + gui.border_offset);
gdk_gc_destroy(invert_gc);
}
/*
* 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)
{
GdkGCValues values;
GdkGC *invert_gc;
if (gui.drawarea->window == NULL)
return;
values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
values.function = GDK_XOR;
invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
&values,
GDK_GC_FOREGROUND |
GDK_GC_BACKGROUND |
GDK_GC_FUNCTION);
gdk_gc_set_exposures(invert_gc, gui.visibility !=
GDK_VISIBILITY_UNOBSCURED);
gdk_draw_rectangle(gui.drawarea->window, invert_gc,
TRUE,
FILL_X(c), FILL_Y(r),
(nc) * gui.char_width, (nr) * gui.char_height);
gdk_gc_destroy(invert_gc);
}
/*
* Iconify the GUI window.
*/
void
gui_mch_iconify(void)
{
gtk_window_iconify(GTK_WINDOW(gui.mainwin));
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Bring the Vim window to the foreground.
*/
void
gui_mch_set_foreground(void)
{
gtk_window_present(GTK_WINDOW(gui.mainwin));
}
#endif
/*
* Draw a cursor without focus.
*/
void
gui_mch_draw_hollow_cursor(guicolor_T color)
{
int i = 1;
if (gui.drawarea->window == NULL)
return;
gui_mch_set_fg_color(color);
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
if (mb_lefthalve(gui.row, gui.col))
i = 2;
gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
FALSE,
FILL_X(gui.col), FILL_Y(gui.row),
i * gui.char_width - 1, gui.char_height - 1);
}
/*
* 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)
{
if (gui.drawarea->window == NULL)
return;
gui_mch_set_fg_color(color);
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
TRUE,
#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),
FILL_Y(gui.row) + gui.char_height - h,
w, h);
}
/*
* Catch up with any queued X11 events. This may put keyboard input into the
* input buffer, call resize call-backs, trigger timers etc. If there is
* nothing in the X11 event queue (& no timers pending), then we return
* immediately.
*/
void
gui_mch_update(void)
{
while (g_main_context_pending(NULL) && !vim_is_input_buf_full())
g_main_context_iteration(NULL, TRUE);
}
static gint
input_timer_cb(gpointer data)
{
int *timed_out = (int *) data;
/* Just inform the caller about the occurrence of it */
*timed_out = TRUE;
return FALSE; /* don't happen again */
}
#ifdef FEAT_SNIFF
/*
* Callback function, used when data is available on the SNiFF connection.
*/
static void
sniff_request_cb(
gpointer data,
gint source_fd,
GdkInputCondition condition)
{
static char_u bytes[3] = {CSI, (int)KS_EXTRA, (int)KE_SNIFF};
add_to_input_buf(bytes, 3);
}
#endif
/*
* 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(long wtime)
{
int focus;
guint timer;
static int timed_out;
#ifdef FEAT_SNIFF
static int sniff_on = 0;
static gint sniff_input_id = 0;
#endif
#ifdef FEAT_SNIFF
if (sniff_on && !want_sniff_request)
{
if (sniff_input_id)
gdk_input_remove(sniff_input_id);
sniff_on = 0;
}
else if (!sniff_on && want_sniff_request)
{
/* Add fd_from_sniff to watch for available data in main loop. */
sniff_input_id = gdk_input_add(fd_from_sniff,
GDK_INPUT_READ, sniff_request_cb, NULL);
sniff_on = 1;
}
#endif
timed_out = FALSE;
/* this timeout makes sure that we will return if no characters arrived in
* time */
if (wtime > 0)
timer = gtk_timeout_add((guint32)wtime, input_timer_cb, &timed_out);
else
timer = 0;
focus = gui.in_focus;
do
{
/* 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 defined(FEAT_NETBEANS_INTG)
/* Process any queued netbeans messages. */
netbeans_parse_messages();
#endif
/*
* Loop in GTK+ processing until a timeout or input occurs.
* Skip this if input is available anyway (can happen in rare
* situations, sort of race condition).
*/
if (!input_available())
g_main_context_iteration(NULL, TRUE);
/* Got char, return immediately */
if (input_available())
{
if (timer != 0 && !timed_out)
gtk_timeout_remove(timer);
return OK;
}
} while (wtime < 0 || !timed_out);
/*
* Flush all eventually pending (drawing) events.
*/
gui_mch_update();
return FAIL;
}
/****************************************************************************
* Output drawing routines.
****************************************************************************/
/* Flush any output to the screen */
void
gui_mch_flush(void)
{
#ifdef HAVE_GTK_MULTIHEAD
if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
gdk_display_sync(gtk_widget_get_display(gui.mainwin));
#else
gdk_flush(); /* historical misnomer: calls XSync(), not XFlush() */
#endif
/* This happens to actually do what gui_mch_flush() is supposed to do,
* according to the comment above. */
if (gui.drawarea != NULL && gui.drawarea->window != NULL)
gdk_window_process_updates(gui.drawarea->window, FALSE);
}
/*
* 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)
{
GdkColor color;
if (gui.drawarea->window == NULL)
return;
color.pixel = gui.back_pixel;
gdk_gc_set_foreground(gui.text_gc, &color);
/* Clear one extra pixel at the far right, for when bold characters have
* spilled over to the window border. */
gdk_draw_rectangle(gui.drawarea->window, gui.text_gc, TRUE,
FILL_X(col1), FILL_Y(row1),
(col2 - col1 + 1) * gui.char_width
+ (col2 == Columns - 1),
(row2 - row1 + 1) * gui.char_height);
}
void
gui_mch_clear_all(void)
{
if (gui.drawarea->window != NULL)
gdk_window_clear(gui.drawarea->window);
}
/*
* Redraw any text revealed by scrolling up/down.
*/
static void
check_copy_area(void)
{
GdkEvent *event;
int expose_count;
if (gui.visibility != GDK_VISIBILITY_PARTIAL)
return;
/* Avoid redrawing the cursor while scrolling or it'll end up where
* we don't want it to be. I'm not sure if it's correct to call
* gui_dont_update_cursor() at this point but it works as a quick
* fix for now. */
gui_dont_update_cursor();
do
{
/* Wait to check whether the scroll worked or not. */
event = gdk_event_get_graphics_expose(gui.drawarea->window);
if (event == NULL)
break; /* received NoExpose event */
gui_redraw(event->expose.area.x, event->expose.area.y,
event->expose.area.width, event->expose.area.height);
expose_count = event->expose.count;
gdk_event_free(event);
}
while (expose_count > 0); /* more events follow */
gui_can_update_cursor();
}
/*
* 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)
{
if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
return; /* Can't see the window */
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
gdk_gc_set_background(gui.text_gc, gui.bgcolor);
/* copy one extra pixel, for when bold has spilled over */
gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
FILL_X(gui.scroll_region_left), FILL_Y(row),
gui.drawarea->window,
FILL_X(gui.scroll_region_left),
FILL_Y(row + num_lines),
gui.char_width * (gui.scroll_region_right
- gui.scroll_region_left + 1) + 1,
gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
gui_clear_block(gui.scroll_region_bot - num_lines + 1,
gui.scroll_region_left,
gui.scroll_region_bot, gui.scroll_region_right);
check_copy_area();
}
/*
* 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)
{
if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
return; /* Can't see the window */
gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
gdk_gc_set_background(gui.text_gc, gui.bgcolor);
/* copy one extra pixel, for when bold has spilled over */
gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines),
gui.drawarea->window,
FILL_X(gui.scroll_region_left), FILL_Y(row),
gui.char_width * (gui.scroll_region_right
- gui.scroll_region_left + 1) + 1,
gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
gui_clear_block(row, gui.scroll_region_left,
row + num_lines - 1, gui.scroll_region_right);
check_copy_area();
}
/*
* X Selection stuff, for cutting and pasting text to other windows.
*/
void
clip_mch_request_selection(VimClipboard *cbd)
{
GdkAtom target;
unsigned i;
time_t start;
for (i = 0; i < N_SELECTION_TARGETS; ++i)
{
if (!clip_html && selection_targets[i].info == TARGET_HTML)
continue;
received_selection = RS_NONE;
target = gdk_atom_intern(selection_targets[i].target, FALSE);
gtk_selection_convert(gui.drawarea,
cbd->gtk_sel_atom, target,
(guint32)GDK_CURRENT_TIME);
/* Hack: Wait up to three seconds for the selection. A hang was
* noticed here when using the netrw plugin combined with ":gui"
* during the FocusGained event. */
start = time(NULL);
while (received_selection == RS_NONE && time(NULL) < start + 3)
g_main_context_iteration(NULL, TRUE); /* wait for selection_received_cb */
if (received_selection != RS_FAIL)
return;
}
/* Final fallback position - use the X CUT_BUFFER0 store */
yank_cut_buffer0(GDK_WINDOW_XDISPLAY(gui.mainwin->window), cbd);
}
/*
* Disown the selection.
*/
void
clip_mch_lose_selection(VimClipboard *cbd UNUSED)
{
/* WEIRD: when using NULL to actually disown the selection, we lose the
* selection the first time we own it. */
/*
gtk_selection_owner_set(NULL, cbd->gtk_sel_atom, (guint32)GDK_CURRENT_TIME);
gui_mch_update();
*/
}
/*
* Own the selection and return OK if it worked.
*/
int
clip_mch_own_selection(VimClipboard *cbd)
{
int success;
success = gtk_selection_owner_set(gui.drawarea, cbd->gtk_sel_atom,
gui.event_time);
gui_mch_update();
return (success) ? OK : FAIL;
}
/*
* Send the current selection to the clipboard. Do nothing for X because we
* will fill in the selection only when requested by another app.
*/
void
clip_mch_set_selection(VimClipboard *cbd UNUSED)
{
}
#if defined(FEAT_MENU) || defined(PROTO)
/*
* Make a menu item appear either active or not active (grey or not grey).
*/
void
gui_mch_menu_grey(vimmenu_T *menu, int grey)
{
if (menu->id == NULL)
return;
if (menu_is_separator(menu->name))
grey = TRUE;
gui_mch_menu_hidden(menu, FALSE);
/* Be clever about bitfields versus true booleans here! */
if (!GTK_WIDGET_SENSITIVE(menu->id) == !grey)
{
gtk_widget_set_sensitive(menu->id, !grey);
gui_mch_update();
}
}
/*
* Make menu item hidden or not hidden.
*/
void
gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
{
if (menu->id == 0)
return;
if (hidden)
{
if (GTK_WIDGET_VISIBLE(menu->id))
{
gtk_widget_hide(menu->id);
gui_mch_update();
}
}
else
{
if (!GTK_WIDGET_VISIBLE(menu->id))
{
gtk_widget_show(menu->id);
gui_mch_update();
}
}
}
/*
* This is called after setting all the menus to grey/hidden or not.
*/
void
gui_mch_draw_menubar(void)
{
/* just make sure that the visual changes get effect immediately */
gui_mch_update();
}
#endif /* FEAT_MENU */
/*
* Scrollbar stuff.
*/
void
gui_mch_enable_scrollbar(scrollbar_T *sb, int flag)
{
if (sb->id == NULL)
return;
if (flag)
gtk_widget_show(sb->id);
else
gtk_widget_hide(sb->id);
update_window_manager_hints(0, 0);
}
/*
* Return the RGB value of a pixel as long.
*/
long_u
gui_mch_get_rgb(guicolor_T pixel)
{
GdkColor color;
gdk_colormap_query_color(gtk_widget_get_colormap(gui.drawarea),
(unsigned long)pixel, &color);
return (((unsigned)color.red & 0xff00) << 8)
| ((unsigned)color.green & 0xff00)
| (((unsigned)color.blue & 0xff00) >> 8);
}
/*
* Get current mouse coordinates in text window.
*/
void
gui_mch_getmouse(int *x, int *y)
{
gdk_window_get_pointer(gui.drawarea->window, x, y, NULL);
}
void
gui_mch_setmouse(int x, int y)
{
/* Sorry for the Xlib call, but we can't avoid it, since there is no
* internal GDK mechanism present to accomplish this. (and for good
* reason...) */
XWarpPointer(GDK_WINDOW_XDISPLAY(gui.drawarea->window),
(Window)0, GDK_WINDOW_XWINDOW(gui.drawarea->window),
0, 0, 0U, 0U, x, y);
}
#ifdef FEAT_MOUSESHAPE
/* The last set mouse pointer shape is remembered, to be used when it goes
* from hidden to not hidden. */
static int last_shape = 0;
#endif
/*
* Use the blank mouse pointer or not.
*
* hide: TRUE = use blank ptr, FALSE = use parent ptr
*/
void
gui_mch_mousehide(int hide)
{
if (gui.pointer_hidden != hide)
{
gui.pointer_hidden = hide;
if (gui.drawarea->window && gui.blank_pointer != NULL)
{
if (hide)
gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
else
#ifdef FEAT_MOUSESHAPE
mch_set_mouse_shape(last_shape);
#else
gdk_window_set_cursor(gui.drawarea->window, NULL);
#endif
}
}
}
#if defined(FEAT_MOUSESHAPE) || defined(PROTO)
/* Table for shape IDs. Keep in sync with the mshape_names[] table in
* misc2.c! */
static const int mshape_ids[] =
{
GDK_LEFT_PTR, /* arrow */
GDK_CURSOR_IS_PIXMAP, /* blank */
GDK_XTERM, /* beam */
GDK_SB_V_DOUBLE_ARROW, /* updown */
GDK_SIZING, /* udsizing */
GDK_SB_H_DOUBLE_ARROW, /* leftright */
GDK_SIZING, /* lrsizing */
GDK_WATCH, /* busy */
GDK_X_CURSOR, /* no */
GDK_CROSSHAIR, /* crosshair */
GDK_HAND1, /* hand1 */
GDK_HAND2, /* hand2 */
GDK_PENCIL, /* pencil */
GDK_QUESTION_ARROW, /* question */
GDK_RIGHT_PTR, /* right-arrow */
GDK_CENTER_PTR, /* up-arrow */
GDK_LEFT_PTR /* last one */
};
void
mch_set_mouse_shape(int shape)
{
int id;
GdkCursor *c;
if (gui.drawarea->window == NULL)
return;
if (shape == MSHAPE_HIDE || gui.pointer_hidden)
gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
else
{
if (shape >= MSHAPE_NUMBERED)
{
id = shape - MSHAPE_NUMBERED;
if (id >= GDK_LAST_CURSOR)
id = GDK_LEFT_PTR;
else
id &= ~1; /* they are always even (why?) */
}
else if (shape < (int)(sizeof(mshape_ids) / sizeof(int)))
id = mshape_ids[shape];
else
return;
# ifdef HAVE_GTK_MULTIHEAD
c = gdk_cursor_new_for_display(
gtk_widget_get_display(gui.drawarea), (GdkCursorType)id);
# else
c = gdk_cursor_new((GdkCursorType)id);
# endif
gdk_window_set_cursor(gui.drawarea->window, c);
gdk_cursor_destroy(c); /* Unref, actually. Bloody GTK+ 1. */
}
if (shape != MSHAPE_HIDE)
last_shape = shape;
}
#endif /* FEAT_MOUSESHAPE */
#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
/*
* Signs are currently always 2 chars wide. With GTK+ 2, the image will be
* scaled down if the current font is not big enough, or scaled up if the image
* size is less than 3/4 of the maximum sign size. With GTK+ 1, the pixmap
* will be cut off if the current font is not big enough, or centered if it's
* too small.
*/
# define SIGN_WIDTH (2 * gui.char_width)
# define SIGN_HEIGHT (gui.char_height)
# define SIGN_ASPECT ((double)SIGN_HEIGHT / (double)SIGN_WIDTH)
void
gui_mch_drawsign(int row, int col, int typenr)
{
GdkPixbuf *sign;
sign = (GdkPixbuf *)sign_get_image(typenr);
if (sign != NULL && gui.drawarea != NULL && gui.drawarea->window != NULL)
{
int width;
int height;
int xoffset;
int yoffset;
int need_scale;
width = gdk_pixbuf_get_width(sign);
height = gdk_pixbuf_get_height(sign);
/*
* Decide whether we need to scale. Allow one pixel of border
* width to be cut off, in order to avoid excessive scaling for
* tiny differences in font size.
*/
need_scale = (width > SIGN_WIDTH + 2
|| height > SIGN_HEIGHT + 2
|| (width < 3 * SIGN_WIDTH / 4
&& height < 3 * SIGN_HEIGHT / 4));
if (need_scale)
{
double aspect;
/* Keep the original aspect ratio */
aspect = (double)height / (double)width;
width = (double)SIGN_WIDTH * SIGN_ASPECT / aspect;
width = MIN(width, SIGN_WIDTH);
height = (double)width * aspect;
/* This doesn't seem to be worth caching, and doing so
* would complicate the code quite a bit. */
sign = gdk_pixbuf_scale_simple(sign, width, height,
GDK_INTERP_BILINEAR);
if (sign == NULL)
return; /* out of memory */
}
/* The origin is the upper-left corner of the pixmap. Therefore
* these offset may become negative if the pixmap is smaller than
* the 2x1 cells reserved for the sign icon. */
xoffset = (width - SIGN_WIDTH) / 2;
yoffset = (height - SIGN_HEIGHT) / 2;
gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
gdk_draw_rectangle(gui.drawarea->window,
gui.text_gc,
TRUE,
FILL_X(col),
FILL_Y(row),
SIGN_WIDTH,
SIGN_HEIGHT);
gdk_pixbuf_render_to_drawable_alpha(sign,
gui.drawarea->window,
MAX(0, xoffset),
MAX(0, yoffset),
FILL_X(col) - MIN(0, xoffset),
FILL_Y(row) - MIN(0, yoffset),
MIN(width, SIGN_WIDTH),
MIN(height, SIGN_HEIGHT),
GDK_PIXBUF_ALPHA_BILEVEL,
127,
GDK_RGB_DITHER_NORMAL,
0, 0);
if (need_scale)
g_object_unref(sign);
}
}
void *
gui_mch_register_sign(char_u *signfile)
{
if (signfile[0] != NUL && signfile[0] != '-' && gui.in_use)
{
GdkPixbuf *sign;
GError *error = NULL;
char_u *message;
sign = gdk_pixbuf_new_from_file((const char *)signfile, &error);
if (error == NULL)
return sign;
message = (char_u *)error->message;
if (message != NULL && input_conv.vc_type != CONV_NONE)
message = string_convert(&input_conv, message, NULL);
if (message != NULL)
{
/* The error message is already translated and will be more
* descriptive than anything we could possibly do ourselves. */
EMSG2("E255: %s", message);
if (input_conv.vc_type != CONV_NONE)
vim_free(message);
}
g_error_free(error);
}
return NULL;
}
void
gui_mch_destroy_sign(void *sign)
{
if (sign != NULL)
g_object_unref(sign);
}
#endif /* FEAT_SIGN_ICONS */
| zyz2011-vim | src/gui_gtk_x11.c | C | gpl2 | 162,064 |
/* 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.
*/
/*
* ui.c: functions that handle the user interface.
* 1. Keyboard input stuff, and a bit of windowing stuff. These are called
* before the machine specific stuff (mch_*) so that we can call the GUI
* stuff instead if the GUI is running.
* 2. Clipboard stuff.
* 3. Input buffer stuff.
*/
#include "vim.h"
void
ui_write(s, len)
char_u *s;
int len;
{
#ifdef FEAT_GUI
if (gui.in_use && !gui.dying && !gui.starting)
{
gui_write(s, len);
if (p_wd)
gui_wait_for_chars(p_wd);
return;
}
#endif
#ifndef NO_CONSOLE
/* Don't output anything in silent mode ("ex -s") unless 'verbose' set */
if (!(silent_mode && p_verbose == 0))
{
#ifdef FEAT_MBYTE
char_u *tofree = NULL;
if (output_conv.vc_type != CONV_NONE)
{
/* Convert characters from 'encoding' to 'termencoding'. */
tofree = string_convert(&output_conv, s, &len);
if (tofree != NULL)
s = tofree;
}
#endif
mch_write(s, len);
#ifdef FEAT_MBYTE
if (output_conv.vc_type != CONV_NONE)
vim_free(tofree);
#endif
}
#endif
}
#if defined(UNIX) || defined(VMS) || defined(PROTO) || defined(WIN3264)
/*
* When executing an external program, there may be some typed characters that
* are not consumed by it. Give them back to ui_inchar() and they are stored
* here for the next call.
*/
static char_u *ta_str = NULL;
static int ta_off; /* offset for next char to use when ta_str != NULL */
static int ta_len; /* length of ta_str when it's not NULL*/
void
ui_inchar_undo(s, len)
char_u *s;
int len;
{
char_u *new;
int newlen;
newlen = len;
if (ta_str != NULL)
newlen += ta_len - ta_off;
new = alloc(newlen);
if (new != NULL)
{
if (ta_str != NULL)
{
mch_memmove(new, ta_str + ta_off, (size_t)(ta_len - ta_off));
mch_memmove(new + ta_len - ta_off, s, (size_t)len);
vim_free(ta_str);
}
else
mch_memmove(new, s, (size_t)len);
ta_str = new;
ta_len = newlen;
ta_off = 0;
}
}
#endif
/*
* ui_inchar(): low level input funcion.
* Get characters from the keyboard.
* Return the number of characters that are available.
* If "wtime" == 0 do not wait for characters.
* If "wtime" == -1 wait forever for characters.
* If "wtime" > 0 wait "wtime" milliseconds for a character.
*
* "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 NULL
* otherwise.
*/
int
ui_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 retval = 0;
#if defined(FEAT_GUI) && (defined(UNIX) || defined(VMS))
/*
* Use the typeahead if there is any.
*/
if (ta_str != NULL)
{
if (maxlen >= ta_len - ta_off)
{
mch_memmove(buf, ta_str + ta_off, (size_t)ta_len);
vim_free(ta_str);
ta_str = NULL;
return ta_len;
}
mch_memmove(buf, ta_str + ta_off, (size_t)maxlen);
ta_off += maxlen;
return maxlen;
}
#endif
#ifdef FEAT_PROFILE
if (do_profiling == PROF_YES && wtime != 0)
prof_inchar_enter();
#endif
#ifdef NO_CONSOLE_INPUT
/* Don't wait for character input when the window hasn't been opened yet.
* Do try reading, this works when redirecting stdin from a file.
* Must return something, otherwise we'll loop forever. If we run into
* this very often we probably got stuck, exit Vim. */
if (no_console_input())
{
static int count = 0;
# ifndef NO_CONSOLE
retval = mch_inchar(buf, maxlen, (wtime >= 0 && wtime < 10)
? 10L : wtime, tb_change_cnt);
if (retval > 0 || typebuf_changed(tb_change_cnt) || wtime >= 0)
goto theend;
# endif
if (wtime == -1 && ++count == 1000)
read_error_exit();
buf[0] = CAR;
retval = 1;
goto theend;
}
#endif
/* If we are going to wait for some time or block... */
if (wtime == -1 || wtime > 100L)
{
/* ... allow signals to kill us. */
(void)vim_handle_signal(SIGNAL_UNBLOCK);
/* ... there is no need for CTRL-C to interrupt something, don't let
* it set got_int when it was mapped. */
if (mapped_ctrl_c)
ctrl_c_interrupts = FALSE;
}
#ifdef FEAT_GUI
if (gui.in_use)
{
if (gui_wait_for_chars(wtime) && !typebuf_changed(tb_change_cnt))
retval = read_from_input_buf(buf, (long)maxlen);
}
#endif
#ifndef NO_CONSOLE
# ifdef FEAT_GUI
else
# endif
{
retval = mch_inchar(buf, maxlen, wtime, tb_change_cnt);
}
#endif
if (wtime == -1 || wtime > 100L)
/* block SIGHUP et al. */
(void)vim_handle_signal(SIGNAL_BLOCK);
ctrl_c_interrupts = TRUE;
#ifdef NO_CONSOLE_INPUT
theend:
#endif
#ifdef FEAT_PROFILE
if (do_profiling == PROF_YES && wtime != 0)
prof_inchar_exit();
#endif
return retval;
}
/*
* return non-zero if a character is available
*/
int
ui_char_avail()
{
#ifdef FEAT_GUI
if (gui.in_use)
{
gui_mch_update();
return input_available();
}
#endif
#ifndef NO_CONSOLE
# ifdef NO_CONSOLE_INPUT
if (no_console_input())
return 0;
# endif
return mch_char_avail();
#else
return 0;
#endif
}
/*
* Delay for the given number of milliseconds. If ignoreinput is FALSE then we
* cancel the delay if a key is hit.
*/
void
ui_delay(msec, ignoreinput)
long msec;
int ignoreinput;
{
#ifdef FEAT_GUI
if (gui.in_use && !ignoreinput)
gui_wait_for_chars(msec);
else
#endif
mch_delay(msec, ignoreinput);
}
/*
* If the machine has job control, use it to suspend the program,
* otherwise fake it by starting a new shell.
* When running the GUI iconify the window.
*/
void
ui_suspend()
{
#ifdef FEAT_GUI
if (gui.in_use)
{
gui_mch_iconify();
return;
}
#endif
mch_suspend();
}
#if !defined(UNIX) || !defined(SIGTSTP) || defined(PROTO) || defined(__BEOS__)
/*
* When the OS can't really suspend, call this function to start a shell.
* This is never called in the GUI.
*/
void
suspend_shell()
{
if (*p_sh == NUL)
EMSG(_(e_shellempty));
else
{
MSG_PUTS(_("new shell started\n"));
do_shell(NULL, 0);
}
}
#endif
/*
* Try to get the current Vim shell size. Put the result in Rows and Columns.
* Use the new sizes as defaults for 'columns' and 'lines'.
* Return OK when size could be determined, FAIL otherwise.
*/
int
ui_get_shellsize()
{
int retval;
#ifdef FEAT_GUI
if (gui.in_use)
retval = gui_get_shellsize();
else
#endif
retval = mch_get_shellsize();
check_shellsize();
/* adjust the default for 'lines' and 'columns' */
if (retval == OK)
{
set_number_default("lines", Rows);
set_number_default("columns", Columns);
}
return retval;
}
/*
* Set the size of the Vim shell according to Rows and Columns, if possible.
* The gui_set_shellsize() or mch_set_shellsize() function will try to set the
* new size. If this is not possible, it will adjust Rows and Columns.
*/
void
ui_set_shellsize(mustset)
int mustset UNUSED; /* set by the user */
{
#ifdef FEAT_GUI
if (gui.in_use)
gui_set_shellsize(mustset,
# ifdef WIN3264
TRUE
# else
FALSE
# endif
, RESIZE_BOTH);
else
#endif
mch_set_shellsize();
}
/*
* Called when Rows and/or Columns changed. Adjust scroll region and mouse
* region.
*/
void
ui_new_shellsize()
{
if (full_screen && !exiting)
{
#ifdef FEAT_GUI
if (gui.in_use)
gui_new_shellsize();
else
#endif
mch_new_shellsize();
}
}
void
ui_breakcheck()
{
#ifdef FEAT_GUI
if (gui.in_use)
gui_mch_update();
else
#endif
mch_breakcheck();
}
/*****************************************************************************
* Functions for copying and pasting text between applications.
* This is always included in a GUI version, but may also be included when the
* clipboard and mouse is available to a terminal version such as xterm.
* Note: there are some more functions in ops.c that handle selection stuff.
*
* Also note that the majority of functions here deal with the X 'primary'
* (visible - for Visual mode use) selection, and only that. There are no
* versions of these for the 'clipboard' selection, as Visual mode has no use
* for them.
*/
#if defined(FEAT_CLIPBOARD) || defined(PROTO)
/*
* Selection stuff using Visual mode, for cutting and pasting text to other
* windows.
*/
/*
* Call this to initialise the clipboard. Pass it FALSE if the clipboard code
* is included, but the clipboard can not be used, or TRUE if the clipboard can
* be used. Eg unix may call this with FALSE, then call it again with TRUE if
* the GUI starts.
*/
void
clip_init(can_use)
int can_use;
{
VimClipboard *cb;
cb = &clip_star;
for (;;)
{
cb->available = can_use;
cb->owned = FALSE;
cb->start.lnum = 0;
cb->start.col = 0;
cb->end.lnum = 0;
cb->end.col = 0;
cb->state = SELECT_CLEARED;
if (cb == &clip_plus)
break;
cb = &clip_plus;
}
}
/*
* Check whether the VIsual area has changed, and if so try to become the owner
* of the selection, and free any old converted selection we may still have
* lying around. If the VIsual mode has ended, make a copy of what was
* selected so we can still give it to others. Will probably have to make sure
* this is called whenever VIsual mode is ended.
*/
void
clip_update_selection()
{
pos_T start, end;
/* If visual mode is only due to a redo command ("."), then ignore it */
if (!redo_VIsual_busy && VIsual_active && (State & NORMAL))
{
if (lt(VIsual, curwin->w_cursor))
{
start = VIsual;
end = curwin->w_cursor;
#ifdef FEAT_MBYTE
if (has_mbyte)
end.col += (*mb_ptr2len)(ml_get_cursor()) - 1;
#endif
}
else
{
start = curwin->w_cursor;
end = VIsual;
}
if (!equalpos(clip_star.start, start)
|| !equalpos(clip_star.end, end)
|| clip_star.vmode != VIsual_mode)
{
clip_clear_selection();
clip_star.start = start;
clip_star.end = end;
clip_star.vmode = VIsual_mode;
clip_free_selection(&clip_star);
clip_own_selection(&clip_star);
clip_gen_set_selection(&clip_star);
}
}
}
void
clip_own_selection(cbd)
VimClipboard *cbd;
{
/*
* Also want to check somehow that we are reading from the keyboard rather
* than a mapping etc.
*/
#ifdef FEAT_X11
/* Always own the selection, we might have lost it without being
* notified, e.g. during a ":sh" command. */
if (cbd->available)
{
int was_owned = cbd->owned;
cbd->owned = (clip_gen_own_selection(cbd) == OK);
if (!was_owned && cbd == &clip_star)
{
/* May have to show a different kind of highlighting for the
* selected area. There is no specific redraw command for this,
* just redraw all windows on the current buffer. */
if (cbd->owned
&& (get_real_state() == VISUAL
|| get_real_state() == SELECTMODE)
&& clip_isautosel()
&& hl_attr(HLF_V) != hl_attr(HLF_VNC))
redraw_curbuf_later(INVERTED_ALL);
}
}
#else
/* Only own the clibpard when we didn't own it yet. */
if (!cbd->owned && cbd->available)
cbd->owned = (clip_gen_own_selection(cbd) == OK);
#endif
}
void
clip_lose_selection(cbd)
VimClipboard *cbd;
{
#ifdef FEAT_X11
int was_owned = cbd->owned;
#endif
int visual_selection = (cbd == &clip_star);
clip_free_selection(cbd);
cbd->owned = FALSE;
if (visual_selection)
clip_clear_selection();
clip_gen_lose_selection(cbd);
#ifdef FEAT_X11
if (visual_selection)
{
/* May have to show a different kind of highlighting for the selected
* area. There is no specific redraw command for this, just redraw all
* windows on the current buffer. */
if (was_owned
&& (get_real_state() == VISUAL
|| get_real_state() == SELECTMODE)
&& clip_isautosel()
&& hl_attr(HLF_V) != hl_attr(HLF_VNC))
{
update_curbuf(INVERTED_ALL);
setcursor();
cursor_on();
out_flush();
# ifdef FEAT_GUI
if (gui.in_use)
gui_update_cursor(TRUE, FALSE);
# endif
}
}
#endif
}
void
clip_copy_selection()
{
if (VIsual_active && (State & NORMAL) && clip_star.available)
{
if (clip_isautosel())
clip_update_selection();
clip_free_selection(&clip_star);
clip_own_selection(&clip_star);
if (clip_star.owned)
clip_get_selection(&clip_star);
clip_gen_set_selection(&clip_star);
}
}
/*
* Called when Visual mode is ended: update the selection.
*/
void
clip_auto_select()
{
if (clip_isautosel())
clip_copy_selection();
}
/*
* Return TRUE if automatic selection of Visual area is desired.
*/
int
clip_isautosel()
{
return (
#ifdef FEAT_GUI
gui.in_use ? (vim_strchr(p_go, GO_ASEL) != NULL) :
#endif
clip_autoselect);
}
/*
* Stuff for general mouse selection, without using Visual mode.
*/
static int clip_compare_pos __ARGS((int row1, int col1, int row2, int col2));
static void clip_invert_area __ARGS((int, int, int, int, int how));
static void clip_invert_rectangle __ARGS((int row, int col, int height, int width, int invert));
static void clip_get_word_boundaries __ARGS((VimClipboard *, int, int));
static int clip_get_line_end __ARGS((int));
static void clip_update_modeless_selection __ARGS((VimClipboard *, int, int,
int, int));
/* flags for clip_invert_area() */
#define CLIP_CLEAR 1
#define CLIP_SET 2
#define CLIP_TOGGLE 3
/*
* Start, continue or end a modeless selection. Used when editing the
* command-line and in the cmdline window.
*/
void
clip_modeless(button, is_click, is_drag)
int button;
int is_click;
int is_drag;
{
int repeat;
repeat = ((clip_star.mode == SELECT_MODE_CHAR
|| clip_star.mode == SELECT_MODE_LINE)
&& (mod_mask & MOD_MASK_2CLICK))
|| (clip_star.mode == SELECT_MODE_WORD
&& (mod_mask & MOD_MASK_3CLICK));
if (is_click && button == MOUSE_RIGHT)
{
/* Right mouse button: If there was no selection, start one.
* Otherwise extend the existing selection. */
if (clip_star.state == SELECT_CLEARED)
clip_start_selection(mouse_col, mouse_row, FALSE);
clip_process_selection(button, mouse_col, mouse_row, repeat);
}
else if (is_click)
clip_start_selection(mouse_col, mouse_row, repeat);
else if (is_drag)
{
/* Don't try extending a selection if there isn't one. Happens when
* button-down is in the cmdline and them moving mouse upwards. */
if (clip_star.state != SELECT_CLEARED)
clip_process_selection(button, mouse_col, mouse_row, repeat);
}
else /* release */
clip_process_selection(MOUSE_RELEASE, mouse_col, mouse_row, FALSE);
}
/*
* Compare two screen positions ala strcmp()
*/
static int
clip_compare_pos(row1, col1, row2, col2)
int row1;
int col1;
int row2;
int col2;
{
if (row1 > row2) return(1);
if (row1 < row2) return(-1);
if (col1 > col2) return(1);
if (col1 < col2) return(-1);
return(0);
}
/*
* Start the selection
*/
void
clip_start_selection(col, row, repeated_click)
int col;
int row;
int repeated_click;
{
VimClipboard *cb = &clip_star;
if (cb->state == SELECT_DONE)
clip_clear_selection();
row = check_row(row);
col = check_col(col);
#ifdef FEAT_MBYTE
col = mb_fix_col(col, row);
#endif
cb->start.lnum = row;
cb->start.col = col;
cb->end = cb->start;
cb->origin_row = (short_u)cb->start.lnum;
cb->state = SELECT_IN_PROGRESS;
if (repeated_click)
{
if (++cb->mode > SELECT_MODE_LINE)
cb->mode = SELECT_MODE_CHAR;
}
else
cb->mode = SELECT_MODE_CHAR;
#ifdef FEAT_GUI
/* clear the cursor until the selection is made */
if (gui.in_use)
gui_undraw_cursor();
#endif
switch (cb->mode)
{
case SELECT_MODE_CHAR:
cb->origin_start_col = cb->start.col;
cb->word_end_col = clip_get_line_end((int)cb->start.lnum);
break;
case SELECT_MODE_WORD:
clip_get_word_boundaries(cb, (int)cb->start.lnum, cb->start.col);
cb->origin_start_col = cb->word_start_col;
cb->origin_end_col = cb->word_end_col;
clip_invert_area((int)cb->start.lnum, cb->word_start_col,
(int)cb->end.lnum, cb->word_end_col, CLIP_SET);
cb->start.col = cb->word_start_col;
cb->end.col = cb->word_end_col;
break;
case SELECT_MODE_LINE:
clip_invert_area((int)cb->start.lnum, 0, (int)cb->start.lnum,
(int)Columns, CLIP_SET);
cb->start.col = 0;
cb->end.col = Columns;
break;
}
cb->prev = cb->start;
#ifdef DEBUG_SELECTION
printf("Selection started at (%u,%u)\n", cb->start.lnum, cb->start.col);
#endif
}
/*
* Continue processing the selection
*/
void
clip_process_selection(button, col, row, repeated_click)
int button;
int col;
int row;
int_u repeated_click;
{
VimClipboard *cb = &clip_star;
int diff;
int slen = 1; /* cursor shape width */
if (button == MOUSE_RELEASE)
{
/* Check to make sure we have something selected */
if (cb->start.lnum == cb->end.lnum && cb->start.col == cb->end.col)
{
#ifdef FEAT_GUI
if (gui.in_use)
gui_update_cursor(FALSE, FALSE);
#endif
cb->state = SELECT_CLEARED;
return;
}
#ifdef DEBUG_SELECTION
printf("Selection ended: (%u,%u) to (%u,%u)\n", cb->start.lnum,
cb->start.col, cb->end.lnum, cb->end.col);
#endif
if (clip_isautosel()
|| (
#ifdef FEAT_GUI
gui.in_use ? (vim_strchr(p_go, GO_ASELML) != NULL) :
#endif
clip_autoselectml))
clip_copy_modeless_selection(FALSE);
#ifdef FEAT_GUI
if (gui.in_use)
gui_update_cursor(FALSE, FALSE);
#endif
cb->state = SELECT_DONE;
return;
}
row = check_row(row);
col = check_col(col);
#ifdef FEAT_MBYTE
col = mb_fix_col(col, row);
#endif
if (col == (int)cb->prev.col && row == cb->prev.lnum && !repeated_click)
return;
/*
* When extending the selection with the right mouse button, swap the
* start and end if the position is before half the selection
*/
if (cb->state == SELECT_DONE && button == MOUSE_RIGHT)
{
/*
* If the click is before the start, or the click is inside the
* selection and the start is the closest side, set the origin to the
* end of the selection.
*/
if (clip_compare_pos(row, col, (int)cb->start.lnum, cb->start.col) < 0
|| (clip_compare_pos(row, col,
(int)cb->end.lnum, cb->end.col) < 0
&& (((cb->start.lnum == cb->end.lnum
&& cb->end.col - col > col - cb->start.col))
|| ((diff = (cb->end.lnum - row) -
(row - cb->start.lnum)) > 0
|| (diff == 0 && col < (int)(cb->start.col +
cb->end.col) / 2)))))
{
cb->origin_row = (short_u)cb->end.lnum;
cb->origin_start_col = cb->end.col - 1;
cb->origin_end_col = cb->end.col;
}
else
{
cb->origin_row = (short_u)cb->start.lnum;
cb->origin_start_col = cb->start.col;
cb->origin_end_col = cb->start.col;
}
if (cb->mode == SELECT_MODE_WORD && !repeated_click)
cb->mode = SELECT_MODE_CHAR;
}
/* set state, for when using the right mouse button */
cb->state = SELECT_IN_PROGRESS;
#ifdef DEBUG_SELECTION
printf("Selection extending to (%d,%d)\n", row, col);
#endif
if (repeated_click && ++cb->mode > SELECT_MODE_LINE)
cb->mode = SELECT_MODE_CHAR;
switch (cb->mode)
{
case SELECT_MODE_CHAR:
/* If we're on a different line, find where the line ends */
if (row != cb->prev.lnum)
cb->word_end_col = clip_get_line_end(row);
/* See if we are before or after the origin of the selection */
if (clip_compare_pos(row, col, cb->origin_row,
cb->origin_start_col) >= 0)
{
if (col >= (int)cb->word_end_col)
clip_update_modeless_selection(cb, cb->origin_row,
cb->origin_start_col, row, (int)Columns);
else
{
#ifdef FEAT_MBYTE
if (has_mbyte && mb_lefthalve(row, col))
slen = 2;
#endif
clip_update_modeless_selection(cb, cb->origin_row,
cb->origin_start_col, row, col + slen);
}
}
else
{
#ifdef FEAT_MBYTE
if (has_mbyte
&& mb_lefthalve(cb->origin_row, cb->origin_start_col))
slen = 2;
#endif
if (col >= (int)cb->word_end_col)
clip_update_modeless_selection(cb, row, cb->word_end_col,
cb->origin_row, cb->origin_start_col + slen);
else
clip_update_modeless_selection(cb, row, col,
cb->origin_row, cb->origin_start_col + slen);
}
break;
case SELECT_MODE_WORD:
/* If we are still within the same word, do nothing */
if (row == cb->prev.lnum && col >= (int)cb->word_start_col
&& col < (int)cb->word_end_col && !repeated_click)
return;
/* Get new word boundaries */
clip_get_word_boundaries(cb, row, col);
/* Handle being after the origin point of selection */
if (clip_compare_pos(row, col, cb->origin_row,
cb->origin_start_col) >= 0)
clip_update_modeless_selection(cb, cb->origin_row,
cb->origin_start_col, row, cb->word_end_col);
else
clip_update_modeless_selection(cb, row, cb->word_start_col,
cb->origin_row, cb->origin_end_col);
break;
case SELECT_MODE_LINE:
if (row == cb->prev.lnum && !repeated_click)
return;
if (clip_compare_pos(row, col, cb->origin_row,
cb->origin_start_col) >= 0)
clip_update_modeless_selection(cb, cb->origin_row, 0, row,
(int)Columns);
else
clip_update_modeless_selection(cb, row, 0, cb->origin_row,
(int)Columns);
break;
}
cb->prev.lnum = row;
cb->prev.col = col;
#ifdef DEBUG_SELECTION
printf("Selection is: (%u,%u) to (%u,%u)\n", cb->start.lnum,
cb->start.col, cb->end.lnum, cb->end.col);
#endif
}
# if defined(FEAT_GUI) || defined(PROTO)
/*
* Redraw part of the selection if character at "row,col" is inside of it.
* Only used for the GUI.
*/
void
clip_may_redraw_selection(row, col, len)
int row, col;
int len;
{
int start = col;
int end = col + len;
if (clip_star.state != SELECT_CLEARED
&& row >= clip_star.start.lnum
&& row <= clip_star.end.lnum)
{
if (row == clip_star.start.lnum && start < (int)clip_star.start.col)
start = clip_star.start.col;
if (row == clip_star.end.lnum && end > (int)clip_star.end.col)
end = clip_star.end.col;
if (end > start)
clip_invert_area(row, start, row, end, 0);
}
}
# endif
/*
* Called from outside to clear selected region from the display
*/
void
clip_clear_selection()
{
VimClipboard *cb = &clip_star;
if (cb->state == SELECT_CLEARED)
return;
clip_invert_area((int)cb->start.lnum, cb->start.col, (int)cb->end.lnum,
cb->end.col, CLIP_CLEAR);
cb->state = SELECT_CLEARED;
}
/*
* Clear the selection if any lines from "row1" to "row2" are inside of it.
*/
void
clip_may_clear_selection(row1, row2)
int row1, row2;
{
if (clip_star.state == SELECT_DONE
&& row2 >= clip_star.start.lnum
&& row1 <= clip_star.end.lnum)
clip_clear_selection();
}
/*
* Called before the screen is scrolled up or down. Adjusts the line numbers
* of the selection. Call with big number when clearing the screen.
*/
void
clip_scroll_selection(rows)
int rows; /* negative for scroll down */
{
int lnum;
if (clip_star.state == SELECT_CLEARED)
return;
lnum = clip_star.start.lnum - rows;
if (lnum <= 0)
clip_star.start.lnum = 0;
else if (lnum >= screen_Rows) /* scrolled off of the screen */
clip_star.state = SELECT_CLEARED;
else
clip_star.start.lnum = lnum;
lnum = clip_star.end.lnum - rows;
if (lnum < 0) /* scrolled off of the screen */
clip_star.state = SELECT_CLEARED;
else if (lnum >= screen_Rows)
clip_star.end.lnum = screen_Rows - 1;
else
clip_star.end.lnum = lnum;
}
/*
* Invert a region of the display between a starting and ending row and column
* Values for "how":
* CLIP_CLEAR: undo inversion
* CLIP_SET: set inversion
* CLIP_TOGGLE: set inversion if pos1 < pos2, undo inversion otherwise.
* 0: invert (GUI only).
*/
static void
clip_invert_area(row1, col1, row2, col2, how)
int row1;
int col1;
int row2;
int col2;
int how;
{
int invert = FALSE;
if (how == CLIP_SET)
invert = TRUE;
/* Swap the from and to positions so the from is always before */
if (clip_compare_pos(row1, col1, row2, col2) > 0)
{
int tmp_row, tmp_col;
tmp_row = row1;
tmp_col = col1;
row1 = row2;
col1 = col2;
row2 = tmp_row;
col2 = tmp_col;
}
else if (how == CLIP_TOGGLE)
invert = TRUE;
/* If all on the same line, do it the easy way */
if (row1 == row2)
{
clip_invert_rectangle(row1, col1, 1, col2 - col1, invert);
}
else
{
/* Handle a piece of the first line */
if (col1 > 0)
{
clip_invert_rectangle(row1, col1, 1, (int)Columns - col1, invert);
row1++;
}
/* Handle a piece of the last line */
if (col2 < Columns - 1)
{
clip_invert_rectangle(row2, 0, 1, col2, invert);
row2--;
}
/* Handle the rectangle thats left */
if (row2 >= row1)
clip_invert_rectangle(row1, 0, row2 - row1 + 1, (int)Columns,
invert);
}
}
/*
* Invert or un-invert a rectangle of the screen.
* "invert" is true if the result is inverted.
*/
static void
clip_invert_rectangle(row, col, height, width, invert)
int row;
int col;
int height;
int width;
int invert;
{
#ifdef FEAT_GUI
if (gui.in_use)
gui_mch_invert_rectangle(row, col, height, width);
else
#endif
screen_draw_rectangle(row, col, height, width, invert);
}
/*
* Copy the currently selected area into the '*' register so it will be
* available for pasting.
* When "both" is TRUE also copy to the '+' register.
*/
void
clip_copy_modeless_selection(both)
int both UNUSED;
{
char_u *buffer;
char_u *bufp;
int row;
int start_col;
int end_col;
int line_end_col;
int add_newline_flag = FALSE;
int len;
#ifdef FEAT_MBYTE
char_u *p;
#endif
int row1 = clip_star.start.lnum;
int col1 = clip_star.start.col;
int row2 = clip_star.end.lnum;
int col2 = clip_star.end.col;
/* Can't use ScreenLines unless initialized */
if (ScreenLines == NULL)
return;
/*
* Make sure row1 <= row2, and if row1 == row2 that col1 <= col2.
*/
if (row1 > row2)
{
row = row1; row1 = row2; row2 = row;
row = col1; col1 = col2; col2 = row;
}
else if (row1 == row2 && col1 > col2)
{
row = col1; col1 = col2; col2 = row;
}
#ifdef FEAT_MBYTE
/* correct starting point for being on right halve of double-wide char */
p = ScreenLines + LineOffset[row1];
if (enc_dbcs != 0)
col1 -= (*mb_head_off)(p, p + col1);
else if (enc_utf8 && p[col1] == 0)
--col1;
#endif
/* Create a temporary buffer for storing the text */
len = (row2 - row1 + 1) * Columns + 1;
#ifdef FEAT_MBYTE
if (enc_dbcs != 0)
len *= 2; /* max. 2 bytes per display cell */
else if (enc_utf8)
len *= MB_MAXBYTES;
#endif
buffer = lalloc((long_u)len, TRUE);
if (buffer == NULL) /* out of memory */
return;
/* Process each row in the selection */
for (bufp = buffer, row = row1; row <= row2; row++)
{
if (row == row1)
start_col = col1;
else
start_col = 0;
if (row == row2)
end_col = col2;
else
end_col = Columns;
line_end_col = clip_get_line_end(row);
/* See if we need to nuke some trailing whitespace */
if (end_col >= Columns && (row < row2 || end_col > line_end_col))
{
/* Get rid of trailing whitespace */
end_col = line_end_col;
if (end_col < start_col)
end_col = start_col;
/* If the last line extended to the end, add an extra newline */
if (row == row2)
add_newline_flag = TRUE;
}
/* If after the first row, we need to always add a newline */
if (row > row1 && !LineWraps[row - 1])
*bufp++ = NL;
if (row < screen_Rows && end_col <= screen_Columns)
{
#ifdef FEAT_MBYTE
if (enc_dbcs != 0)
{
int i;
p = ScreenLines + LineOffset[row];
for (i = start_col; i < end_col; ++i)
if (enc_dbcs == DBCS_JPNU && p[i] == 0x8e)
{
/* single-width double-byte char */
*bufp++ = 0x8e;
*bufp++ = ScreenLines2[LineOffset[row] + i];
}
else
{
*bufp++ = p[i];
if (MB_BYTE2LEN(p[i]) == 2)
*bufp++ = p[++i];
}
}
else if (enc_utf8)
{
int off;
int i;
int ci;
off = LineOffset[row];
for (i = start_col; i < end_col; ++i)
{
/* The base character is either in ScreenLinesUC[] or
* ScreenLines[]. */
if (ScreenLinesUC[off + i] == 0)
*bufp++ = ScreenLines[off + i];
else
{
bufp += utf_char2bytes(ScreenLinesUC[off + i], bufp);
for (ci = 0; ci < Screen_mco; ++ci)
{
/* Add a composing character. */
if (ScreenLinesC[ci][off + i] == 0)
break;
bufp += utf_char2bytes(ScreenLinesC[ci][off + i],
bufp);
}
}
/* Skip right halve of double-wide character. */
if (ScreenLines[off + i + 1] == 0)
++i;
}
}
else
#endif
{
STRNCPY(bufp, ScreenLines + LineOffset[row] + start_col,
end_col - start_col);
bufp += end_col - start_col;
}
}
}
/* Add a newline at the end if the selection ended there */
if (add_newline_flag)
*bufp++ = NL;
/* First cleanup any old selection and become the owner. */
clip_free_selection(&clip_star);
clip_own_selection(&clip_star);
/* Yank the text into the '*' register. */
clip_yank_selection(MCHAR, buffer, (long)(bufp - buffer), &clip_star);
/* Make the register contents available to the outside world. */
clip_gen_set_selection(&clip_star);
#ifdef FEAT_X11
if (both)
{
/* Do the same for the '+' register. */
clip_free_selection(&clip_plus);
clip_own_selection(&clip_plus);
clip_yank_selection(MCHAR, buffer, (long)(bufp - buffer), &clip_plus);
clip_gen_set_selection(&clip_plus);
}
#endif
vim_free(buffer);
}
/*
* Find the starting and ending positions of the word at the given row and
* column. Only white-separated words are recognized here.
*/
#define CHAR_CLASS(c) (c <= ' ' ? ' ' : vim_iswordc(c))
static void
clip_get_word_boundaries(cb, row, col)
VimClipboard *cb;
int row;
int col;
{
int start_class;
int temp_col;
char_u *p;
#ifdef FEAT_MBYTE
int mboff;
#endif
if (row >= screen_Rows || col >= screen_Columns || ScreenLines == NULL)
return;
p = ScreenLines + LineOffset[row];
#ifdef FEAT_MBYTE
/* Correct for starting in the right halve of a double-wide char */
if (enc_dbcs != 0)
col -= dbcs_screen_head_off(p, p + col);
else if (enc_utf8 && p[col] == 0)
--col;
#endif
start_class = CHAR_CLASS(p[col]);
temp_col = col;
for ( ; temp_col > 0; temp_col--)
#ifdef FEAT_MBYTE
if (enc_dbcs != 0
&& (mboff = dbcs_screen_head_off(p, p + temp_col - 1)) > 0)
temp_col -= mboff;
else
#endif
if (CHAR_CLASS(p[temp_col - 1]) != start_class
#ifdef FEAT_MBYTE
&& !(enc_utf8 && p[temp_col - 1] == 0)
#endif
)
break;
cb->word_start_col = temp_col;
temp_col = col;
for ( ; temp_col < screen_Columns; temp_col++)
#ifdef FEAT_MBYTE
if (enc_dbcs != 0 && dbcs_ptr2cells(p + temp_col) == 2)
++temp_col;
else
#endif
if (CHAR_CLASS(p[temp_col]) != start_class
#ifdef FEAT_MBYTE
&& !(enc_utf8 && p[temp_col] == 0)
#endif
)
break;
cb->word_end_col = temp_col;
}
/*
* Find the column position for the last non-whitespace character on the given
* line.
*/
static int
clip_get_line_end(row)
int row;
{
int i;
if (row >= screen_Rows || ScreenLines == NULL)
return 0;
for (i = screen_Columns; i > 0; i--)
if (ScreenLines[LineOffset[row] + i - 1] != ' ')
break;
return i;
}
/*
* Update the currently selected region by adding and/or subtracting from the
* beginning or end and inverting the changed area(s).
*/
static void
clip_update_modeless_selection(cb, row1, col1, row2, col2)
VimClipboard *cb;
int row1;
int col1;
int row2;
int col2;
{
/* See if we changed at the beginning of the selection */
if (row1 != cb->start.lnum || col1 != (int)cb->start.col)
{
clip_invert_area(row1, col1, (int)cb->start.lnum, cb->start.col,
CLIP_TOGGLE);
cb->start.lnum = row1;
cb->start.col = col1;
}
/* See if we changed at the end of the selection */
if (row2 != cb->end.lnum || col2 != (int)cb->end.col)
{
clip_invert_area((int)cb->end.lnum, cb->end.col, row2, col2,
CLIP_TOGGLE);
cb->end.lnum = row2;
cb->end.col = col2;
}
}
int
clip_gen_own_selection(cbd)
VimClipboard *cbd;
{
#ifdef FEAT_XCLIPBOARD
# ifdef FEAT_GUI
if (gui.in_use)
return clip_mch_own_selection(cbd);
else
# endif
return clip_xterm_own_selection(cbd);
#else
return clip_mch_own_selection(cbd);
#endif
}
void
clip_gen_lose_selection(cbd)
VimClipboard *cbd;
{
#ifdef FEAT_XCLIPBOARD
# ifdef FEAT_GUI
if (gui.in_use)
clip_mch_lose_selection(cbd);
else
# endif
clip_xterm_lose_selection(cbd);
#else
clip_mch_lose_selection(cbd);
#endif
}
void
clip_gen_set_selection(cbd)
VimClipboard *cbd;
{
#ifdef FEAT_XCLIPBOARD
# ifdef FEAT_GUI
if (gui.in_use)
clip_mch_set_selection(cbd);
else
# endif
clip_xterm_set_selection(cbd);
#else
clip_mch_set_selection(cbd);
#endif
}
void
clip_gen_request_selection(cbd)
VimClipboard *cbd;
{
#ifdef FEAT_XCLIPBOARD
# ifdef FEAT_GUI
if (gui.in_use)
clip_mch_request_selection(cbd);
else
# endif
clip_xterm_request_selection(cbd);
#else
clip_mch_request_selection(cbd);
#endif
}
#endif /* FEAT_CLIPBOARD */
/*****************************************************************************
* Functions that handle the input buffer.
* This is used for any GUI version, and the unix terminal version.
*
* For Unix, the input characters are buffered to be able to check for a
* CTRL-C. This should be done with signals, but I don't know how to do that
* in a portable way for a tty in RAW mode.
*
* For the client-server code in the console the received keys are put in the
* input buffer.
*/
#if defined(USE_INPUT_BUF) || defined(PROTO)
/*
* Internal typeahead buffer. Includes extra space for long key code
* descriptions which would otherwise overflow. The buffer is considered full
* when only this extra space (or part of it) remains.
*/
#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
|| defined(FEAT_CLIENTSERVER)
/*
* Sun WorkShop and NetBeans stuff debugger commands into the input buffer.
* This requires a larger buffer...
* (Madsen) Go with this for remote input as well ...
*/
# define INBUFLEN 4096
#else
# define INBUFLEN 250
#endif
static char_u inbuf[INBUFLEN + MAX_KEY_CODE_LEN];
static int inbufcount = 0; /* number of chars in inbuf[] */
/*
* vim_is_input_buf_full(), vim_is_input_buf_empty(), add_to_input_buf(), and
* trash_input_buf() are functions for manipulating the input buffer. These
* are used by the gui_* calls when a GUI is used to handle keyboard input.
*/
int
vim_is_input_buf_full()
{
return (inbufcount >= INBUFLEN);
}
int
vim_is_input_buf_empty()
{
return (inbufcount == 0);
}
#if defined(FEAT_OLE) || defined(PROTO)
int
vim_free_in_input_buf()
{
return (INBUFLEN - inbufcount);
}
#endif
#if defined(FEAT_GUI_GTK) || defined(PROTO)
int
vim_used_in_input_buf()
{
return inbufcount;
}
#endif
#if defined(FEAT_EVAL) || defined(FEAT_EX_EXTRA) || defined(PROTO)
/*
* Return the current contents of the input buffer and make it empty.
* The returned pointer must be passed to set_input_buf() later.
*/
char_u *
get_input_buf()
{
garray_T *gap;
/* We use a growarray to store the data pointer and the length. */
gap = (garray_T *)alloc((unsigned)sizeof(garray_T));
if (gap != NULL)
{
/* Add one to avoid a zero size. */
gap->ga_data = alloc((unsigned)inbufcount + 1);
if (gap->ga_data != NULL)
mch_memmove(gap->ga_data, inbuf, (size_t)inbufcount);
gap->ga_len = inbufcount;
}
trash_input_buf();
return (char_u *)gap;
}
/*
* Restore the input buffer with a pointer returned from get_input_buf().
* The allocated memory is freed, this only works once!
*/
void
set_input_buf(p)
char_u *p;
{
garray_T *gap = (garray_T *)p;
if (gap != NULL)
{
if (gap->ga_data != NULL)
{
mch_memmove(inbuf, gap->ga_data, gap->ga_len);
inbufcount = gap->ga_len;
vim_free(gap->ga_data);
}
vim_free(gap);
}
}
#endif
#if defined(FEAT_GUI) \
|| defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE) \
|| defined(FEAT_XCLIPBOARD) || defined(VMS) \
|| defined(FEAT_SNIFF) || defined(FEAT_CLIENTSERVER) \
|| defined(PROTO)
/*
* Add the given bytes to the input buffer
* Special keys start with CSI. A real CSI must have been translated to
* CSI KS_EXTRA KE_CSI. K_SPECIAL doesn't require translation.
*/
void
add_to_input_buf(s, len)
char_u *s;
int len;
{
if (inbufcount + len > INBUFLEN + MAX_KEY_CODE_LEN)
return; /* Shouldn't ever happen! */
#ifdef FEAT_HANGULIN
if ((State & (INSERT|CMDLINE)) && hangul_input_state_get())
if ((len = hangul_input_process(s, len)) == 0)
return;
#endif
while (len--)
inbuf[inbufcount++] = *s++;
}
#endif
#if ((defined(FEAT_XIM) || defined(FEAT_DND)) && defined(FEAT_GUI_GTK)) \
|| defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MAC) \
|| (defined(FEAT_MBYTE) && defined(FEAT_MBYTE_IME)) \
|| (defined(FEAT_GUI) && (!defined(USE_ON_FLY_SCROLL) \
|| defined(FEAT_MENU))) \
|| defined(PROTO)
/*
* Add "str[len]" to the input buffer while escaping CSI bytes.
*/
void
add_to_input_buf_csi(char_u *str, int len)
{
int i;
char_u buf[2];
for (i = 0; i < len; ++i)
{
add_to_input_buf(str + i, 1);
if (str[i] == CSI)
{
/* Turn CSI into K_CSI. */
buf[0] = KS_EXTRA;
buf[1] = (int)KE_CSI;
add_to_input_buf(buf, 2);
}
}
}
#endif
#if defined(FEAT_HANGULIN) || defined(PROTO)
void
push_raw_key(s, len)
char_u *s;
int len;
{
while (len--)
inbuf[inbufcount++] = *s++;
}
#endif
#if defined(FEAT_GUI) || defined(FEAT_EVAL) || defined(FEAT_EX_EXTRA) \
|| defined(PROTO)
/* Remove everything from the input buffer. Called when ^C is found */
void
trash_input_buf()
{
inbufcount = 0;
}
#endif
/*
* Read as much data from the input buffer as possible up to maxlen, and store
* it in buf.
* Note: this function used to be Read() in unix.c
*/
int
read_from_input_buf(buf, maxlen)
char_u *buf;
long maxlen;
{
if (inbufcount == 0) /* if the buffer is empty, fill it */
fill_input_buf(TRUE);
if (maxlen > inbufcount)
maxlen = inbufcount;
mch_memmove(buf, inbuf, (size_t)maxlen);
inbufcount -= maxlen;
if (inbufcount)
mch_memmove(inbuf, inbuf + maxlen, (size_t)inbufcount);
return (int)maxlen;
}
void
fill_input_buf(exit_on_error)
int exit_on_error UNUSED;
{
#if defined(UNIX) || defined(OS2) || defined(VMS) || defined(MACOS_X_UNIX)
int len;
int try;
static int did_read_something = FALSE;
# ifdef FEAT_MBYTE
static char_u *rest = NULL; /* unconverted rest of previous read */
static int restlen = 0;
int unconverted;
# endif
#endif
#ifdef FEAT_GUI
if (gui.in_use
# ifdef NO_CONSOLE_INPUT
/* Don't use the GUI input when the window hasn't been opened yet.
* We get here from ui_inchar() when we should try reading from stdin. */
&& !no_console_input()
# endif
)
{
gui_mch_update();
return;
}
#endif
#if defined(UNIX) || defined(OS2) || defined(VMS) || defined(MACOS_X_UNIX)
if (vim_is_input_buf_full())
return;
/*
* Fill_input_buf() is only called when we really need a character.
* If we can't get any, but there is some in the buffer, just return.
* If we can't get any, and there isn't any in the buffer, we give up and
* exit Vim.
*/
# ifdef __BEOS__
/*
* On the BeBox version (for now), all input is secretly performed within
* beos_select() which is called from RealWaitForChar().
*/
while (!vim_is_input_buf_full() && RealWaitForChar(read_cmd_fd, 0, NULL))
;
len = inbufcount;
inbufcount = 0;
# else
# ifdef FEAT_SNIFF
if (sniff_request_waiting)
{
add_to_input_buf((char_u *)"\233sniff",6); /* results in K_SNIFF */
sniff_request_waiting = 0;
want_sniff_request = 0;
return;
}
# endif
# ifdef FEAT_MBYTE
if (rest != NULL)
{
/* Use remainder of previous call, starts with an invalid character
* that may become valid when reading more. */
if (restlen > INBUFLEN - inbufcount)
unconverted = INBUFLEN - inbufcount;
else
unconverted = restlen;
mch_memmove(inbuf + inbufcount, rest, unconverted);
if (unconverted == restlen)
{
vim_free(rest);
rest = NULL;
}
else
{
restlen -= unconverted;
mch_memmove(rest, rest + unconverted, restlen);
}
inbufcount += unconverted;
}
else
unconverted = 0;
#endif
len = 0; /* to avoid gcc warning */
for (try = 0; try < 100; ++try)
{
# ifdef VMS
len = vms_read(
# else
len = read(read_cmd_fd,
# endif
(char *)inbuf + inbufcount, (size_t)((INBUFLEN - inbufcount)
# ifdef FEAT_MBYTE
/ input_conv.vc_factor
# endif
));
# if 0
) /* avoid syntax highlight error */
# endif
if (len > 0 || got_int)
break;
/*
* If reading stdin results in an error, continue reading stderr.
* This helps when using "foo | xargs vim".
*/
if (!did_read_something && !isatty(read_cmd_fd) && read_cmd_fd == 0)
{
int m = cur_tmode;
/* We probably set the wrong file descriptor to raw mode. Switch
* back to cooked mode, use another descriptor and set the mode to
* what it was. */
settmode(TMODE_COOK);
#ifdef HAVE_DUP
/* Use stderr for stdin, also works for shell commands. */
close(0);
ignored = dup(2);
#else
read_cmd_fd = 2; /* read from stderr instead of stdin */
#endif
settmode(m);
}
if (!exit_on_error)
return;
}
# endif
if (len <= 0 && !got_int)
read_error_exit();
if (len > 0)
did_read_something = TRUE;
if (got_int)
{
/* Interrupted, pretend a CTRL-C was typed. */
inbuf[0] = 3;
inbufcount = 1;
}
else
{
# ifdef FEAT_MBYTE
/*
* May perform conversion on the input characters.
* Include the unconverted rest of the previous call.
* If there is an incomplete char at the end it is kept for the next
* time, reading more bytes should make conversion possible.
* Don't do this in the unlikely event that the input buffer is too
* small ("rest" still contains more bytes).
*/
if (input_conv.vc_type != CONV_NONE)
{
inbufcount -= unconverted;
len = convert_input_safe(inbuf + inbufcount,
len + unconverted, INBUFLEN - inbufcount,
rest == NULL ? &rest : NULL, &restlen);
}
# endif
while (len-- > 0)
{
/*
* if a CTRL-C was typed, remove it from the buffer and set got_int
*/
if (inbuf[inbufcount] == 3 && ctrl_c_interrupts)
{
/* remove everything typed before the CTRL-C */
mch_memmove(inbuf, inbuf + inbufcount, (size_t)(len + 1));
inbufcount = 0;
got_int = TRUE;
}
++inbufcount;
}
}
#endif /* UNIX or OS2 or VMS*/
}
#endif /* defined(UNIX) || defined(FEAT_GUI) || defined(OS2) || defined(VMS) */
/*
* Exit because of an input read error.
*/
void
read_error_exit()
{
if (silent_mode) /* Normal way to exit for "ex -s" */
getout(0);
STRCPY(IObuff, _("Vim: Error reading input, exiting...\n"));
preserve_exit();
}
#if defined(CURSOR_SHAPE) || defined(PROTO)
/*
* May update the shape of the cursor.
*/
void
ui_cursor_shape()
{
# ifdef FEAT_GUI
if (gui.in_use)
gui_update_cursor_later();
else
# endif
term_cursor_shape();
# ifdef MCH_CURSOR_SHAPE
mch_update_cursor();
# endif
# ifdef FEAT_CONCEAL
conceal_check_cursur_line();
# endif
}
#endif
#if defined(FEAT_CLIPBOARD) || defined(FEAT_GUI) || defined(FEAT_RIGHTLEFT) \
|| defined(FEAT_MBYTE) || defined(PROTO)
/*
* Check bounds for column number
*/
int
check_col(col)
int col;
{
if (col < 0)
return 0;
if (col >= (int)screen_Columns)
return (int)screen_Columns - 1;
return col;
}
/*
* Check bounds for row number
*/
int
check_row(row)
int row;
{
if (row < 0)
return 0;
if (row >= (int)screen_Rows)
return (int)screen_Rows - 1;
return row;
}
#endif
/*
* Stuff for the X clipboard. Shared between VMS and Unix.
*/
#if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) || defined(PROTO)
# include <X11/Xatom.h>
# include <X11/Intrinsic.h>
/*
* Open the application context (if it hasn't been opened yet).
* Used for Motif and Athena GUI and the xterm clipboard.
*/
void
open_app_context()
{
if (app_context == NULL)
{
XtToolkitInitialize();
app_context = XtCreateApplicationContext();
}
}
static Atom vim_atom; /* Vim's own special selection format */
#ifdef FEAT_MBYTE
static Atom vimenc_atom; /* Vim's extended selection format */
static Atom utf8_atom;
#endif
static Atom compound_text_atom;
static Atom text_atom;
static Atom targets_atom;
static Atom timestamp_atom; /* Used to get a timestamp */
void
x11_setup_atoms(dpy)
Display *dpy;
{
vim_atom = XInternAtom(dpy, VIM_ATOM_NAME, False);
#ifdef FEAT_MBYTE
vimenc_atom = XInternAtom(dpy, VIMENC_ATOM_NAME,False);
utf8_atom = XInternAtom(dpy, "UTF8_STRING", False);
#endif
compound_text_atom = XInternAtom(dpy, "COMPOUND_TEXT", False);
text_atom = XInternAtom(dpy, "TEXT", False);
targets_atom = XInternAtom(dpy, "TARGETS", False);
clip_star.sel_atom = XA_PRIMARY;
clip_plus.sel_atom = XInternAtom(dpy, "CLIPBOARD", False);
timestamp_atom = XInternAtom(dpy, "TIMESTAMP", False);
}
/*
* X Selection stuff, for cutting and pasting text to other windows.
*/
static Boolean clip_x11_convert_selection_cb __ARGS((Widget, Atom *, Atom *, Atom *, XtPointer *, long_u *, int *));
static void clip_x11_lose_ownership_cb __ARGS((Widget, Atom *));
static void clip_x11_timestamp_cb __ARGS((Widget w, XtPointer n, XEvent *event, Boolean *cont));
static void clip_x11_request_selection_cb __ARGS((Widget, XtPointer, Atom *, Atom *, XtPointer, long_u *, int *));
/*
* Property callback to get a timestamp for XtOwnSelection.
*/
static void
clip_x11_timestamp_cb(w, n, event, cont)
Widget w;
XtPointer n UNUSED;
XEvent *event;
Boolean *cont UNUSED;
{
Atom actual_type;
int format;
unsigned long nitems, bytes_after;
unsigned char *prop=NULL;
XPropertyEvent *xproperty=&event->xproperty;
/* Must be a property notify, state can't be Delete (True), has to be
* one of the supported selection types. */
if (event->type != PropertyNotify || xproperty->state
|| (xproperty->atom != clip_star.sel_atom
&& xproperty->atom != clip_plus.sel_atom))
return;
if (XGetWindowProperty(xproperty->display, xproperty->window,
xproperty->atom, 0, 0, False, timestamp_atom, &actual_type, &format,
&nitems, &bytes_after, &prop))
return;
if (prop)
XFree(prop);
/* Make sure the property type is "TIMESTAMP" and it's 32 bits. */
if (actual_type != timestamp_atom || format != 32)
return;
/* Get the selection, using the event timestamp. */
if (XtOwnSelection(w, xproperty->atom, xproperty->time,
clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
NULL) == OK)
{
/* Set the "owned" flag now, there may have been a call to
* lose_ownership_cb in between. */
if (xproperty->atom == clip_plus.sel_atom)
clip_plus.owned = TRUE;
else
clip_star.owned = TRUE;
}
}
void
x11_setup_selection(w)
Widget w;
{
XtAddEventHandler(w, PropertyChangeMask, False,
/*(XtEventHandler)*/clip_x11_timestamp_cb, (XtPointer)NULL);
}
static void
clip_x11_request_selection_cb(w, success, sel_atom, type, value, length,
format)
Widget w UNUSED;
XtPointer success;
Atom *sel_atom;
Atom *type;
XtPointer value;
long_u *length;
int *format;
{
int motion_type = MAUTO;
long_u len;
char_u *p;
char **text_list = NULL;
VimClipboard *cbd;
#ifdef FEAT_MBYTE
char_u *tmpbuf = NULL;
#endif
if (*sel_atom == clip_plus.sel_atom)
cbd = &clip_plus;
else
cbd = &clip_star;
if (value == NULL || *length == 0)
{
clip_free_selection(cbd); /* nothing received, clear register */
*(int *)success = FALSE;
return;
}
p = (char_u *)value;
len = *length;
if (*type == vim_atom)
{
motion_type = *p++;
len--;
}
#ifdef FEAT_MBYTE
else if (*type == vimenc_atom)
{
char_u *enc;
vimconv_T conv;
int convlen;
motion_type = *p++;
--len;
enc = p;
p += STRLEN(p) + 1;
len -= p - enc;
/* If the encoding of the text is different from 'encoding', attempt
* converting it. */
conv.vc_type = CONV_NONE;
convert_setup(&conv, enc, p_enc);
if (conv.vc_type != CONV_NONE)
{
convlen = len; /* Need to use an int here. */
tmpbuf = string_convert(&conv, p, &convlen);
len = convlen;
if (tmpbuf != NULL)
p = tmpbuf;
convert_setup(&conv, NULL, NULL);
}
}
#endif
else if (*type == compound_text_atom
#ifdef FEAT_MBYTE
|| *type == utf8_atom
#endif
|| (
#ifdef FEAT_MBYTE
enc_dbcs != 0 &&
#endif
*type == text_atom))
{
XTextProperty text_prop;
int n_text = 0;
int status;
text_prop.value = (unsigned char *)value;
text_prop.encoding = *type;
text_prop.format = *format;
text_prop.nitems = len;
status = XmbTextPropertyToTextList(X_DISPLAY, &text_prop,
&text_list, &n_text);
if (status != Success || n_text < 1)
{
*(int *)success = FALSE;
return;
}
p = (char_u *)text_list[0];
len = STRLEN(p);
}
clip_yank_selection(motion_type, p, (long)len, cbd);
if (text_list != NULL)
XFreeStringList(text_list);
#ifdef FEAT_MBYTE
vim_free(tmpbuf);
#endif
XtFree((char *)value);
*(int *)success = TRUE;
}
void
clip_x11_request_selection(myShell, dpy, cbd)
Widget myShell;
Display *dpy;
VimClipboard *cbd;
{
XEvent event;
Atom type;
static int success;
int i;
time_t start_time;
int timed_out = FALSE;
for (i =
#ifdef FEAT_MBYTE
0
#else
1
#endif
; i < 6; i++)
{
switch (i)
{
#ifdef FEAT_MBYTE
case 0: type = vimenc_atom; break;
#endif
case 1: type = vim_atom; break;
#ifdef FEAT_MBYTE
case 2: type = utf8_atom; break;
#endif
case 3: type = compound_text_atom; break;
case 4: type = text_atom; break;
default: type = XA_STRING;
}
#ifdef FEAT_MBYTE
if (type == utf8_atom && !enc_utf8)
/* Only request utf-8 when 'encoding' is utf8. */
continue;
#endif
success = MAYBE;
XtGetSelectionValue(myShell, cbd->sel_atom, type,
clip_x11_request_selection_cb, (XtPointer)&success, CurrentTime);
/* Make sure the request for the selection goes out before waiting for
* a response. */
XFlush(dpy);
/*
* Wait for result of selection request, otherwise if we type more
* characters, then they will appear before the one that requested the
* paste! Don't worry, we will catch up with any other events later.
*/
start_time = time(NULL);
while (success == MAYBE)
{
if (XCheckTypedEvent(dpy, SelectionNotify, &event)
|| XCheckTypedEvent(dpy, SelectionRequest, &event)
|| XCheckTypedEvent(dpy, PropertyNotify, &event))
{
/* This is where clip_x11_request_selection_cb() should be
* called. It may actually happen a bit later, so we loop
* until "success" changes.
* We may get a SelectionRequest here and if we don't handle
* it we hang. KDE klipper does this, for example.
* We need to handle a PropertyNotify for large selections. */
XtDispatchEvent(&event);
continue;
}
/* Time out after 2 to 3 seconds to avoid that we hang when the
* other process doesn't respond. Note that the SelectionNotify
* event may still come later when the selection owner comes back
* to life and the text gets inserted unexpectedly. Don't know
* why that happens or how to avoid that :-(. */
if (time(NULL) > start_time + 2)
{
timed_out = TRUE;
break;
}
/* Do we need this? Probably not. */
XSync(dpy, False);
/* Wait for 1 msec to avoid that we eat up all CPU time. */
ui_delay(1L, TRUE);
}
if (success == TRUE)
return;
/* don't do a retry with another type after timing out, otherwise we
* hang for 15 seconds. */
if (timed_out)
break;
}
/* Final fallback position - use the X CUT_BUFFER0 store */
yank_cut_buffer0(dpy, cbd);
}
static Boolean
clip_x11_convert_selection_cb(w, sel_atom, target, type, value, length, format)
Widget w UNUSED;
Atom *sel_atom;
Atom *target;
Atom *type;
XtPointer *value;
long_u *length;
int *format;
{
char_u *string;
char_u *result;
int motion_type;
VimClipboard *cbd;
int i;
if (*sel_atom == clip_plus.sel_atom)
cbd = &clip_plus;
else
cbd = &clip_star;
if (!cbd->owned)
return False; /* Shouldn't ever happen */
/* requestor wants to know what target types we support */
if (*target == targets_atom)
{
Atom *array;
if ((array = (Atom *)XtMalloc((unsigned)(sizeof(Atom) * 7))) == NULL)
return False;
*value = (XtPointer)array;
i = 0;
array[i++] = targets_atom;
#ifdef FEAT_MBYTE
array[i++] = vimenc_atom;
#endif
array[i++] = vim_atom;
#ifdef FEAT_MBYTE
if (enc_utf8)
array[i++] = utf8_atom;
#endif
array[i++] = XA_STRING;
array[i++] = text_atom;
array[i++] = compound_text_atom;
*type = XA_ATOM;
/* This used to be: *format = sizeof(Atom) * 8; but that caused
* crashes on 64 bit machines. (Peter Derr) */
*format = 32;
*length = i;
return True;
}
if ( *target != XA_STRING
#ifdef FEAT_MBYTE
&& *target != vimenc_atom
&& *target != utf8_atom
#endif
&& *target != vim_atom
&& *target != text_atom
&& *target != compound_text_atom)
return False;
clip_get_selection(cbd);
motion_type = clip_convert_selection(&string, length, cbd);
if (motion_type < 0)
return False;
/* For our own format, the first byte contains the motion type */
if (*target == vim_atom)
(*length)++;
#ifdef FEAT_MBYTE
/* Our own format with encoding: motion 'encoding' NUL text */
if (*target == vimenc_atom)
*length += STRLEN(p_enc) + 2;
#endif
*value = XtMalloc((Cardinal)*length);
result = (char_u *)*value;
if (result == NULL)
{
vim_free(string);
return False;
}
if (*target == XA_STRING
#ifdef FEAT_MBYTE
|| (*target == utf8_atom && enc_utf8)
#endif
)
{
mch_memmove(result, string, (size_t)(*length));
*type = *target;
}
else if (*target == compound_text_atom || *target == text_atom)
{
XTextProperty text_prop;
char *string_nt = (char *)alloc((unsigned)*length + 1);
/* create NUL terminated string which XmbTextListToTextProperty wants */
mch_memmove(string_nt, string, (size_t)*length);
string_nt[*length] = NUL;
XmbTextListToTextProperty(X_DISPLAY, (char **)&string_nt, 1,
XCompoundTextStyle, &text_prop);
vim_free(string_nt);
XtFree(*value); /* replace with COMPOUND text */
*value = (XtPointer)(text_prop.value); /* from plain text */
*length = text_prop.nitems;
*type = compound_text_atom;
}
#ifdef FEAT_MBYTE
else if (*target == vimenc_atom)
{
int l = STRLEN(p_enc);
result[0] = motion_type;
STRCPY(result + 1, p_enc);
mch_memmove(result + l + 2, string, (size_t)(*length - l - 2));
*type = vimenc_atom;
}
#endif
else
{
result[0] = motion_type;
mch_memmove(result + 1, string, (size_t)(*length - 1));
*type = vim_atom;
}
*format = 8; /* 8 bits per char */
vim_free(string);
return True;
}
static void
clip_x11_lose_ownership_cb(w, sel_atom)
Widget w UNUSED;
Atom *sel_atom;
{
if (*sel_atom == clip_plus.sel_atom)
clip_lose_selection(&clip_plus);
else
clip_lose_selection(&clip_star);
}
void
clip_x11_lose_selection(myShell, cbd)
Widget myShell;
VimClipboard *cbd;
{
XtDisownSelection(myShell, cbd->sel_atom, CurrentTime);
}
int
clip_x11_own_selection(myShell, cbd)
Widget myShell;
VimClipboard *cbd;
{
/* When using the GUI we have proper timestamps, use the one of the last
* event. When in the console we don't get events (the terminal gets
* them), Get the time by a zero-length append, clip_x11_timestamp_cb will
* be called with the current timestamp. */
#ifdef FEAT_GUI
if (gui.in_use)
{
if (XtOwnSelection(myShell, cbd->sel_atom,
XtLastTimestampProcessed(XtDisplay(myShell)),
clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
NULL) == False)
return FAIL;
}
else
#endif
{
if (!XChangeProperty(XtDisplay(myShell), XtWindow(myShell),
cbd->sel_atom, timestamp_atom, 32, PropModeAppend, NULL, 0))
return FAIL;
}
/* Flush is required in a terminal as nothing else is doing it. */
XFlush(XtDisplay(myShell));
return OK;
}
/*
* Send the current selection to the clipboard. Do nothing for X because we
* will fill in the selection only when requested by another app.
*/
void
clip_x11_set_selection(cbd)
VimClipboard *cbd UNUSED;
{
}
#endif
#if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) \
|| defined(FEAT_GUI_GTK) || defined(PROTO)
/*
* Get the contents of the X CUT_BUFFER0 and put it in "cbd".
*/
void
yank_cut_buffer0(dpy, cbd)
Display *dpy;
VimClipboard *cbd;
{
int nbytes = 0;
char_u *buffer = (char_u *)XFetchBuffer(dpy, &nbytes, 0);
if (nbytes > 0)
{
#ifdef FEAT_MBYTE
int done = FALSE;
/* CUT_BUFFER0 is supposed to be always latin1. Convert to 'enc' when
* using a multi-byte encoding. Conversion between two 8-bit
* character sets usually fails and the text might actually be in
* 'enc' anyway. */
if (has_mbyte)
{
char_u *conv_buf;
vimconv_T vc;
vc.vc_type = CONV_NONE;
if (convert_setup(&vc, (char_u *)"latin1", p_enc) == OK)
{
conv_buf = string_convert(&vc, buffer, &nbytes);
if (conv_buf != NULL)
{
clip_yank_selection(MCHAR, conv_buf, (long)nbytes, cbd);
vim_free(conv_buf);
done = TRUE;
}
convert_setup(&vc, NULL, NULL);
}
}
if (!done) /* use the text without conversion */
#endif
clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
XFree((void *)buffer);
if (p_verbose > 0)
{
verbose_enter();
verb_msg((char_u *)_("Used CUT_BUFFER0 instead of empty selection"));
verbose_leave();
}
}
}
#endif
#if defined(FEAT_MOUSE) || defined(PROTO)
/*
* Move the cursor to the specified row and column on the screen.
* Change current window if necessary. Returns an integer with the
* CURSOR_MOVED bit set if the cursor has moved or unset otherwise.
*
* The MOUSE_FOLD_CLOSE bit is set when clicked on the '-' in a fold column.
* The MOUSE_FOLD_OPEN bit is set when clicked on the '+' in a fold column.
*
* If flags has MOUSE_FOCUS, then the current window will not be changed, and
* if the mouse is outside the window then the text will scroll, or if the
* mouse was previously on a status line, then the status line may be dragged.
*
* If flags has MOUSE_MAY_VIS, then VIsual mode will be started before the
* cursor is moved unless the cursor was on a status line.
* This function returns one of IN_UNKNOWN, IN_BUFFER, IN_STATUS_LINE or
* IN_SEP_LINE depending on where the cursor was clicked.
*
* If flags has MOUSE_MAY_STOP_VIS, then Visual mode will be stopped, unless
* the mouse is on the status line of the same window.
*
* If flags has MOUSE_DID_MOVE, nothing is done if the mouse didn't move since
* the last call.
*
* If flags has MOUSE_SETPOS, nothing is done, only the current position is
* remembered.
*/
int
jump_to_mouse(flags, inclusive, which_button)
int flags;
int *inclusive; /* used for inclusive operator, can be NULL */
int which_button; /* MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE */
{
static int on_status_line = 0; /* #lines below bottom of window */
#ifdef FEAT_VERTSPLIT
static int on_sep_line = 0; /* on separator right of window */
#endif
static int prev_row = -1;
static int prev_col = -1;
static win_T *dragwin = NULL; /* window being dragged */
static int did_drag = FALSE; /* drag was noticed */
win_T *wp, *old_curwin;
pos_T old_cursor;
int count;
int first;
int row = mouse_row;
int col = mouse_col;
#ifdef FEAT_FOLDING
int mouse_char;
#endif
mouse_past_bottom = FALSE;
mouse_past_eol = FALSE;
if (flags & MOUSE_RELEASED)
{
/* On button release we may change window focus if positioned on a
* status line and no dragging happened. */
if (dragwin != NULL && !did_drag)
flags &= ~(MOUSE_FOCUS | MOUSE_DID_MOVE);
dragwin = NULL;
did_drag = FALSE;
}
if ((flags & MOUSE_DID_MOVE)
&& prev_row == mouse_row
&& prev_col == mouse_col)
{
retnomove:
/* before moving the cursor for a left click which is NOT in a status
* line, stop Visual mode */
if (on_status_line)
return IN_STATUS_LINE;
#ifdef FEAT_VERTSPLIT
if (on_sep_line)
return IN_SEP_LINE;
#endif
#ifdef FEAT_VISUAL
if (flags & MOUSE_MAY_STOP_VIS)
{
end_visual_mode();
redraw_curbuf_later(INVERTED); /* delete the inversion */
}
#endif
#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)
/* Continue a modeless selection in another window. */
if (cmdwin_type != 0 && row < W_WINROW(curwin))
return IN_OTHER_WIN;
#endif
return IN_BUFFER;
}
prev_row = mouse_row;
prev_col = mouse_col;
if (flags & MOUSE_SETPOS)
goto retnomove; /* ugly goto... */
#ifdef FEAT_FOLDING
/* Remember the character under the mouse, it might be a '-' or '+' in the
* fold column. */
if (row >= 0 && row < Rows && col >= 0 && col <= Columns
&& ScreenLines != NULL)
mouse_char = ScreenLines[LineOffset[row] + col];
else
mouse_char = ' ';
#endif
old_curwin = curwin;
old_cursor = curwin->w_cursor;
if (!(flags & MOUSE_FOCUS))
{
if (row < 0 || col < 0) /* check if it makes sense */
return IN_UNKNOWN;
#ifdef FEAT_WINDOWS
/* find the window where the row is in */
wp = mouse_find_win(&row, &col);
#else
wp = firstwin;
#endif
dragwin = NULL;
/*
* winpos and height may change in win_enter()!
*/
if (row >= wp->w_height) /* In (or below) status line */
{
on_status_line = row - wp->w_height + 1;
dragwin = wp;
}
else
on_status_line = 0;
#ifdef FEAT_VERTSPLIT
if (col >= wp->w_width) /* In separator line */
{
on_sep_line = col - wp->w_width + 1;
dragwin = wp;
}
else
on_sep_line = 0;
/* The rightmost character of the status line might be a vertical
* separator character if there is no connecting window to the right. */
if (on_status_line && on_sep_line)
{
if (stl_connected(wp))
on_sep_line = 0;
else
on_status_line = 0;
}
#endif
#ifdef FEAT_VISUAL
/* Before jumping to another buffer, or moving the cursor for a left
* click, stop Visual mode. */
if (VIsual_active
&& (wp->w_buffer != curwin->w_buffer
|| (!on_status_line
# ifdef FEAT_VERTSPLIT
&& !on_sep_line
# endif
# ifdef FEAT_FOLDING
&& (
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? col < W_WIDTH(wp) - wp->w_p_fdc :
# endif
col >= wp->w_p_fdc
# ifdef FEAT_CMDWIN
+ (cmdwin_type == 0 && wp == curwin ? 0 : 1)
# endif
)
# endif
&& (flags & MOUSE_MAY_STOP_VIS))))
{
end_visual_mode();
redraw_curbuf_later(INVERTED); /* delete the inversion */
}
#endif
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0 && wp != curwin)
{
/* A click outside the command-line window: Use modeless
* selection if possible. Allow dragging the status lines. */
# ifdef FEAT_VERTSPLIT
on_sep_line = 0;
# endif
# ifdef FEAT_CLIPBOARD
if (on_status_line)
return IN_STATUS_LINE;
return IN_OTHER_WIN;
# else
row = 0;
col += wp->w_wincol;
wp = curwin;
# endif
}
#endif
#ifdef FEAT_WINDOWS
/* Only change window focus when not clicking on or dragging the
* status line. Do change focus when releasing the mouse button
* (MOUSE_FOCUS was set above if we dragged first). */
if (dragwin == NULL || (flags & MOUSE_RELEASED))
win_enter(wp, TRUE); /* can make wp invalid! */
# ifdef CHECK_DOUBLE_CLICK
/* set topline, to be able to check for double click ourselves */
if (curwin != old_curwin)
set_mouse_topline(curwin);
# endif
#endif
if (on_status_line) /* In (or below) status line */
{
/* Don't use start_arrow() if we're in the same window */
if (curwin == old_curwin)
return IN_STATUS_LINE;
else
return IN_STATUS_LINE | CURSOR_MOVED;
}
#ifdef FEAT_VERTSPLIT
if (on_sep_line) /* In (or below) status line */
{
/* Don't use start_arrow() if we're in the same window */
if (curwin == old_curwin)
return IN_SEP_LINE;
else
return IN_SEP_LINE | CURSOR_MOVED;
}
#endif
curwin->w_cursor.lnum = curwin->w_topline;
#ifdef FEAT_GUI
/* remember topline, needed for double click */
gui_prev_topline = curwin->w_topline;
# ifdef FEAT_DIFF
gui_prev_topfill = curwin->w_topfill;
# endif
#endif
}
else if (on_status_line && which_button == MOUSE_LEFT)
{
#ifdef FEAT_WINDOWS
if (dragwin != NULL)
{
/* Drag the status line */
count = row - dragwin->w_winrow - dragwin->w_height + 1
- on_status_line;
win_drag_status_line(dragwin, count);
did_drag |= count;
}
#endif
return IN_STATUS_LINE; /* Cursor didn't move */
}
#ifdef FEAT_VERTSPLIT
else if (on_sep_line && which_button == MOUSE_LEFT)
{
if (dragwin != NULL)
{
/* Drag the separator column */
count = col - dragwin->w_wincol - dragwin->w_width + 1
- on_sep_line;
win_drag_vsep_line(dragwin, count);
did_drag |= count;
}
return IN_SEP_LINE; /* Cursor didn't move */
}
#endif
else /* keep_window_focus must be TRUE */
{
#ifdef FEAT_VISUAL
/* before moving the cursor for a left click, stop Visual mode */
if (flags & MOUSE_MAY_STOP_VIS)
{
end_visual_mode();
redraw_curbuf_later(INVERTED); /* delete the inversion */
}
#endif
#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)
/* Continue a modeless selection in another window. */
if (cmdwin_type != 0 && row < W_WINROW(curwin))
return IN_OTHER_WIN;
#endif
row -= W_WINROW(curwin);
#ifdef FEAT_VERTSPLIT
col -= W_WINCOL(curwin);
#endif
/*
* When clicking beyond the end of the window, scroll the screen.
* Scroll by however many rows outside the window we are.
*/
if (row < 0)
{
count = 0;
for (first = TRUE; curwin->w_topline > 1; )
{
#ifdef FEAT_DIFF
if (curwin->w_topfill < diff_check(curwin, curwin->w_topline))
++count;
else
#endif
count += plines(curwin->w_topline - 1);
if (!first && count > -row)
break;
first = FALSE;
#ifdef FEAT_FOLDING
hasFolding(curwin->w_topline, &curwin->w_topline, NULL);
#endif
#ifdef FEAT_DIFF
if (curwin->w_topfill < diff_check(curwin, curwin->w_topline))
++curwin->w_topfill;
else
#endif
{
--curwin->w_topline;
#ifdef FEAT_DIFF
curwin->w_topfill = 0;
#endif
}
}
#ifdef FEAT_DIFF
check_topfill(curwin, FALSE);
#endif
curwin->w_valid &=
~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
redraw_later(VALID);
row = 0;
}
else if (row >= curwin->w_height)
{
count = 0;
for (first = TRUE; curwin->w_topline < curbuf->b_ml.ml_line_count; )
{
#ifdef FEAT_DIFF
if (curwin->w_topfill > 0)
++count;
else
#endif
count += plines(curwin->w_topline);
if (!first && count > row - curwin->w_height + 1)
break;
first = FALSE;
#ifdef FEAT_FOLDING
if (hasFolding(curwin->w_topline, NULL, &curwin->w_topline)
&& curwin->w_topline == curbuf->b_ml.ml_line_count)
break;
#endif
#ifdef FEAT_DIFF
if (curwin->w_topfill > 0)
--curwin->w_topfill;
else
#endif
{
++curwin->w_topline;
#ifdef FEAT_DIFF
curwin->w_topfill =
diff_check_fill(curwin, curwin->w_topline);
#endif
}
}
#ifdef FEAT_DIFF
check_topfill(curwin, FALSE);
#endif
redraw_later(VALID);
curwin->w_valid &=
~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
row = curwin->w_height - 1;
}
else if (row == 0)
{
/* When dragging the mouse, while the text has been scrolled up as
* far as it goes, moving the mouse in the top line should scroll
* the text down (done later when recomputing w_topline). */
if (mouse_dragging > 0
&& curwin->w_cursor.lnum
== curwin->w_buffer->b_ml.ml_line_count
&& curwin->w_cursor.lnum == curwin->w_topline)
curwin->w_valid &= ~(VALID_TOPLINE);
}
}
#ifdef FEAT_FOLDING
/* Check for position outside of the fold column. */
if (
# ifdef FEAT_RIGHTLEFT
curwin->w_p_rl ? col < W_WIDTH(curwin) - curwin->w_p_fdc :
# endif
col >= curwin->w_p_fdc
# ifdef FEAT_CMDWIN
+ (cmdwin_type == 0 ? 0 : 1)
# endif
)
mouse_char = ' ';
#endif
/* compute the position in the buffer line from the posn on the screen */
if (mouse_comp_pos(curwin, &row, &col, &curwin->w_cursor.lnum))
mouse_past_bottom = TRUE;
#ifdef FEAT_VISUAL
/* Start Visual mode before coladvance(), for when 'sel' != "old" */
if ((flags & MOUSE_MAY_VIS) && !VIsual_active)
{
check_visual_highlight();
VIsual = old_cursor;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
/* if 'selectmode' contains "mouse", start Select mode */
may_start_select('o');
setmouse();
if (p_smd && msg_silent == 0)
redraw_cmdline = TRUE; /* show visual mode later */
}
#endif
curwin->w_curswant = col;
curwin->w_set_curswant = FALSE; /* May still have been TRUE */
if (coladvance(col) == FAIL) /* Mouse click beyond end of line */
{
if (inclusive != NULL)
*inclusive = TRUE;
mouse_past_eol = TRUE;
}
else if (inclusive != NULL)
*inclusive = FALSE;
count = IN_BUFFER;
if (curwin != old_curwin || curwin->w_cursor.lnum != old_cursor.lnum
|| curwin->w_cursor.col != old_cursor.col)
count |= CURSOR_MOVED; /* Cursor has moved */
#ifdef FEAT_FOLDING
if (mouse_char == '+')
count |= MOUSE_FOLD_OPEN;
else if (mouse_char != ' ')
count |= MOUSE_FOLD_CLOSE;
#endif
return count;
}
/*
* Compute the position in the buffer line from the posn on the screen in
* window "win".
* Returns TRUE if the position is below the last line.
*/
int
mouse_comp_pos(win, rowp, colp, lnump)
win_T *win;
int *rowp;
int *colp;
linenr_T *lnump;
{
int col = *colp;
int row = *rowp;
linenr_T lnum;
int retval = FALSE;
int off;
int count;
#ifdef FEAT_RIGHTLEFT
if (win->w_p_rl)
col = W_WIDTH(win) - 1 - col;
#endif
lnum = win->w_topline;
while (row > 0)
{
#ifdef FEAT_DIFF
/* Don't include filler lines in "count" */
if (win->w_p_diff
# ifdef FEAT_FOLDING
&& !hasFoldingWin(win, lnum, NULL, NULL, TRUE, NULL)
# endif
)
{
if (lnum == win->w_topline)
row -= win->w_topfill;
else
row -= diff_check_fill(win, lnum);
count = plines_win_nofill(win, lnum, TRUE);
}
else
#endif
count = plines_win(win, lnum, TRUE);
if (count > row)
break; /* Position is in this buffer line. */
#ifdef FEAT_FOLDING
(void)hasFoldingWin(win, lnum, NULL, &lnum, TRUE, NULL);
#endif
if (lnum == win->w_buffer->b_ml.ml_line_count)
{
retval = TRUE;
break; /* past end of file */
}
row -= count;
++lnum;
}
if (!retval)
{
/* Compute the column without wrapping. */
off = win_col_off(win) - win_col_off2(win);
if (col < off)
col = off;
col += row * (W_WIDTH(win) - off);
/* add skip column (for long wrapping line) */
col += win->w_skipcol;
}
if (!win->w_p_wrap)
col += win->w_leftcol;
/* skip line number and fold column in front of the line */
col -= win_col_off(win);
if (col < 0)
{
#ifdef FEAT_NETBEANS_INTG
netbeans_gutter_click(lnum);
#endif
col = 0;
}
*colp = col;
*rowp = row;
*lnump = lnum;
return retval;
}
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Find the window at screen position "*rowp" and "*colp". The positions are
* updated to become relative to the top-left of the window.
*/
win_T *
mouse_find_win(rowp, colp)
int *rowp;
int *colp UNUSED;
{
frame_T *fp;
fp = topframe;
*rowp -= firstwin->w_winrow;
for (;;)
{
if (fp->fr_layout == FR_LEAF)
break;
#ifdef FEAT_VERTSPLIT
if (fp->fr_layout == FR_ROW)
{
for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)
{
if (*colp < fp->fr_width)
break;
*colp -= fp->fr_width;
}
}
#endif
else /* fr_layout == FR_COL */
{
for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)
{
if (*rowp < fp->fr_height)
break;
*rowp -= fp->fr_height;
}
}
}
return fp->fr_win;
}
#endif
#if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MAC) \
|| defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_PHOTON) || defined(PROTO)
/*
* Translate window coordinates to buffer position without any side effects
*/
int
get_fpos_of_mouse(mpos)
pos_T *mpos;
{
win_T *wp;
int row = mouse_row;
int col = mouse_col;
if (row < 0 || col < 0) /* check if it makes sense */
return IN_UNKNOWN;
#ifdef FEAT_WINDOWS
/* find the window where the row is in */
wp = mouse_find_win(&row, &col);
#else
wp = firstwin;
#endif
/*
* winpos and height may change in win_enter()!
*/
if (row >= wp->w_height) /* In (or below) status line */
return IN_STATUS_LINE;
#ifdef FEAT_VERTSPLIT
if (col >= wp->w_width) /* In vertical separator line */
return IN_SEP_LINE;
#endif
if (wp != curwin)
return IN_UNKNOWN;
/* compute the position in the buffer line from the posn on the screen */
if (mouse_comp_pos(curwin, &row, &col, &mpos->lnum))
return IN_STATUS_LINE; /* past bottom */
mpos->col = vcol2col(wp, mpos->lnum, col);
if (mpos->col > 0)
--mpos->col;
#ifdef FEAT_VIRTUALEDIT
mpos->coladd = 0;
#endif
return IN_BUFFER;
}
/*
* Convert a virtual (screen) column to a character column.
* The first column is one.
*/
int
vcol2col(wp, lnum, vcol)
win_T *wp;
linenr_T lnum;
int vcol;
{
/* try to advance to the specified column */
int count = 0;
char_u *ptr;
char_u *start;
start = ptr = ml_get_buf(wp->w_buffer, lnum, FALSE);
while (count <= vcol && *ptr != NUL)
{
count += win_lbr_chartabsize(wp, ptr, count, NULL);
mb_ptr_adv(ptr);
}
return (int)(ptr - start);
}
#endif
#endif /* FEAT_MOUSE */
#if defined(FEAT_GUI) || defined(WIN3264) || defined(PROTO)
/*
* Called when focus changed. Used for the GUI or for systems where this can
* be done in the console (Win32).
*/
void
ui_focus_change(in_focus)
int in_focus; /* TRUE if focus gained. */
{
static time_t last_time = (time_t)0;
int need_redraw = FALSE;
/* When activated: Check if any file was modified outside of Vim.
* Only do this when not done within the last two seconds (could get
* several events in a row). */
if (in_focus && last_time + 2 < time(NULL))
{
need_redraw = check_timestamps(
# ifdef FEAT_GUI
gui.in_use
# else
FALSE
# endif
);
last_time = time(NULL);
}
#ifdef FEAT_AUTOCMD
/*
* Fire the focus gained/lost autocommand.
*/
need_redraw |= apply_autocmds(in_focus ? EVENT_FOCUSGAINED
: EVENT_FOCUSLOST, NULL, NULL, FALSE, curbuf);
#endif
if (need_redraw)
{
/* Something was executed, make sure the cursor is put back where it
* belongs. */
need_wait_return = FALSE;
if (State & CMDLINE)
redrawcmdline();
else if (State == HITRETURN || State == SETWSIZE || State == ASKMORE
|| State == EXTERNCMD || State == CONFIRM || exmode_active)
repeat_message();
else if ((State & NORMAL) || (State & INSERT))
{
if (must_redraw != 0)
update_screen(0);
setcursor();
}
cursor_on(); /* redrawing may have switched it off */
out_flush();
# ifdef FEAT_GUI
if (gui.in_use)
{
gui_update_cursor(FALSE, TRUE);
gui_update_scrollbars(FALSE);
}
# endif
}
#ifdef FEAT_TITLE
/* File may have been changed from 'readonly' to 'noreadonly' */
if (need_maketitle)
maketitle();
#endif
}
#endif
#if defined(USE_IM_CONTROL) || defined(PROTO)
/*
* Save current Input Method status to specified place.
*/
void
im_save_status(psave)
long *psave;
{
/* Don't save when 'imdisable' is set or "xic" is NULL, IM is always
* disabled then (but might start later).
* Also don't save when inside a mapping, vgetc_im_active has not been set
* then.
* And don't save when the keys were stuffed (e.g., for a "." command).
* And don't save when the GUI is running but our window doesn't have
* input focus (e.g., when a find dialog is open). */
if (!p_imdisable && KeyTyped && !KeyStuffed
# ifdef FEAT_XIM
&& xic != NULL
# endif
# ifdef FEAT_GUI
&& (!gui.in_use || gui.in_focus)
# endif
)
{
/* Do save when IM is on, or IM is off and saved status is on. */
if (vgetc_im_active)
*psave = B_IMODE_IM;
else if (*psave == B_IMODE_IM)
*psave = B_IMODE_NONE;
}
}
#endif
| zyz2011-vim | src/ui.c | C | gpl2 | 78,207 |
/* vi:set ts=8 sw=4 sts=4:
*
* VIM - Vi IMproved by Bram Moolenaar
* Photon GUI support by Julian Kinraid
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
*
*
* Clipboard support is in os_qnx.c
* PhAttach() is called in os_qnx.c:qnx_init()
*/
#include "vim.h"
#ifdef FEAT_TOOLBAR
# include <photon/PxImage.h>
#endif
#if !defined(__QNX__)
/* Used when generating prototypes. */
# define PgColor_t int
# define PhEvent_t int
# define PhPoint_t int
# define PtWidget_t int
# define Pg_BLACK 0
# define PtCallbackF_t int
# define PtCallbackInfo_t int
# define PhTile_t int
# define PtWidget_t int
# define PhImage_t int
#endif
#define ARRAY_LENGTH(a) (sizeof(a) / sizeof(a[0]))
#define RGB(r, g, b) PgRGB(r, g, b)
#define EVENT_BUFFER_SIZE sizeof(PhEvent_t) + 1000
/* Some defines for gui_mch_mousehide() */
#define MOUSE_HIDE TRUE
#define MOUSE_SHOW FALSE
/* Optional support for using a PtPanelGroup widget, needs work */
#undef USE_PANEL_GROUP
#ifdef USE_PANEL_GROUP
static char *empty_title = " ";
static char **panel_titles = NULL;
static ushort_t num_panels = 0;
static short pg_margin_left, pg_margin_right, pg_margin_top, pg_margin_bottom;
#endif
#define GUI_PH_MARGIN 4 /* Size of the bevel */
#define GUI_PH_MOUSE_TYPE Ph_CURSOR_INSERT
static PgColor_t gui_ph_mouse_color = Pg_BLACK;
static PhPoint_t gui_ph_raw_offset;
static PtWidget_t *gui_ph_timer_cursor; /* handle cursor blinking */
static PtWidget_t *gui_ph_timer_timeout; /* used in gui_mch_wait_for_chars */
static short is_timeout; /* Has the timeout occured? */
/*
* This is set inside the mouse callback for a right mouse
* button click, and used for the popup menus
*/
static PhPoint_t abs_mouse;
/* Try and avoid redraws while a resize is in progress */
static int is_ignore_draw = FALSE;
/* Used for converting to/from utf-8 and other charsets */
static struct PxTransCtrl *charset_translate;
/*
* 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
*/
static enum {
BLINK_NONE,
BLINK_OFF,
BLINK_ON
} blink_state = BLINK_NONE;
static long_u blink_waittime = 700;
static long_u blink_ontime = 400;
static long_u blink_offtime = 250;
static struct
{
int key_sym;
char_u vim_code0;
char_u vim_code1;
} special_keys[] =
{
{Pk_Up, 'k', 'u'},
{Pk_Down, 'k', 'd'},
{Pk_Left, 'k', 'l'},
{Pk_Right, 'k', 'r'},
{Pk_F1, 'k', '1'},
{Pk_F2, 'k', '2'},
{Pk_F3, 'k', '3'},
{Pk_F4, 'k', '4'},
{Pk_F5, 'k', '5'},
{Pk_F6, 'k', '6'},
{Pk_F7, 'k', '7'},
{Pk_F8, 'k', '8'},
{Pk_F9, 'k', '9'},
{Pk_F10, 'k', ';'},
{Pk_F11, 'F', '1'},
{Pk_F12, 'F', '2'},
{Pk_F13, 'F', '3'},
{Pk_F14, 'F', '4'},
{Pk_F15, 'F', '5'},
{Pk_F16, 'F', '6'},
{Pk_F17, 'F', '7'},
{Pk_F18, 'F', '8'},
{Pk_F19, 'F', '9'},
{Pk_F20, 'F', 'A'},
{Pk_F21, 'F', 'B'},
{Pk_F22, 'F', 'C'},
{Pk_F23, 'F', 'D'},
{Pk_F24, 'F', 'E'},
{Pk_F25, 'F', 'F'},
{Pk_F26, 'F', 'G'},
{Pk_F27, 'F', 'H'},
{Pk_F28, 'F', 'I'},
{Pk_F29, 'F', 'J'},
{Pk_F30, 'F', 'K'},
{Pk_F31, 'F', 'L'},
{Pk_F32, 'F', 'M'},
{Pk_F33, 'F', 'N'},
{Pk_F34, 'F', 'O'},
{Pk_F35, 'F', 'P'},
{Pk_Help, '%', '1'},
{Pk_BackSpace, 'k', 'b'},
{Pk_Insert, 'k', 'I'},
{Pk_Delete, 'k', 'D'},
{Pk_Home, 'k', 'h'},
{Pk_End, '@', '7'},
{Pk_Prior, 'k', 'P'},
{Pk_Next, 'k', 'N'},
{Pk_Print, '%', '9'},
{Pk_KP_Add, 'K', '6'},
{Pk_KP_Subtract,'K', '7'},
{Pk_KP_Divide, 'K', '8'},
{Pk_KP_Multiply,'K', '9'},
{Pk_KP_Enter, 'K', 'A'},
{Pk_KP_0, KS_EXTRA, KE_KINS}, /* Insert */
{Pk_KP_Decimal, KS_EXTRA, KE_KDEL}, /* Delete */
{Pk_KP_4, 'k', 'l'}, /* Left */
{Pk_KP_6, 'k', 'r'}, /* Right */
{Pk_KP_8, 'k', 'u'}, /* Up */
{Pk_KP_2, 'k', 'd'}, /* Down */
{Pk_KP_7, 'K', '1'}, /* Home */
{Pk_KP_1, 'K', '4'}, /* End */
{Pk_KP_9, 'K', '3'}, /* Page Up */
{Pk_KP_3, 'K', '5'}, /* Page Down */
{Pk_KP_5, '&', '8'}, /* Undo */
/* Keys that we want to be able to use any modifier with: */
{Pk_Return, CAR, NUL},
{Pk_space, ' ', NUL},
{Pk_Tab, TAB, NUL},
{Pk_Escape, ESC, NUL},
{NL, NL, NUL},
{CAR, CAR, NUL},
/* End of list marker: */
{0, 0, 0}
};
/****************************************************************************/
static PtCallbackF_t gui_ph_handle_timer_cursor;
static PtCallbackF_t gui_ph_handle_timer_timeout;
static PtCallbackF_t gui_ph_handle_window_cb;
static PtCallbackF_t gui_ph_handle_scrollbar;
static PtCallbackF_t gui_ph_handle_keyboard;
static PtCallbackF_t gui_ph_handle_mouse;
static PtCallbackF_t gui_ph_handle_pulldown_menu;
static PtCallbackF_t gui_ph_handle_menu;
static PtCallbackF_t gui_ph_handle_focus; /* focus change of text area */
static PtCallbackF_t gui_ph_handle_menu_resize;
/* When a menu is unrealized, give focus back to vimTextArea */
static PtCallbackF_t gui_ph_handle_menu_unrealized;
#ifdef USE_PANEL_GROUP
static void gui_ph_get_panelgroup_margins(short*, short*, short*, short*);
#endif
#ifdef FEAT_TOOLBAR
static PhImage_t *gui_ph_toolbar_find_icon(vimmenu_T *menu);
#endif
static void gui_ph_draw_start(void);
static void gui_ph_draw_end(void);
/* Set the text for the balloon */
static PtWidget_t * gui_ph_show_tooltip(PtWidget_t *window,
PtWidget_t *widget,
int position,
char *text,
char *font,
PgColor_t fill_color,
PgColor_t text_color);
/****************************************************************************/
static PtWidget_t * gui_ph_show_tooltip(PtWidget_t *window,
PtWidget_t *widget,
int position,
char *text,
char *font,
PgColor_t fill_color,
PgColor_t text_color)
{
PtArg_t arg;
vimmenu_T *menu;
char_u *tooltip;
PtSetArg(&arg, Pt_ARG_POINTER, &menu, 0);
PtGetResources(widget, 1, &arg);
/* Override the text and position */
tooltip = text;
if (menu != NULL)
{
int index = MENU_INDEX_TIP;
if (menu->strings[ index ] != NULL)
tooltip = menu->strings[ index ];
}
return PtInflateBalloon(
window,
widget,
/* Don't put the balloon at the bottom,
* it gets drawn over by gfx done in the PtRaw */
Pt_BALLOON_TOP,
tooltip,
font,
fill_color,
text_color);
}
static void
gui_ph_resize_container(void)
{
PhArea_t area;
PtWidgetArea(gui.vimWindow, &area);
PtWidgetPos (gui.vimContainer, &area.pos);
PtSetResource(gui.vimContainer, Pt_ARG_AREA, &area, 0);
}
static int
gui_ph_handle_menu_resize(
PtWidget_t *widget,
void *other,
PtCallbackInfo_t *info)
{
PtContainerCallback_t *sizes = info->cbdata;
PtWidget_t *container;
PhPoint_t below_menu;
int_u height;
height = sizes->new_dim.h;
/* Because vim treats the toolbar and menubar separately,
* and here they're lumped together into a PtToolbarGroup,
* we only need either menu_height or toolbar_height set at once */
if (gui.menu_is_active)
{
gui.menu_height = height;
gui.toolbar_height = 0;
}
#ifdef FEAT_TOOLBAR
else
gui.toolbar_height = height;
#endif
below_menu.x = 0;
below_menu.y = height;
#ifdef USE_PANEL_GROUP
container = gui.vimPanelGroup;
#else
container = gui.vimContainer;
#endif
PtSetResource(container, Pt_ARG_POS, &below_menu, 0);
gui_ph_resize_container();
#ifdef USE_PANEL_GROUP
gui_ph_get_panelgroup_margins(
&pg_margin_top, &pg_margin_bottom,
&pg_margin_left, &pg_margin_right);
#endif
return Pt_CONTINUE;
}
/*
* Pt_ARG_TIMER_REPEAT isn't used because the on & off times
* are different
*/
static int
gui_ph_handle_timer_cursor(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
if (blink_state == BLINK_ON)
{
gui_undraw_cursor();
blink_state = BLINK_OFF;
PtSetResource(gui_ph_timer_cursor, Pt_ARG_TIMER_INITIAL,
blink_offtime, 0);
}
else
{
gui_update_cursor(TRUE, FALSE);
blink_state = BLINK_ON;
PtSetResource(gui_ph_timer_cursor, Pt_ARG_TIMER_INITIAL,
blink_ontime, 0);
}
return Pt_CONTINUE;
}
static int
gui_ph_handle_timer_timeout(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
is_timeout = TRUE;
return Pt_CONTINUE;
}
static int
gui_ph_handle_window_cb(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
PhWindowEvent_t *we = info->cbdata;
ushort_t *width, *height;
switch (we->event_f) {
case Ph_WM_CLOSE:
gui_shell_closed();
break;
case Ph_WM_FOCUS:
/* Just in case it's hidden and needs to be shown */
gui_mch_mousehide(MOUSE_SHOW);
if (we->event_state == Ph_WM_EVSTATE_FOCUS)
{
gui_focus_change(TRUE);
gui_mch_start_blink();
}
else
{
gui_focus_change(FALSE);
gui_mch_stop_blink();
}
break;
case Ph_WM_RESIZE:
PtGetResource(gui.vimWindow, Pt_ARG_WIDTH, &width, 0);
PtGetResource(gui.vimWindow, Pt_ARG_HEIGHT, &height, 0);
#ifdef USE_PANEL_GROUP
width -= (pg_margin_left + pg_margin_right);
height -= (pg_margin_top + pg_margin_bottom);
#endif
gui_resize_shell(*width, *height);
gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
is_ignore_draw = FALSE;
PtEndFlux(gui.vimContainer);
PtContainerRelease(gui.vimContainer);
break;
default:
break;
}
return Pt_CONTINUE;
}
static int
gui_ph_handle_scrollbar(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
PtScrollbarCallback_t *scroll;
scrollbar_T *sb;
int value, dragging = FALSE;
scroll = info->cbdata;
sb = (scrollbar_T *) data;
if (sb != NULL)
{
value = scroll->position;
switch (scroll->action)
{
case Pt_SCROLL_DRAGGED:
dragging = TRUE;
break;
case Pt_SCROLL_SET:
/* FIXME: return straight away here? */
return Pt_CONTINUE;
break;
}
gui_drag_scrollbar(sb, value, dragging);
}
return Pt_CONTINUE;
}
static int
gui_ph_handle_keyboard(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
PhKeyEvent_t *key;
unsigned char string[6];
int len, i;
int ch, modifiers;
key = PhGetData(info->event);
ch = modifiers = len = 0;
if (p_mh)
gui_mch_mousehide(MOUSE_HIDE);
/* We're a good lil photon program, aren't we? yes we are, yeess wee arrr */
if (key->key_flags & Pk_KF_Compose)
{
return Pt_CONTINUE;
}
if ((key->key_flags & Pk_KF_Cap_Valid) &&
PkIsKeyDown(key->key_flags))
{
#ifdef FEAT_MENU
/*
* Only show the menu if the Alt key is down, and the Shift & Ctrl
* keys aren't down, as well as the other conditions
*/
if (((key->key_mods & Pk_KM_Alt) &&
!(key->key_mods & Pk_KM_Shift) &&
!(key->key_mods & Pk_KM_Ctrl)) &&
gui.menu_is_active &&
(*p_wak == 'y' ||
(*p_wak == 'm' &&
gui_is_menu_shortcut(key->key_cap))))
{
/* Fallthrough and let photon look for the hotkey */
return Pt_CONTINUE;
}
#endif
for (i = 0; special_keys[i].key_sym != 0; i++)
{
if (special_keys[i].key_sym == key->key_cap)
{
len = 0;
if (special_keys[i].vim_code1 == NUL)
ch = special_keys[i].vim_code0;
else
{
/* Detect if a keypad number key has been pressed
* and change the key if Num Lock is on */
if (key->key_cap >= Pk_KP_Enter && key->key_cap <= Pk_KP_9
&& (key->key_mods & Pk_KM_Num_Lock))
{
/* FIXME: For now, just map the key to a ascii value
* (see <photon/PkKeyDef.h>) */
ch = key->key_cap - 0xf080;
}
else
ch = TO_SPECIAL(special_keys[i].vim_code0,
special_keys[i].vim_code1);
}
break;
}
}
if (key->key_mods & Pk_KM_Ctrl)
modifiers |= MOD_MASK_CTRL;
if (key->key_mods & Pk_KM_Alt)
modifiers |= MOD_MASK_ALT;
if (key->key_mods & Pk_KM_Shift)
modifiers |= MOD_MASK_SHIFT;
/* Is this not a special key? */
if (special_keys[i].key_sym == 0)
{
ch = PhTo8859_1(key);
if (ch == -1
#ifdef FEAT_MBYTE
|| (enc_utf8 && ch > 127)
#endif
)
{
#ifdef FEAT_MBYTE
len = PhKeyToMb(string, key);
if (len > 0)
{
static char buf[6];
int src_taken, dst_made;
if (enc_utf8 != TRUE)
{
PxTranslateFromUTF(
charset_translate,
string,
len,
&src_taken,
buf,
6,
&dst_made);
add_to_input_buf(buf, dst_made);
}
else
{
add_to_input_buf(string, len);
}
return Pt_CONSUME;
}
len = 0;
#endif
ch = key->key_cap;
if (ch < 0xff)
{
/* FIXME: is this the right thing to do? */
if (modifiers & MOD_MASK_CTRL)
{
modifiers &= ~MOD_MASK_CTRL;
if ((ch >= 'a' && ch <= 'z') ||
ch == '[' ||
ch == ']' ||
ch == '\\')
ch = Ctrl_chr(ch);
else if (ch == '2')
ch = NUL;
else if (ch == '6')
ch = 0x1e;
else if (ch == '-')
ch = 0x1f;
else
modifiers |= MOD_MASK_CTRL;
}
if (modifiers & MOD_MASK_ALT)
{
ch = Meta(ch);
modifiers &= ~MOD_MASK_ALT;
}
}
else
{
return Pt_CONTINUE;
}
}
else
modifiers &= ~MOD_MASK_SHIFT;
}
ch = simplify_key(ch, &modifiers);
if (modifiers)
{
string[ len++ ] = CSI;
string[ len++ ] = KS_MODIFIER;
string[ len++ ] = modifiers;
}
if (IS_SPECIAL(ch))
{
string[ len++ ] = CSI;
string[ len++ ] = K_SECOND(ch);
string[ len++ ] = K_THIRD(ch);
}
else
{
string[ len++ ] = ch;
}
if (len == 1 && ((ch == Ctrl_C && ctrl_c_interrupts)
|| ch == intr_char))
{
trash_input_buf();
got_int = TRUE;
}
if (len == 1 && string[0] == CSI)
{
/* Turn CSI into K_CSI. */
string[ len++ ] = KS_EXTRA;
string[ len++ ] = KE_CSI;
}
if (len > 0)
{
add_to_input_buf(string, len);
return Pt_CONSUME;
}
}
return Pt_CONTINUE;
}
static int
gui_ph_handle_mouse(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
PhPointerEvent_t *pointer;
PhRect_t *pos;
int button = 0, repeated_click, modifiers = 0x0;
short mouse_x, mouse_y;
pointer = PhGetData(info->event);
pos = PhGetRects(info->event);
gui_mch_mousehide(MOUSE_SHOW);
/*
* Coordinates need to be relative to the base window,
* not relative to the vimTextArea widget
*/
mouse_x = pos->ul.x + gui.border_width;
mouse_y = pos->ul.y + gui.border_width;
if (info->event->type == Ph_EV_PTR_MOTION_NOBUTTON)
{
gui_mouse_moved(mouse_x, mouse_y);
return Pt_CONTINUE;
}
if (pointer->key_mods & Pk_KM_Shift)
modifiers |= MOUSE_SHIFT;
if (pointer->key_mods & Pk_KM_Ctrl)
modifiers |= MOUSE_CTRL;
if (pointer->key_mods & Pk_KM_Alt)
modifiers |= MOUSE_ALT;
/*
* FIXME More than one button may be involved, but for
* now just deal with one
*/
if (pointer->buttons & Ph_BUTTON_SELECT)
button = MOUSE_LEFT;
if (pointer->buttons & Ph_BUTTON_MENU)
{
button = MOUSE_RIGHT;
/* Need the absolute coordinates for the popup menu */
abs_mouse.x = pointer->pos.x;
abs_mouse.y = pointer->pos.y;
}
if (pointer->buttons & Ph_BUTTON_ADJUST)
button = MOUSE_MIDDLE;
/* Catch a real release (not phantom or other releases */
if (info->event->type == Ph_EV_BUT_RELEASE)
button = MOUSE_RELEASE;
if (info->event->type & Ph_EV_PTR_MOTION_BUTTON)
button = MOUSE_DRAG;
#if 0
/* Vim doesn't use button repeats */
if (info->event->type & Ph_EV_BUT_REPEAT)
button = MOUSE_DRAG;
#endif
/* Don't do anything if it is one of the phantom mouse release events */
if ((button != MOUSE_RELEASE) ||
(info->event->subtype == Ph_EV_RELEASE_REAL))
{
repeated_click = (pointer->click_count >= 2) ? TRUE : FALSE;
gui_send_mouse_event(button , mouse_x, mouse_y, repeated_click, modifiers);
}
return Pt_CONTINUE;
}
/* Handle a focus change of the PtRaw widget */
static int
gui_ph_handle_focus(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
if (info->reason == Pt_CB_LOST_FOCUS)
{
PtRemoveEventHandler(gui.vimTextArea, Ph_EV_PTR_MOTION_NOBUTTON,
gui_ph_handle_mouse, NULL);
gui_mch_mousehide(MOUSE_SHOW);
}
else
{
PtAddEventHandler(gui.vimTextArea, Ph_EV_PTR_MOTION_NOBUTTON,
gui_ph_handle_mouse, NULL);
}
return Pt_CONTINUE;
}
static void
gui_ph_handle_raw_draw(PtWidget_t *widget, PhTile_t *damage)
{
PhRect_t *r;
PhPoint_t offset;
PhPoint_t translation;
if (is_ignore_draw == TRUE)
return;
PtSuperClassDraw(PtBasic, widget, damage);
PgGetTranslation(&translation);
PgClearTranslation();
#if 0
/*
* This causes some weird problems, with drawing being done from
* within this raw drawing function (rather than just simple clearing
* and text drawing done by gui_redraw)
*
* The main problem is when PhBlit is used, and the cursor appearing
* in places where it shouldn't
*/
out_flush();
#endif
PtWidgetOffset(widget, &offset);
PhTranslatePoint(&offset, PtWidgetPos(gui.vimTextArea, NULL));
#if 1
/* Redraw individual damage regions */
if (damage->next != NULL)
damage = damage->next;
while (damage != NULL)
{
r = &damage->rect;
gui_redraw(
r->ul.x - offset.x, r->ul.y - offset.y,
r->lr.x - r->ul.x + 1,
r->lr.y - r->ul.y + 1);
damage = damage->next;
}
#else
/* Redraw the rectangle that covers all the damaged regions */
r = &damage->rect;
gui_redraw(
r->ul.x - offset.x, r->ul.y - offset.y,
r->lr.x - r->ul.x + 1,
r->lr.y - r->ul.y + 1);
#endif
PgSetTranslation(&translation, 0);
}
static int
gui_ph_handle_pulldown_menu(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
if (data != NULL)
{
vimmenu_T *menu = (vimmenu_T *) data;
PtPositionMenu(menu->submenu_id, NULL);
PtRealizeWidget(menu->submenu_id);
}
return Pt_CONTINUE;
}
/* This is used for pulldown/popup menus and also toolbar buttons */
static int
gui_ph_handle_menu(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
if (data != NULL)
{
vimmenu_T *menu = (vimmenu_T *) data;
gui_menu_cb(menu);
}
return Pt_CONTINUE;
}
/* Stop focus from disappearing into the menubar... */
static int
gui_ph_handle_menu_unrealized(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
PtGiveFocus(gui.vimTextArea, NULL);
return Pt_CONTINUE;
}
static int
gui_ph_handle_window_open(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
return Pt_CONTINUE;
}
/****************************************************************************/
#define DRAW_START gui_ph_draw_start()
#define DRAW_END gui_ph_draw_end()
/* TODO: Set a clipping rect? */
static void
gui_ph_draw_start(void)
{
PhGC_t *gc;
gc = PgGetGC();
PgSetRegion(PtWidgetRid(PtFindDisjoint(gui.vimTextArea)));
PgClearClippingsCx(gc);
PgClearTranslationCx(gc);
PtWidgetOffset(gui.vimTextArea, &gui_ph_raw_offset);
PhTranslatePoint(&gui_ph_raw_offset, PtWidgetPos(gui.vimTextArea, NULL));
PgSetTranslation(&gui_ph_raw_offset, Pg_RELATIVE);
}
static void
gui_ph_draw_end(void)
{
gui_ph_raw_offset.x = -gui_ph_raw_offset.x;
gui_ph_raw_offset.y = -gui_ph_raw_offset.y;
PgSetTranslation(&gui_ph_raw_offset, Pg_RELATIVE);
}
#ifdef USE_PANEL_GROUP
static vimmenu_T *
gui_ph_find_buffer_item(char_u *name)
{
vimmenu_T *top_level = root_menu;
vimmenu_T *items = NULL;
while (top_level != NULL &&
(STRCMP(top_level->dname, "Buffers") != 0))
top_level = top_level->next;
if (top_level != NULL)
{
items = top_level->children;
while (items != NULL &&
(STRCMP(items->dname, name) != 0))
items = items->next;
}
return items;
}
static void
gui_ph_pg_set_buffer_num(int_u buf_num)
{
int i;
char search[16];
char *mark;
if (gui.vimTextArea == NULL || buf_num == 0)
return;
search[0] = '(';
ultoa(buf_num, &search[1], 10);
STRCAT(search, ")");
for (i = 0; i < num_panels; i++)
{
/* find the last "(" in the panel title and see if the buffer
* number in the title matches the one we're looking for */
mark = STRRCHR(panel_titles[ i ], '(');
if (mark != NULL && STRCMP(mark, search) == 0)
{
PtSetResource(gui.vimPanelGroup, Pt_ARG_PG_CURRENT_INDEX,
i, 0);
}
}
}
static int
gui_ph_handle_pg_change(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
vimmenu_T *menu;
PtPanelGroupCallback_t *panel;
if (info->event != NULL)
{
panel = info->cbdata;
if (panel->new_panel != NULL)
{
menu = gui_ph_find_buffer_item(panel->new_panel);
if (menu)
gui_menu_cb(menu);
}
}
return Pt_CONTINUE;
}
static void
gui_ph_get_panelgroup_margins(
short *top,
short *bottom,
short *left,
short *right)
{
unsigned short abs_raw_x, abs_raw_y, abs_panel_x, abs_panel_y;
const unsigned short *margin_top, *margin_bottom;
const unsigned short *margin_left, *margin_right;
PtGetAbsPosition(gui.vimTextArea, &abs_raw_x, &abs_raw_y);
PtGetAbsPosition(gui.vimPanelGroup, &abs_panel_x, &abs_panel_y);
PtGetResource(gui.vimPanelGroup, Pt_ARG_MARGIN_RIGHT, &margin_right, 0);
PtGetResource(gui.vimPanelGroup, Pt_ARG_MARGIN_BOTTOM, &margin_bottom, 0);
abs_raw_x -= abs_panel_x;
abs_raw_y -= abs_panel_y;
*top = abs_raw_y;
*bottom = *margin_bottom;
*left = abs_raw_x;
*right = *margin_right;
}
/* Used for the tabs for PtPanelGroup */
static int
gui_ph_is_buffer_item(vimmenu_T *menu, vimmenu_T *parent)
{
char *mark;
if (STRCMP(parent->dname, "Buffers") == 0)
{
/* Look for '(' digits ')' */
mark = vim_strchr(menu->dname, '(');
if (mark != NULL)
{
mark++;
while (isdigit(*mark))
mark++;
if (*mark == ')')
return TRUE;
}
}
return FALSE;
}
static void
gui_ph_pg_add_buffer(char *name)
{
char **new_titles = NULL;
new_titles = (char **) alloc((num_panels + 1) * sizeof(char **));
if (new_titles != NULL)
{
if (num_panels > 0)
memcpy(new_titles, panel_titles, num_panels * sizeof(char **));
new_titles[ num_panels++ ] = name;
PtSetResource(gui.vimPanelGroup, Pt_ARG_PG_PANEL_TITLES, new_titles,
num_panels);
vim_free(panel_titles);
panel_titles = new_titles;
}
}
static void
gui_ph_pg_remove_buffer(char *name)
{
int i;
char **new_titles = NULL;
/* If there is only 1 panel, we just use the temporary place holder */
if (num_panels > 1)
{
new_titles = (char **) alloc((num_panels - 1) * sizeof(char **));
if (new_titles != NULL)
{
char **s = new_titles;
/* Copy all the titles except the one we're removing */
for (i = 0; i < num_panels; i++)
{
if (STRCMP(panel_titles[ i ], name) != 0)
{
*s++ = panel_titles[ i ];
}
}
num_panels--;
PtSetResource(gui.vimPanelGroup, Pt_ARG_PG_PANEL_TITLES, new_titles,
num_panels);
vim_free(panel_titles);
panel_titles = new_titles;
}
}
else
{
num_panels--;
PtSetResource(gui.vimPanelGroup, Pt_ARG_PG_PANEL_TITLES, &empty_title,
1);
vim_free(panel_titles);
panel_titles = NULL;
}
}
/* When a buffer item is deleted from the buffer menu */
static int
gui_ph_handle_buffer_remove(
PtWidget_t *widget,
void *data,
PtCallbackInfo_t *info)
{
vimmenu_T *menu;
if (data != NULL)
{
menu = (vimmenu_T *) data;
gui_ph_pg_remove_buffer(menu->dname);
}
return Pt_CONTINUE;
}
#endif
static int
gui_ph_pane_resize(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
if (PtWidgetIsRealized(widget))
{
is_ignore_draw = TRUE;
PtStartFlux(gui.vimContainer);
PtContainerHold(gui.vimContainer);
}
return Pt_CONTINUE;
}
/****************************************************************************/
#ifdef FEAT_MBYTE
void
gui_ph_encoding_changed(int new_encoding)
{
/* Default encoding is latin1 */
char *charset = "latin1";
int i;
struct {
int encoding;
char *name;
} charsets[] = {
{ DBCS_JPN, "SHIFT_JIS" },
{ DBCS_KOR, "csEUCKR" },
{ DBCS_CHT, "big5" },
{ DBCS_CHS, "gb" }
};
for (i = 0; i < ARRAY_LENGTH(charsets); i++)
{
if (new_encoding == charsets[ i ].encoding)
charset = charsets[ i ].name;
}
charset_translate = PxTranslateSet(charset_translate, charset);
}
#endif
/****************************************************************************/
/****************************************************************************/
void
gui_mch_prepare(argc, argv)
int *argc;
char **argv;
{
PtInit(NULL);
}
int
gui_mch_init(void)
{
PtArg_t args[10];
int flags = 0, n = 0;
PhDim_t window_size = {100, 100}; /* Arbitrary values */
PhPoint_t pos = {0, 0};
gui.event_buffer = (PhEvent_t *) alloc(EVENT_BUFFER_SIZE);
if (gui.event_buffer == NULL)
return FAIL;
/* Get a translation so we can convert from ISO Latin-1 to UTF */
charset_translate = PxTranslateSet(NULL, "latin1");
/* The +2 is for the 1 pixel dark line on each side */
gui.border_offset = gui.border_width = GUI_PH_MARGIN + 2;
/* Handle close events ourselves */
PtSetArg(&args[ n++ ], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_CLOSE);
PtSetArg(&args[ n++ ], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE,
Ph_WM_CLOSE | Ph_WM_RESIZE | Ph_WM_FOCUS);
PtSetArg(&args[ n++ ], Pt_ARG_DIM, &window_size, 0);
gui.vimWindow = PtCreateWidget(PtWindow, NULL, n, args);
if (gui.vimWindow == NULL)
return FAIL;
PtAddCallback(gui.vimWindow, Pt_CB_WINDOW, gui_ph_handle_window_cb, NULL);
PtAddCallback(gui.vimWindow, Pt_CB_WINDOW_OPENING,
gui_ph_handle_window_open, NULL);
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_ANCHOR_FLAGS, Pt_ANCHOR_ALL, Pt_IS_ANCHORED);
PtSetArg(&args[ n++ ], Pt_ARG_DIM, &window_size, 0);
PtSetArg(&args[ n++ ], Pt_ARG_POS, &pos, 0);
#ifdef USE_PANEL_GROUP
/* Put in a temprary place holder title */
PtSetArg(&args[ n++ ], Pt_ARG_PG_PANEL_TITLES, &empty_title, 1);
gui.vimPanelGroup = PtCreateWidget(PtPanelGroup, gui.vimWindow, n, args);
if (gui.vimPanelGroup == NULL)
return FAIL;
PtAddCallback(gui.vimPanelGroup, Pt_CB_PG_PANEL_SWITCHING,
gui_ph_handle_pg_change, NULL);
#else
/* Turn off all edge decorations */
PtSetArg(&args[ n++ ], Pt_ARG_BASIC_FLAGS, Pt_FALSE, Pt_ALL);
PtSetArg(&args[ n++ ], Pt_ARG_BEVEL_WIDTH, 0, 0);
PtSetArg(&args[ n++ ], Pt_ARG_MARGIN_WIDTH, 0, 0);
PtSetArg(&args[ n++ ], Pt_ARG_MARGIN_HEIGHT, 0, 0);
PtSetArg(&args[ n++ ], Pt_ARG_CONTAINER_FLAGS, Pt_TRUE, Pt_AUTO_EXTENT);
gui.vimContainer = PtCreateWidget(PtPane, gui.vimWindow, n, args);
if (gui.vimContainer == NULL)
return FAIL;
PtAddCallback(gui.vimContainer, Pt_CB_RESIZE, gui_ph_pane_resize, NULL);
#endif
/* Size for the text area is set in gui_mch_set_text_area_pos */
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_RAW_DRAW_F, gui_ph_handle_raw_draw, 1);
PtSetArg(&args[ n++ ], Pt_ARG_BEVEL_WIDTH, GUI_PH_MARGIN, 0);
/*
* Using focus render also causes the whole widget to be redrawn
* whenever it changes focus, which is very annoying :p
*/
PtSetArg(&args[ n++ ], Pt_ARG_FLAGS, Pt_TRUE,
Pt_GETS_FOCUS | Pt_HIGHLIGHTED);
#ifndef FEAT_MOUSESHAPE
PtSetArg(&args[ n++ ], Pt_ARG_CURSOR_TYPE, GUI_PH_MOUSE_TYPE, 0);
PtSetArg(&args[ n++ ], Pt_ARG_CURSOR_COLOR, gui_ph_mouse_color, 0);
#endif
gui.vimTextArea = PtCreateWidget(PtRaw, Pt_DFLT_PARENT, n, args);
if (gui.vimTextArea == NULL)
return FAIL;
/* TODO: use PtAddEventHandlers instead? */
/* Not using Ph_EV_BUT_REPEAT because vim wouldn't use it anyway */
PtAddEventHandler(gui.vimTextArea,
Ph_EV_BUT_PRESS | Ph_EV_BUT_RELEASE | Ph_EV_PTR_MOTION_BUTTON,
gui_ph_handle_mouse, NULL);
PtAddEventHandler(gui.vimTextArea, Ph_EV_KEY,
gui_ph_handle_keyboard, NULL);
PtAddCallback(gui.vimTextArea, Pt_CB_GOT_FOCUS,
gui_ph_handle_focus, NULL);
PtAddCallback(gui.vimTextArea, Pt_CB_LOST_FOCUS,
gui_ph_handle_focus, NULL);
/*
* Now that the text area widget has been created, set up the colours,
* which wil call PtSetResource from gui_mch_new_colors
*/
/*
* Create the two timers, not as accurate as using the kernel timer
* functions, but good enough
*/
gui_ph_timer_cursor = PtCreateWidget(PtTimer, gui.vimWindow, 0, NULL);
if (gui_ph_timer_cursor == NULL)
return FAIL;
gui_ph_timer_timeout = PtCreateWidget(PtTimer, gui.vimWindow, 0, NULL);
if (gui_ph_timer_timeout == NULL)
return FAIL;
PtAddCallback(gui_ph_timer_cursor, Pt_CB_TIMER_ACTIVATE,
gui_ph_handle_timer_cursor, NULL);
PtAddCallback(gui_ph_timer_timeout, Pt_CB_TIMER_ACTIVATE,
gui_ph_handle_timer_timeout, NULL);
#ifdef FEAT_MENU
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_WIDTH, window_size.w, 0);
PtSetArg(&args[ n++ ], Pt_ARG_ANCHOR_FLAGS, Pt_ANCHOR_LEFT_RIGHT,
Pt_IS_ANCHORED);
gui.vimToolBarGroup = PtCreateWidget(PtToolbarGroup, gui.vimWindow,
n, args);
if (gui.vimToolBarGroup == NULL)
return FAIL;
PtAddCallback(gui.vimToolBarGroup, Pt_CB_RESIZE,
gui_ph_handle_menu_resize, NULL);
n = 0;
flags = 0;
PtSetArg(&args[ n++ ], Pt_ARG_WIDTH, window_size.w, 0);
if (! vim_strchr(p_go, GO_MENUS))
{
flags |= Pt_DELAY_REALIZE;
PtSetArg(&args[ n++ ], Pt_ARG_FLAGS, Pt_TRUE, flags);
}
gui.vimMenuBar = PtCreateWidget(PtMenuBar, gui.vimToolBarGroup, n, args);
if (gui.vimMenuBar == NULL)
return FAIL;
# ifdef FEAT_TOOLBAR
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_ANCHOR_FLAGS,
Pt_ANCHOR_LEFT_RIGHT |Pt_TOP_ANCHORED_TOP, Pt_IS_ANCHORED);
PtSetArg(&args[ n++ ], Pt_ARG_RESIZE_FLAGS, Pt_TRUE,
Pt_RESIZE_Y_AS_REQUIRED);
PtSetArg(&args[ n++ ], Pt_ARG_WIDTH, window_size.w, 0);
flags = Pt_GETS_FOCUS;
if (! vim_strchr(p_go, GO_TOOLBAR))
flags |= Pt_DELAY_REALIZE;
PtSetArg(&args[ n++ ], Pt_ARG_FLAGS, Pt_DELAY_REALIZE, flags);
gui.vimToolBar = PtCreateWidget(PtToolbar, gui.vimToolBarGroup, n, args);
if (gui.vimToolBar == NULL)
return FAIL;
/*
* Size for the toolbar is fetched in gui_mch_show_toolbar, after
* the buttons have been added and the toolbar has resized it's height
* for the buttons to fit
*/
# endif
#endif
return OK;
}
int
gui_mch_init_check(void)
{
return (is_photon_available == TRUE) ? OK : FAIL;
}
int
gui_mch_open(void)
{
gui.norm_pixel = Pg_BLACK;
gui.back_pixel = Pg_WHITE;
set_normal_colors();
gui_check_colors();
gui.def_norm_pixel = gui.norm_pixel;
gui.def_back_pixel = gui.back_pixel;
highlight_gui_started();
if (gui_win_x != -1 && gui_win_y != -1)
gui_mch_set_winpos(gui_win_x, gui_win_y);
return (PtRealizeWidget(gui.vimWindow) == 0) ? OK : FAIL;
}
void
gui_mch_exit(int rc)
{
PtDestroyWidget(gui.vimWindow);
PxTranslateSet(charset_translate, NULL);
vim_free(gui.event_buffer);
#ifdef USE_PANEL_GROUPS
vim_free(panel_titles);
#endif
}
/****************************************************************************/
/* events */
/* When no events are available, photon will call this function, working is
* set to FALSE, and the gui_mch_update loop will exit. */
static int
exit_gui_mch_update(void *data)
{
*(int *)data = FALSE;
return Pt_END;
}
void
gui_mch_update(void)
{
int working = TRUE;
PtAppAddWorkProc(NULL, exit_gui_mch_update, &working);
while ((working == TRUE) && !vim_is_input_buf_full())
{
PtProcessEvent();
}
}
int
gui_mch_wait_for_chars(int wtime)
{
is_timeout = FALSE;
if (wtime > 0)
PtSetResource(gui_ph_timer_timeout, Pt_ARG_TIMER_INITIAL, wtime, 0);
while (1)
{
PtProcessEvent();
if (input_available())
{
PtSetResource(gui_ph_timer_timeout, Pt_ARG_TIMER_INITIAL, 0, 0);
return OK;
}
else if (is_timeout == TRUE)
return FAIL;
}
}
#if defined(FEAT_BROWSE) || defined(PROTO)
/*
* Put up a file requester.
* Returns the selected name in allocated memory, or NULL for Cancel.
* saving, select file to write
* title title for the window
* default_name default name (well duh!)
* ext not used (extension added)
* initdir initial directory, NULL for current dir
* filter not used (file name filter)
*/
char_u *
gui_mch_browse(
int saving,
char_u *title,
char_u *default_name,
char_u *ext,
char_u *initdir,
char_u *filter)
{
PtFileSelectionInfo_t file;
int flags;
char_u *default_path;
char_u *open_text = NULL;
flags = 0;
memset(&file, 0, sizeof(file));
default_path = alloc(MAXPATHL + 1 + NAME_MAX + 1);
if (default_path != NULL)
{
if (saving == TRUE)
{
/* Don't need Pt_FSR_CONFIRM_EXISTING, vim will ask anyway */
flags |= Pt_FSR_NO_FCHECK;
open_text = "&Save";
}
/* combine the directory and filename into a single path */
if (initdir == NULL || *initdir == NUL)
{
mch_dirname(default_path, MAXPATHL);
initdir = default_path;
}
else
{
STRCPY(default_path, initdir);
initdir = default_path;
}
if (default_name != NULL)
{
if (default_path[ STRLEN(default_path) - 1 ] != '/')
STRCAT(default_path, "/");
STRCAT(default_path, default_name);
}
/* TODO: add a filter? */
PtFileSelection(
gui.vimWindow,
NULL,
title,
default_path,
NULL,
open_text,
NULL,
NULL,
&file,
flags);
vim_free(default_path);
if (file.ret == Pt_FSDIALOG_BTN1)
return vim_strsave(file.path);
}
return NULL;
}
#endif
#if defined(FEAT_GUI_DIALOG) || defined(PROTO)
static PtWidget_t *gui_ph_dialog_text = NULL;
static int
gui_ph_dialog_close(int button, void *data)
{
PtModalCtrl_t *modal_ctrl = data;
char_u *dialog_text, *vim_text;
if (gui_ph_dialog_text != NULL)
{
PtGetResource(gui_ph_dialog_text, Pt_ARG_TEXT_STRING, &dialog_text, 0);
PtGetResource(gui_ph_dialog_text, Pt_ARG_POINTER, &vim_text, 0);
STRNCPY(vim_text, dialog_text, IOSIZE - 1);
}
PtModalUnblock(modal_ctrl, (void *) button);
return Pt_TRUE;
}
static int
gui_ph_dialog_text_enter(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
if (info->reason_subtype == Pt_EDIT_ACTIVATE)
gui_ph_dialog_close(1, data);
return Pt_CONTINUE;
}
static int
gui_ph_dialog_esc(PtWidget_t *widget, void *data, PtCallbackInfo_t *info)
{
PhKeyEvent_t *key;
key = PhGetData(info->event);
if ((key->key_flags & Pk_KF_Cap_Valid) && (key->key_cap == Pk_Escape))
{
gui_ph_dialog_close(0, data);
return Pt_CONSUME;
}
return Pt_PROCESS;
}
int
gui_mch_dialog(
int type,
char_u *title,
char_u *message,
char_u *buttons,
int default_button,
char_u *textfield,
int ex_cmd)
{
char_u *str;
char_u **button_array;
char_u *buttons_copy;
int button_count;
int i, len;
int dialog_result = -1;
/* FIXME: the vertical option in guioptions is blatantly ignored */
/* FIXME: so is the type */
button_count = len = i = 0;
if (buttons == NULL || *buttons == NUL)
return -1;
/* There is one less separator than buttons, so bump up the button count */
button_count = 1;
/* Count string length and number of seperators */
for (str = buttons; *str; str++)
{
len++;
if (*str == DLG_BUTTON_SEP)
button_count++;
}
if (title == NULL)
title = "Vim";
buttons_copy = alloc(len + 1);
button_array = (char_u **) alloc(button_count * sizeof(char_u *));
if (buttons_copy != NULL && button_array != NULL)
{
STRCPY(buttons_copy, buttons);
/*
* Convert DLG_BUTTON_SEP into NUL's and fill in
* button_array with the pointer to each NUL terminated string
*/
str = buttons_copy;
for (i = 0; i < button_count; i++)
{
button_array[ i ] = str;
for (; *str; str++)
{
if (*str == DLG_BUTTON_SEP)
{
*str++ = NUL;
break;
}
}
}
#ifndef FEAT_GUI_TEXTDIALOG
dialog_result = PtAlert(
gui.vimWindow, NULL,
title,
NULL,
message, NULL,
button_count, (const char **) button_array, NULL,
default_button, 0, Pt_MODAL);
#else
/* Writing the dialog ourselves lets us add extra features, like
* trapping the escape key and returning 0 to vim */
{
int n;
PtArg_t args[5];
PtWidget_t *dialog, *pane;
PtModalCtrl_t modal_ctrl;
PtDialogInfo_t di;
memset(&di, 0, sizeof(di));
memset(&modal_ctrl, 0, sizeof(modal_ctrl));
n = 0;
PtSetArg(&args[n++], Pt_ARG_GROUP_ROWS_COLS, 0, 0);
PtSetArg(&args[n++], Pt_ARG_WIDTH, 350, 0);
PtSetArg(&args[n++], Pt_ARG_GROUP_ORIENTATION,
Pt_GROUP_VERTICAL, 0);
PtSetArg(&args[n++], Pt_ARG_GROUP_FLAGS,
Pt_TRUE, Pt_GROUP_NO_KEYS | Pt_GROUP_STRETCH_HORIZONTAL);
PtSetArg(&args[n++], Pt_ARG_CONTAINER_FLAGS, Pt_FALSE, Pt_TRUE);
pane = PtCreateWidget(PtGroup, NULL, n, args);
n = 0;
PtSetArg(&args[n++], Pt_ARG_TEXT_STRING, message, 0);
PtCreateWidget(PtLabel, pane, n, args);
if (textfield != NULL)
{
n = 0;
PtSetArg(&args[n++], Pt_ARG_MAX_LENGTH, IOSIZE - 1, 0);
PtSetArg(&args[n++], Pt_ARG_TEXT_STRING, textfield, 0);
PtSetArg(&args[n++], Pt_ARG_POINTER, textfield, 0);
gui_ph_dialog_text = PtCreateWidget(PtText, pane, n, args);
PtAddCallback(gui_ph_dialog_text, Pt_CB_ACTIVATE,
gui_ph_dialog_text_enter, &modal_ctrl);
}
di.parent = gui.vimWindow;
di.pane = pane;
di.title = title;
di.buttons = (const char **) button_array;
di.nbtns = button_count;
di.def_btn = default_button;
/* This is just to give the dialog the close button.
* We check for the Escape key ourselves and return 0 */
di.esc_btn = button_count;
di.callback = gui_ph_dialog_close;
di.data = &modal_ctrl;
dialog = PtCreateDialog(&di);
PtAddFilterCallback(dialog, Ph_EV_KEY,
gui_ph_dialog_esc, &modal_ctrl);
if (gui_ph_dialog_text != NULL)
PtGiveFocus(gui_ph_dialog_text, NULL);
/* Open dialog, block the vim window and wait for the dialog to close */
PtRealizeWidget(dialog);
PtMakeModal(dialog, Ph_CURSOR_NOINPUT, Ph_CURSOR_DEFAULT_COLOR);
dialog_result = (int) PtModalBlock(&modal_ctrl, 0);
PtDestroyWidget(dialog);
gui_ph_dialog_text = NULL;
}
#endif
}
vim_free(button_array);
vim_free(buttons_copy);
return dialog_result;
}
#endif
/****************************************************************************/
/* window size/position/state */
int
gui_mch_get_winpos(int *x, int *y)
{
PhPoint_t *pos;
pos = PtWidgetPos(gui.vimWindow, NULL);
*x = pos->x;
*y = pos->y;
return OK;
}
void
gui_mch_set_winpos(int x, int y)
{
PhPoint_t pos = { x, y };
PtSetResource(gui.vimWindow, Pt_ARG_POS, &pos, 0);
}
void
gui_mch_set_shellsize(int width, int height,
int min_width, int min_height, int base_width, int base_height,
int direction)
{
PhDim_t window_size = { width, height };
PhDim_t min_size = { min_width, min_height };
#ifdef USE_PANEL_GROUP
window_size.w += pg_margin_left + pg_margin_right;
window_size.h += pg_margin_top + pg_margin_bottom;
#endif
PtSetResource(gui.vimWindow, Pt_ARG_MINIMUM_DIM, &min_size, 0);
PtSetResource(gui.vimWindow, Pt_ARG_DIM, &window_size, 0);
if (! PtWidgetIsRealized(gui.vimWindow))
gui_ph_resize_container();
}
/*
* Return the amount of screen space that hasn't been allocated (such as
* by the shelf).
*/
void
gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
{
PhRect_t console;
PhWindowQueryVisible(Ph_QUERY_WORKSPACE, 0,
PhInputGroup(NULL), &console);
*screen_w = console.lr.x - console.ul.x + 1;
*screen_h = console.lr.y - console.ul.y + 1;
}
void
gui_mch_iconify(void)
{
PhWindowEvent_t event;
memset(&event, 0, sizeof (event));
event.event_f = Ph_WM_HIDE;
event.event_state = Ph_WM_EVSTATE_HIDE;
event.rid = PtWidgetRid(gui.vimWindow);
PtForwardWindowEvent(&event);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Bring the Vim window to the foreground.
*/
void
gui_mch_set_foreground()
{
PhWindowEvent_t event;
memset(&event, 0, sizeof (event));
event.event_f = Ph_WM_TOFRONT;
event.event_state = Ph_WM_EVSTATE_FFRONT;
event.rid = PtWidgetRid(gui.vimWindow);
PtForwardWindowEvent(&event);
}
#endif
void
gui_mch_settitle(char_u *title, char_u *icon)
{
#ifdef USE_PANEL_GROUP
gui_ph_pg_set_buffer_num(curwin->w_buffer->b_fnum);
#endif
PtSetResource(gui.vimWindow, Pt_ARG_WINDOW_TITLE, title, 0);
/* Not sure what to do with the icon text, set balloon text somehow? */
}
/****************************************************************************/
/* Scrollbar */
void
gui_mch_set_scrollbar_thumb(scrollbar_T *sb, int val, int size, int max)
{
int n = 0;
PtArg_t args[3];
PtSetArg(&args[ n++ ], Pt_ARG_MAXIMUM, max, 0);
PtSetArg(&args[ n++ ], Pt_ARG_SLIDER_SIZE, size, 0);
PtSetArg(&args[ n++ ], Pt_ARG_GAUGE_VALUE, val, 0);
PtSetResources(sb->id, n, args);
}
void
gui_mch_set_scrollbar_pos(scrollbar_T *sb, int x, int y, int w, int h)
{
PhArea_t area = {{ x, y }, { w, h }};
PtSetResource(sb->id, Pt_ARG_AREA, &area, 0);
}
void
gui_mch_create_scrollbar(scrollbar_T *sb, int orient)
{
int n = 0;
/* int anchor_flags = 0;*/
PtArg_t args[4];
/*
* Stop the scrollbar from being realized when the parent
* is realized, so it can be explicitly realized by vim.
*
* Also, don't let the scrollbar get focus
*/
PtSetArg(&args[ n++ ], Pt_ARG_FLAGS, Pt_DELAY_REALIZE,
Pt_DELAY_REALIZE | Pt_GETS_FOCUS);
PtSetArg(&args[ n++ ], Pt_ARG_SCROLLBAR_FLAGS, Pt_SCROLLBAR_SHOW_ARROWS, 0);
#if 0
/* Don't need this anchoring for the scrollbars */
if (orient == SBAR_HORIZ)
{
anchor_flags = Pt_BOTTOM_ANCHORED_BOTTOM |
Pt_LEFT_ANCHORED_LEFT | Pt_RIGHT_ANCHORED_RIGHT;
}
else
{
anchor_flags = Pt_BOTTOM_ANCHORED_BOTTOM | Pt_TOP_ANCHORED_TOP;
if (sb->wp != NULL)
{
if (sb == &sb->wp->w_scrollbars[ SBAR_LEFT ])
anchor_flags |= Pt_LEFT_ANCHORED_LEFT;
else
anchor_flags |= Pt_RIGHT_ANCHORED_RIGHT;
}
}
PtSetArg(&args[ n++ ], Pt_ARG_ANCHOR_FLAGS, anchor_flags, Pt_IS_ANCHORED);
#endif
PtSetArg(&args[ n++ ], Pt_ARG_ORIENTATION,
(orient == SBAR_HORIZ) ? Pt_HORIZONTAL : Pt_VERTICAL, 0);
#ifdef USE_PANEL_GROUP
sb->id = PtCreateWidget(PtScrollbar, gui.vimPanelGroup, n, args);
#else
sb->id = PtCreateWidget(PtScrollbar, gui.vimContainer, n, args);
#endif
PtAddCallback(sb->id, Pt_CB_SCROLLBAR_MOVE, gui_ph_handle_scrollbar, sb);
}
void
gui_mch_enable_scrollbar(scrollbar_T *sb, int flag)
{
if (flag != 0)
PtRealizeWidget(sb->id);
else
PtUnrealizeWidget(sb->id);
}
void
gui_mch_destroy_scrollbar(scrollbar_T *sb)
{
PtDestroyWidget(sb->id);
sb->id = NULL;
}
/****************************************************************************/
/* Mouse functions */
#if defined(FEAT_MOUSESHAPE) || defined(PROTO)
/* The last set mouse pointer shape is remembered, to be used when it goes
* from hidden to not hidden. */
static int last_shape = 0;
/* Table for shape IDs. Keep in sync with the mshape_names[] table in
* misc2.c! */
static int mshape_ids[] =
{
Ph_CURSOR_POINTER, /* arrow */
Ph_CURSOR_NONE, /* blank */
Ph_CURSOR_INSERT, /* beam */
Ph_CURSOR_DRAG_VERTICAL, /* updown */
Ph_CURSOR_DRAG_VERTICAL, /* udsizing */
Ph_CURSOR_DRAG_HORIZONTAL, /* leftright */
Ph_CURSOR_DRAG_HORIZONTAL, /* lrsizing */
Ph_CURSOR_WAIT, /* busy */
Ph_CURSOR_DONT, /* no */
Ph_CURSOR_CROSSHAIR, /* crosshair */
Ph_CURSOR_FINGER, /* hand1 */
Ph_CURSOR_FINGER, /* hand2 */
Ph_CURSOR_FINGER, /* pencil */
Ph_CURSOR_QUESTION_POINT, /* question */
Ph_CURSOR_POINTER, /* right-arrow */
Ph_CURSOR_POINTER, /* up-arrow */
Ph_CURSOR_POINTER /* last one */
};
void
mch_set_mouse_shape(shape)
int shape;
{
int id;
if (!gui.in_use)
return;
if (shape == MSHAPE_HIDE || gui.pointer_hidden)
PtSetResource(gui.vimTextArea, Pt_ARG_CURSOR_TYPE, Ph_CURSOR_NONE,
0);
else
{
if (shape >= MSHAPE_NUMBERED)
id = Ph_CURSOR_POINTER;
else
id = mshape_ids[shape];
PtSetResource(gui.vimTextArea, Pt_ARG_CURSOR_TYPE, id, 0);
}
if (shape != MSHAPE_HIDE)
last_shape = shape;
}
#endif
void
gui_mch_mousehide(int hide)
{
if (gui.pointer_hidden != hide)
{
gui.pointer_hidden = hide;
#ifdef FEAT_MOUSESHAPE
if (hide)
PtSetResource(gui.vimTextArea, Pt_ARG_CURSOR_TYPE,
Ph_CURSOR_NONE, 0);
else
mch_set_mouse_shape(last_shape);
#else
PtSetResource(gui.vimTextArea, Pt_ARG_CURSOR_TYPE,
(hide == MOUSE_SHOW) ? GUI_PH_MOUSE_TYPE : Ph_CURSOR_NONE,
0);
#endif
}
}
void
gui_mch_getmouse(int *x, int *y)
{
PhCursorInfo_t info;
short ix, iy;
/* FIXME: does this return the correct position,
* with respect to the border? */
PhQueryCursor(PhInputGroup(NULL), &info);
PtGetAbsPosition(gui.vimTextArea , &ix, &iy);
*x = info.pos.x - ix;
*y = info.pos.y - iy;
}
void
gui_mch_setmouse(int x, int y)
{
short abs_x, abs_y;
PtGetAbsPosition(gui.vimTextArea, &abs_x, &abs_y);
/* Add the border offset? */
PhMoveCursorAbs(PhInputGroup(NULL), abs_x + x, abs_y + y);
}
/****************************************************************************/
/* Colours */
/*
* Return the RGB value of a pixel as a long.
*/
long_u
gui_mch_get_rgb(guicolor_T pixel)
{
return PgRGB(PgRedValue(pixel), PgGreenValue(pixel), PgBlueValue(pixel));
}
void
gui_mch_new_colors(void)
{
#if 0 /* Don't bother changing the cursor colour */
short color_diff;
/*
* If there isn't enough difference between the background colour and
* the mouse pointer colour then change the mouse pointer colour
*/
color_diff = gui_get_lightness(gui_ph_mouse_color)
- gui_get_lightness(gui.back_pixel);
if (abs(color_diff) < 64)
{
short r, g, b;
/* not a great algorithm... */
r = PgRedValue(gui_ph_mouse_color) ^ 255;
g = PgGreenValue(gui_ph_mouse_color) ^ 255;
b = PgBlueValue(gui_ph_mouse_color) ^ 255;
#ifndef FEAT_MOUSESHAPE
gui_ph_mouse_color = PgRGB(r, g, b);
PtSetResource(gui.vimTextArea, Pt_ARG_CURSOR_COLOR,
gui_ph_mouse_color, 0);
#endif
}
#endif
PtSetResource(gui.vimTextArea, Pt_ARG_FILL_COLOR, gui.back_pixel, 0);
}
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;
}
/*
* This should be split out into a separate file,
* every port does basically the same thing.
*
* This is the gui_w32.c version (i think..)
* Return INVALCOLOR when failed.
*/
guicolor_T
gui_mch_get_color(char_u *name)
{
int i;
int r, g, b;
typedef struct GuiColourTable
{
char *name;
guicolor_T colour;
} GuiColourTable;
static GuiColourTable 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)},
{"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)},
};
/* is name #rrggbb format? */
if (name[0] == '#' && STRLEN(name) == 7)
{
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);
}
for (i = 0; i < ARRAY_LENGTH(table); i++)
{
if (STRICMP(name, table[i].name) == 0)
return table[i].colour;
}
/*
* 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 = 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 = 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;
}
void
gui_mch_set_fg_color(guicolor_T color)
{
PgSetTextColor(color);
}
void
gui_mch_set_bg_color(guicolor_T color)
{
PgSetFillColor(color);
}
void
gui_mch_set_sp_color(guicolor_T color)
{
}
void
gui_mch_invert_rectangle(int row, int col, int nr, int nc)
{
PhRect_t rect;
rect.ul.x = FILL_X(col);
rect.ul.y = FILL_Y(row);
/* FIXME: This has an off by one pixel problem */
rect.lr.x = rect.ul.x + nc * gui.char_width;
rect.lr.y = rect.ul.y + nr * gui.char_height;
if (nc > 0)
rect.lr.x -= 1;
if (nr > 0)
rect.lr.y -= 1;
DRAW_START;
PgSetDrawMode(Pg_DrawModeDSTINVERT);
PgDrawRect(&rect, Pg_DRAW_FILL);
PgSetDrawMode(Pg_DrawModeSRCCOPY);
DRAW_END;
}
void
gui_mch_clear_block(int row1, int col1, int row2, int col2)
{
PhRect_t block = {
{ FILL_X(col1), FILL_Y(row1) },
{ FILL_X(col2 + 1) - 1, FILL_Y(row2 + 1) - 1}
};
DRAW_START;
gui_mch_set_bg_color(gui.back_pixel);
PgDrawRect(&block, Pg_DRAW_FILL);
DRAW_END;
}
void
gui_mch_clear_all()
{
PhRect_t text_rect = {
{ gui.border_width, gui.border_width },
{ Columns * gui.char_width + gui.border_width - 1 ,
Rows * gui.char_height + gui.border_width - 1 }
};
if (is_ignore_draw == TRUE)
return;
DRAW_START;
gui_mch_set_bg_color(gui.back_pixel);
PgDrawRect(&text_rect, Pg_DRAW_FILL);
DRAW_END;
}
void
gui_mch_delete_lines(int row, int num_lines)
{
PhRect_t rect;
PhPoint_t delta;
rect.ul.x = FILL_X(gui.scroll_region_left);
rect.ul.y = FILL_Y(row + num_lines);
rect.lr.x = FILL_X(gui.scroll_region_right + 1) - 1;
rect.lr.y = FILL_Y(gui.scroll_region_bot + 1) - 1;
PtWidgetOffset(gui.vimTextArea, &gui_ph_raw_offset);
PhTranslatePoint(&gui_ph_raw_offset, PtWidgetPos(gui.vimTextArea, NULL));
PhTranslateRect(&rect, &gui_ph_raw_offset);
delta.x = 0;
delta.y = -num_lines * gui.char_height;
PgFlush();
PhBlit(PtWidgetRid(PtFindDisjoint(gui.vimTextArea)), &rect, &delta);
gui_clear_block(
gui.scroll_region_bot - num_lines + 1,
gui.scroll_region_left,
gui.scroll_region_bot,
gui.scroll_region_right);
}
void
gui_mch_insert_lines(int row, int num_lines)
{
PhRect_t rect;
PhPoint_t delta;
rect.ul.x = FILL_X(gui.scroll_region_left);
rect.ul.y = FILL_Y(row);
rect.lr.x = FILL_X(gui.scroll_region_right + 1) - 1;
rect.lr.y = FILL_Y(gui.scroll_region_bot - num_lines + 1) - 1;
PtWidgetOffset(gui.vimTextArea, &gui_ph_raw_offset);
PhTranslatePoint(&gui_ph_raw_offset, PtWidgetPos(gui.vimTextArea, NULL));
PhTranslateRect(&rect, &gui_ph_raw_offset);
delta.x = 0;
delta.y = num_lines * gui.char_height;
PgFlush();
PhBlit(PtWidgetRid(PtFindDisjoint(gui.vimTextArea)) , &rect, &delta);
gui_clear_block(row, gui.scroll_region_left,
row + num_lines - 1, gui.scroll_region_right);
}
void
gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
{
static char *utf8_buffer = NULL;
static int utf8_len = 0;
PhPoint_t pos = { TEXT_X(col), TEXT_Y(row) };
PhRect_t rect;
if (is_ignore_draw == TRUE)
return;
DRAW_START;
if (!(flags & DRAW_TRANSP))
{
PgDrawIRect(
FILL_X(col), FILL_Y(row),
FILL_X(col + len) - 1, FILL_Y(row + 1) - 1,
Pg_DRAW_FILL);
}
if (flags & DRAW_UNDERL)
PgSetUnderline(gui.norm_pixel, Pg_TRANSPARENT, 0);
if (charset_translate != NULL
#ifdef FEAT_MBYTE
&& enc_utf8 == 0
#endif
)
{
int src_taken, dst_made;
/* Use a static buffer to avoid large amounts of de/allocations */
if (utf8_len < len)
{
utf8_buffer = realloc(utf8_buffer, len * MB_LEN_MAX);
utf8_len = len;
}
PxTranslateToUTF(
charset_translate,
s,
len,
&src_taken,
utf8_buffer,
utf8_len,
&dst_made);
s = utf8_buffer;
len = dst_made;
}
PgDrawText(s, len, &pos, 0);
if (flags & DRAW_BOLD)
{
/* FIXME: try and only calculate these values once... */
rect.ul.x = FILL_X(col) + 1;
rect.ul.y = FILL_Y(row);
rect.lr.x = FILL_X(col + len) - 1;
rect.lr.y = FILL_Y(row + 1) - 1;
/* PgSetUserClip(NULL) causes the scrollbar to not redraw... */
#if 0
pos.x++;
PgSetUserClip(&rect);
PgDrawText(s, len, &pos, 0);
PgSetUserClip(NULL);
#else
rect.lr.y -= (p_linespace + 1) / 2;
/* XXX: DrawTextArea doesn't work with phditto */
PgDrawTextArea(s, len, &rect, Pg_TEXT_BOTTOM);
#endif
}
if (flags & DRAW_UNDERL)
PgSetUnderline(Pg_TRANSPARENT, Pg_TRANSPARENT, 0);
DRAW_END;
}
/****************************************************************************/
/* Cursor */
void
gui_mch_draw_hollow_cursor(guicolor_T color)
{
PhRect_t r;
/* FIXME: Double width characters */
r.ul.x = FILL_X(gui.col);
r.ul.y = FILL_Y(gui.row);
r.lr.x = r.ul.x + gui.char_width - 1;
r.lr.y = r.ul.y + gui.char_height - 1;
DRAW_START;
PgSetStrokeColor(color);
PgDrawRect(&r, Pg_DRAW_STROKE);
DRAW_END;
}
void
gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
{
PhRect_t r;
r.ul.x = FILL_X(gui.col);
r.ul.y = FILL_Y(gui.row) + gui.char_height - h;
r.lr.x = r.ul.x + w - 1;
r.lr.y = r.ul.y + h - 1;
DRAW_START;
gui_mch_set_bg_color(color);
PgDrawRect(&r, Pg_DRAW_FILL);
DRAW_END;
}
void
gui_mch_set_blinking(long wait, long on, long off)
{
blink_waittime = wait;
blink_ontime = on;
blink_offtime = off;
}
void
gui_mch_start_blink(void)
{
/* Only turn on the timer on if none of the times are zero */
if (blink_waittime && blink_ontime && blink_offtime && gui.in_focus)
{
PtSetResource(gui_ph_timer_cursor, Pt_ARG_TIMER_INITIAL,
blink_waittime, 0);
blink_state = BLINK_ON;
gui_update_cursor(TRUE, FALSE);
}
}
void
gui_mch_stop_blink(void)
{
PtSetResource(gui_ph_timer_cursor, Pt_ARG_TIMER_INITIAL, 0, 0);
if (blink_state == BLINK_OFF)
gui_update_cursor(TRUE, FALSE);
blink_state = BLINK_NONE;
}
/****************************************************************************/
/* miscellaneous functions */
void
gui_mch_beep(void)
{
PtBeep();
}
void
gui_mch_flash(int msec)
{
PgSetFillXORColor(Pg_BLACK, Pg_WHITE);
PgSetDrawMode(Pg_DRAWMODE_XOR);
gui_mch_clear_all();
gui_mch_flush();
ui_delay((long) msec, TRUE);
gui_mch_clear_all();
PgSetDrawMode(Pg_DRAWMODE_OPAQUE);
gui_mch_flush();
}
void
gui_mch_flush(void)
{
PgFlush();
}
void
gui_mch_set_text_area_pos(int x, int y, int w, int h)
{
PhArea_t area = {{x, y}, {w, h}};
PtSetResource(gui.vimTextArea, Pt_ARG_AREA, &area, 0);
}
int
gui_mch_haskey(char_u *name)
{
int i;
for (i = 0; special_keys[i].key_sym != 0; i++)
if (name[0] == special_keys[i].vim_code0 &&
name[1] == special_keys[i].vim_code1)
return OK;
return FAIL;
}
/****************************************************************************/
/* Menu */
#ifdef FEAT_TOOLBAR
#include "toolbar.phi"
static PhImage_t *gui_ph_toolbar_images[] = {
&tb_new_phi,
&tb_open_phi,
&tb_save_phi,
&tb_undo_phi,
&tb_redo_phi,
&tb_cut_phi,
&tb_copy_phi,
&tb_paste_phi,
&tb_print_phi,
&tb_help_phi,
&tb_find_phi,
&tb_save_all_phi,
&tb_save_session_phi,
&tb_new_session_phi,
&tb_load_session_phi,
&tb_macro_phi,
&tb_replace_phi,
&tb_close_phi,
&tb_maximize_phi,
&tb_minimize_phi,
&tb_split_phi,
&tb_shell_phi,
&tb_find_prev_phi,
&tb_find_next_phi,
&tb_find_help_phi,
&tb_make_phi,
&tb_jump_phi,
&tb_ctags_phi,
&tb_vsplit_phi,
&tb_maxwidth_phi,
&tb_minwidth_phi
};
static PhImage_t *
gui_ph_toolbar_load_icon(char_u *iconfile)
{
static PhImage_t external_icon;
PhImage_t *temp_phi = NULL;
temp_phi = PxLoadImage(iconfile, NULL);
if (temp_phi != NULL)
{
/* The label widget will free the image/palette/etc. for us when
* it's destroyed */
temp_phi->flags |= Ph_RELEASE_IMAGE_ALL;
memcpy(&external_icon, temp_phi, sizeof(external_icon));
free(temp_phi);
temp_phi = &external_icon;
}
return temp_phi;
}
/*
* This returns either a builtin icon image, an external image or NULL
* if it can't find either. The caller can't and doesn't need to try and
* free() the returned image, and it can't store the image pointer.
* (When setting the Pt_ARG_LABEL_IMAGE resource, the contents of the
* PhImage_t are copied, and the original PhImage_t aren't needed anymore).
*/
static PhImage_t *
gui_ph_toolbar_find_icon(vimmenu_T *menu)
{
char_u full_pathname[ MAXPATHL + 1 ];
PhImage_t *icon = NULL;
if (menu->icon_builtin == FALSE)
{
if (menu->iconfile != NULL)
/* TODO: use gui_find_iconfile() */
icon = gui_ph_toolbar_load_icon(menu->iconfile);
/* TODO: Restrict loading to just .png? Search for any format? */
if ((icon == NULL) &&
((gui_find_bitmap(menu->name, full_pathname, "gif") == OK) ||
(gui_find_bitmap(menu->name, full_pathname, "png") == OK)))
icon = gui_ph_toolbar_load_icon(full_pathname);
if (icon != NULL)
return icon;
}
if (menu->iconidx >= 0 &&
(menu->iconidx < ARRAY_LENGTH(gui_ph_toolbar_images)))
{
return gui_ph_toolbar_images[menu->iconidx];
}
return NULL;
}
#endif
#if defined(FEAT_MENU) || defined(PROTO)
void
gui_mch_enable_menu(int flag)
{
if (flag != 0)
PtRealizeWidget(gui.vimMenuBar);
else
PtUnrealizeWidget(gui.vimMenuBar);
}
void
gui_mch_set_menu_pos(int x, int y, int w, int h)
{
/* Nothing */
}
/* Change the position of a menu button in the parent */
static void
gui_ph_position_menu(PtWidget_t *widget, int priority)
{
PtWidget_t *traverse;
vimmenu_T *menu;
traverse = PtWidgetChildBack(PtWidgetParent(widget));
/* Iterate through the list of widgets in traverse, until
* we find the position we want to insert our widget into */
/* TODO: traverse from front to back, possible speedup? */
while (traverse != NULL)
{
PtGetResource(traverse, Pt_ARG_POINTER, &menu, 0);
if (menu != NULL &&
priority < menu->priority &&
widget != traverse)
{
/* Insert the widget before the current traverse widget */
PtWidgetInsert(widget, traverse, 1);
return;
}
traverse = PtWidgetBrotherInFront(traverse);
}
}
/* the index is ignored because it's not useful for our purposes */
void
gui_mch_add_menu(vimmenu_T *menu, int index)
{
vimmenu_T *parent = menu->parent;
char_u *accel_key;
char_u mnemonic_str[MB_LEN_MAX];
int n;
PtArg_t args[5];
menu->submenu_id = menu->id = NULL;
if (menu_is_menubar(menu->name))
{
accel_key = vim_strchr(menu->name, '&');
if (accel_key != NULL)
{
mnemonic_str[0] = accel_key[1];
mnemonic_str[1] = NUL;
}
/* Create the menu button */
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_TEXT_STRING, menu->dname, 0);
PtSetArg(&args[ n++ ], Pt_ARG_ACCEL_TEXT, menu->actext, 0);
if (accel_key != NULL)
PtSetArg(&args[ n++ ], Pt_ARG_ACCEL_KEY, mnemonic_str, 0);
PtSetArg(&args[ n++ ], Pt_ARG_POINTER, menu, 0);
if (parent != NULL)
PtSetArg(&args[ n++ ], Pt_ARG_BUTTON_TYPE, Pt_MENU_RIGHT, 0);
menu->id = PtCreateWidget(PtMenuButton,
(parent == NULL) ? gui.vimMenuBar : parent->submenu_id,
n, args);
PtAddCallback(menu->id, Pt_CB_ARM, gui_ph_handle_pulldown_menu, menu);
/* Create the actual menu */
n = 0;
if (parent != NULL)
PtSetArg(&args[ n++ ], Pt_ARG_MENU_FLAGS, Pt_TRUE, Pt_MENU_CHILD);
menu->submenu_id = PtCreateWidget(PtMenu, menu->id, n, args);
if (parent == NULL)
{
PtAddCallback(menu->submenu_id, Pt_CB_UNREALIZED,
gui_ph_handle_menu_unrealized, menu);
if (menu->mnemonic != 0)
{
PtAddHotkeyHandler(gui.vimWindow, tolower(menu->mnemonic),
Pk_KM_Alt, 0, menu, gui_ph_handle_pulldown_menu);
}
}
gui_ph_position_menu(menu->id, menu->priority);
/* Redraw menubar here instead of gui_mch_draw_menubar */
if (gui.menu_is_active)
PtRealizeWidget(menu->id);
}
else if (menu_is_popup(menu->name))
{
menu->submenu_id = PtCreateWidget(PtMenu, gui.vimWindow, 0, NULL);
PtAddCallback(menu->submenu_id, Pt_CB_UNREALIZED,
gui_ph_handle_menu_unrealized, menu);
}
}
void
gui_mch_add_menu_item(vimmenu_T *menu, int index)
{
vimmenu_T *parent = menu->parent;
char_u *accel_key;
char_u mnemonic_str[MB_LEN_MAX];
int n;
PtArg_t args[13];
n = 0;
PtSetArg(&args[ n++ ], Pt_ARG_POINTER, menu, 0);
#ifdef FEAT_TOOLBAR
if (menu_is_toolbar(parent->name))
{
if (menu_is_separator(menu->name))
{
PtSetArg(&args[ n++ ], Pt_ARG_SEP_FLAGS,
Pt_SEP_VERTICAL, Pt_SEP_ORIENTATION);
PtSetArg(&args[ n++ ], Pt_ARG_SEP_TYPE, Pt_ETCHED_IN, 0);
PtSetArg(&args[ n++ ], Pt_ARG_ANCHOR_FLAGS,
Pt_TRUE, Pt_ANCHOR_TOP_BOTTOM);
PtSetArg(&args[ n++ ], Pt_ARG_WIDTH, 2, 0);
menu->id = PtCreateWidget(PtSeparator, gui.vimToolBar, n, args);
}
else
{
if (strstr((const char *) p_toolbar, "text") != NULL)
{
PtSetArg(&args[ n++ ], Pt_ARG_BALLOON_POSITION,
Pt_BALLOON_BOTTOM, 0);
PtSetArg(&args[ n++ ], Pt_ARG_TEXT_STRING, menu->dname, 0);
PtSetArg(&args[ n++ ], Pt_ARG_TEXT_FONT, "TextFont08", 0);
}
if ((strstr((const char *) p_toolbar, "icons") != NULL) &&
(gui_ph_toolbar_images != NULL))
{
PtSetArg(&args[ n++ ], Pt_ARG_LABEL_IMAGE,
gui_ph_toolbar_find_icon(menu), 0);
PtSetArg(&args[ n++ ], Pt_ARG_LABEL_TYPE, Pt_TEXT_IMAGE, 0);
PtSetArg(&args[ n++ ], Pt_ARG_TEXT_IMAGE_SPACING, 0, 0);
}
if (strstr((const char *) p_toolbar, "tooltips") != NULL)
{
PtSetArg(&args[ n++ ], Pt_ARG_LABEL_BALLOON,
gui_ph_show_tooltip, 0);
PtSetArg(&args[ n++ ], Pt_ARG_LABEL_FLAGS,
Pt_TRUE, Pt_SHOW_BALLOON);
}
PtSetArg(&args[ n++ ], Pt_ARG_MARGIN_HEIGHT, 1, 0);
PtSetArg(&args[ n++ ], Pt_ARG_MARGIN_WIDTH, 1, 0);
PtSetArg(&args[ n++ ], Pt_ARG_FLAGS, Pt_FALSE,
Pt_HIGHLIGHTED | Pt_GETS_FOCUS);
PtSetArg(&args[ n++ ], Pt_ARG_FILL_COLOR, Pg_TRANSPARENT, 0);
menu->id = PtCreateWidget(PtButton, gui.vimToolBar, n, args);
PtAddCallback(menu->id, Pt_CB_ACTIVATE, gui_ph_handle_menu, menu);
}
/* Update toolbar if it's open */
if (PtWidgetIsRealized(gui.vimToolBar))
PtRealizeWidget(menu->id);
}
else
#endif
if (menu_is_separator(menu->name))
{
menu->id = PtCreateWidget(PtSeparator, parent->submenu_id, n, args);
}
else
{
accel_key = vim_strchr(menu->name, '&');
if (accel_key != NULL)
{
mnemonic_str[0] = accel_key[1];
mnemonic_str[1] = NUL;
}
PtSetArg(&args[ n++ ], Pt_ARG_TEXT_STRING, menu->dname, 0);
if (accel_key != NULL)
PtSetArg(&args[ n++ ], Pt_ARG_ACCEL_KEY, mnemonic_str,
0);
PtSetArg(&args[ n++ ], Pt_ARG_ACCEL_TEXT, menu->actext, 0);
menu->id = PtCreateWidget(PtMenuButton, parent->submenu_id, n, args);
PtAddCallback(menu->id, Pt_CB_ACTIVATE, gui_ph_handle_menu, menu);
#ifdef USE_PANEL_GROUP
if (gui_ph_is_buffer_item(menu, parent) == TRUE)
{
PtAddCallback(menu->id, Pt_CB_DESTROYED,
gui_ph_handle_buffer_remove, menu);
gui_ph_pg_add_buffer(menu->dname);
}
#endif
}
gui_ph_position_menu(menu->id, menu->priority);
}
void
gui_mch_destroy_menu(vimmenu_T *menu)
{
if (menu->submenu_id != NULL)
PtDestroyWidget(menu->submenu_id);
if (menu->id != NULL)
PtDestroyWidget(menu->id);
menu->submenu_id = NULL;
menu->id = NULL;
}
void
gui_mch_menu_grey(vimmenu_T *menu, int grey)
{
long flags, mask, fields;
if (menu->id == NULL)
return;
flags = PtWidgetFlags(menu->id);
if (PtWidgetIsClass(menu->id, PtMenuButton) &&
PtWidgetIsClass(PtWidgetParent(menu->id), PtMenu))
{
fields = Pt_FALSE;
mask = Pt_SELECTABLE | Pt_HIGHLIGHTED;
}
else
{
fields = Pt_TRUE;
mask = Pt_BLOCKED | Pt_GHOST;
}
if (! grey)
fields = ~fields;
PtSetResource(menu->id, Pt_ARG_FLAGS, fields,
mask);
}
void
gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
{
/* TODO: [un]realize the widget? */
}
void
gui_mch_draw_menubar(void)
{
/* The only time a redraw is needed is when a menu button
* is added to the menubar, and that is detected and the bar
* redrawn in gui_mch_add_menu_item
*/
}
void
gui_mch_show_popupmenu(vimmenu_T *menu)
{
PtSetResource(menu->submenu_id, Pt_ARG_POS, &abs_mouse, 0);
PtRealizeWidget(menu->submenu_id);
}
void
gui_mch_toggle_tearoffs(int enable)
{
/* No tearoffs yet */
}
#endif
#if defined(FEAT_TOOLBAR) || defined(PROTO)
void
gui_mch_show_toolbar(int showit)
{
if (showit)
PtRealizeWidget(gui.vimToolBar);
else
PtUnrealizeWidget(gui.vimToolBar);
}
#endif
/****************************************************************************/
/* Fonts */
static GuiFont
gui_ph_get_font(
char_u *font_name,
int_u font_flags,
int_u font_size,
/* Check whether the resulting font has the font flags and size that
* was asked for */
int_u enforce
)
{
char_u *font_tag;
FontQueryInfo info;
int_u style;
font_tag = alloc(MAX_FONT_TAG);
if (font_tag != NULL)
{
if (PfGenerateFontName(font_name, font_flags, font_size,
font_tag) != NULL)
{
/* Enforce some limits on the font used */
style = PHFONT_INFO_FIXED;
if (enforce & PF_STYLE_BOLD)
style |= PHFONT_INFO_BOLD;
if (enforce & PF_STYLE_ANTIALIAS)
style |= PHFONT_INFO_ALIAS;
if (enforce & PF_STYLE_ITALIC)
style |= PHFONT_INFO_ITALIC;
PfQueryFontInfo(font_tag, &info);
if (info.size == 0)
font_size = 0;
/* Make sure font size matches, and that the font style
* at least has the bits we're checking for */
if (font_size == info.size &&
style == (info.style & style))
return (GuiFont)font_tag;
}
vim_free(font_tag);
}
return NULL;
}
/*
* Split up the vim font name
*
* vim_font is in the form of
* <name>:s<height>:a:b:i
*
* a = antialias
* b = bold
* i = italic
*
*/
static int
gui_ph_parse_font_name(
char_u *vim_font,
char_u **font_name,
int_u *font_flags,
int_u *font_size)
{
char_u *mark;
int_u name_len, size;
mark = vim_strchr(vim_font, ':');
if (mark == NULL)
name_len = STRLEN(vim_font);
else
name_len = (int_u) (mark - vim_font);
*font_name = vim_strnsave(vim_font, name_len);
if (*font_name != NULL)
{
if (mark != NULL)
{
while (*mark != NUL && *mark++ == ':')
{
switch (tolower(*mark++))
{
case 'a': *font_flags |= PF_STYLE_ANTIALIAS; break;
case 'b': *font_flags |= PF_STYLE_BOLD; break;
case 'i': *font_flags |= PF_STYLE_ITALIC; break;
case 's':
size = getdigits(&mark);
/* Restrict the size to some vague limits */
if (size < 1 || size > 100)
size = 8;
*font_size = size;
break;
default:
break;
}
}
}
return TRUE;
}
return FALSE;
}
int
gui_mch_init_font(char_u *vim_font_name, int fontset)
{
char_u *font_tag;
char_u *font_name = NULL;
int_u font_flags = 0;
int_u font_size = 12;
FontQueryInfo info;
PhRect_t extent;
if (vim_font_name == NULL)
{
/* Default font */
vim_font_name = "PC Terminal";
}
if (STRCMP(vim_font_name, "*") == 0)
{
font_tag = PtFontSelection(gui.vimWindow, NULL, NULL,
"pcterm12", -1, PHFONT_FIXED, NULL);
if (font_tag == NULL)
return FAIL;
gui_mch_free_font(gui.norm_font);
gui.norm_font = font_tag;
PfQueryFontInfo(font_tag, &info);
font_name = vim_strsave(info.font);
}
else
{
if (gui_ph_parse_font_name(vim_font_name, &font_name, &font_flags,
&font_size) == FALSE)
return FAIL;
font_tag = gui_ph_get_font(font_name, font_flags, font_size, 0);
if (font_tag == NULL)
{
vim_free(font_name);
return FAIL;
}
gui_mch_free_font(gui.norm_font);
gui.norm_font = font_tag;
}
gui_mch_free_font(gui.bold_font);
gui.bold_font = gui_ph_get_font(font_name, font_flags | PF_STYLE_BOLD,
font_size, PF_STYLE_BOLD);
gui_mch_free_font(gui.ital_font);
gui.ital_font = gui_ph_get_font(font_name, font_flags | PF_STYLE_ITALIC,
font_size, PF_STYLE_ITALIC);
/* This extent was brought to you by the letter 'g' */
PfExtentText(&extent, NULL, font_tag, "g", 1);
gui.char_width = extent.lr.x - extent.ul.x + 1;
gui.char_height = (- extent.ul.y) + extent.lr.y + 1;
gui.char_ascent = - extent.ul.y;
vim_free(font_name);
return OK;
}
/*
* Adjust gui.char_height (after 'linespace' was changed).
*/
int
gui_mch_adjust_charheight(void)
{
FontQueryInfo info;
PfQueryFontInfo(gui.norm_font, &info);
gui.char_height = - info.ascender + info.descender + p_linespace;
gui.char_ascent = - info.ascender + p_linespace / 2;
return OK;
}
GuiFont
gui_mch_get_font(char_u *vim_font_name, int report_error)
{
char_u *font_name;
char_u *font_tag;
int_u font_size = 12;
int_u font_flags = 0;
if (gui_ph_parse_font_name(vim_font_name, &font_name, &font_flags,
&font_size) != FALSE)
{
font_tag = gui_ph_get_font(font_name, font_flags, font_size, -1);
vim_free(font_name);
if (font_tag != NULL)
return (GuiFont)font_tag;
}
if (report_error)
EMSG2(e_font, vim_font_name);
return FAIL;
}
#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.
*/
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_set_font(GuiFont font)
{
PgSetFont(font);
}
void
gui_mch_free_font(GuiFont font)
{
vim_free(font);
}
| zyz2011-vim | src/gui_photon.c | C | gpl2 | 73,048 |
/* 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 EnhancedB_H
#define EnhancedB_H
/*
* New resources for the Extended Pushbutton widget
*/
#ifndef XmNshift
# define XmNshift "shift"
#endif
#ifndef XmCShift
# define XmCShift "Shift"
#endif
#ifndef XmNlabelLocation
# define XmNlabelLocation "labelLocation"
#endif
#ifndef XmCLocation
# define XmCLocation "Location"
#endif
#ifndef XmNpixmapData
# define XmNpixmapData "pixmapData"
#endif
#ifndef XmNpixmapFile
# define XmNpixmapFile "pixmapFile"
#endif
/*
* Constants for labelLocation.
*/
#ifdef HAVE_XM_JOINSIDET_H
# include <Xm/JoinSideT.h>
#else
# define XmLEFT 1
# define XmRIGHT 2
# define XmTOP 3
# define XmBOTTOM 4
#endif
#define XmIsEnhancedButton(w) XtIsSubclass(w, xmEnhancedButtonWidgetClass)
/*
* Convenience creation function.
*/
extern Widget XgCreateEPushButtonWidget(Widget, char *, ArgList, Cardinal);
extern WidgetClass xmEnhancedButtonWidgetClass;
typedef struct _XmEnhancedButtonClassRec *XmEnhancedButtonWidgetClass;
typedef struct _XmEnhancedButtonRec *XmEnhancedButtonWidget;
#endif
| zyz2011-vim | src/gui_xmebw.h | C | gpl2 | 1,736 |
/* 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.
*/
/*
* screen.c: code for displaying on the screen
*
* Output to the screen (console, terminal emulator or GUI window) is minimized
* by remembering what is already on the screen, and only updating the parts
* that changed.
*
* ScreenLines[off] Contains a copy of the whole screen, as it is currently
* displayed (excluding text written by external commands).
* ScreenAttrs[off] Contains the associated attributes.
* LineOffset[row] Contains the offset into ScreenLines*[] and ScreenAttrs[]
* for each line.
* LineWraps[row] Flag for each line whether it wraps to the next line.
*
* For double-byte characters, two consecutive bytes in ScreenLines[] can form
* one character which occupies two display cells.
* For UTF-8 a multi-byte character is converted to Unicode and stored in
* ScreenLinesUC[]. ScreenLines[] contains the first byte only. For an ASCII
* character without composing chars ScreenLinesUC[] will be 0 and
* ScreenLinesC[][] is not used. When the character occupies two display
* cells the next byte in ScreenLines[] is 0.
* ScreenLinesC[][] contain up to 'maxcombine' composing characters
* (drawn on top of the first character). There is 0 after the last one used.
* ScreenLines2[] is only used for euc-jp to store the second byte if the
* first byte is 0x8e (single-width character).
*
* The screen_*() functions write to the screen and handle updating
* ScreenLines[].
*
* update_screen() is the function that updates all windows and status lines.
* It is called form the main loop when must_redraw is non-zero. It may be
* called from other places when an immediate screen update is needed.
*
* The part of the buffer that is displayed in a window is set with:
* - w_topline (first buffer line in window)
* - w_topfill (filler line above the first line)
* - w_leftcol (leftmost window cell in window),
* - w_skipcol (skipped window cells of first line)
*
* Commands that only move the cursor around in a window, do not need to take
* action to update the display. The main loop will check if w_topline is
* valid and update it (scroll the window) when needed.
*
* Commands that scroll a window change w_topline and must call
* check_cursor() to move the cursor into the visible part of the window, and
* call redraw_later(VALID) to have the window displayed by update_screen()
* later.
*
* Commands that change text in the buffer must call changed_bytes() or
* changed_lines() to mark the area that changed and will require updating
* later. The main loop will call update_screen(), which will update each
* window that shows the changed buffer. This assumes text above the change
* can remain displayed as it is. Text after the change may need updating for
* scrolling, folding and syntax highlighting.
*
* Commands that change how a window is displayed (e.g., setting 'list') or
* invalidate the contents of a window in another way (e.g., change fold
* settings), must call redraw_later(NOT_VALID) to have the whole window
* redisplayed by update_screen() later.
*
* Commands that change how a buffer is displayed (e.g., setting 'tabstop')
* must call redraw_curbuf_later(NOT_VALID) to have all the windows for the
* buffer redisplayed by update_screen() later.
*
* Commands that change highlighting and possibly cause a scroll too must call
* redraw_later(SOME_VALID) to update the whole window but still use scrolling
* to avoid redrawing everything. But the length of displayed lines must not
* change, use NOT_VALID then.
*
* Commands that move the window position must call redraw_later(NOT_VALID).
* TODO: should minimize redrawing by scrolling when possible.
*
* Commands that change everything (e.g., resizing the screen) must call
* redraw_all_later(NOT_VALID) or redraw_all_later(CLEAR).
*
* Things that are handled indirectly:
* - When messages scroll the screen up, msg_scrolled will be set and
* update_screen() called to redraw.
*/
#include "vim.h"
#define MB_FILLER_CHAR '<' /* character used when a double-width character
* doesn't fit. */
/*
* The attributes that are actually active for writing to the screen.
*/
static int screen_attr = 0;
/*
* Positioning the cursor is reduced by remembering the last position.
* Mostly used by windgoto() and screen_char().
*/
static int screen_cur_row, screen_cur_col; /* last known cursor position */
#ifdef FEAT_SEARCH_EXTRA
static match_T search_hl; /* used for 'hlsearch' highlight matching */
#endif
#ifdef FEAT_FOLDING
static foldinfo_T win_foldinfo; /* info for 'foldcolumn' */
#endif
/*
* Buffer for one screen line (characters and attributes).
*/
static schar_T *current_ScreenLine;
static void win_update __ARGS((win_T *wp));
static void win_draw_end __ARGS((win_T *wp, int c1, int c2, int row, int endrow, hlf_T hl));
#ifdef FEAT_FOLDING
static void fold_line __ARGS((win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T lnum, int row));
static void fill_foldcolumn __ARGS((char_u *p, win_T *wp, int closed, linenr_T lnum));
static void copy_text_attr __ARGS((int off, char_u *buf, int len, int attr));
#endif
static int win_line __ARGS((win_T *, linenr_T, int, int, int nochange));
static int char_needs_redraw __ARGS((int off_from, int off_to, int cols));
#ifdef FEAT_RIGHTLEFT
static void screen_line __ARGS((int row, int coloff, int endcol, int clear_width, int rlflag));
# define SCREEN_LINE(r, o, e, c, rl) screen_line((r), (o), (e), (c), (rl))
#else
static void screen_line __ARGS((int row, int coloff, int endcol, int clear_width));
# define SCREEN_LINE(r, o, e, c, rl) screen_line((r), (o), (e), (c))
#endif
#ifdef FEAT_VERTSPLIT
static void draw_vsep_win __ARGS((win_T *wp, int row));
#endif
#ifdef FEAT_STL_OPT
static void redraw_custom_statusline __ARGS((win_T *wp));
#endif
#ifdef FEAT_SEARCH_EXTRA
#define SEARCH_HL_PRIORITY 0
static void start_search_hl __ARGS((void));
static void end_search_hl __ARGS((void));
static void init_search_hl __ARGS((win_T *wp));
static void prepare_search_hl __ARGS((win_T *wp, linenr_T lnum));
static void next_search_hl __ARGS((win_T *win, match_T *shl, linenr_T lnum, colnr_T mincol));
#endif
static void screen_start_highlight __ARGS((int attr));
static void screen_char __ARGS((unsigned off, int row, int col));
#ifdef FEAT_MBYTE
static void screen_char_2 __ARGS((unsigned off, int row, int col));
#endif
static void screenclear2 __ARGS((void));
static void lineclear __ARGS((unsigned off, int width));
static void lineinvalid __ARGS((unsigned off, int width));
#ifdef FEAT_VERTSPLIT
static void linecopy __ARGS((int to, int from, win_T *wp));
static void redraw_block __ARGS((int row, int end, win_T *wp));
#endif
static int win_do_lines __ARGS((win_T *wp, int row, int line_count, int mayclear, int del));
static void win_rest_invalid __ARGS((win_T *wp));
static void msg_pos_mode __ARGS((void));
#if defined(FEAT_WINDOWS)
static void draw_tabline __ARGS((void));
#endif
#if defined(FEAT_WINDOWS) || defined(FEAT_WILDMENU) || defined(FEAT_STL_OPT)
static int fillchar_status __ARGS((int *attr, int is_curwin));
#endif
#ifdef FEAT_VERTSPLIT
static int fillchar_vsep __ARGS((int *attr));
#endif
#ifdef FEAT_STL_OPT
static void win_redr_custom __ARGS((win_T *wp, int draw_ruler));
#endif
#ifdef FEAT_CMDL_INFO
static void win_redr_ruler __ARGS((win_T *wp, int always));
#endif
#if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT)
/* Ugly global: overrule attribute used by screen_char() */
static int screen_char_attr = 0;
#endif
/*
* Redraw the current window later, with update_screen(type).
* Set must_redraw only if not already set to a higher value.
* e.g. if must_redraw is CLEAR, type NOT_VALID will do nothing.
*/
void
redraw_later(type)
int type;
{
redraw_win_later(curwin, type);
}
void
redraw_win_later(wp, type)
win_T *wp;
int type;
{
if (wp->w_redr_type < type)
{
wp->w_redr_type = type;
if (type >= NOT_VALID)
wp->w_lines_valid = 0;
if (must_redraw < type) /* must_redraw is the maximum of all windows */
must_redraw = type;
}
}
/*
* Force a complete redraw later. Also resets the highlighting. To be used
* after executing a shell command that messes up the screen.
*/
void
redraw_later_clear()
{
redraw_all_later(CLEAR);
#ifdef FEAT_GUI
if (gui.in_use)
/* Use a code that will reset gui.highlight_mask in
* gui_stop_highlight(). */
screen_attr = HL_ALL + 1;
else
#endif
/* Use attributes that is very unlikely to appear in text. */
screen_attr = HL_BOLD | HL_UNDERLINE | HL_INVERSE;
}
/*
* Mark all windows to be redrawn later.
*/
void
redraw_all_later(type)
int type;
{
win_T *wp;
FOR_ALL_WINDOWS(wp)
{
redraw_win_later(wp, type);
}
}
/*
* Mark all windows that are editing the current buffer to be updated later.
*/
void
redraw_curbuf_later(type)
int type;
{
redraw_buf_later(curbuf, type);
}
void
redraw_buf_later(buf, type)
buf_T *buf;
int type;
{
win_T *wp;
FOR_ALL_WINDOWS(wp)
{
if (wp->w_buffer == buf)
redraw_win_later(wp, type);
}
}
/*
* Changed something in the current window, at buffer line "lnum", that
* requires that line and possibly other lines to be redrawn.
* Used when entering/leaving Insert mode with the cursor on a folded line.
* Used to remove the "$" from a change command.
* Note that when also inserting/deleting lines w_redraw_top and w_redraw_bot
* may become invalid and the whole window will have to be redrawn.
*/
void
redrawWinline(lnum, invalid)
linenr_T lnum;
int invalid UNUSED; /* window line height is invalid now */
{
#ifdef FEAT_FOLDING
int i;
#endif
if (curwin->w_redraw_top == 0 || curwin->w_redraw_top > lnum)
curwin->w_redraw_top = lnum;
if (curwin->w_redraw_bot == 0 || curwin->w_redraw_bot < lnum)
curwin->w_redraw_bot = lnum;
redraw_later(VALID);
#ifdef FEAT_FOLDING
if (invalid)
{
/* A w_lines[] entry for this lnum has become invalid. */
i = find_wl_entry(curwin, lnum);
if (i >= 0)
curwin->w_lines[i].wl_valid = FALSE;
}
#endif
}
#if defined(FEAT_RUBY) || defined(FEAT_PERL) || defined(FEAT_VISUAL) || \
(defined(FEAT_CLIPBOARD) && defined(FEAT_X11)) || defined(PROTO)
/*
* update all windows that are editing the current buffer
*/
void
update_curbuf(type)
int type;
{
redraw_curbuf_later(type);
update_screen(type);
}
#endif
/*
* update_screen()
*
* Based on the current value of curwin->w_topline, transfer a screenfull
* of stuff from Filemem to ScreenLines[], and update curwin->w_botline.
*/
void
update_screen(type)
int type;
{
win_T *wp;
static int did_intro = FALSE;
#if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
int did_one;
#endif
/* Don't do anything if the screen structures are (not yet) valid. */
if (!screen_valid(TRUE))
return;
if (must_redraw)
{
if (type < must_redraw) /* use maximal type */
type = must_redraw;
/* must_redraw is reset here, so that when we run into some weird
* reason to redraw while busy redrawing (e.g., asynchronous
* scrolling), or update_topline() in win_update() will cause a
* scroll, the screen will be redrawn later or in win_update(). */
must_redraw = 0;
}
/* Need to update w_lines[]. */
if (curwin->w_lines_valid == 0 && type < NOT_VALID)
type = NOT_VALID;
/* Postpone the redrawing when it's not needed and when being called
* recursively. */
if (!redrawing() || updating_screen)
{
redraw_later(type); /* remember type for next time */
must_redraw = type;
if (type > INVERTED_ALL)
curwin->w_lines_valid = 0; /* don't use w_lines[].wl_size now */
return;
}
updating_screen = TRUE;
#ifdef FEAT_SYN_HL
++display_tick; /* let syntax code know we're in a next round of
* display updating */
#endif
/*
* if the screen was scrolled up when displaying a message, scroll it down
*/
if (msg_scrolled)
{
clear_cmdline = TRUE;
if (msg_scrolled > Rows - 5) /* clearing is faster */
type = CLEAR;
else if (type != CLEAR)
{
check_for_delay(FALSE);
if (screen_ins_lines(0, 0, msg_scrolled, (int)Rows, NULL) == FAIL)
type = CLEAR;
FOR_ALL_WINDOWS(wp)
{
if (W_WINROW(wp) < msg_scrolled)
{
if (W_WINROW(wp) + wp->w_height > msg_scrolled
&& wp->w_redr_type < REDRAW_TOP
&& wp->w_lines_valid > 0
&& wp->w_topline == wp->w_lines[0].wl_lnum)
{
wp->w_upd_rows = msg_scrolled - W_WINROW(wp);
wp->w_redr_type = REDRAW_TOP;
}
else
{
wp->w_redr_type = NOT_VALID;
#ifdef FEAT_WINDOWS
if (W_WINROW(wp) + wp->w_height + W_STATUS_HEIGHT(wp)
<= msg_scrolled)
wp->w_redr_status = TRUE;
#endif
}
}
}
redraw_cmdline = TRUE;
#ifdef FEAT_WINDOWS
redraw_tabline = TRUE;
#endif
}
msg_scrolled = 0;
need_wait_return = FALSE;
}
/* reset cmdline_row now (may have been changed temporarily) */
compute_cmdrow();
/* Check for changed highlighting */
if (need_highlight_changed)
highlight_changed();
if (type == CLEAR) /* first clear screen */
{
screenclear(); /* will reset clear_cmdline */
type = NOT_VALID;
}
if (clear_cmdline) /* going to clear cmdline (done below) */
check_for_delay(FALSE);
#ifdef FEAT_LINEBREAK
/* Force redraw when width of 'number' or 'relativenumber' column
* changes. */
if (curwin->w_redr_type < NOT_VALID
&& curwin->w_nrwidth != ((curwin->w_p_nu || curwin->w_p_rnu)
? number_width(curwin) : 0))
curwin->w_redr_type = NOT_VALID;
#endif
/*
* Only start redrawing if there is really something to do.
*/
if (type == INVERTED)
update_curswant();
if (curwin->w_redr_type < type
&& !((type == VALID
&& curwin->w_lines[0].wl_valid
#ifdef FEAT_DIFF
&& curwin->w_topfill == curwin->w_old_topfill
&& curwin->w_botfill == curwin->w_old_botfill
#endif
&& curwin->w_topline == curwin->w_lines[0].wl_lnum)
#ifdef FEAT_VISUAL
|| (type == INVERTED
&& VIsual_active
&& curwin->w_old_cursor_lnum == curwin->w_cursor.lnum
&& curwin->w_old_visual_mode == VIsual_mode
&& (curwin->w_valid & VALID_VIRTCOL)
&& curwin->w_old_curswant == curwin->w_curswant)
#endif
))
curwin->w_redr_type = type;
#ifdef FEAT_WINDOWS
/* Redraw the tab pages line if needed. */
if (redraw_tabline || type >= NOT_VALID)
draw_tabline();
#endif
#ifdef FEAT_SYN_HL
/*
* Correct stored syntax highlighting info for changes in each displayed
* buffer. Each buffer must only be done once.
*/
FOR_ALL_WINDOWS(wp)
{
if (wp->w_buffer->b_mod_set)
{
# ifdef FEAT_WINDOWS
win_T *wwp;
/* Check if we already did this buffer. */
for (wwp = firstwin; wwp != wp; wwp = wwp->w_next)
if (wwp->w_buffer == wp->w_buffer)
break;
# endif
if (
# ifdef FEAT_WINDOWS
wwp == wp &&
# endif
syntax_present(wp))
syn_stack_apply_changes(wp->w_buffer);
}
}
#endif
/*
* Go from top to bottom through the windows, redrawing the ones that need
* it.
*/
#if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
did_one = FALSE;
#endif
#ifdef FEAT_SEARCH_EXTRA
search_hl.rm.regprog = NULL;
#endif
FOR_ALL_WINDOWS(wp)
{
if (wp->w_redr_type != 0)
{
cursor_off();
#if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
if (!did_one)
{
did_one = TRUE;
# ifdef FEAT_SEARCH_EXTRA
start_search_hl();
# endif
# ifdef FEAT_CLIPBOARD
/* When Visual area changed, may have to update selection. */
if (clip_star.available && clip_isautosel())
clip_update_selection();
# endif
#ifdef FEAT_GUI
/* Remove the cursor before starting to do anything, because
* scrolling may make it difficult to redraw the text under
* it. */
if (gui.in_use)
gui_undraw_cursor();
#endif
}
#endif
win_update(wp);
}
#ifdef FEAT_WINDOWS
/* redraw status line after the window to minimize cursor movement */
if (wp->w_redr_status)
{
cursor_off();
win_redr_status(wp);
}
#endif
}
#if defined(FEAT_SEARCH_EXTRA)
end_search_hl();
#endif
#ifdef FEAT_WINDOWS
/* Reset b_mod_set flags. Going through all windows is probably faster
* than going through all buffers (there could be many buffers). */
for (wp = firstwin; wp != NULL; wp = wp->w_next)
wp->w_buffer->b_mod_set = FALSE;
#else
curbuf->b_mod_set = FALSE;
#endif
updating_screen = FALSE;
#ifdef FEAT_GUI
gui_may_resize_shell();
#endif
/* Clear or redraw the command line. Done last, because scrolling may
* mess up the command line. */
if (clear_cmdline || redraw_cmdline)
showmode();
/* May put up an introductory message when not editing a file */
if (!did_intro && bufempty()
&& curbuf->b_fname == NULL
#ifdef FEAT_WINDOWS
&& firstwin->w_next == NULL
#endif
&& vim_strchr(p_shm, SHM_INTRO) == NULL)
intro_message(FALSE);
did_intro = TRUE;
#ifdef FEAT_GUI
/* Redraw the cursor and update the scrollbars when all screen updating is
* done. */
if (gui.in_use)
{
out_flush(); /* required before updating the cursor */
if (did_one)
gui_update_cursor(FALSE, FALSE);
gui_update_scrollbars(FALSE);
}
#endif
}
#if defined(FEAT_CONCEAL) || defined(PROTO)
/*
* Return TRUE if the cursor line in window "wp" may be concealed, according
* to the 'concealcursor' option.
*/
int
conceal_cursor_line(wp)
win_T *wp;
{
int c;
if (*wp->w_p_cocu == NUL)
return FALSE;
if (get_real_state() & VISUAL)
c = 'v';
else if (State & INSERT)
c = 'i';
else if (State & NORMAL)
c = 'n';
else if (State & CMDLINE)
c = 'c';
else
return FALSE;
return vim_strchr(wp->w_p_cocu, c) != NULL;
}
/*
* Check if the cursor line needs to be redrawn because of 'concealcursor'.
*/
void
conceal_check_cursur_line()
{
if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin))
{
need_cursor_line_redraw = TRUE;
/* Need to recompute cursor column, e.g., when starting Visual mode
* without concealing. */
curs_columns(TRUE);
}
}
void
update_single_line(wp, lnum)
win_T *wp;
linenr_T lnum;
{
int row;
int j;
if (lnum >= wp->w_topline && lnum < wp->w_botline
&& foldedCount(wp, lnum, &win_foldinfo) == 0)
{
# ifdef FEAT_GUI
/* Remove the cursor before starting to do anything, because scrolling
* may make it difficult to redraw the text under it. */
if (gui.in_use)
gui_undraw_cursor();
# endif
row = 0;
for (j = 0; j < wp->w_lines_valid; ++j)
{
if (lnum == wp->w_lines[j].wl_lnum)
{
screen_start(); /* not sure of screen cursor */
# ifdef FEAT_SEARCH_EXTRA
init_search_hl(wp);
start_search_hl();
prepare_search_hl(wp, lnum);
# endif
win_line(wp, lnum, row, row + wp->w_lines[j].wl_size, FALSE);
# if defined(FEAT_SEARCH_EXTRA)
end_search_hl();
# endif
break;
}
row += wp->w_lines[j].wl_size;
}
# ifdef FEAT_GUI
/* Redraw the cursor */
if (gui.in_use)
{
out_flush(); /* required before updating the cursor */
gui_update_cursor(FALSE, FALSE);
}
# endif
}
need_cursor_line_redraw = FALSE;
}
#endif
#if defined(FEAT_SIGNS) || defined(FEAT_GUI)
static void update_prepare __ARGS((void));
static void update_finish __ARGS((void));
/*
* Prepare for updating one or more windows.
* Caller must check for "updating_screen" already set to avoid recursiveness.
*/
static void
update_prepare()
{
cursor_off();
updating_screen = TRUE;
#ifdef FEAT_GUI
/* Remove the cursor before starting to do anything, because scrolling may
* make it difficult to redraw the text under it. */
if (gui.in_use)
gui_undraw_cursor();
#endif
#ifdef FEAT_SEARCH_EXTRA
start_search_hl();
#endif
}
/*
* Finish updating one or more windows.
*/
static void
update_finish()
{
if (redraw_cmdline)
showmode();
# ifdef FEAT_SEARCH_EXTRA
end_search_hl();
# endif
updating_screen = FALSE;
# ifdef FEAT_GUI
gui_may_resize_shell();
/* Redraw the cursor and update the scrollbars when all screen updating is
* done. */
if (gui.in_use)
{
out_flush(); /* required before updating the cursor */
gui_update_cursor(FALSE, FALSE);
gui_update_scrollbars(FALSE);
}
# endif
}
#endif
#if defined(FEAT_SIGNS) || defined(PROTO)
void
update_debug_sign(buf, lnum)
buf_T *buf;
linenr_T lnum;
{
win_T *wp;
int doit = FALSE;
# ifdef FEAT_FOLDING
win_foldinfo.fi_level = 0;
# endif
/* update/delete a specific mark */
FOR_ALL_WINDOWS(wp)
{
if (buf != NULL && lnum > 0)
{
if (wp->w_buffer == buf && lnum >= wp->w_topline
&& lnum < wp->w_botline)
{
if (wp->w_redraw_top == 0 || wp->w_redraw_top > lnum)
wp->w_redraw_top = lnum;
if (wp->w_redraw_bot == 0 || wp->w_redraw_bot < lnum)
wp->w_redraw_bot = lnum;
redraw_win_later(wp, VALID);
}
}
else
redraw_win_later(wp, VALID);
if (wp->w_redr_type != 0)
doit = TRUE;
}
/* Return when there is nothing to do, screen updating is already
* happening (recursive call) or still starting up. */
if (!doit || updating_screen
#ifdef FEAT_GUI
|| gui.starting
#endif
|| starting)
return;
/* update all windows that need updating */
update_prepare();
# ifdef FEAT_WINDOWS
for (wp = firstwin; wp; wp = wp->w_next)
{
if (wp->w_redr_type != 0)
win_update(wp);
if (wp->w_redr_status)
win_redr_status(wp);
}
# else
if (curwin->w_redr_type != 0)
win_update(curwin);
# endif
update_finish();
}
#endif
#if defined(FEAT_GUI) || defined(PROTO)
/*
* Update a single window, its status line and maybe the command line msg.
* Used for the GUI scrollbar.
*/
void
updateWindow(wp)
win_T *wp;
{
/* return if already busy updating */
if (updating_screen)
return;
update_prepare();
#ifdef FEAT_CLIPBOARD
/* When Visual area changed, may have to update selection. */
if (clip_star.available && clip_isautosel())
clip_update_selection();
#endif
win_update(wp);
#ifdef FEAT_WINDOWS
/* When the screen was cleared redraw the tab pages line. */
if (redraw_tabline)
draw_tabline();
if (wp->w_redr_status
# ifdef FEAT_CMDL_INFO
|| p_ru
# endif
# ifdef FEAT_STL_OPT
|| *p_stl != NUL || *wp->w_p_stl != NUL
# endif
)
win_redr_status(wp);
#endif
update_finish();
}
#endif
/*
* Update a single window.
*
* This may cause the windows below it also to be redrawn (when clearing the
* screen or scrolling lines).
*
* How the window is redrawn depends on wp->w_redr_type. Each type also
* implies the one below it.
* NOT_VALID redraw the whole window
* SOME_VALID redraw the whole window but do scroll when possible
* REDRAW_TOP redraw the top w_upd_rows window lines, otherwise like VALID
* INVERTED redraw the changed part of the Visual area
* INVERTED_ALL redraw the whole Visual area
* VALID 1. scroll up/down to adjust for a changed w_topline
* 2. update lines at the top when scrolled down
* 3. redraw changed text:
* - if wp->w_buffer->b_mod_set set, update lines between
* b_mod_top and b_mod_bot.
* - if wp->w_redraw_top non-zero, redraw lines between
* wp->w_redraw_top and wp->w_redr_bot.
* - continue redrawing when syntax status is invalid.
* 4. if scrolled up, update lines at the bottom.
* This results in three areas that may need updating:
* top: from first row to top_end (when scrolled down)
* mid: from mid_start to mid_end (update inversion or changed text)
* bot: from bot_start to last row (when scrolled up)
*/
static void
win_update(wp)
win_T *wp;
{
buf_T *buf = wp->w_buffer;
int type;
int top_end = 0; /* Below last row of the top area that needs
updating. 0 when no top area updating. */
int mid_start = 999;/* first row of the mid area that needs
updating. 999 when no mid area updating. */
int mid_end = 0; /* Below last row of the mid area that needs
updating. 0 when no mid area updating. */
int bot_start = 999;/* first row of the bot area that needs
updating. 999 when no bot area updating */
#ifdef FEAT_VISUAL
int scrolled_down = FALSE; /* TRUE when scrolled down when
w_topline got smaller a bit */
#endif
#ifdef FEAT_SEARCH_EXTRA
matchitem_T *cur; /* points to the match list */
int top_to_mod = FALSE; /* redraw above mod_top */
#endif
int row; /* current window row to display */
linenr_T lnum; /* current buffer lnum to display */
int idx; /* current index in w_lines[] */
int srow; /* starting row of the current line */
int eof = FALSE; /* if TRUE, we hit the end of the file */
int didline = FALSE; /* if TRUE, we finished the last line */
int i;
long j;
static int recursive = FALSE; /* being called recursively */
int old_botline = wp->w_botline;
#ifdef FEAT_FOLDING
long fold_count;
#endif
#ifdef FEAT_SYN_HL
/* remember what happened to the previous line, to know if
* check_visual_highlight() can be used */
#define DID_NONE 1 /* didn't update a line */
#define DID_LINE 2 /* updated a normal line */
#define DID_FOLD 3 /* updated a folded line */
int did_update = DID_NONE;
linenr_T syntax_last_parsed = 0; /* last parsed text line */
#endif
linenr_T mod_top = 0;
linenr_T mod_bot = 0;
#if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
int save_got_int;
#endif
type = wp->w_redr_type;
if (type == NOT_VALID)
{
#ifdef FEAT_WINDOWS
wp->w_redr_status = TRUE;
#endif
wp->w_lines_valid = 0;
}
/* Window is zero-height: nothing to draw. */
if (wp->w_height == 0)
{
wp->w_redr_type = 0;
return;
}
#ifdef FEAT_VERTSPLIT
/* Window is zero-width: Only need to draw the separator. */
if (wp->w_width == 0)
{
/* draw the vertical separator right of this window */
draw_vsep_win(wp, 0);
wp->w_redr_type = 0;
return;
}
#endif
#ifdef FEAT_SEARCH_EXTRA
init_search_hl(wp);
#endif
#ifdef FEAT_LINEBREAK
/* Force redraw when width of 'number' or 'relativenumber' column
* changes. */
i = (wp->w_p_nu || wp->w_p_rnu) ? number_width(wp) : 0;
if (wp->w_nrwidth != i)
{
type = NOT_VALID;
wp->w_nrwidth = i;
}
else
#endif
if (buf->b_mod_set && buf->b_mod_xlines != 0 && wp->w_redraw_top != 0)
{
/*
* When there are both inserted/deleted lines and specific lines to be
* redrawn, w_redraw_top and w_redraw_bot may be invalid, just redraw
* everything (only happens when redrawing is off for while).
*/
type = NOT_VALID;
}
else
{
/*
* Set mod_top to the first line that needs displaying because of
* changes. Set mod_bot to the first line after the changes.
*/
mod_top = wp->w_redraw_top;
if (wp->w_redraw_bot != 0)
mod_bot = wp->w_redraw_bot + 1;
else
mod_bot = 0;
wp->w_redraw_top = 0; /* reset for next time */
wp->w_redraw_bot = 0;
if (buf->b_mod_set)
{
if (mod_top == 0 || mod_top > buf->b_mod_top)
{
mod_top = buf->b_mod_top;
#ifdef FEAT_SYN_HL
/* Need to redraw lines above the change that may be included
* in a pattern match. */
if (syntax_present(wp))
{
mod_top -= buf->b_s.b_syn_sync_linebreaks;
if (mod_top < 1)
mod_top = 1;
}
#endif
}
if (mod_bot == 0 || mod_bot < buf->b_mod_bot)
mod_bot = buf->b_mod_bot;
#ifdef FEAT_SEARCH_EXTRA
/* When 'hlsearch' is on and using a multi-line search pattern, a
* change in one line may make the Search highlighting in a
* previous line invalid. Simple solution: redraw all visible
* lines above the change.
* Same for a match pattern.
*/
if (search_hl.rm.regprog != NULL
&& re_multiline(search_hl.rm.regprog))
top_to_mod = TRUE;
else
{
cur = wp->w_match_head;
while (cur != NULL)
{
if (cur->match.regprog != NULL
&& re_multiline(cur->match.regprog))
{
top_to_mod = TRUE;
break;
}
cur = cur->next;
}
}
#endif
}
#ifdef FEAT_FOLDING
if (mod_top != 0 && hasAnyFolding(wp))
{
linenr_T lnumt, lnumb;
/*
* A change in a line can cause lines above it to become folded or
* unfolded. Find the top most buffer line that may be affected.
* If the line was previously folded and displayed, get the first
* line of that fold. If the line is folded now, get the first
* folded line. Use the minimum of these two.
*/
/* Find last valid w_lines[] entry above mod_top. Set lnumt to
* the line below it. If there is no valid entry, use w_topline.
* Find the first valid w_lines[] entry below mod_bot. Set lnumb
* to this line. If there is no valid entry, use MAXLNUM. */
lnumt = wp->w_topline;
lnumb = MAXLNUM;
for (i = 0; i < wp->w_lines_valid; ++i)
if (wp->w_lines[i].wl_valid)
{
if (wp->w_lines[i].wl_lastlnum < mod_top)
lnumt = wp->w_lines[i].wl_lastlnum + 1;
if (lnumb == MAXLNUM && wp->w_lines[i].wl_lnum >= mod_bot)
{
lnumb = wp->w_lines[i].wl_lnum;
/* When there is a fold column it might need updating
* in the next line ("J" just above an open fold). */
if (wp->w_p_fdc > 0)
++lnumb;
}
}
(void)hasFoldingWin(wp, mod_top, &mod_top, NULL, TRUE, NULL);
if (mod_top > lnumt)
mod_top = lnumt;
/* Now do the same for the bottom line (one above mod_bot). */
--mod_bot;
(void)hasFoldingWin(wp, mod_bot, NULL, &mod_bot, TRUE, NULL);
++mod_bot;
if (mod_bot < lnumb)
mod_bot = lnumb;
}
#endif
/* When a change starts above w_topline and the end is below
* w_topline, start redrawing at w_topline.
* If the end of the change is above w_topline: do like no change was
* made, but redraw the first line to find changes in syntax. */
if (mod_top != 0 && mod_top < wp->w_topline)
{
if (mod_bot > wp->w_topline)
mod_top = wp->w_topline;
#ifdef FEAT_SYN_HL
else if (syntax_present(wp))
top_end = 1;
#endif
}
/* When line numbers are displayed need to redraw all lines below
* inserted/deleted lines. */
if (mod_top != 0 && buf->b_mod_xlines != 0 && wp->w_p_nu)
mod_bot = MAXLNUM;
}
/*
* When only displaying the lines at the top, set top_end. Used when
* window has scrolled down for msg_scrolled.
*/
if (type == REDRAW_TOP)
{
j = 0;
for (i = 0; i < wp->w_lines_valid; ++i)
{
j += wp->w_lines[i].wl_size;
if (j >= wp->w_upd_rows)
{
top_end = j;
break;
}
}
if (top_end == 0)
/* not found (cannot happen?): redraw everything */
type = NOT_VALID;
else
/* top area defined, the rest is VALID */
type = VALID;
}
/* Trick: we want to avoid clearing the screen twice. screenclear() will
* set "screen_cleared" to TRUE. The special value MAYBE (which is still
* non-zero and thus not FALSE) will indicate that screenclear() was not
* called. */
if (screen_cleared)
screen_cleared = MAYBE;
/*
* If there are no changes on the screen that require a complete redraw,
* handle three cases:
* 1: we are off the top of the screen by a few lines: scroll down
* 2: wp->w_topline is below wp->w_lines[0].wl_lnum: may scroll up
* 3: wp->w_topline is wp->w_lines[0].wl_lnum: find first entry in
* w_lines[] that needs updating.
*/
if ((type == VALID || type == SOME_VALID
|| type == INVERTED || type == INVERTED_ALL)
#ifdef FEAT_DIFF
&& !wp->w_botfill && !wp->w_old_botfill
#endif
)
{
if (mod_top != 0 && wp->w_topline == mod_top)
{
/*
* w_topline is the first changed line, the scrolling will be done
* further down.
*/
}
else if (wp->w_lines[0].wl_valid
&& (wp->w_topline < wp->w_lines[0].wl_lnum
#ifdef FEAT_DIFF
|| (wp->w_topline == wp->w_lines[0].wl_lnum
&& wp->w_topfill > wp->w_old_topfill)
#endif
))
{
/*
* New topline is above old topline: May scroll down.
*/
#ifdef FEAT_FOLDING
if (hasAnyFolding(wp))
{
linenr_T ln;
/* count the number of lines we are off, counting a sequence
* of folded lines as one */
j = 0;
for (ln = wp->w_topline; ln < wp->w_lines[0].wl_lnum; ++ln)
{
++j;
if (j >= wp->w_height - 2)
break;
(void)hasFoldingWin(wp, ln, NULL, &ln, TRUE, NULL);
}
}
else
#endif
j = wp->w_lines[0].wl_lnum - wp->w_topline;
if (j < wp->w_height - 2) /* not too far off */
{
i = plines_m_win(wp, wp->w_topline, wp->w_lines[0].wl_lnum - 1);
#ifdef FEAT_DIFF
/* insert extra lines for previously invisible filler lines */
if (wp->w_lines[0].wl_lnum != wp->w_topline)
i += diff_check_fill(wp, wp->w_lines[0].wl_lnum)
- wp->w_old_topfill;
#endif
if (i < wp->w_height - 2) /* less than a screen off */
{
/*
* Try to insert the correct number of lines.
* If not the last window, delete the lines at the bottom.
* win_ins_lines may fail when the terminal can't do it.
*/
if (i > 0)
check_for_delay(FALSE);
if (win_ins_lines(wp, 0, i, FALSE, wp == firstwin) == OK)
{
if (wp->w_lines_valid != 0)
{
/* Need to update rows that are new, stop at the
* first one that scrolled down. */
top_end = i;
#ifdef FEAT_VISUAL
scrolled_down = TRUE;
#endif
/* Move the entries that were scrolled, disable
* the entries for the lines to be redrawn. */
if ((wp->w_lines_valid += j) > wp->w_height)
wp->w_lines_valid = wp->w_height;
for (idx = wp->w_lines_valid; idx - j >= 0; idx--)
wp->w_lines[idx] = wp->w_lines[idx - j];
while (idx >= 0)
wp->w_lines[idx--].wl_valid = FALSE;
}
}
else
mid_start = 0; /* redraw all lines */
}
else
mid_start = 0; /* redraw all lines */
}
else
mid_start = 0; /* redraw all lines */
}
else
{
/*
* New topline is at or below old topline: May scroll up.
* When topline didn't change, find first entry in w_lines[] that
* needs updating.
*/
/* try to find wp->w_topline in wp->w_lines[].wl_lnum */
j = -1;
row = 0;
for (i = 0; i < wp->w_lines_valid; i++)
{
if (wp->w_lines[i].wl_valid
&& wp->w_lines[i].wl_lnum == wp->w_topline)
{
j = i;
break;
}
row += wp->w_lines[i].wl_size;
}
if (j == -1)
{
/* if wp->w_topline is not in wp->w_lines[].wl_lnum redraw all
* lines */
mid_start = 0;
}
else
{
/*
* Try to delete the correct number of lines.
* wp->w_topline is at wp->w_lines[i].wl_lnum.
*/
#ifdef FEAT_DIFF
/* If the topline didn't change, delete old filler lines,
* otherwise delete filler lines of the new topline... */
if (wp->w_lines[0].wl_lnum == wp->w_topline)
row += wp->w_old_topfill;
else
row += diff_check_fill(wp, wp->w_topline);
/* ... but don't delete new filler lines. */
row -= wp->w_topfill;
#endif
if (row > 0)
{
check_for_delay(FALSE);
if (win_del_lines(wp, 0, row, FALSE, wp == firstwin) == OK)
bot_start = wp->w_height - row;
else
mid_start = 0; /* redraw all lines */
}
if ((row == 0 || bot_start < 999) && wp->w_lines_valid != 0)
{
/*
* Skip the lines (below the deleted lines) that are still
* valid and don't need redrawing. Copy their info
* upwards, to compensate for the deleted lines. Set
* bot_start to the first row that needs redrawing.
*/
bot_start = 0;
idx = 0;
for (;;)
{
wp->w_lines[idx] = wp->w_lines[j];
/* stop at line that didn't fit, unless it is still
* valid (no lines deleted) */
if (row > 0 && bot_start + row
+ (int)wp->w_lines[j].wl_size > wp->w_height)
{
wp->w_lines_valid = idx + 1;
break;
}
bot_start += wp->w_lines[idx++].wl_size;
/* stop at the last valid entry in w_lines[].wl_size */
if (++j >= wp->w_lines_valid)
{
wp->w_lines_valid = idx;
break;
}
}
#ifdef FEAT_DIFF
/* Correct the first entry for filler lines at the top
* when it won't get updated below. */
if (wp->w_p_diff && bot_start > 0)
wp->w_lines[0].wl_size =
plines_win_nofill(wp, wp->w_topline, TRUE)
+ wp->w_topfill;
#endif
}
}
}
/* When starting redraw in the first line, redraw all lines. When
* there is only one window it's probably faster to clear the screen
* first. */
if (mid_start == 0)
{
mid_end = wp->w_height;
if (lastwin == firstwin)
{
/* Clear the screen when it was not done by win_del_lines() or
* win_ins_lines() above, "screen_cleared" is FALSE or MAYBE
* then. */
if (screen_cleared != TRUE)
screenclear();
#ifdef FEAT_WINDOWS
/* The screen was cleared, redraw the tab pages line. */
if (redraw_tabline)
draw_tabline();
#endif
}
}
/* When win_del_lines() or win_ins_lines() caused the screen to be
* cleared (only happens for the first window) or when screenclear()
* was called directly above, "must_redraw" will have been set to
* NOT_VALID, need to reset it here to avoid redrawing twice. */
if (screen_cleared == TRUE)
must_redraw = 0;
}
else
{
/* Not VALID or INVERTED: redraw all lines. */
mid_start = 0;
mid_end = wp->w_height;
}
if (type == SOME_VALID)
{
/* SOME_VALID: redraw all lines. */
mid_start = 0;
mid_end = wp->w_height;
type = NOT_VALID;
}
#ifdef FEAT_VISUAL
/* check if we are updating or removing the inverted part */
if ((VIsual_active && buf == curwin->w_buffer)
|| (wp->w_old_cursor_lnum != 0 && type != NOT_VALID))
{
linenr_T from, to;
if (VIsual_active)
{
if (VIsual_active
&& (VIsual_mode != wp->w_old_visual_mode
|| type == INVERTED_ALL))
{
/*
* If the type of Visual selection changed, redraw the whole
* selection. Also when the ownership of the X selection is
* gained or lost.
*/
if (curwin->w_cursor.lnum < VIsual.lnum)
{
from = curwin->w_cursor.lnum;
to = VIsual.lnum;
}
else
{
from = VIsual.lnum;
to = curwin->w_cursor.lnum;
}
/* redraw more when the cursor moved as well */
if (wp->w_old_cursor_lnum < from)
from = wp->w_old_cursor_lnum;
if (wp->w_old_cursor_lnum > to)
to = wp->w_old_cursor_lnum;
if (wp->w_old_visual_lnum < from)
from = wp->w_old_visual_lnum;
if (wp->w_old_visual_lnum > to)
to = wp->w_old_visual_lnum;
}
else
{
/*
* Find the line numbers that need to be updated: The lines
* between the old cursor position and the current cursor
* position. Also check if the Visual position changed.
*/
if (curwin->w_cursor.lnum < wp->w_old_cursor_lnum)
{
from = curwin->w_cursor.lnum;
to = wp->w_old_cursor_lnum;
}
else
{
from = wp->w_old_cursor_lnum;
to = curwin->w_cursor.lnum;
if (from == 0) /* Visual mode just started */
from = to;
}
if (VIsual.lnum != wp->w_old_visual_lnum
|| VIsual.col != wp->w_old_visual_col)
{
if (wp->w_old_visual_lnum < from
&& wp->w_old_visual_lnum != 0)
from = wp->w_old_visual_lnum;
if (wp->w_old_visual_lnum > to)
to = wp->w_old_visual_lnum;
if (VIsual.lnum < from)
from = VIsual.lnum;
if (VIsual.lnum > to)
to = VIsual.lnum;
}
}
/*
* If in block mode and changed column or curwin->w_curswant:
* update all lines.
* First compute the actual start and end column.
*/
if (VIsual_mode == Ctrl_V)
{
colnr_T fromc, toc;
getvcols(wp, &VIsual, &curwin->w_cursor, &fromc, &toc);
++toc;
if (curwin->w_curswant == MAXCOL)
toc = MAXCOL;
if (fromc != wp->w_old_cursor_fcol
|| toc != wp->w_old_cursor_lcol)
{
if (from > VIsual.lnum)
from = VIsual.lnum;
if (to < VIsual.lnum)
to = VIsual.lnum;
}
wp->w_old_cursor_fcol = fromc;
wp->w_old_cursor_lcol = toc;
}
}
else
{
/* Use the line numbers of the old Visual area. */
if (wp->w_old_cursor_lnum < wp->w_old_visual_lnum)
{
from = wp->w_old_cursor_lnum;
to = wp->w_old_visual_lnum;
}
else
{
from = wp->w_old_visual_lnum;
to = wp->w_old_cursor_lnum;
}
}
/*
* There is no need to update lines above the top of the window.
*/
if (from < wp->w_topline)
from = wp->w_topline;
/*
* If we know the value of w_botline, use it to restrict the update to
* the lines that are visible in the window.
*/
if (wp->w_valid & VALID_BOTLINE)
{
if (from >= wp->w_botline)
from = wp->w_botline - 1;
if (to >= wp->w_botline)
to = wp->w_botline - 1;
}
/*
* Find the minimal part to be updated.
* Watch out for scrolling that made entries in w_lines[] invalid.
* E.g., CTRL-U makes the first half of w_lines[] invalid and sets
* top_end; need to redraw from top_end to the "to" line.
* A middle mouse click with a Visual selection may change the text
* above the Visual area and reset wl_valid, do count these for
* mid_end (in srow).
*/
if (mid_start > 0)
{
lnum = wp->w_topline;
idx = 0;
srow = 0;
if (scrolled_down)
mid_start = top_end;
else
mid_start = 0;
while (lnum < from && idx < wp->w_lines_valid) /* find start */
{
if (wp->w_lines[idx].wl_valid)
mid_start += wp->w_lines[idx].wl_size;
else if (!scrolled_down)
srow += wp->w_lines[idx].wl_size;
++idx;
# ifdef FEAT_FOLDING
if (idx < wp->w_lines_valid && wp->w_lines[idx].wl_valid)
lnum = wp->w_lines[idx].wl_lnum;
else
# endif
++lnum;
}
srow += mid_start;
mid_end = wp->w_height;
for ( ; idx < wp->w_lines_valid; ++idx) /* find end */
{
if (wp->w_lines[idx].wl_valid
&& wp->w_lines[idx].wl_lnum >= to + 1)
{
/* Only update until first row of this line */
mid_end = srow;
break;
}
srow += wp->w_lines[idx].wl_size;
}
}
}
if (VIsual_active && buf == curwin->w_buffer)
{
wp->w_old_visual_mode = VIsual_mode;
wp->w_old_cursor_lnum = curwin->w_cursor.lnum;
wp->w_old_visual_lnum = VIsual.lnum;
wp->w_old_visual_col = VIsual.col;
wp->w_old_curswant = curwin->w_curswant;
}
else
{
wp->w_old_visual_mode = 0;
wp->w_old_cursor_lnum = 0;
wp->w_old_visual_lnum = 0;
wp->w_old_visual_col = 0;
}
#endif /* FEAT_VISUAL */
#if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
/* reset got_int, otherwise regexp won't work */
save_got_int = got_int;
got_int = 0;
#endif
#ifdef FEAT_FOLDING
win_foldinfo.fi_level = 0;
#endif
/*
* Update all the window rows.
*/
idx = 0; /* first entry in w_lines[].wl_size */
row = 0;
srow = 0;
lnum = wp->w_topline; /* first line shown in window */
for (;;)
{
/* stop updating when reached the end of the window (check for _past_
* the end of the window is at the end of the loop) */
if (row == wp->w_height)
{
didline = TRUE;
break;
}
/* stop updating when hit the end of the file */
if (lnum > buf->b_ml.ml_line_count)
{
eof = TRUE;
break;
}
/* Remember the starting row of the line that is going to be dealt
* with. It is used further down when the line doesn't fit. */
srow = row;
/*
* Update a line when it is in an area that needs updating, when it
* has changes or w_lines[idx] is invalid.
* bot_start may be halfway a wrapped line after using
* win_del_lines(), check if the current line includes it.
* When syntax folding is being used, the saved syntax states will
* already have been updated, we can't see where the syntax state is
* the same again, just update until the end of the window.
*/
if (row < top_end
|| (row >= mid_start && row < mid_end)
#ifdef FEAT_SEARCH_EXTRA
|| top_to_mod
#endif
|| idx >= wp->w_lines_valid
|| (row + wp->w_lines[idx].wl_size > bot_start)
|| (mod_top != 0
&& (lnum == mod_top
|| (lnum >= mod_top
&& (lnum < mod_bot
#ifdef FEAT_SYN_HL
|| did_update == DID_FOLD
|| (did_update == DID_LINE
&& syntax_present(wp)
&& (
# ifdef FEAT_FOLDING
(foldmethodIsSyntax(wp)
&& hasAnyFolding(wp)) ||
# endif
syntax_check_changed(lnum)))
#endif
)))))
{
#ifdef FEAT_SEARCH_EXTRA
if (lnum == mod_top)
top_to_mod = FALSE;
#endif
/*
* When at start of changed lines: May scroll following lines
* up or down to minimize redrawing.
* Don't do this when the change continues until the end.
* Don't scroll when dollar_vcol >= 0, keep the "$".
*/
if (lnum == mod_top
&& mod_bot != MAXLNUM
&& !(dollar_vcol >= 0 && mod_bot == mod_top + 1))
{
int old_rows = 0;
int new_rows = 0;
int xtra_rows;
linenr_T l;
/* Count the old number of window rows, using w_lines[], which
* should still contain the sizes for the lines as they are
* currently displayed. */
for (i = idx; i < wp->w_lines_valid; ++i)
{
/* Only valid lines have a meaningful wl_lnum. Invalid
* lines are part of the changed area. */
if (wp->w_lines[i].wl_valid
&& wp->w_lines[i].wl_lnum == mod_bot)
break;
old_rows += wp->w_lines[i].wl_size;
#ifdef FEAT_FOLDING
if (wp->w_lines[i].wl_valid
&& wp->w_lines[i].wl_lastlnum + 1 == mod_bot)
{
/* Must have found the last valid entry above mod_bot.
* Add following invalid entries. */
++i;
while (i < wp->w_lines_valid
&& !wp->w_lines[i].wl_valid)
old_rows += wp->w_lines[i++].wl_size;
break;
}
#endif
}
if (i >= wp->w_lines_valid)
{
/* We can't find a valid line below the changed lines,
* need to redraw until the end of the window.
* Inserting/deleting lines has no use. */
bot_start = 0;
}
else
{
/* Able to count old number of rows: Count new window
* rows, and may insert/delete lines */
j = idx;
for (l = lnum; l < mod_bot; ++l)
{
#ifdef FEAT_FOLDING
if (hasFoldingWin(wp, l, NULL, &l, TRUE, NULL))
++new_rows;
else
#endif
#ifdef FEAT_DIFF
if (l == wp->w_topline)
new_rows += plines_win_nofill(wp, l, TRUE)
+ wp->w_topfill;
else
#endif
new_rows += plines_win(wp, l, TRUE);
++j;
if (new_rows > wp->w_height - row - 2)
{
/* it's getting too much, must redraw the rest */
new_rows = 9999;
break;
}
}
xtra_rows = new_rows - old_rows;
if (xtra_rows < 0)
{
/* May scroll text up. If there is not enough
* remaining text or scrolling fails, must redraw the
* rest. If scrolling works, must redraw the text
* below the scrolled text. */
if (row - xtra_rows >= wp->w_height - 2)
mod_bot = MAXLNUM;
else
{
check_for_delay(FALSE);
if (win_del_lines(wp, row,
-xtra_rows, FALSE, FALSE) == FAIL)
mod_bot = MAXLNUM;
else
bot_start = wp->w_height + xtra_rows;
}
}
else if (xtra_rows > 0)
{
/* May scroll text down. If there is not enough
* remaining text of scrolling fails, must redraw the
* rest. */
if (row + xtra_rows >= wp->w_height - 2)
mod_bot = MAXLNUM;
else
{
check_for_delay(FALSE);
if (win_ins_lines(wp, row + old_rows,
xtra_rows, FALSE, FALSE) == FAIL)
mod_bot = MAXLNUM;
else if (top_end > row + old_rows)
/* Scrolled the part at the top that requires
* updating down. */
top_end += xtra_rows;
}
}
/* When not updating the rest, may need to move w_lines[]
* entries. */
if (mod_bot != MAXLNUM && i != j)
{
if (j < i)
{
int x = row + new_rows;
/* move entries in w_lines[] upwards */
for (;;)
{
/* stop at last valid entry in w_lines[] */
if (i >= wp->w_lines_valid)
{
wp->w_lines_valid = j;
break;
}
wp->w_lines[j] = wp->w_lines[i];
/* stop at a line that won't fit */
if (x + (int)wp->w_lines[j].wl_size
> wp->w_height)
{
wp->w_lines_valid = j + 1;
break;
}
x += wp->w_lines[j++].wl_size;
++i;
}
if (bot_start > x)
bot_start = x;
}
else /* j > i */
{
/* move entries in w_lines[] downwards */
j -= i;
wp->w_lines_valid += j;
if (wp->w_lines_valid > wp->w_height)
wp->w_lines_valid = wp->w_height;
for (i = wp->w_lines_valid; i - j >= idx; --i)
wp->w_lines[i] = wp->w_lines[i - j];
/* The w_lines[] entries for inserted lines are
* now invalid, but wl_size may be used above.
* Reset to zero. */
while (i >= idx)
{
wp->w_lines[i].wl_size = 0;
wp->w_lines[i--].wl_valid = FALSE;
}
}
}
}
}
#ifdef FEAT_FOLDING
/*
* When lines are folded, display one line for all of them.
* Otherwise, display normally (can be several display lines when
* 'wrap' is on).
*/
fold_count = foldedCount(wp, lnum, &win_foldinfo);
if (fold_count != 0)
{
fold_line(wp, fold_count, &win_foldinfo, lnum, row);
++row;
--fold_count;
wp->w_lines[idx].wl_folded = TRUE;
wp->w_lines[idx].wl_lastlnum = lnum + fold_count;
# ifdef FEAT_SYN_HL
did_update = DID_FOLD;
# endif
}
else
#endif
if (idx < wp->w_lines_valid
&& wp->w_lines[idx].wl_valid
&& wp->w_lines[idx].wl_lnum == lnum
&& lnum > wp->w_topline
&& !(dy_flags & DY_LASTLINE)
&& srow + wp->w_lines[idx].wl_size > wp->w_height
#ifdef FEAT_DIFF
&& diff_check_fill(wp, lnum) == 0
#endif
)
{
/* This line is not going to fit. Don't draw anything here,
* will draw "@ " lines below. */
row = wp->w_height + 1;
}
else
{
#ifdef FEAT_SEARCH_EXTRA
prepare_search_hl(wp, lnum);
#endif
#ifdef FEAT_SYN_HL
/* Let the syntax stuff know we skipped a few lines. */
if (syntax_last_parsed != 0 && syntax_last_parsed + 1 < lnum
&& syntax_present(wp))
syntax_end_parsing(syntax_last_parsed + 1);
#endif
/*
* Display one line.
*/
row = win_line(wp, lnum, srow, wp->w_height, mod_top == 0);
#ifdef FEAT_FOLDING
wp->w_lines[idx].wl_folded = FALSE;
wp->w_lines[idx].wl_lastlnum = lnum;
#endif
#ifdef FEAT_SYN_HL
did_update = DID_LINE;
syntax_last_parsed = lnum;
#endif
}
wp->w_lines[idx].wl_lnum = lnum;
wp->w_lines[idx].wl_valid = TRUE;
if (row > wp->w_height) /* past end of screen */
{
/* we may need the size of that too long line later on */
if (dollar_vcol == -1)
wp->w_lines[idx].wl_size = plines_win(wp, lnum, TRUE);
++idx;
break;
}
if (dollar_vcol == -1)
wp->w_lines[idx].wl_size = row - srow;
++idx;
#ifdef FEAT_FOLDING
lnum += fold_count + 1;
#else
++lnum;
#endif
}
else
{
/* This line does not need updating, advance to the next one */
row += wp->w_lines[idx++].wl_size;
if (row > wp->w_height) /* past end of screen */
break;
#ifdef FEAT_FOLDING
lnum = wp->w_lines[idx - 1].wl_lastlnum + 1;
#else
++lnum;
#endif
#ifdef FEAT_SYN_HL
did_update = DID_NONE;
#endif
}
if (lnum > buf->b_ml.ml_line_count)
{
eof = TRUE;
break;
}
}
/*
* End of loop over all window lines.
*/
if (idx > wp->w_lines_valid)
wp->w_lines_valid = idx;
#ifdef FEAT_SYN_HL
/*
* Let the syntax stuff know we stop parsing here.
*/
if (syntax_last_parsed != 0 && syntax_present(wp))
syntax_end_parsing(syntax_last_parsed + 1);
#endif
/*
* If we didn't hit the end of the file, and we didn't finish the last
* line we were working on, then the line didn't fit.
*/
wp->w_empty_rows = 0;
#ifdef FEAT_DIFF
wp->w_filler_rows = 0;
#endif
if (!eof && !didline)
{
if (lnum == wp->w_topline)
{
/*
* Single line that does not fit!
* Don't overwrite it, it can be edited.
*/
wp->w_botline = lnum + 1;
}
#ifdef FEAT_DIFF
else if (diff_check_fill(wp, lnum) >= wp->w_height - srow)
{
/* Window ends in filler lines. */
wp->w_botline = lnum;
wp->w_filler_rows = wp->w_height - srow;
}
#endif
else if (dy_flags & DY_LASTLINE) /* 'display' has "lastline" */
{
/*
* Last line isn't finished: Display "@@@" at the end.
*/
screen_fill(W_WINROW(wp) + wp->w_height - 1,
W_WINROW(wp) + wp->w_height,
(int)W_ENDCOL(wp) - 3, (int)W_ENDCOL(wp),
'@', '@', hl_attr(HLF_AT));
set_empty_rows(wp, srow);
wp->w_botline = lnum;
}
else
{
win_draw_end(wp, '@', ' ', srow, wp->w_height, HLF_AT);
wp->w_botline = lnum;
}
}
else
{
#ifdef FEAT_VERTSPLIT
draw_vsep_win(wp, row);
#endif
if (eof) /* we hit the end of the file */
{
wp->w_botline = buf->b_ml.ml_line_count + 1;
#ifdef FEAT_DIFF
j = diff_check_fill(wp, wp->w_botline);
if (j > 0 && !wp->w_botfill)
{
/*
* Display filler lines at the end of the file
*/
if (char2cells(fill_diff) > 1)
i = '-';
else
i = fill_diff;
if (row + j > wp->w_height)
j = wp->w_height - row;
win_draw_end(wp, i, i, row, row + (int)j, HLF_DED);
row += j;
}
#endif
}
else if (dollar_vcol == -1)
wp->w_botline = lnum;
/* make sure the rest of the screen is blank */
/* put '~'s on rows that aren't part of the file. */
win_draw_end(wp, '~', ' ', row, wp->w_height, HLF_AT);
}
/* Reset the type of redrawing required, the window has been updated. */
wp->w_redr_type = 0;
#ifdef FEAT_DIFF
wp->w_old_topfill = wp->w_topfill;
wp->w_old_botfill = wp->w_botfill;
#endif
if (dollar_vcol == -1)
{
/*
* There is a trick with w_botline. If we invalidate it on each
* change that might modify it, this will cause a lot of expensive
* calls to plines() in update_topline() each time. Therefore the
* value of w_botline is often approximated, and this value is used to
* compute the value of w_topline. If the value of w_botline was
* wrong, check that the value of w_topline is correct (cursor is on
* the visible part of the text). If it's not, we need to redraw
* again. Mostly this just means scrolling up a few lines, so it
* doesn't look too bad. Only do this for the current window (where
* changes are relevant).
*/
wp->w_valid |= VALID_BOTLINE;
if (wp == curwin && wp->w_botline != old_botline && !recursive)
{
recursive = TRUE;
curwin->w_valid &= ~VALID_TOPLINE;
update_topline(); /* may invalidate w_botline again */
if (must_redraw != 0)
{
/* Don't update for changes in buffer again. */
i = curbuf->b_mod_set;
curbuf->b_mod_set = FALSE;
win_update(curwin);
must_redraw = 0;
curbuf->b_mod_set = i;
}
recursive = FALSE;
}
}
#if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
/* restore got_int, unless CTRL-C was hit while redrawing */
if (!got_int)
got_int = save_got_int;
#endif
}
#ifdef FEAT_SIGNS
static int draw_signcolumn __ARGS((win_T *wp));
/*
* Return TRUE when window "wp" has a column to draw signs in.
*/
static int
draw_signcolumn(wp)
win_T *wp;
{
return (wp->w_buffer->b_signlist != NULL
# ifdef FEAT_NETBEANS_INTG
|| netbeans_active()
# endif
);
}
#endif
/*
* Clear the rest of the window and mark the unused lines with "c1". use "c2"
* as the filler character.
*/
static void
win_draw_end(wp, c1, c2, row, endrow, hl)
win_T *wp;
int c1;
int c2;
int row;
int endrow;
hlf_T hl;
{
#if defined(FEAT_FOLDING) || defined(FEAT_SIGNS) || defined(FEAT_CMDWIN)
int n = 0;
# define FDC_OFF n
#else
# define FDC_OFF 0
#endif
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
/* No check for cmdline window: should never be right-left. */
# ifdef FEAT_FOLDING
n = wp->w_p_fdc;
if (n > 0)
{
/* draw the fold column at the right */
if (n > W_WIDTH(wp))
n = W_WIDTH(wp);
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_ENDCOL(wp) - n, (int)W_ENDCOL(wp),
' ', ' ', hl_attr(HLF_FC));
}
# endif
# ifdef FEAT_SIGNS
if (draw_signcolumn(wp))
{
int nn = n + 2;
/* draw the sign column left of the fold column */
if (nn > W_WIDTH(wp))
nn = W_WIDTH(wp);
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_ENDCOL(wp) - nn, (int)W_ENDCOL(wp) - n,
' ', ' ', hl_attr(HLF_SC));
n = nn;
}
# endif
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_WINCOL(wp), W_ENDCOL(wp) - 1 - FDC_OFF,
c2, c2, hl_attr(hl));
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_ENDCOL(wp) - 1 - FDC_OFF, W_ENDCOL(wp) - FDC_OFF,
c1, c2, hl_attr(hl));
}
else
#endif
{
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0 && wp == curwin)
{
/* draw the cmdline character in the leftmost column */
n = 1;
if (n > wp->w_width)
n = wp->w_width;
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_WINCOL(wp), (int)W_WINCOL(wp) + n,
cmdwin_type, ' ', hl_attr(HLF_AT));
}
#endif
#ifdef FEAT_FOLDING
if (wp->w_p_fdc > 0)
{
int nn = n + wp->w_p_fdc;
/* draw the fold column at the left */
if (nn > W_WIDTH(wp))
nn = W_WIDTH(wp);
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_WINCOL(wp) + n, (int)W_WINCOL(wp) + nn,
' ', ' ', hl_attr(HLF_FC));
n = nn;
}
#endif
#ifdef FEAT_SIGNS
if (draw_signcolumn(wp))
{
int nn = n + 2;
/* draw the sign column after the fold column */
if (nn > W_WIDTH(wp))
nn = W_WIDTH(wp);
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_WINCOL(wp) + n, (int)W_WINCOL(wp) + nn,
' ', ' ', hl_attr(HLF_SC));
n = nn;
}
#endif
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
W_WINCOL(wp) + FDC_OFF, (int)W_ENDCOL(wp),
c1, c2, hl_attr(hl));
}
set_empty_rows(wp, row);
}
#ifdef FEAT_SYN_HL
static int advance_color_col __ARGS((int vcol, int **color_cols));
/*
* Advance **color_cols and return TRUE when there are columns to draw.
*/
static int
advance_color_col(vcol, color_cols)
int vcol;
int **color_cols;
{
while (**color_cols >= 0 && vcol > **color_cols)
++*color_cols;
return (**color_cols >= 0);
}
#endif
#ifdef FEAT_FOLDING
/*
* Display one folded line.
*/
static void
fold_line(wp, fold_count, foldinfo, lnum, row)
win_T *wp;
long fold_count;
foldinfo_T *foldinfo;
linenr_T lnum;
int row;
{
char_u buf[51];
pos_T *top, *bot;
linenr_T lnume = lnum + fold_count - 1;
int len;
char_u *text;
int fdc;
int col;
int txtcol;
int off = (int)(current_ScreenLine - ScreenLines);
int ri;
/* Build the fold line:
* 1. Add the cmdwin_type for the command-line window
* 2. Add the 'foldcolumn'
* 3. Add the 'number' or 'relativenumber' column
* 4. Compose the text
* 5. Add the text
* 6. set highlighting for the Visual area an other text
*/
col = 0;
/*
* 1. Add the cmdwin_type for the command-line window
* Ignores 'rightleft', this window is never right-left.
*/
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0 && wp == curwin)
{
ScreenLines[off] = cmdwin_type;
ScreenAttrs[off] = hl_attr(HLF_AT);
#ifdef FEAT_MBYTE
if (enc_utf8)
ScreenLinesUC[off] = 0;
#endif
++col;
}
#endif
/*
* 2. Add the 'foldcolumn'
*/
fdc = wp->w_p_fdc;
if (fdc > W_WIDTH(wp) - col)
fdc = W_WIDTH(wp) - col;
if (fdc > 0)
{
fill_foldcolumn(buf, wp, TRUE, lnum);
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
int i;
copy_text_attr(off + W_WIDTH(wp) - fdc - col, buf, fdc,
hl_attr(HLF_FC));
/* reverse the fold column */
for (i = 0; i < fdc; ++i)
ScreenLines[off + W_WIDTH(wp) - i - 1 - col] = buf[i];
}
else
#endif
copy_text_attr(off + col, buf, fdc, hl_attr(HLF_FC));
col += fdc;
}
#ifdef FEAT_RIGHTLEFT
# define RL_MEMSET(p, v, l) if (wp->w_p_rl) \
for (ri = 0; ri < l; ++ri) \
ScreenAttrs[off + (W_WIDTH(wp) - (p) - (l)) + ri] = v; \
else \
for (ri = 0; ri < l; ++ri) \
ScreenAttrs[off + (p) + ri] = v
#else
# define RL_MEMSET(p, v, l) for (ri = 0; ri < l; ++ri) \
ScreenAttrs[off + (p) + ri] = v
#endif
/* Set all attributes of the 'number' or 'relativenumber' column and the
* text */
RL_MEMSET(col, hl_attr(HLF_FL), W_WIDTH(wp) - col);
#ifdef FEAT_SIGNS
/* If signs are being displayed, add two spaces. */
if (draw_signcolumn(wp))
{
len = W_WIDTH(wp) - col;
if (len > 0)
{
if (len > 2)
len = 2;
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
/* the line number isn't reversed */
copy_text_attr(off + W_WIDTH(wp) - len - col,
(char_u *)" ", len, hl_attr(HLF_FL));
else
# endif
copy_text_attr(off + col, (char_u *)" ", len, hl_attr(HLF_FL));
col += len;
}
}
#endif
/*
* 3. Add the 'number' or 'relativenumber' column
*/
if (wp->w_p_nu || wp->w_p_rnu)
{
len = W_WIDTH(wp) - col;
if (len > 0)
{
int w = number_width(wp);
long num;
if (len > w + 1)
len = w + 1;
if (wp->w_p_nu)
/* 'number' */
num = (long)lnum;
else
/* 'relativenumber', don't use negative numbers */
num = labs((long)get_cursor_rel_lnum(wp, lnum));
sprintf((char *)buf, "%*ld ", w, num);
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
/* the line number isn't reversed */
copy_text_attr(off + W_WIDTH(wp) - len - col, buf, len,
hl_attr(HLF_FL));
else
#endif
copy_text_attr(off + col, buf, len, hl_attr(HLF_FL));
col += len;
}
}
/*
* 4. Compose the folded-line string with 'foldtext', if set.
*/
text = get_foldtext(wp, lnum, lnume, foldinfo, buf);
txtcol = col; /* remember where text starts */
/*
* 5. move the text to current_ScreenLine. Fill up with "fill_fold".
* Right-left text is put in columns 0 - number-col, normal text is put
* in columns number-col - window-width.
*/
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int cells;
int u8c, u8cc[MAX_MCO];
int i;
int idx;
int c_len;
char_u *p;
# ifdef FEAT_ARABIC
int prev_c = 0; /* previous Arabic character */
int prev_c1 = 0; /* first composing char for prev_c */
# endif
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
idx = off;
else
# endif
idx = off + col;
/* Store multibyte characters in ScreenLines[] et al. correctly. */
for (p = text; *p != NUL; )
{
cells = (*mb_ptr2cells)(p);
c_len = (*mb_ptr2len)(p);
if (col + cells > W_WIDTH(wp)
# ifdef FEAT_RIGHTLEFT
- (wp->w_p_rl ? col : 0)
# endif
)
break;
ScreenLines[idx] = *p;
if (enc_utf8)
{
u8c = utfc_ptr2char(p, u8cc);
if (*p < 0x80 && u8cc[0] == 0)
{
ScreenLinesUC[idx] = 0;
#ifdef FEAT_ARABIC
prev_c = u8c;
#endif
}
else
{
#ifdef FEAT_ARABIC
if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c))
{
/* Do Arabic shaping. */
int pc, pc1, nc;
int pcc[MAX_MCO];
int firstbyte = *p;
/* The idea of what is the previous and next
* character depends on 'rightleft'. */
if (wp->w_p_rl)
{
pc = prev_c;
pc1 = prev_c1;
nc = utf_ptr2char(p + c_len);
prev_c1 = u8cc[0];
}
else
{
pc = utfc_ptr2char(p + c_len, pcc);
nc = prev_c;
pc1 = pcc[0];
}
prev_c = u8c;
u8c = arabic_shape(u8c, &firstbyte, &u8cc[0],
pc, pc1, nc);
ScreenLines[idx] = firstbyte;
}
else
prev_c = u8c;
#endif
/* Non-BMP character: display as ? or fullwidth ?. */
#ifdef UNICODE16
if (u8c >= 0x10000)
ScreenLinesUC[idx] = (cells == 2) ? 0xff1f : (int)'?';
else
#endif
ScreenLinesUC[idx] = u8c;
for (i = 0; i < Screen_mco; ++i)
{
ScreenLinesC[i][idx] = u8cc[i];
if (u8cc[i] == 0)
break;
}
}
if (cells > 1)
ScreenLines[idx + 1] = 0;
}
else if (enc_dbcs == DBCS_JPNU && *p == 0x8e)
/* double-byte single width character */
ScreenLines2[idx] = p[1];
else if (cells > 1)
/* double-width character */
ScreenLines[idx + 1] = p[1];
col += cells;
idx += cells;
p += c_len;
}
}
else
#endif
{
len = (int)STRLEN(text);
if (len > W_WIDTH(wp) - col)
len = W_WIDTH(wp) - col;
if (len > 0)
{
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
STRNCPY(current_ScreenLine, text, len);
else
#endif
STRNCPY(current_ScreenLine + col, text, len);
col += len;
}
}
/* Fill the rest of the line with the fold filler */
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
col -= txtcol;
#endif
while (col < W_WIDTH(wp)
#ifdef FEAT_RIGHTLEFT
- (wp->w_p_rl ? txtcol : 0)
#endif
)
{
#ifdef FEAT_MBYTE
if (enc_utf8)
{
if (fill_fold >= 0x80)
{
ScreenLinesUC[off + col] = fill_fold;
ScreenLinesC[0][off + col] = 0;
}
else
ScreenLinesUC[off + col] = 0;
}
#endif
ScreenLines[off + col++] = fill_fold;
}
if (text != buf)
vim_free(text);
/*
* 6. set highlighting for the Visual area an other text.
* If all folded lines are in the Visual area, highlight the line.
*/
#ifdef FEAT_VISUAL
if (VIsual_active && wp->w_buffer == curwin->w_buffer)
{
if (ltoreq(curwin->w_cursor, VIsual))
{
/* Visual is after curwin->w_cursor */
top = &curwin->w_cursor;
bot = &VIsual;
}
else
{
/* Visual is before curwin->w_cursor */
top = &VIsual;
bot = &curwin->w_cursor;
}
if (lnum >= top->lnum
&& lnume <= bot->lnum
&& (VIsual_mode != 'v'
|| ((lnum > top->lnum
|| (lnum == top->lnum
&& top->col == 0))
&& (lnume < bot->lnum
|| (lnume == bot->lnum
&& (bot->col - (*p_sel == 'e'))
>= (colnr_T)STRLEN(ml_get_buf(wp->w_buffer, lnume, FALSE)))))))
{
if (VIsual_mode == Ctrl_V)
{
/* Visual block mode: highlight the chars part of the block */
if (wp->w_old_cursor_fcol + txtcol < (colnr_T)W_WIDTH(wp))
{
if (wp->w_old_cursor_lcol != MAXCOL
&& wp->w_old_cursor_lcol + txtcol
< (colnr_T)W_WIDTH(wp))
len = wp->w_old_cursor_lcol;
else
len = W_WIDTH(wp) - txtcol;
RL_MEMSET(wp->w_old_cursor_fcol + txtcol, hl_attr(HLF_V),
len - (int)wp->w_old_cursor_fcol);
}
}
else
{
/* Set all attributes of the text */
RL_MEMSET(txtcol, hl_attr(HLF_V), W_WIDTH(wp) - txtcol);
}
}
}
#endif
#ifdef FEAT_SYN_HL
/* Show 'cursorcolumn' in the fold line. */
if (wp->w_p_cuc)
{
txtcol += wp->w_virtcol;
if (wp->w_p_wrap)
txtcol -= wp->w_skipcol;
else
txtcol -= wp->w_leftcol;
if (txtcol >= 0 && txtcol < W_WIDTH(wp))
ScreenAttrs[off + txtcol] = hl_combine_attr(
ScreenAttrs[off + txtcol], hl_attr(HLF_CUC));
}
#endif
SCREEN_LINE(row + W_WINROW(wp), W_WINCOL(wp), (int)W_WIDTH(wp),
(int)W_WIDTH(wp), FALSE);
/*
* Update w_cline_height and w_cline_folded if the cursor line was
* updated (saves a call to plines() later).
*/
if (wp == curwin
&& lnum <= curwin->w_cursor.lnum
&& lnume >= curwin->w_cursor.lnum)
{
curwin->w_cline_row = row;
curwin->w_cline_height = 1;
curwin->w_cline_folded = TRUE;
curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW);
}
}
/*
* Copy "buf[len]" to ScreenLines["off"] and set attributes to "attr".
*/
static void
copy_text_attr(off, buf, len, attr)
int off;
char_u *buf;
int len;
int attr;
{
int i;
mch_memmove(ScreenLines + off, buf, (size_t)len);
# ifdef FEAT_MBYTE
if (enc_utf8)
vim_memset(ScreenLinesUC + off, 0, sizeof(u8char_T) * (size_t)len);
# endif
for (i = 0; i < len; ++i)
ScreenAttrs[off + i] = attr;
}
/*
* Fill the foldcolumn at "p" for window "wp".
* Only to be called when 'foldcolumn' > 0.
*/
static void
fill_foldcolumn(p, wp, closed, lnum)
char_u *p;
win_T *wp;
int closed; /* TRUE of FALSE */
linenr_T lnum; /* current line number */
{
int i = 0;
int level;
int first_level;
int empty;
/* Init to all spaces. */
copy_spaces(p, (size_t)wp->w_p_fdc);
level = win_foldinfo.fi_level;
if (level > 0)
{
/* If there is only one column put more info in it. */
empty = (wp->w_p_fdc == 1) ? 0 : 1;
/* If the column is too narrow, we start at the lowest level that
* fits and use numbers to indicated the depth. */
first_level = level - wp->w_p_fdc - closed + 1 + empty;
if (first_level < 1)
first_level = 1;
for (i = 0; i + empty < wp->w_p_fdc; ++i)
{
if (win_foldinfo.fi_lnum == lnum
&& first_level + i >= win_foldinfo.fi_low_level)
p[i] = '-';
else if (first_level == 1)
p[i] = '|';
else if (first_level + i <= 9)
p[i] = '0' + first_level + i;
else
p[i] = '>';
if (first_level + i == level)
break;
}
}
if (closed)
p[i >= wp->w_p_fdc ? i - 1 : i] = '+';
}
#endif /* FEAT_FOLDING */
/*
* Display line "lnum" of window 'wp' on the screen.
* Start at row "startrow", stop when "endrow" is reached.
* wp->w_virtcol needs to be valid.
*
* Return the number of last row the line occupies.
*/
static int
win_line(wp, lnum, startrow, endrow, nochange)
win_T *wp;
linenr_T lnum;
int startrow;
int endrow;
int nochange UNUSED; /* not updating for changed text */
{
int col; /* visual column on screen */
unsigned off; /* offset in ScreenLines/ScreenAttrs */
int c = 0; /* init for GCC */
long vcol = 0; /* virtual column (for tabs) */
long vcol_prev = -1; /* "vcol" of previous character */
char_u *line; /* current line */
char_u *ptr; /* current position in "line" */
int row; /* row in the window, excl w_winrow */
int screen_row; /* row on the screen, incl w_winrow */
char_u extra[18]; /* "%ld" and 'fdc' must fit in here */
int n_extra = 0; /* number of extra chars */
char_u *p_extra = NULL; /* string of extra chars, plus NUL */
int c_extra = NUL; /* extra chars, all the same */
int extra_attr = 0; /* attributes when n_extra != 0 */
static char_u *at_end_str = (char_u *)""; /* used for p_extra when
displaying lcs_eol at end-of-line */
int lcs_eol_one = lcs_eol; /* lcs_eol until it's been used */
int lcs_prec_todo = lcs_prec; /* lcs_prec until it's been used */
/* saved "extra" items for when draw_state becomes WL_LINE (again) */
int saved_n_extra = 0;
char_u *saved_p_extra = NULL;
int saved_c_extra = 0;
int saved_char_attr = 0;
int n_attr = 0; /* chars with special attr */
int saved_attr2 = 0; /* char_attr saved for n_attr */
int n_attr3 = 0; /* chars with overruling special attr */
int saved_attr3 = 0; /* char_attr saved for n_attr3 */
int n_skip = 0; /* nr of chars to skip for 'nowrap' */
int fromcol, tocol; /* start/end of inverting */
int fromcol_prev = -2; /* start of inverting after cursor */
int noinvcur = FALSE; /* don't invert the cursor */
#ifdef FEAT_VISUAL
pos_T *top, *bot;
int lnum_in_visual_area = FALSE;
#endif
pos_T pos;
long v;
int char_attr = 0; /* attributes for next character */
int attr_pri = FALSE; /* char_attr has priority */
int area_highlighting = FALSE; /* Visual or incsearch highlighting
in this line */
int attr = 0; /* attributes for area highlighting */
int area_attr = 0; /* attributes desired by highlighting */
int search_attr = 0; /* attributes desired by 'hlsearch' */
#ifdef FEAT_SYN_HL
int vcol_save_attr = 0; /* saved attr for 'cursorcolumn' */
int syntax_attr = 0; /* attributes desired by syntax */
int has_syntax = FALSE; /* this buffer has syntax highl. */
int save_did_emsg;
int eol_hl_off = 0; /* 1 if highlighted char after EOL */
int draw_color_col = FALSE; /* highlight colorcolumn */
int *color_cols = NULL; /* pointer to according columns array */
#endif
#ifdef FEAT_SPELL
int has_spell = FALSE; /* this buffer has spell checking */
# define SPWORDLEN 150
char_u nextline[SPWORDLEN * 2];/* text with start of the next line */
int nextlinecol = 0; /* column where nextline[] starts */
int nextline_idx = 0; /* index in nextline[] where next line
starts */
int spell_attr = 0; /* attributes desired by spelling */
int word_end = 0; /* last byte with same spell_attr */
static linenr_T checked_lnum = 0; /* line number for "checked_col" */
static int checked_col = 0; /* column in "checked_lnum" up to which
* there are no spell errors */
static int cap_col = -1; /* column to check for Cap word */
static linenr_T capcol_lnum = 0; /* line number where "cap_col" used */
int cur_checked_col = 0; /* checked column for current line */
#endif
int extra_check; /* has syntax or linebreak */
#ifdef FEAT_MBYTE
int multi_attr = 0; /* attributes desired by multibyte */
int mb_l = 1; /* multi-byte byte length */
int mb_c = 0; /* decoded multi-byte character */
int mb_utf8 = FALSE; /* screen char is UTF-8 char */
int u8cc[MAX_MCO]; /* composing UTF-8 chars */
#endif
#ifdef FEAT_DIFF
int filler_lines; /* nr of filler lines to be drawn */
int filler_todo; /* nr of filler lines still to do + 1 */
hlf_T diff_hlf = (hlf_T)0; /* type of diff highlighting */
int change_start = MAXCOL; /* first col of changed area */
int change_end = -1; /* last col of changed area */
#endif
colnr_T trailcol = MAXCOL; /* start of trailing spaces */
#ifdef FEAT_LINEBREAK
int need_showbreak = FALSE;
#endif
#if defined(FEAT_SIGNS) || (defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS)) \
|| defined(FEAT_SYN_HL) || defined(FEAT_DIFF)
# define LINE_ATTR
int line_attr = 0; /* attribute for the whole line */
#endif
#ifdef FEAT_SEARCH_EXTRA
matchitem_T *cur; /* points to the match list */
match_T *shl; /* points to search_hl or a match */
int shl_flag; /* flag to indicate whether search_hl
has been processed or not */
int prevcol_hl_flag; /* flag to indicate whether prevcol
equals startcol of search_hl or one
of the matches */
#endif
#ifdef FEAT_ARABIC
int prev_c = 0; /* previous Arabic character */
int prev_c1 = 0; /* first composing char for prev_c */
#endif
#if defined(LINE_ATTR)
int did_line_attr = 0;
#endif
/* draw_state: items that are drawn in sequence: */
#define WL_START 0 /* nothing done yet */
#ifdef FEAT_CMDWIN
# define WL_CMDLINE WL_START + 1 /* cmdline window column */
#else
# define WL_CMDLINE WL_START
#endif
#ifdef FEAT_FOLDING
# define WL_FOLD WL_CMDLINE + 1 /* 'foldcolumn' */
#else
# define WL_FOLD WL_CMDLINE
#endif
#ifdef FEAT_SIGNS
# define WL_SIGN WL_FOLD + 1 /* column for signs */
#else
# define WL_SIGN WL_FOLD /* column for signs */
#endif
#define WL_NR WL_SIGN + 1 /* line number */
#if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF)
# define WL_SBR WL_NR + 1 /* 'showbreak' or 'diff' */
#else
# define WL_SBR WL_NR
#endif
#define WL_LINE WL_SBR + 1 /* text in the line */
int draw_state = WL_START; /* what to draw next */
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
int feedback_col = 0;
int feedback_old_attr = -1;
#endif
#ifdef FEAT_CONCEAL
int syntax_flags = 0;
int syntax_seqnr = 0;
int prev_syntax_id = 0;
int conceal_attr = hl_attr(HLF_CONCEAL);
int is_concealing = FALSE;
int boguscols = 0; /* nonexistent columns added to force
wrapping */
int vcol_off = 0; /* offset for concealed characters */
int did_wcol = FALSE;
# define VCOL_HLC (vcol - vcol_off)
#else
# define VCOL_HLC (vcol)
#endif
if (startrow > endrow) /* past the end already! */
return startrow;
row = startrow;
screen_row = row + W_WINROW(wp);
/*
* To speed up the loop below, set extra_check when there is linebreak,
* trailing white space and/or syntax processing to be done.
*/
#ifdef FEAT_LINEBREAK
extra_check = wp->w_p_lbr;
#else
extra_check = 0;
#endif
#ifdef FEAT_SYN_HL
if (syntax_present(wp) && !wp->w_s->b_syn_error)
{
/* Prepare for syntax highlighting in this line. When there is an
* error, stop syntax highlighting. */
save_did_emsg = did_emsg;
did_emsg = FALSE;
syntax_start(wp, lnum);
if (did_emsg)
wp->w_s->b_syn_error = TRUE;
else
{
did_emsg = save_did_emsg;
has_syntax = TRUE;
extra_check = TRUE;
}
}
/* Check for columns to display for 'colorcolumn'. */
color_cols = wp->w_p_cc_cols;
if (color_cols != NULL)
draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
#endif
#ifdef FEAT_SPELL
if (wp->w_p_spell
&& *wp->w_s->b_p_spl != NUL
&& wp->w_s->b_langp.ga_len > 0
&& *(char **)(wp->w_s->b_langp.ga_data) != NULL)
{
/* Prepare for spell checking. */
has_spell = TRUE;
extra_check = TRUE;
/* Get the start of the next line, so that words that wrap to the next
* line are found too: "et<line-break>al.".
* Trick: skip a few chars for C/shell/Vim comments */
nextline[SPWORDLEN] = NUL;
if (lnum < wp->w_buffer->b_ml.ml_line_count)
{
line = ml_get_buf(wp->w_buffer, lnum + 1, FALSE);
spell_cat_line(nextline + SPWORDLEN, line, SPWORDLEN);
}
/* When a word wrapped from the previous line the start of the current
* line is valid. */
if (lnum == checked_lnum)
cur_checked_col = checked_col;
checked_lnum = 0;
/* When there was a sentence end in the previous line may require a
* word starting with capital in this line. In line 1 always check
* the first word. */
if (lnum != capcol_lnum)
cap_col = -1;
if (lnum == 1)
cap_col = 0;
capcol_lnum = 0;
}
#endif
/*
* handle visual active in this window
*/
fromcol = -10;
tocol = MAXCOL;
#ifdef FEAT_VISUAL
if (VIsual_active && wp->w_buffer == curwin->w_buffer)
{
/* Visual is after curwin->w_cursor */
if (ltoreq(curwin->w_cursor, VIsual))
{
top = &curwin->w_cursor;
bot = &VIsual;
}
else /* Visual is before curwin->w_cursor */
{
top = &VIsual;
bot = &curwin->w_cursor;
}
lnum_in_visual_area = (lnum >= top->lnum && lnum <= bot->lnum);
if (VIsual_mode == Ctrl_V) /* block mode */
{
if (lnum_in_visual_area)
{
fromcol = wp->w_old_cursor_fcol;
tocol = wp->w_old_cursor_lcol;
}
}
else /* non-block mode */
{
if (lnum > top->lnum && lnum <= bot->lnum)
fromcol = 0;
else if (lnum == top->lnum)
{
if (VIsual_mode == 'V') /* linewise */
fromcol = 0;
else
{
getvvcol(wp, top, (colnr_T *)&fromcol, NULL, NULL);
if (gchar_pos(top) == NUL)
tocol = fromcol + 1;
}
}
if (VIsual_mode != 'V' && lnum == bot->lnum)
{
if (*p_sel == 'e' && bot->col == 0
#ifdef FEAT_VIRTUALEDIT
&& bot->coladd == 0
#endif
)
{
fromcol = -10;
tocol = MAXCOL;
}
else if (bot->col == MAXCOL)
tocol = MAXCOL;
else
{
pos = *bot;
if (*p_sel == 'e')
getvvcol(wp, &pos, (colnr_T *)&tocol, NULL, NULL);
else
{
getvvcol(wp, &pos, NULL, NULL, (colnr_T *)&tocol);
++tocol;
}
}
}
}
#ifndef MSDOS
/* Check if the character under the cursor should not be inverted */
if (!highlight_match && lnum == curwin->w_cursor.lnum && wp == curwin
# ifdef FEAT_GUI
&& !gui.in_use
# endif
)
noinvcur = TRUE;
#endif
/* if inverting in this line set area_highlighting */
if (fromcol >= 0)
{
area_highlighting = TRUE;
attr = hl_attr(HLF_V);
#if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
if (clip_star.available && !clip_star.owned && clip_isautosel())
attr = hl_attr(HLF_VNC);
#endif
}
}
/*
* handle 'incsearch' and ":s///c" highlighting
*/
else
#endif /* FEAT_VISUAL */
if (highlight_match
&& wp == curwin
&& lnum >= curwin->w_cursor.lnum
&& lnum <= curwin->w_cursor.lnum + search_match_lines)
{
if (lnum == curwin->w_cursor.lnum)
getvcol(curwin, &(curwin->w_cursor),
(colnr_T *)&fromcol, NULL, NULL);
else
fromcol = 0;
if (lnum == curwin->w_cursor.lnum + search_match_lines)
{
pos.lnum = lnum;
pos.col = search_match_endcol;
getvcol(curwin, &pos, (colnr_T *)&tocol, NULL, NULL);
}
else
tocol = MAXCOL;
/* do at least one character; happens when past end of line */
if (fromcol == tocol)
tocol = fromcol + 1;
area_highlighting = TRUE;
attr = hl_attr(HLF_I);
}
#ifdef FEAT_DIFF
filler_lines = diff_check(wp, lnum);
if (filler_lines < 0)
{
if (filler_lines == -1)
{
if (diff_find_change(wp, lnum, &change_start, &change_end))
diff_hlf = HLF_ADD; /* added line */
else if (change_start == 0)
diff_hlf = HLF_TXD; /* changed text */
else
diff_hlf = HLF_CHD; /* changed line */
}
else
diff_hlf = HLF_ADD; /* added line */
filler_lines = 0;
area_highlighting = TRUE;
}
if (lnum == wp->w_topline)
filler_lines = wp->w_topfill;
filler_todo = filler_lines;
#endif
#ifdef LINE_ATTR
# ifdef FEAT_SIGNS
/* If this line has a sign with line highlighting set line_attr. */
v = buf_getsigntype(wp->w_buffer, lnum, SIGN_LINEHL);
if (v != 0)
line_attr = sign_get_attr((int)v, TRUE);
# endif
# if defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS)
/* Highlight the current line in the quickfix window. */
if (bt_quickfix(wp->w_buffer) && qf_current_entry(wp) == lnum)
line_attr = hl_attr(HLF_L);
# endif
if (line_attr != 0)
area_highlighting = TRUE;
#endif
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
ptr = line;
#ifdef FEAT_SPELL
if (has_spell)
{
/* For checking first word with a capital skip white space. */
if (cap_col == 0)
cap_col = (int)(skipwhite(line) - line);
/* To be able to spell-check over line boundaries copy the end of the
* current line into nextline[]. Above the start of the next line was
* copied to nextline[SPWORDLEN]. */
if (nextline[SPWORDLEN] == NUL)
{
/* No next line or it is empty. */
nextlinecol = MAXCOL;
nextline_idx = 0;
}
else
{
v = (long)STRLEN(line);
if (v < SPWORDLEN)
{
/* Short line, use it completely and append the start of the
* next line. */
nextlinecol = 0;
mch_memmove(nextline, line, (size_t)v);
STRMOVE(nextline + v, nextline + SPWORDLEN);
nextline_idx = v + 1;
}
else
{
/* Long line, use only the last SPWORDLEN bytes. */
nextlinecol = v - SPWORDLEN;
mch_memmove(nextline, line + nextlinecol, SPWORDLEN);
nextline_idx = SPWORDLEN + 1;
}
}
}
#endif
/* find start of trailing whitespace */
if (wp->w_p_list && lcs_trail)
{
trailcol = (colnr_T)STRLEN(ptr);
while (trailcol > (colnr_T)0 && vim_iswhite(ptr[trailcol - 1]))
--trailcol;
trailcol += (colnr_T) (ptr - line);
extra_check = TRUE;
}
/*
* 'nowrap' or 'wrap' and a single line that doesn't fit: Advance to the
* first character to be displayed.
*/
if (wp->w_p_wrap)
v = wp->w_skipcol;
else
v = wp->w_leftcol;
if (v > 0)
{
#ifdef FEAT_MBYTE
char_u *prev_ptr = ptr;
#endif
while (vcol < v && *ptr != NUL)
{
c = win_lbr_chartabsize(wp, ptr, (colnr_T)vcol, NULL);
vcol += c;
#ifdef FEAT_MBYTE
prev_ptr = ptr;
#endif
mb_ptr_adv(ptr);
}
#if defined(FEAT_SYN_HL) || defined(FEAT_VIRTUALEDIT) || defined(FEAT_VISUAL)
/* When:
* - 'cuc' is set, or
* - 'colorcolumn' is set, or
* - 'virtualedit' is set, or
* - the visual mode is active,
* the end of the line may be before the start of the displayed part.
*/
if (vcol < v && (
# ifdef FEAT_SYN_HL
wp->w_p_cuc
|| draw_color_col
# if defined(FEAT_VIRTUALEDIT) || defined(FEAT_VISUAL)
||
# endif
# endif
# ifdef FEAT_VIRTUALEDIT
virtual_active()
# ifdef FEAT_VISUAL
||
# endif
# endif
# ifdef FEAT_VISUAL
(VIsual_active && wp->w_buffer == curwin->w_buffer)
# endif
))
{
vcol = v;
}
#endif
/* Handle a character that's not completely on the screen: Put ptr at
* that character but skip the first few screen characters. */
if (vcol > v)
{
vcol -= c;
#ifdef FEAT_MBYTE
ptr = prev_ptr;
#else
--ptr;
#endif
n_skip = v - vcol;
}
/*
* Adjust for when the inverted text is before the screen,
* and when the start of the inverted text is before the screen.
*/
if (tocol <= vcol)
fromcol = 0;
else if (fromcol >= 0 && fromcol < vcol)
fromcol = vcol;
#ifdef FEAT_LINEBREAK
/* When w_skipcol is non-zero, first line needs 'showbreak' */
if (wp->w_p_wrap)
need_showbreak = TRUE;
#endif
#ifdef FEAT_SPELL
/* When spell checking a word we need to figure out the start of the
* word and if it's badly spelled or not. */
if (has_spell)
{
int len;
colnr_T linecol = (colnr_T)(ptr - line);
hlf_T spell_hlf = HLF_COUNT;
pos = wp->w_cursor;
wp->w_cursor.lnum = lnum;
wp->w_cursor.col = linecol;
len = spell_move_to(wp, FORWARD, TRUE, TRUE, &spell_hlf);
/* spell_move_to() may call ml_get() and make "line" invalid */
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
ptr = line + linecol;
if (len == 0 || (int)wp->w_cursor.col > ptr - line)
{
/* no bad word found at line start, don't check until end of a
* word */
spell_hlf = HLF_COUNT;
word_end = (int)(spell_to_word_end(ptr, wp) - line + 1);
}
else
{
/* bad word found, use attributes until end of word */
word_end = wp->w_cursor.col + len + 1;
/* Turn index into actual attributes. */
if (spell_hlf != HLF_COUNT)
spell_attr = highlight_attr[spell_hlf];
}
wp->w_cursor = pos;
# ifdef FEAT_SYN_HL
/* Need to restart syntax highlighting for this line. */
if (has_syntax)
syntax_start(wp, lnum);
# endif
}
#endif
}
/*
* Correct highlighting for cursor that can't be disabled.
* Avoids having to check this for each character.
*/
if (fromcol >= 0)
{
if (noinvcur)
{
if ((colnr_T)fromcol == wp->w_virtcol)
{
/* highlighting starts at cursor, let it start just after the
* cursor */
fromcol_prev = fromcol;
fromcol = -1;
}
else if ((colnr_T)fromcol < wp->w_virtcol)
/* restart highlighting after the cursor */
fromcol_prev = wp->w_virtcol;
}
if (fromcol >= tocol)
fromcol = -1;
}
#ifdef FEAT_SEARCH_EXTRA
/*
* Handle highlighting the last used search pattern and matches.
* Do this for both search_hl and the match list.
*/
cur = wp->w_match_head;
shl_flag = FALSE;
while (cur != NULL || shl_flag == FALSE)
{
if (shl_flag == FALSE)
{
shl = &search_hl;
shl_flag = TRUE;
}
else
shl = &cur->hl;
shl->startcol = MAXCOL;
shl->endcol = MAXCOL;
shl->attr_cur = 0;
if (shl->rm.regprog != NULL)
{
v = (long)(ptr - line);
next_search_hl(wp, shl, lnum, (colnr_T)v);
/* Need to get the line again, a multi-line regexp may have made it
* invalid. */
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
ptr = line + v;
if (shl->lnum != 0 && shl->lnum <= lnum)
{
if (shl->lnum == lnum)
shl->startcol = shl->rm.startpos[0].col;
else
shl->startcol = 0;
if (lnum == shl->lnum + shl->rm.endpos[0].lnum
- shl->rm.startpos[0].lnum)
shl->endcol = shl->rm.endpos[0].col;
else
shl->endcol = MAXCOL;
/* Highlight one character for an empty match. */
if (shl->startcol == shl->endcol)
{
#ifdef FEAT_MBYTE
if (has_mbyte && line[shl->endcol] != NUL)
shl->endcol += (*mb_ptr2len)(line + shl->endcol);
else
#endif
++shl->endcol;
}
if ((long)shl->startcol < v) /* match at leftcol */
{
shl->attr_cur = shl->attr;
search_attr = shl->attr;
}
area_highlighting = TRUE;
}
}
if (shl != &search_hl && cur != NULL)
cur = cur->next;
}
#endif
#ifdef FEAT_SYN_HL
/* Cursor line highlighting for 'cursorline'. Not when Visual mode is
* active, because it's not clear what is selected then. */
if (wp->w_p_cul && lnum == wp->w_cursor.lnum && !VIsual_active)
{
line_attr = hl_attr(HLF_CUL);
area_highlighting = TRUE;
}
#endif
off = (unsigned)(current_ScreenLine - ScreenLines);
col = 0;
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
/* Rightleft window: process the text in the normal direction, but put
* it in current_ScreenLine[] from right to left. Start at the
* rightmost column of the window. */
col = W_WIDTH(wp) - 1;
off += col;
}
#endif
/*
* Repeat for the whole displayed line.
*/
for (;;)
{
/* Skip this quickly when working on the text. */
if (draw_state != WL_LINE)
{
#ifdef FEAT_CMDWIN
if (draw_state == WL_CMDLINE - 1 && n_extra == 0)
{
draw_state = WL_CMDLINE;
if (cmdwin_type != 0 && wp == curwin)
{
/* Draw the cmdline character. */
n_extra = 1;
c_extra = cmdwin_type;
char_attr = hl_attr(HLF_AT);
}
}
#endif
#ifdef FEAT_FOLDING
if (draw_state == WL_FOLD - 1 && n_extra == 0)
{
draw_state = WL_FOLD;
if (wp->w_p_fdc > 0)
{
/* Draw the 'foldcolumn'. */
fill_foldcolumn(extra, wp, FALSE, lnum);
n_extra = wp->w_p_fdc;
p_extra = extra;
p_extra[n_extra] = NUL;
c_extra = NUL;
char_attr = hl_attr(HLF_FC);
}
}
#endif
#ifdef FEAT_SIGNS
if (draw_state == WL_SIGN - 1 && n_extra == 0)
{
draw_state = WL_SIGN;
/* Show the sign column when there are any signs in this
* buffer or when using Netbeans. */
if (draw_signcolumn(wp)
# ifdef FEAT_DIFF
&& filler_todo <= 0
# endif
)
{
int text_sign;
# ifdef FEAT_SIGN_ICONS
int icon_sign;
# endif
/* Draw two cells with the sign value or blank. */
c_extra = ' ';
char_attr = hl_attr(HLF_SC);
n_extra = 2;
if (row == startrow)
{
text_sign = buf_getsigntype(wp->w_buffer, lnum,
SIGN_TEXT);
# ifdef FEAT_SIGN_ICONS
icon_sign = buf_getsigntype(wp->w_buffer, lnum,
SIGN_ICON);
if (gui.in_use && icon_sign != 0)
{
/* Use the image in this position. */
c_extra = SIGN_BYTE;
# ifdef FEAT_NETBEANS_INTG
if (buf_signcount(wp->w_buffer, lnum) > 1)
c_extra = MULTISIGN_BYTE;
# endif
char_attr = icon_sign;
}
else
# endif
if (text_sign != 0)
{
p_extra = sign_get_text(text_sign);
if (p_extra != NULL)
{
c_extra = NUL;
n_extra = (int)STRLEN(p_extra);
}
char_attr = sign_get_attr(text_sign, FALSE);
}
}
}
}
#endif
if (draw_state == WL_NR - 1 && n_extra == 0)
{
draw_state = WL_NR;
/* Display the absolute or relative line number. After the
* first fill with blanks when the 'n' flag isn't in 'cpo' */
if ((wp->w_p_nu || wp->w_p_rnu)
&& (row == startrow
#ifdef FEAT_DIFF
+ filler_lines
#endif
|| vim_strchr(p_cpo, CPO_NUMCOL) == NULL))
{
/* Draw the line number (empty space after wrapping). */
if (row == startrow
#ifdef FEAT_DIFF
+ filler_lines
#endif
)
{
long num;
if (wp->w_p_nu)
/* 'number' */
num = (long)lnum;
else
/* 'relativenumber', don't use negative numbers */
num = labs((long)get_cursor_rel_lnum(wp, lnum));
sprintf((char *)extra, "%*ld ",
number_width(wp), num);
if (wp->w_skipcol > 0)
for (p_extra = extra; *p_extra == ' '; ++p_extra)
*p_extra = '-';
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl) /* reverse line numbers */
rl_mirror(extra);
#endif
p_extra = extra;
c_extra = NUL;
}
else
c_extra = ' ';
n_extra = number_width(wp) + 1;
char_attr = hl_attr(HLF_N);
#ifdef FEAT_SYN_HL
/* When 'cursorline' is set highlight the line number of
* the current line differently.
* TODO: Can we use CursorLine instead of CursorLineNr
* when CursorLineNr isn't set? */
if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
char_attr = hl_attr(HLF_CLN);
#endif
}
}
#if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF)
if (draw_state == WL_SBR - 1 && n_extra == 0)
{
draw_state = WL_SBR;
# ifdef FEAT_DIFF
if (filler_todo > 0)
{
/* Draw "deleted" diff line(s). */
if (char2cells(fill_diff) > 1)
c_extra = '-';
else
c_extra = fill_diff;
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
n_extra = col + 1;
else
# endif
n_extra = W_WIDTH(wp) - col;
char_attr = hl_attr(HLF_DED);
}
# endif
# ifdef FEAT_LINEBREAK
if (*p_sbr != NUL && need_showbreak)
{
/* Draw 'showbreak' at the start of each broken line. */
p_extra = p_sbr;
c_extra = NUL;
n_extra = (int)STRLEN(p_sbr);
char_attr = hl_attr(HLF_AT);
need_showbreak = FALSE;
/* Correct end of highlighted area for 'showbreak',
* required when 'linebreak' is also set. */
if (tocol == vcol)
tocol += n_extra;
}
# endif
}
#endif
if (draw_state == WL_LINE - 1 && n_extra == 0)
{
draw_state = WL_LINE;
if (saved_n_extra)
{
/* Continue item from end of wrapped line. */
n_extra = saved_n_extra;
c_extra = saved_c_extra;
p_extra = saved_p_extra;
char_attr = saved_char_attr;
}
else
char_attr = 0;
}
}
/* When still displaying '$' of change command, stop at cursor */
if (dollar_vcol >= 0 && wp == curwin
&& lnum == wp->w_cursor.lnum && vcol >= (long)wp->w_virtcol
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
)
{
SCREEN_LINE(screen_row, W_WINCOL(wp), col, -(int)W_WIDTH(wp),
wp->w_p_rl);
/* Pretend we have finished updating the window. Except when
* 'cursorcolumn' is set. */
#ifdef FEAT_SYN_HL
if (wp->w_p_cuc)
row = wp->w_cline_row + wp->w_cline_height;
else
#endif
row = wp->w_height;
break;
}
if (draw_state == WL_LINE && area_highlighting)
{
/* handle Visual or match highlighting in this line */
if (vcol == fromcol
#ifdef FEAT_MBYTE
|| (has_mbyte && vcol + 1 == fromcol && n_extra == 0
&& (*mb_ptr2cells)(ptr) > 1)
#endif
|| ((int)vcol_prev == fromcol_prev
&& vcol_prev < vcol /* not at margin */
&& vcol < tocol))
area_attr = attr; /* start highlighting */
else if (area_attr != 0
&& (vcol == tocol
|| (noinvcur && (colnr_T)vcol == wp->w_virtcol)))
area_attr = 0; /* stop highlighting */
#ifdef FEAT_SEARCH_EXTRA
if (!n_extra)
{
/*
* Check for start/end of search pattern match.
* After end, check for start/end of next match.
* When another match, have to check for start again.
* Watch out for matching an empty string!
* Do this for 'search_hl' and the match list (ordered by
* priority).
*/
v = (long)(ptr - line);
cur = wp->w_match_head;
shl_flag = FALSE;
while (cur != NULL || shl_flag == FALSE)
{
if (shl_flag == FALSE
&& ((cur != NULL
&& cur->priority > SEARCH_HL_PRIORITY)
|| cur == NULL))
{
shl = &search_hl;
shl_flag = TRUE;
}
else
shl = &cur->hl;
while (shl->rm.regprog != NULL)
{
if (shl->startcol != MAXCOL
&& v >= (long)shl->startcol
&& v < (long)shl->endcol)
{
shl->attr_cur = shl->attr;
}
else if (v == (long)shl->endcol)
{
shl->attr_cur = 0;
next_search_hl(wp, shl, lnum, (colnr_T)v);
/* Need to get the line again, a multi-line regexp
* may have made it invalid. */
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
ptr = line + v;
if (shl->lnum == lnum)
{
shl->startcol = shl->rm.startpos[0].col;
if (shl->rm.endpos[0].lnum == 0)
shl->endcol = shl->rm.endpos[0].col;
else
shl->endcol = MAXCOL;
if (shl->startcol == shl->endcol)
{
/* highlight empty match, try again after
* it */
#ifdef FEAT_MBYTE
if (has_mbyte)
shl->endcol += (*mb_ptr2len)(line
+ shl->endcol);
else
#endif
++shl->endcol;
}
/* Loop to check if the match starts at the
* current position */
continue;
}
}
break;
}
if (shl != &search_hl && cur != NULL)
cur = cur->next;
}
/* Use attributes from match with highest priority among
* 'search_hl' and the match list. */
search_attr = search_hl.attr_cur;
cur = wp->w_match_head;
shl_flag = FALSE;
while (cur != NULL || shl_flag == FALSE)
{
if (shl_flag == FALSE
&& ((cur != NULL
&& cur->priority > SEARCH_HL_PRIORITY)
|| cur == NULL))
{
shl = &search_hl;
shl_flag = TRUE;
}
else
shl = &cur->hl;
if (shl->attr_cur != 0)
search_attr = shl->attr_cur;
if (shl != &search_hl && cur != NULL)
cur = cur->next;
}
}
#endif
#ifdef FEAT_DIFF
if (diff_hlf != (hlf_T)0)
{
if (diff_hlf == HLF_CHD && ptr - line >= change_start
&& n_extra == 0)
diff_hlf = HLF_TXD; /* changed text */
if (diff_hlf == HLF_TXD && ptr - line > change_end
&& n_extra == 0)
diff_hlf = HLF_CHD; /* changed line */
line_attr = hl_attr(diff_hlf);
}
#endif
/* Decide which of the highlight attributes to use. */
attr_pri = TRUE;
if (area_attr != 0)
char_attr = area_attr;
else if (search_attr != 0)
char_attr = search_attr;
#ifdef LINE_ATTR
/* Use line_attr when not in the Visual or 'incsearch' area
* (area_attr may be 0 when "noinvcur" is set). */
else if (line_attr != 0 && ((fromcol == -10 && tocol == MAXCOL)
|| vcol < fromcol || vcol_prev < fromcol_prev
|| vcol >= tocol))
char_attr = line_attr;
#endif
else
{
attr_pri = FALSE;
#ifdef FEAT_SYN_HL
if (has_syntax)
char_attr = syntax_attr;
else
#endif
char_attr = 0;
}
}
/*
* Get the next character to put on the screen.
*/
/*
* The "p_extra" points to the extra stuff that is inserted to
* represent special characters (non-printable stuff) and other
* things. When all characters are the same, c_extra is used.
* "p_extra" must end in a NUL to avoid mb_ptr2len() reads past
* "p_extra[n_extra]".
* For the '$' of the 'list' option, n_extra == 1, p_extra == "".
*/
if (n_extra > 0)
{
if (c_extra != NUL)
{
c = c_extra;
#ifdef FEAT_MBYTE
mb_c = c; /* doesn't handle non-utf-8 multi-byte! */
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE;
#endif
}
else
{
c = *p_extra;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
mb_c = c;
if (enc_utf8)
{
/* If the UTF-8 character is more than one byte:
* Decode it into "mb_c". */
mb_l = (*mb_ptr2len)(p_extra);
mb_utf8 = FALSE;
if (mb_l > n_extra)
mb_l = 1;
else if (mb_l > 1)
{
mb_c = utfc_ptr2char(p_extra, u8cc);
mb_utf8 = TRUE;
c = 0xc0;
}
}
else
{
/* if this is a DBCS character, put it in "mb_c" */
mb_l = MB_BYTE2LEN(c);
if (mb_l >= n_extra)
mb_l = 1;
else if (mb_l > 1)
mb_c = (c << 8) + p_extra[1];
}
if (mb_l == 0) /* at the NUL at end-of-line */
mb_l = 1;
/* If a double-width char doesn't fit display a '>' in the
* last column. */
if ((
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col <= 0) :
# endif
(col >= W_WIDTH(wp) - 1))
&& (*mb_char2cells)(mb_c) == 2)
{
c = '>';
mb_c = c;
mb_l = 1;
mb_utf8 = FALSE;
multi_attr = hl_attr(HLF_AT);
/* put the pointer back to output the double-width
* character at the start of the next line. */
++n_extra;
--p_extra;
}
else
{
n_extra -= mb_l - 1;
p_extra += mb_l - 1;
}
}
#endif
++p_extra;
}
--n_extra;
}
else
{
/*
* Get a character from the line itself.
*/
c = *ptr;
#ifdef FEAT_MBYTE
if (has_mbyte)
{
mb_c = c;
if (enc_utf8)
{
/* If the UTF-8 character is more than one byte: Decode it
* into "mb_c". */
mb_l = (*mb_ptr2len)(ptr);
mb_utf8 = FALSE;
if (mb_l > 1)
{
mb_c = utfc_ptr2char(ptr, u8cc);
/* Overlong encoded ASCII or ASCII with composing char
* is displayed normally, except a NUL. */
if (mb_c < 0x80)
c = mb_c;
mb_utf8 = TRUE;
/* At start of the line we can have a composing char.
* Draw it as a space with a composing char. */
if (utf_iscomposing(mb_c))
{
int i;
for (i = Screen_mco - 1; i > 0; --i)
u8cc[i] = u8cc[i - 1];
u8cc[0] = mb_c;
mb_c = ' ';
}
}
if ((mb_l == 1 && c >= 0x80)
|| (mb_l >= 1 && mb_c == 0)
|| (mb_l > 1 && (!vim_isprintc(mb_c)
# ifdef UNICODE16
|| mb_c >= 0x10000
# endif
)))
{
/*
* Illegal UTF-8 byte: display as <xx>.
* Non-BMP character : display as ? or fullwidth ?.
*/
# ifdef UNICODE16
if (mb_c < 0x10000)
# endif
{
transchar_hex(extra, mb_c);
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl) /* reverse */
rl_mirror(extra);
# endif
}
# ifdef UNICODE16
else if (utf_char2cells(mb_c) != 2)
STRCPY(extra, "?");
else
/* 0xff1f in UTF-8: full-width '?' */
STRCPY(extra, "\357\274\237");
# endif
p_extra = extra;
c = *p_extra;
mb_c = mb_ptr2char_adv(&p_extra);
mb_utf8 = (c >= 0x80);
n_extra = (int)STRLEN(p_extra);
c_extra = NUL;
if (area_attr == 0 && search_attr == 0)
{
n_attr = n_extra + 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
}
}
else if (mb_l == 0) /* at the NUL at end-of-line */
mb_l = 1;
#ifdef FEAT_ARABIC
else if (p_arshape && !p_tbidi && ARABIC_CHAR(mb_c))
{
/* Do Arabic shaping. */
int pc, pc1, nc;
int pcc[MAX_MCO];
/* The idea of what is the previous and next
* character depends on 'rightleft'. */
if (wp->w_p_rl)
{
pc = prev_c;
pc1 = prev_c1;
nc = utf_ptr2char(ptr + mb_l);
prev_c1 = u8cc[0];
}
else
{
pc = utfc_ptr2char(ptr + mb_l, pcc);
nc = prev_c;
pc1 = pcc[0];
}
prev_c = mb_c;
mb_c = arabic_shape(mb_c, &c, &u8cc[0], pc, pc1, nc);
}
else
prev_c = mb_c;
#endif
}
else /* enc_dbcs */
{
mb_l = MB_BYTE2LEN(c);
if (mb_l == 0) /* at the NUL at end-of-line */
mb_l = 1;
else if (mb_l > 1)
{
/* We assume a second byte below 32 is illegal.
* Hopefully this is OK for all double-byte encodings!
*/
if (ptr[1] >= 32)
mb_c = (c << 8) + ptr[1];
else
{
if (ptr[1] == NUL)
{
/* head byte at end of line */
mb_l = 1;
transchar_nonprint(extra, c);
}
else
{
/* illegal tail byte */
mb_l = 2;
STRCPY(extra, "XX");
}
p_extra = extra;
n_extra = (int)STRLEN(extra) - 1;
c_extra = NUL;
c = *p_extra++;
if (area_attr == 0 && search_attr == 0)
{
n_attr = n_extra + 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
}
mb_c = c;
}
}
}
/* If a double-width char doesn't fit display a '>' in the
* last column; the character is displayed at the start of the
* next line. */
if ((
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col <= 0) :
# endif
(col >= W_WIDTH(wp) - 1))
&& (*mb_char2cells)(mb_c) == 2)
{
c = '>';
mb_c = c;
mb_utf8 = FALSE;
mb_l = 1;
multi_attr = hl_attr(HLF_AT);
/* Put pointer back so that the character will be
* displayed at the start of the next line. */
--ptr;
}
else if (*ptr != NUL)
ptr += mb_l - 1;
/* If a double-width char doesn't fit at the left side display
* a '<' in the first column. Don't do this for unprintable
* charactes. */
if (n_skip > 0 && mb_l > 1 && n_extra == 0)
{
n_extra = 1;
c_extra = MB_FILLER_CHAR;
c = ' ';
if (area_attr == 0 && search_attr == 0)
{
n_attr = n_extra + 1;
extra_attr = hl_attr(HLF_AT);
saved_attr2 = char_attr; /* save current attr */
}
mb_c = c;
mb_utf8 = FALSE;
mb_l = 1;
}
}
#endif
++ptr;
/* 'list' : change char 160 to lcs_nbsp. */
if (wp->w_p_list && (c == 160
#ifdef FEAT_MBYTE
|| (mb_utf8 && mb_c == 160)
#endif
) && lcs_nbsp)
{
c = lcs_nbsp;
if (area_attr == 0 && search_attr == 0)
{
n_attr = 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
}
#ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE;
#endif
}
if (extra_check)
{
#ifdef FEAT_SPELL
int can_spell = TRUE;
#endif
#ifdef FEAT_SYN_HL
/* Get syntax attribute, unless still at the start of the line
* (double-wide char that doesn't fit). */
v = (long)(ptr - line);
if (has_syntax && v > 0)
{
/* Get the syntax attribute for the character. If there
* is an error, disable syntax highlighting. */
save_did_emsg = did_emsg;
did_emsg = FALSE;
syntax_attr = get_syntax_attr((colnr_T)v - 1,
# ifdef FEAT_SPELL
has_spell ? &can_spell :
# endif
NULL, FALSE);
if (did_emsg)
{
wp->w_s->b_syn_error = TRUE;
has_syntax = FALSE;
}
else
did_emsg = save_did_emsg;
/* Need to get the line again, a multi-line regexp may
* have made it invalid. */
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
ptr = line + v;
if (!attr_pri)
char_attr = syntax_attr;
else
char_attr = hl_combine_attr(syntax_attr, char_attr);
# ifdef FEAT_CONCEAL
/* no concealing past the end of the line, it interferes
* with line highlighting */
if (c == NUL)
syntax_flags = 0;
else
syntax_flags = get_syntax_info(&syntax_seqnr);
# endif
}
#endif
#ifdef FEAT_SPELL
/* Check spelling (unless at the end of the line).
* Only do this when there is no syntax highlighting, the
* @Spell cluster is not used or the current syntax item
* contains the @Spell cluster. */
if (has_spell && v >= word_end && v > cur_checked_col)
{
spell_attr = 0;
# ifdef FEAT_SYN_HL
if (!attr_pri)
char_attr = syntax_attr;
# endif
if (c != 0 && (
# ifdef FEAT_SYN_HL
!has_syntax ||
# endif
can_spell))
{
char_u *prev_ptr, *p;
int len;
hlf_T spell_hlf = HLF_COUNT;
# ifdef FEAT_MBYTE
if (has_mbyte)
{
prev_ptr = ptr - mb_l;
v -= mb_l - 1;
}
else
# endif
prev_ptr = ptr - 1;
/* Use nextline[] if possible, it has the start of the
* next line concatenated. */
if ((prev_ptr - line) - nextlinecol >= 0)
p = nextline + (prev_ptr - line) - nextlinecol;
else
p = prev_ptr;
cap_col -= (int)(prev_ptr - line);
len = spell_check(wp, p, &spell_hlf, &cap_col,
nochange);
word_end = v + len;
/* In Insert mode only highlight a word that
* doesn't touch the cursor. */
if (spell_hlf != HLF_COUNT
&& (State & INSERT) != 0
&& wp->w_cursor.lnum == lnum
&& wp->w_cursor.col >=
(colnr_T)(prev_ptr - line)
&& wp->w_cursor.col < (colnr_T)word_end)
{
spell_hlf = HLF_COUNT;
spell_redraw_lnum = lnum;
}
if (spell_hlf == HLF_COUNT && p != prev_ptr
&& (p - nextline) + len > nextline_idx)
{
/* Remember that the good word continues at the
* start of the next line. */
checked_lnum = lnum + 1;
checked_col = (int)((p - nextline) + len - nextline_idx);
}
/* Turn index into actual attributes. */
if (spell_hlf != HLF_COUNT)
spell_attr = highlight_attr[spell_hlf];
if (cap_col > 0)
{
if (p != prev_ptr
&& (p - nextline) + cap_col >= nextline_idx)
{
/* Remember that the word in the next line
* must start with a capital. */
capcol_lnum = lnum + 1;
cap_col = (int)((p - nextline) + cap_col
- nextline_idx);
}
else
/* Compute the actual column. */
cap_col += (int)(prev_ptr - line);
}
}
}
if (spell_attr != 0)
{
if (!attr_pri)
char_attr = hl_combine_attr(char_attr, spell_attr);
else
char_attr = hl_combine_attr(spell_attr, char_attr);
}
#endif
#ifdef FEAT_LINEBREAK
/*
* Found last space before word: check for line break.
*/
if (wp->w_p_lbr && vim_isbreak(c) && !vim_isbreak(*ptr)
&& !wp->w_p_list)
{
n_extra = win_lbr_chartabsize(wp, ptr - (
# ifdef FEAT_MBYTE
has_mbyte ? mb_l :
# endif
1), (colnr_T)vcol, NULL) - 1;
c_extra = ' ';
if (vim_iswhite(c))
c = ' ';
}
#endif
if (trailcol != MAXCOL && ptr > line + trailcol && c == ' ')
{
c = lcs_trail;
if (!attr_pri)
{
n_attr = 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
}
#ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE;
#endif
}
}
/*
* Handling of non-printable characters.
*/
if (!(chartab[c & 0xff] & CT_PRINT_CHAR))
{
/*
* when getting a character from the file, we may have to
* turn it into something else on the way to putting it
* into "ScreenLines".
*/
if (c == TAB && (!wp->w_p_list || lcs_tab1))
{
/* tab amount depends on current column */
n_extra = (int)wp->w_buffer->b_p_ts
- VCOL_HLC % (int)wp->w_buffer->b_p_ts - 1;
#ifdef FEAT_MBYTE
mb_utf8 = FALSE; /* don't draw as UTF-8 */
#endif
if (wp->w_p_list)
{
c = lcs_tab1;
c_extra = lcs_tab2;
n_attr = n_extra + 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
#ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
#endif
}
else
{
c_extra = ' ';
c = ' ';
}
}
else if (c == NUL
&& ((wp->w_p_list && lcs_eol > 0)
|| ((fromcol >= 0 || fromcol_prev >= 0)
&& tocol > vcol
#ifdef FEAT_VISUAL
&& VIsual_mode != Ctrl_V
#endif
&& (
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col >= 0) :
# endif
(col < W_WIDTH(wp)))
&& !(noinvcur
&& lnum == wp->w_cursor.lnum
&& (colnr_T)vcol == wp->w_virtcol)))
&& lcs_eol_one >= 0)
{
/* Display a '$' after the line or highlight an extra
* character if the line break is included. */
#if defined(FEAT_DIFF) || defined(LINE_ATTR)
/* For a diff line the highlighting continues after the
* "$". */
if (
# ifdef FEAT_DIFF
diff_hlf == (hlf_T)0
# ifdef LINE_ATTR
&&
# endif
# endif
# ifdef LINE_ATTR
line_attr == 0
# endif
)
#endif
{
#ifdef FEAT_VIRTUALEDIT
/* In virtualedit, visual selections may extend
* beyond end of line. */
if (area_highlighting && virtual_active()
&& tocol != MAXCOL && vcol < tocol)
n_extra = 0;
else
#endif
{
p_extra = at_end_str;
n_extra = 1;
c_extra = NUL;
}
}
if (wp->w_p_list)
c = lcs_eol;
else
c = ' ';
lcs_eol_one = -1;
--ptr; /* put it back at the NUL */
if (!attr_pri)
{
extra_attr = hl_attr(HLF_AT);
n_attr = 1;
}
#ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE; /* don't draw as UTF-8 */
#endif
}
else if (c != NUL)
{
p_extra = transchar(c);
#ifdef FEAT_RIGHTLEFT
if ((dy_flags & DY_UHEX) && wp->w_p_rl)
rl_mirror(p_extra); /* reverse "<12>" */
#endif
n_extra = byte2cells(c) - 1;
c_extra = NUL;
c = *p_extra++;
if (!attr_pri)
{
n_attr = n_extra + 1;
extra_attr = hl_attr(HLF_8);
saved_attr2 = char_attr; /* save current attr */
}
#ifdef FEAT_MBYTE
mb_utf8 = FALSE; /* don't draw as UTF-8 */
#endif
}
#ifdef FEAT_VIRTUALEDIT
else if (VIsual_active
&& (VIsual_mode == Ctrl_V
|| VIsual_mode == 'v')
&& virtual_active()
&& tocol != MAXCOL
&& vcol < tocol
&& (
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col >= 0) :
# endif
(col < W_WIDTH(wp))))
{
c = ' ';
--ptr; /* put it back at the NUL */
}
#endif
#if defined(LINE_ATTR)
else if ((
# ifdef FEAT_DIFF
diff_hlf != (hlf_T)0 ||
# endif
line_attr != 0
) && (
# ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col >= 0) :
# endif
(col
# ifdef FEAT_CONCEAL
- boguscols
# endif
< W_WIDTH(wp))))
{
/* Highlight until the right side of the window */
c = ' ';
--ptr; /* put it back at the NUL */
/* Remember we do the char for line highlighting. */
++did_line_attr;
/* don't do search HL for the rest of the line */
if (line_attr != 0 && char_attr == search_attr && col > 0)
char_attr = line_attr;
# ifdef FEAT_DIFF
if (diff_hlf == HLF_TXD)
{
diff_hlf = HLF_CHD;
if (attr == 0 || char_attr != attr)
char_attr = hl_attr(diff_hlf);
}
# endif
}
#endif
}
#ifdef FEAT_CONCEAL
if ( wp->w_p_cole > 0
&& (wp != curwin || lnum != wp->w_cursor.lnum ||
conceal_cursor_line(wp))
&& (syntax_flags & HL_CONCEAL) != 0
&& !(lnum_in_visual_area
&& vim_strchr(wp->w_p_cocu, 'v') == NULL))
{
char_attr = conceal_attr;
if (prev_syntax_id != syntax_seqnr
&& (syn_get_sub_char() != NUL || wp->w_p_cole == 1)
&& wp->w_p_cole != 3)
{
/* First time at this concealed item: display one
* character. */
if (syn_get_sub_char() != NUL)
c = syn_get_sub_char();
else if (lcs_conceal != NUL)
c = lcs_conceal;
else
c = ' ';
prev_syntax_id = syntax_seqnr;
if (n_extra > 0)
vcol_off += n_extra;
vcol += n_extra;
if (wp->w_p_wrap && n_extra > 0)
{
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
col -= n_extra;
boguscols -= n_extra;
}
else
# endif
{
boguscols += n_extra;
col += n_extra;
}
}
n_extra = 0;
n_attr = 0;
}
else if (n_skip == 0)
{
is_concealing = TRUE;
n_skip = 1;
}
# ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE; /* don't draw as UTF-8 */
# endif
}
else
{
prev_syntax_id = 0;
is_concealing = FALSE;
}
#endif /* FEAT_CONCEAL */
}
#ifdef FEAT_CONCEAL
/* In the cursor line and we may be concealing characters: correct
* the cursor column when we reach its position. */
if (!did_wcol && draw_state == WL_LINE
&& wp == curwin && lnum == wp->w_cursor.lnum
&& conceal_cursor_line(wp)
&& (int)wp->w_virtcol <= vcol + n_skip)
{
wp->w_wcol = col - boguscols;
wp->w_wrow = row;
did_wcol = TRUE;
}
#endif
/* Don't override visual selection highlighting. */
if (n_attr > 0
&& draw_state == WL_LINE
&& !attr_pri)
char_attr = extra_attr;
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
/* XIM don't send preedit_start and preedit_end, but they send
* preedit_changed and commit. Thus Vim can't set "im_is_active", use
* im_is_preediting() here. */
if (xic != NULL
&& lnum == wp->w_cursor.lnum
&& (State & INSERT)
&& !p_imdisable
&& im_is_preediting()
&& draw_state == WL_LINE)
{
colnr_T tcol;
if (preedit_end_col == MAXCOL)
getvcol(curwin, &(wp->w_cursor), &tcol, NULL, NULL);
else
tcol = preedit_end_col;
if ((long)preedit_start_col <= vcol && vcol < (long)tcol)
{
if (feedback_old_attr < 0)
{
feedback_col = 0;
feedback_old_attr = char_attr;
}
char_attr = im_get_feedback_attr(feedback_col);
if (char_attr < 0)
char_attr = feedback_old_attr;
feedback_col++;
}
else if (feedback_old_attr >= 0)
{
char_attr = feedback_old_attr;
feedback_old_attr = -1;
feedback_col = 0;
}
}
#endif
/*
* Handle the case where we are in column 0 but not on the first
* character of the line and the user wants us to show us a
* special character (via 'listchars' option "precedes:<char>".
*/
if (lcs_prec_todo != NUL
&& (wp->w_p_wrap ? wp->w_skipcol > 0 : wp->w_leftcol > 0)
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
&& draw_state > WL_NR
&& c != NUL)
{
c = lcs_prec;
lcs_prec_todo = NUL;
#ifdef FEAT_MBYTE
if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
{
/* Double-width character being overwritten by the "precedes"
* character, need to fill up half the character. */
c_extra = MB_FILLER_CHAR;
n_extra = 1;
n_attr = 2;
extra_attr = hl_attr(HLF_AT);
}
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE; /* don't draw as UTF-8 */
#endif
if (!attr_pri)
{
saved_attr3 = char_attr; /* save current attr */
char_attr = hl_attr(HLF_AT); /* later copied to char_attr */
n_attr3 = 1;
}
}
/*
* At end of the text line or just after the last character.
*/
if (c == NUL
#if defined(LINE_ATTR)
|| did_line_attr == 1
#endif
)
{
#ifdef FEAT_SEARCH_EXTRA
long prevcol = (long)(ptr - line) - (c == NUL);
/* we're not really at that column when skipping some text */
if ((long)(wp->w_p_wrap ? wp->w_skipcol : wp->w_leftcol) > prevcol)
++prevcol;
#endif
/* Invert at least one char, used for Visual and empty line or
* highlight match at end of line. If it's beyond the last
* char on the screen, just overwrite that one (tricky!) Not
* needed when a '$' was displayed for 'list'. */
#ifdef FEAT_SEARCH_EXTRA
prevcol_hl_flag = FALSE;
if (prevcol == (long)search_hl.startcol)
prevcol_hl_flag = TRUE;
else
{
cur = wp->w_match_head;
while (cur != NULL)
{
if (prevcol == (long)cur->hl.startcol)
{
prevcol_hl_flag = TRUE;
break;
}
cur = cur->next;
}
}
#endif
if (lcs_eol == lcs_eol_one
&& ((area_attr != 0 && vcol == fromcol
#ifdef FEAT_VISUAL
&& (VIsual_mode != Ctrl_V
|| lnum == VIsual.lnum
|| lnum == curwin->w_cursor.lnum)
#endif
&& c == NUL)
#ifdef FEAT_SEARCH_EXTRA
/* highlight 'hlsearch' match at end of line */
|| (prevcol_hl_flag == TRUE
# if defined(LINE_ATTR)
&& did_line_attr <= 1
# endif
)
#endif
))
{
int n = 0;
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
if (col < 0)
n = 1;
}
else
#endif
{
if (col >= W_WIDTH(wp))
n = -1;
}
if (n != 0)
{
/* At the window boundary, highlight the last character
* instead (better than nothing). */
off += n;
col += n;
}
else
{
/* Add a blank character to highlight. */
ScreenLines[off] = ' ';
#ifdef FEAT_MBYTE
if (enc_utf8)
ScreenLinesUC[off] = 0;
#endif
}
#ifdef FEAT_SEARCH_EXTRA
if (area_attr == 0)
{
/* Use attributes from match with highest priority among
* 'search_hl' and the match list. */
char_attr = search_hl.attr;
cur = wp->w_match_head;
shl_flag = FALSE;
while (cur != NULL || shl_flag == FALSE)
{
if (shl_flag == FALSE
&& ((cur != NULL
&& cur->priority > SEARCH_HL_PRIORITY)
|| cur == NULL))
{
shl = &search_hl;
shl_flag = TRUE;
}
else
shl = &cur->hl;
if ((ptr - line) - 1 == (long)shl->startcol)
char_attr = shl->attr;
if (shl != &search_hl && cur != NULL)
cur = cur->next;
}
}
#endif
ScreenAttrs[off] = char_attr;
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
--col;
--off;
}
else
#endif
{
++col;
++off;
}
++vcol;
#ifdef FEAT_SYN_HL
eol_hl_off = 1;
#endif
}
}
/*
* At end of the text line.
*/
if (c == NUL)
{
#ifdef FEAT_SYN_HL
if (eol_hl_off > 0 && vcol - eol_hl_off == (long)wp->w_virtcol
&& lnum == wp->w_cursor.lnum)
{
/* highlight last char after line */
--col;
--off;
--vcol;
}
/* Highlight 'cursorcolumn' & 'colorcolumn' past end of the line. */
if (wp->w_p_wrap)
v = wp->w_skipcol;
else
v = wp->w_leftcol;
/* check if line ends before left margin */
if (vcol < v + col - win_col_off(wp))
vcol = v + col - win_col_off(wp);
#ifdef FEAT_CONCEAL
/* Get rid of the boguscols now, we want to draw until the right
* edge for 'cursorcolumn'. */
col -= boguscols;
boguscols = 0;
#endif
if (draw_color_col)
draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
if (((wp->w_p_cuc
&& (int)wp->w_virtcol >= VCOL_HLC - eol_hl_off
&& (int)wp->w_virtcol <
W_WIDTH(wp) * (row - startrow + 1) + v
&& lnum != wp->w_cursor.lnum)
|| draw_color_col)
# ifdef FEAT_RIGHTLEFT
&& !wp->w_p_rl
# endif
)
{
int rightmost_vcol = 0;
int i;
if (wp->w_p_cuc)
rightmost_vcol = wp->w_virtcol;
if (draw_color_col)
/* determine rightmost colorcolumn to possibly draw */
for (i = 0; color_cols[i] >= 0; ++i)
if (rightmost_vcol < color_cols[i])
rightmost_vcol = color_cols[i];
while (col < W_WIDTH(wp))
{
ScreenLines[off] = ' ';
#ifdef FEAT_MBYTE
if (enc_utf8)
ScreenLinesUC[off] = 0;
#endif
++col;
if (draw_color_col)
draw_color_col = advance_color_col(VCOL_HLC,
&color_cols);
if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol)
ScreenAttrs[off++] = hl_attr(HLF_CUC);
else if (draw_color_col && VCOL_HLC == *color_cols)
ScreenAttrs[off++] = hl_attr(HLF_MC);
else
ScreenAttrs[off++] = 0;
if (VCOL_HLC >= rightmost_vcol)
break;
++vcol;
}
}
#endif
SCREEN_LINE(screen_row, W_WINCOL(wp), col,
(int)W_WIDTH(wp), wp->w_p_rl);
row++;
/*
* Update w_cline_height and w_cline_folded if the cursor line was
* updated (saves a call to plines() later).
*/
if (wp == curwin && lnum == curwin->w_cursor.lnum)
{
curwin->w_cline_row = startrow;
curwin->w_cline_height = row - startrow;
#ifdef FEAT_FOLDING
curwin->w_cline_folded = FALSE;
#endif
curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW);
}
break;
}
/* line continues beyond line end */
if (lcs_ext
&& !wp->w_p_wrap
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
&& (
#ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? col == 0 :
#endif
col == W_WIDTH(wp) - 1)
&& (*ptr != NUL
|| (wp->w_p_list && lcs_eol_one > 0)
|| (n_extra && (c_extra != NUL || *p_extra != NUL))))
{
c = lcs_ext;
char_attr = hl_attr(HLF_AT);
#ifdef FEAT_MBYTE
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1)
{
mb_utf8 = TRUE;
u8cc[0] = 0;
c = 0xc0;
}
else
mb_utf8 = FALSE;
#endif
}
#ifdef FEAT_SYN_HL
/* advance to the next 'colorcolumn' */
if (draw_color_col)
draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
/* Highlight the cursor column if 'cursorcolumn' is set. But don't
* highlight the cursor position itself.
* Also highlight the 'colorcolumn' if it is different than
* 'cursorcolumn' */
vcol_save_attr = -1;
if (draw_state == WL_LINE && !lnum_in_visual_area)
{
if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol
&& lnum != wp->w_cursor.lnum)
{
vcol_save_attr = char_attr;
char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUC));
}
else if (draw_color_col && VCOL_HLC == *color_cols)
{
vcol_save_attr = char_attr;
char_attr = hl_combine_attr(char_attr, hl_attr(HLF_MC));
}
}
#endif
/*
* Store character to be displayed.
* Skip characters that are left of the screen for 'nowrap'.
*/
vcol_prev = vcol;
if (draw_state < WL_LINE || n_skip <= 0)
{
/*
* Store the character.
*/
#if defined(FEAT_RIGHTLEFT) && defined(FEAT_MBYTE)
if (has_mbyte && wp->w_p_rl && (*mb_char2cells)(mb_c) > 1)
{
/* A double-wide character is: put first halve in left cell. */
--off;
--col;
}
#endif
ScreenLines[off] = c;
#ifdef FEAT_MBYTE
if (enc_dbcs == DBCS_JPNU)
{
if ((mb_c & 0xff00) == 0x8e00)
ScreenLines[off] = 0x8e;
ScreenLines2[off] = mb_c & 0xff;
}
else if (enc_utf8)
{
if (mb_utf8)
{
int i;
ScreenLinesUC[off] = mb_c;
if ((c & 0xff) == 0)
ScreenLines[off] = 0x80; /* avoid storing zero */
for (i = 0; i < Screen_mco; ++i)
{
ScreenLinesC[i][off] = u8cc[i];
if (u8cc[i] == 0)
break;
}
}
else
ScreenLinesUC[off] = 0;
}
if (multi_attr)
{
ScreenAttrs[off] = multi_attr;
multi_attr = 0;
}
else
#endif
ScreenAttrs[off] = char_attr;
#ifdef FEAT_MBYTE
if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
{
/* Need to fill two screen columns. */
++off;
++col;
if (enc_utf8)
/* UTF-8: Put a 0 in the second screen char. */
ScreenLines[off] = 0;
else
/* DBCS: Put second byte in the second screen char. */
ScreenLines[off] = mb_c & 0xff;
++vcol;
/* When "tocol" is halfway a character, set it to the end of
* the character, otherwise highlighting won't stop. */
if (tocol == vcol)
++tocol;
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
/* now it's time to backup one cell */
--off;
--col;
}
#endif
}
#endif
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
--off;
--col;
}
else
#endif
{
++off;
++col;
}
}
#ifdef FEAT_CONCEAL
else if (wp->w_p_cole > 0 && is_concealing)
{
--n_skip;
++vcol_off;
if (n_extra > 0)
vcol_off += n_extra;
if (wp->w_p_wrap)
{
/*
* Special voodoo required if 'wrap' is on.
*
* Advance the column indicator to force the line
* drawing to wrap early. This will make the line
* take up the same screen space when parts are concealed,
* so that cursor line computations aren't messed up.
*
* To avoid the fictitious advance of 'col' causing
* trailing junk to be written out of the screen line
* we are building, 'boguscols' keeps track of the number
* of bad columns we have advanced.
*/
if (n_extra > 0)
{
vcol += n_extra;
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
col -= n_extra;
boguscols -= n_extra;
}
else
# endif
{
col += n_extra;
boguscols += n_extra;
}
n_extra = 0;
n_attr = 0;
}
# ifdef FEAT_MBYTE
if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
{
/* Need to fill two screen columns. */
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
--boguscols;
--col;
}
else
# endif
{
++boguscols;
++col;
}
}
# endif
# ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
--boguscols;
--col;
}
else
# endif
{
++boguscols;
++col;
}
}
else
{
if (n_extra > 0)
{
vcol += n_extra;
n_extra = 0;
n_attr = 0;
}
}
}
#endif /* FEAT_CONCEAL */
else
--n_skip;
/* Only advance the "vcol" when after the 'number' or 'relativenumber'
* column. */
if (draw_state > WL_NR
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
)
++vcol;
#ifdef FEAT_SYN_HL
if (vcol_save_attr >= 0)
char_attr = vcol_save_attr;
#endif
/* restore attributes after "predeces" in 'listchars' */
if (draw_state > WL_NR && n_attr3 > 0 && --n_attr3 == 0)
char_attr = saved_attr3;
/* restore attributes after last 'listchars' or 'number' char */
if (n_attr > 0 && draw_state == WL_LINE && --n_attr == 0)
char_attr = saved_attr2;
/*
* At end of screen line and there is more to come: Display the line
* so far. If there is no more to display it is caught above.
*/
if ((
#ifdef FEAT_RIGHTLEFT
wp->w_p_rl ? (col < 0) :
#endif
(col >= W_WIDTH(wp)))
&& (*ptr != NUL
#ifdef FEAT_DIFF
|| filler_todo > 0
#endif
|| (wp->w_p_list && lcs_eol != NUL && p_extra != at_end_str)
|| (n_extra != 0 && (c_extra != NUL || *p_extra != NUL)))
)
{
#ifdef FEAT_CONCEAL
SCREEN_LINE(screen_row, W_WINCOL(wp), col - boguscols,
(int)W_WIDTH(wp), wp->w_p_rl);
boguscols = 0;
#else
SCREEN_LINE(screen_row, W_WINCOL(wp), col,
(int)W_WIDTH(wp), wp->w_p_rl);
#endif
++row;
++screen_row;
/* When not wrapping and finished diff lines, or when displayed
* '$' and highlighting until last column, break here. */
if ((!wp->w_p_wrap
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
) || lcs_eol_one == -1)
break;
/* When the window is too narrow draw all "@" lines. */
if (draw_state != WL_LINE
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
)
{
win_draw_end(wp, '@', ' ', row, wp->w_height, HLF_AT);
#ifdef FEAT_VERTSPLIT
draw_vsep_win(wp, row);
#endif
row = endrow;
}
/* When line got too long for screen break here. */
if (row == endrow)
{
++row;
break;
}
if (screen_cur_row == screen_row - 1
#ifdef FEAT_DIFF
&& filler_todo <= 0
#endif
&& W_WIDTH(wp) == Columns)
{
/* Remember that the line wraps, used for modeless copy. */
LineWraps[screen_row - 1] = TRUE;
/*
* Special trick to make copy/paste of wrapped lines work with
* xterm/screen: write an extra character beyond the end of
* the line. This will work with all terminal types
* (regardless of the xn,am settings).
* Only do this on a fast tty.
* Only do this if the cursor is on the current line
* (something has been written in it).
* Don't do this for the GUI.
* Don't do this for double-width characters.
* Don't do this for a window not at the right screen border.
*/
if (p_tf
#ifdef FEAT_GUI
&& !gui.in_use
#endif
#ifdef FEAT_MBYTE
&& !(has_mbyte
&& ((*mb_off2cells)(LineOffset[screen_row],
LineOffset[screen_row] + screen_Columns)
== 2
|| (*mb_off2cells)(LineOffset[screen_row - 1]
+ (int)Columns - 2,
LineOffset[screen_row] + screen_Columns)
== 2))
#endif
)
{
/* First make sure we are at the end of the screen line,
* then output the same character again to let the
* terminal know about the wrap. If the terminal doesn't
* auto-wrap, we overwrite the character. */
if (screen_cur_col != W_WIDTH(wp))
screen_char(LineOffset[screen_row - 1]
+ (unsigned)Columns - 1,
screen_row - 1, (int)(Columns - 1));
#ifdef FEAT_MBYTE
/* When there is a multi-byte character, just output a
* space to keep it simple. */
if (has_mbyte && MB_BYTE2LEN(ScreenLines[LineOffset[
screen_row - 1] + (Columns - 1)]) > 1)
out_char(' ');
else
#endif
out_char(ScreenLines[LineOffset[screen_row - 1]
+ (Columns - 1)]);
/* force a redraw of the first char on the next line */
ScreenAttrs[LineOffset[screen_row]] = (sattr_T)-1;
screen_start(); /* don't know where cursor is now */
}
}
col = 0;
off = (unsigned)(current_ScreenLine - ScreenLines);
#ifdef FEAT_RIGHTLEFT
if (wp->w_p_rl)
{
col = W_WIDTH(wp) - 1; /* col is not used if breaking! */
off += col;
}
#endif
/* reset the drawing state for the start of a wrapped line */
draw_state = WL_START;
saved_n_extra = n_extra;
saved_p_extra = p_extra;
saved_c_extra = c_extra;
saved_char_attr = char_attr;
n_extra = 0;
lcs_prec_todo = lcs_prec;
#ifdef FEAT_LINEBREAK
# ifdef FEAT_DIFF
if (filler_todo <= 0)
# endif
need_showbreak = TRUE;
#endif
#ifdef FEAT_DIFF
--filler_todo;
/* When the filler lines are actually below the last line of the
* file, don't draw the line itself, break here. */
if (filler_todo == 0 && wp->w_botfill)
break;
#endif
}
} /* for every character in the line */
#ifdef FEAT_SPELL
/* After an empty line check first word for capital. */
if (*skipwhite(line) == NUL)
{
capcol_lnum = lnum + 1;
cap_col = 0;
}
#endif
return row;
}
#ifdef FEAT_MBYTE
static int comp_char_differs __ARGS((int, int));
/*
* Return if the composing characters at "off_from" and "off_to" differ.
* Only to be used when ScreenLinesUC[off_from] != 0.
*/
static int
comp_char_differs(off_from, off_to)
int off_from;
int off_to;
{
int i;
for (i = 0; i < Screen_mco; ++i)
{
if (ScreenLinesC[i][off_from] != ScreenLinesC[i][off_to])
return TRUE;
if (ScreenLinesC[i][off_from] == 0)
break;
}
return FALSE;
}
#endif
/*
* Check whether the given character needs redrawing:
* - the (first byte of the) character is different
* - the attributes are different
* - the character is multi-byte and the next byte is different
* - the character is two cells wide and the second cell differs.
*/
static int
char_needs_redraw(off_from, off_to, cols)
int off_from;
int off_to;
int cols;
{
if (cols > 0
&& ((ScreenLines[off_from] != ScreenLines[off_to]
|| ScreenAttrs[off_from] != ScreenAttrs[off_to])
#ifdef FEAT_MBYTE
|| (enc_dbcs != 0
&& MB_BYTE2LEN(ScreenLines[off_from]) > 1
&& (enc_dbcs == DBCS_JPNU && ScreenLines[off_from] == 0x8e
? ScreenLines2[off_from] != ScreenLines2[off_to]
: (cols > 1 && ScreenLines[off_from + 1]
!= ScreenLines[off_to + 1])))
|| (enc_utf8
&& (ScreenLinesUC[off_from] != ScreenLinesUC[off_to]
|| (ScreenLinesUC[off_from] != 0
&& comp_char_differs(off_from, off_to))
|| (cols > 1 && ScreenLines[off_from + 1]
!= ScreenLines[off_to + 1])))
#endif
))
return TRUE;
return FALSE;
}
/*
* Move one "cooked" screen line to the screen, but only the characters that
* have actually changed. Handle insert/delete character.
* "coloff" gives the first column on the screen for this line.
* "endcol" gives the columns where valid characters are.
* "clear_width" is the width of the window. It's > 0 if the rest of the line
* needs to be cleared, negative otherwise.
* "rlflag" is TRUE in a rightleft window:
* When TRUE and "clear_width" > 0, clear columns 0 to "endcol"
* When FALSE and "clear_width" > 0, clear columns "endcol" to "clear_width"
*/
static void
screen_line(row, coloff, endcol, clear_width
#ifdef FEAT_RIGHTLEFT
, rlflag
#endif
)
int row;
int coloff;
int endcol;
int clear_width;
#ifdef FEAT_RIGHTLEFT
int rlflag;
#endif
{
unsigned off_from;
unsigned off_to;
#ifdef FEAT_MBYTE
unsigned max_off_from;
unsigned max_off_to;
#endif
int col = 0;
#if defined(FEAT_GUI) || defined(UNIX) || defined(FEAT_VERTSPLIT)
int hl;
#endif
int force = FALSE; /* force update rest of the line */
int redraw_this /* bool: does character need redraw? */
#ifdef FEAT_GUI
= TRUE /* For GUI when while-loop empty */
#endif
;
int redraw_next; /* redraw_this for next character */
#ifdef FEAT_MBYTE
int clear_next = FALSE;
int char_cells; /* 1: normal char */
/* 2: occupies two display cells */
# define CHAR_CELLS char_cells
#else
# define CHAR_CELLS 1
#endif
/* Check for illegal row and col, just in case. */
if (row >= Rows)
row = Rows - 1;
if (endcol > Columns)
endcol = Columns;
# ifdef FEAT_CLIPBOARD
clip_may_clear_selection(row, row);
# endif
off_from = (unsigned)(current_ScreenLine - ScreenLines);
off_to = LineOffset[row] + coloff;
#ifdef FEAT_MBYTE
max_off_from = off_from + screen_Columns;
max_off_to = LineOffset[row] + screen_Columns;
#endif
#ifdef FEAT_RIGHTLEFT
if (rlflag)
{
/* Clear rest first, because it's left of the text. */
if (clear_width > 0)
{
while (col <= endcol && ScreenLines[off_to] == ' '
&& ScreenAttrs[off_to] == 0
# ifdef FEAT_MBYTE
&& (!enc_utf8 || ScreenLinesUC[off_to] == 0)
# endif
)
{
++off_to;
++col;
}
if (col <= endcol)
screen_fill(row, row + 1, col + coloff,
endcol + coloff + 1, ' ', ' ', 0);
}
col = endcol + 1;
off_to = LineOffset[row] + col + coloff;
off_from += col;
endcol = (clear_width > 0 ? clear_width : -clear_width);
}
#endif /* FEAT_RIGHTLEFT */
redraw_next = char_needs_redraw(off_from, off_to, endcol - col);
while (col < endcol)
{
#ifdef FEAT_MBYTE
if (has_mbyte && (col + 1 < endcol))
char_cells = (*mb_off2cells)(off_from, max_off_from);
else
char_cells = 1;
#endif
redraw_this = redraw_next;
redraw_next = force || char_needs_redraw(off_from + CHAR_CELLS,
off_to + CHAR_CELLS, endcol - col - CHAR_CELLS);
#ifdef FEAT_GUI
/* If the next character was bold, then redraw the current character to
* remove any pixels that might have spilt over into us. This only
* happens in the GUI.
*/
if (redraw_next && gui.in_use)
{
hl = ScreenAttrs[off_to + CHAR_CELLS];
if (hl > HL_ALL)
hl = syn_attr2attr(hl);
if (hl & HL_BOLD)
redraw_this = TRUE;
}
#endif
if (redraw_this)
{
/*
* Special handling when 'xs' termcap flag set (hpterm):
* Attributes for characters are stored at the position where the
* cursor is when writing the highlighting code. The
* start-highlighting code must be written with the cursor on the
* first highlighted character. The stop-highlighting code must
* be written with the cursor just after the last highlighted
* character.
* Overwriting a character doesn't remove it's highlighting. Need
* to clear the rest of the line, and force redrawing it
* completely.
*/
if ( p_wiv
&& !force
#ifdef FEAT_GUI
&& !gui.in_use
#endif
&& ScreenAttrs[off_to] != 0
&& ScreenAttrs[off_from] != ScreenAttrs[off_to])
{
/*
* Need to remove highlighting attributes here.
*/
windgoto(row, col + coloff);
out_str(T_CE); /* clear rest of this screen line */
screen_start(); /* don't know where cursor is now */
force = TRUE; /* force redraw of rest of the line */
redraw_next = TRUE; /* or else next char would miss out */
/*
* If the previous character was highlighted, need to stop
* highlighting at this character.
*/
if (col + coloff > 0 && ScreenAttrs[off_to - 1] != 0)
{
screen_attr = ScreenAttrs[off_to - 1];
term_windgoto(row, col + coloff);
screen_stop_highlight();
}
else
screen_attr = 0; /* highlighting has stopped */
}
#ifdef FEAT_MBYTE
if (enc_dbcs != 0)
{
/* Check if overwriting a double-byte with a single-byte or
* the other way around requires another character to be
* redrawn. For UTF-8 this isn't needed, because comparing
* ScreenLinesUC[] is sufficient. */
if (char_cells == 1
&& col + 1 < endcol
&& (*mb_off2cells)(off_to, max_off_to) > 1)
{
/* Writing a single-cell character over a double-cell
* character: need to redraw the next cell. */
ScreenLines[off_to + 1] = 0;
redraw_next = TRUE;
}
else if (char_cells == 2
&& col + 2 < endcol
&& (*mb_off2cells)(off_to, max_off_to) == 1
&& (*mb_off2cells)(off_to + 1, max_off_to) > 1)
{
/* Writing the second half of a double-cell character over
* a double-cell character: need to redraw the second
* cell. */
ScreenLines[off_to + 2] = 0;
redraw_next = TRUE;
}
if (enc_dbcs == DBCS_JPNU)
ScreenLines2[off_to] = ScreenLines2[off_from];
}
/* When writing a single-width character over a double-width
* character and at the end of the redrawn text, need to clear out
* the right halve of the old character.
* Also required when writing the right halve of a double-width
* char over the left halve of an existing one. */
if (has_mbyte && col + char_cells == endcol
&& ((char_cells == 1
&& (*mb_off2cells)(off_to, max_off_to) > 1)
|| (char_cells == 2
&& (*mb_off2cells)(off_to, max_off_to) == 1
&& (*mb_off2cells)(off_to + 1, max_off_to) > 1)))
clear_next = TRUE;
#endif
ScreenLines[off_to] = ScreenLines[off_from];
#ifdef FEAT_MBYTE
if (enc_utf8)
{
ScreenLinesUC[off_to] = ScreenLinesUC[off_from];
if (ScreenLinesUC[off_from] != 0)
{
int i;
for (i = 0; i < Screen_mco; ++i)
ScreenLinesC[i][off_to] = ScreenLinesC[i][off_from];
}
}
if (char_cells == 2)
ScreenLines[off_to + 1] = ScreenLines[off_from + 1];
#endif
#if defined(FEAT_GUI) || defined(UNIX)
/* The bold trick makes a single column of pixels appear in the
* next character. When a bold character is removed, the next
* character should be redrawn too. This happens for our own GUI
* and for some xterms. */
if (
# ifdef FEAT_GUI
gui.in_use
# endif
# if defined(FEAT_GUI) && defined(UNIX)
||
# endif
# ifdef UNIX
term_is_xterm
# endif
)
{
hl = ScreenAttrs[off_to];
if (hl > HL_ALL)
hl = syn_attr2attr(hl);
if (hl & HL_BOLD)
redraw_next = TRUE;
}
#endif
ScreenAttrs[off_to] = ScreenAttrs[off_from];
#ifdef FEAT_MBYTE
/* For simplicity set the attributes of second half of a
* double-wide character equal to the first half. */
if (char_cells == 2)
ScreenAttrs[off_to + 1] = ScreenAttrs[off_from];
if (enc_dbcs != 0 && char_cells == 2)
screen_char_2(off_to, row, col + coloff);
else
#endif
screen_char(off_to, row, col + coloff);
}
else if ( p_wiv
#ifdef FEAT_GUI
&& !gui.in_use
#endif
&& col + coloff > 0)
{
if (ScreenAttrs[off_to] == ScreenAttrs[off_to - 1])
{
/*
* Don't output stop-highlight when moving the cursor, it will
* stop the highlighting when it should continue.
*/
screen_attr = 0;
}
else if (screen_attr != 0)
screen_stop_highlight();
}
off_to += CHAR_CELLS;
off_from += CHAR_CELLS;
col += CHAR_CELLS;
}
#ifdef FEAT_MBYTE
if (clear_next)
{
/* Clear the second half of a double-wide character of which the left
* half was overwritten with a single-wide character. */
ScreenLines[off_to] = ' ';
if (enc_utf8)
ScreenLinesUC[off_to] = 0;
screen_char(off_to, row, col + coloff);
}
#endif
if (clear_width > 0
#ifdef FEAT_RIGHTLEFT
&& !rlflag
#endif
)
{
#ifdef FEAT_GUI
int startCol = col;
#endif
/* blank out the rest of the line */
while (col < clear_width && ScreenLines[off_to] == ' '
&& ScreenAttrs[off_to] == 0
#ifdef FEAT_MBYTE
&& (!enc_utf8 || ScreenLinesUC[off_to] == 0)
#endif
)
{
++off_to;
++col;
}
if (col < clear_width)
{
#ifdef FEAT_GUI
/*
* In the GUI, clearing the rest of the line may leave pixels
* behind if the first character cleared was bold. Some bold
* fonts spill over the left. In this case we redraw the previous
* character too. If we didn't skip any blanks above, then we
* only redraw if the character wasn't already redrawn anyway.
*/
if (gui.in_use && (col > startCol || !redraw_this))
{
hl = ScreenAttrs[off_to];
if (hl > HL_ALL || (hl & HL_BOLD))
{
int prev_cells = 1;
# ifdef FEAT_MBYTE
if (enc_utf8)
/* for utf-8, ScreenLines[char_offset + 1] == 0 means
* that its width is 2. */
prev_cells = ScreenLines[off_to - 1] == 0 ? 2 : 1;
else if (enc_dbcs != 0)
{
/* find previous character by counting from first
* column and get its width. */
unsigned off = LineOffset[row];
unsigned max_off = LineOffset[row] + screen_Columns;
while (off < off_to)
{
prev_cells = (*mb_off2cells)(off, max_off);
off += prev_cells;
}
}
if (enc_dbcs != 0 && prev_cells > 1)
screen_char_2(off_to - prev_cells, row,
col + coloff - prev_cells);
else
# endif
screen_char(off_to - prev_cells, row,
col + coloff - prev_cells);
}
}
#endif
screen_fill(row, row + 1, col + coloff, clear_width + coloff,
' ', ' ', 0);
#ifdef FEAT_VERTSPLIT
off_to += clear_width - col;
col = clear_width;
#endif
}
}
if (clear_width > 0)
{
#ifdef FEAT_VERTSPLIT
/* For a window that's left of another, draw the separator char. */
if (col + coloff < Columns)
{
int c;
c = fillchar_vsep(&hl);
if (ScreenLines[off_to] != c
# ifdef FEAT_MBYTE
|| (enc_utf8 && (int)ScreenLinesUC[off_to]
!= (c >= 0x80 ? c : 0))
# endif
|| ScreenAttrs[off_to] != hl)
{
ScreenLines[off_to] = c;
ScreenAttrs[off_to] = hl;
# ifdef FEAT_MBYTE
if (enc_utf8)
{
if (c >= 0x80)
{
ScreenLinesUC[off_to] = c;
ScreenLinesC[0][off_to] = 0;
}
else
ScreenLinesUC[off_to] = 0;
}
# endif
screen_char(off_to, row, col + coloff);
}
}
else
#endif
LineWraps[row] = FALSE;
}
}
#if defined(FEAT_RIGHTLEFT) || defined(PROTO)
/*
* Mirror text "str" for right-left displaying.
* Only works for single-byte characters (e.g., numbers).
*/
void
rl_mirror(str)
char_u *str;
{
char_u *p1, *p2;
int t;
for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2)
{
t = *p1;
*p1 = *p2;
*p2 = t;
}
}
#endif
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* mark all status lines for redraw; used after first :cd
*/
void
status_redraw_all()
{
win_T *wp;
for (wp = firstwin; wp; wp = wp->w_next)
if (wp->w_status_height)
{
wp->w_redr_status = TRUE;
redraw_later(VALID);
}
}
/*
* mark all status lines of the current buffer for redraw
*/
void
status_redraw_curbuf()
{
win_T *wp;
for (wp = firstwin; wp; wp = wp->w_next)
if (wp->w_status_height != 0 && wp->w_buffer == curbuf)
{
wp->w_redr_status = TRUE;
redraw_later(VALID);
}
}
/*
* Redraw all status lines that need to be redrawn.
*/
void
redraw_statuslines()
{
win_T *wp;
for (wp = firstwin; wp; wp = wp->w_next)
if (wp->w_redr_status)
win_redr_status(wp);
if (redraw_tabline)
draw_tabline();
}
#endif
#if (defined(FEAT_WILDMENU) && defined(FEAT_VERTSPLIT)) || defined(PROTO)
/*
* Redraw all status lines at the bottom of frame "frp".
*/
void
win_redraw_last_status(frp)
frame_T *frp;
{
if (frp->fr_layout == FR_LEAF)
frp->fr_win->w_redr_status = TRUE;
else if (frp->fr_layout == FR_ROW)
{
for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
win_redraw_last_status(frp);
}
else /* frp->fr_layout == FR_COL */
{
frp = frp->fr_child;
while (frp->fr_next != NULL)
frp = frp->fr_next;
win_redraw_last_status(frp);
}
}
#endif
#ifdef FEAT_VERTSPLIT
/*
* Draw the verticap separator right of window "wp" starting with line "row".
*/
static void
draw_vsep_win(wp, row)
win_T *wp;
int row;
{
int hl;
int c;
if (wp->w_vsep_width)
{
/* draw the vertical separator right of this window */
c = fillchar_vsep(&hl);
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
W_ENDCOL(wp), W_ENDCOL(wp) + 1,
c, ' ', hl);
}
}
#endif
#ifdef FEAT_WILDMENU
static int status_match_len __ARGS((expand_T *xp, char_u *s));
static int skip_status_match_char __ARGS((expand_T *xp, char_u *s));
/*
* Get the length of an item as it will be shown in the status line.
*/
static int
status_match_len(xp, s)
expand_T *xp;
char_u *s;
{
int len = 0;
#ifdef FEAT_MENU
int emenu = (xp->xp_context == EXPAND_MENUS
|| xp->xp_context == EXPAND_MENUNAMES);
/* Check for menu separators - replace with '|'. */
if (emenu && menu_is_separator(s))
return 1;
#endif
while (*s != NUL)
{
s += skip_status_match_char(xp, s);
len += ptr2cells(s);
mb_ptr_adv(s);
}
return len;
}
/*
* Return the number of characters that should be skipped in a status match.
* These are backslashes used for escaping. Do show backslashes in help tags.
*/
static int
skip_status_match_char(xp, s)
expand_T *xp;
char_u *s;
{
if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP)
#ifdef FEAT_MENU
|| ((xp->xp_context == EXPAND_MENUS
|| xp->xp_context == EXPAND_MENUNAMES)
&& (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL)))
#endif
)
{
#ifndef BACKSLASH_IN_FILENAME
if (xp->xp_shell && csh_like_shell() && s[1] == '\\' && s[2] == '!')
return 2;
#endif
return 1;
}
return 0;
}
/*
* Show wildchar matches in the status line.
* Show at least the "match" item.
* We start at item 'first_match' in the list and show all matches that fit.
*
* If inversion is possible we use it. Else '=' characters are used.
*/
void
win_redr_status_matches(xp, num_matches, matches, match, showtail)
expand_T *xp;
int num_matches;
char_u **matches; /* list of matches */
int match;
int showtail;
{
#define L_MATCH(m) (showtail ? sm_gettail(matches[m]) : matches[m])
int row;
char_u *buf;
int len;
int clen; /* length in screen cells */
int fillchar;
int attr;
int i;
int highlight = TRUE;
char_u *selstart = NULL;
int selstart_col = 0;
char_u *selend = NULL;
static int first_match = 0;
int add_left = FALSE;
char_u *s;
#ifdef FEAT_MENU
int emenu;
#endif
#if defined(FEAT_MBYTE) || defined(FEAT_MENU)
int l;
#endif
if (matches == NULL) /* interrupted completion? */
return;
#ifdef FEAT_MBYTE
if (has_mbyte)
buf = alloc((unsigned)Columns * MB_MAXBYTES + 1);
else
#endif
buf = alloc((unsigned)Columns + 1);
if (buf == NULL)
return;
if (match == -1) /* don't show match but original text */
{
match = 0;
highlight = FALSE;
}
/* count 1 for the ending ">" */
clen = status_match_len(xp, L_MATCH(match)) + 3;
if (match == 0)
first_match = 0;
else if (match < first_match)
{
/* jumping left, as far as we can go */
first_match = match;
add_left = TRUE;
}
else
{
/* check if match fits on the screen */
for (i = first_match; i < match; ++i)
clen += status_match_len(xp, L_MATCH(i)) + 2;
if (first_match > 0)
clen += 2;
/* jumping right, put match at the left */
if ((long)clen > Columns)
{
first_match = match;
/* if showing the last match, we can add some on the left */
clen = 2;
for (i = match; i < num_matches; ++i)
{
clen += status_match_len(xp, L_MATCH(i)) + 2;
if ((long)clen >= Columns)
break;
}
if (i == num_matches)
add_left = TRUE;
}
}
if (add_left)
while (first_match > 0)
{
clen += status_match_len(xp, L_MATCH(first_match - 1)) + 2;
if ((long)clen >= Columns)
break;
--first_match;
}
fillchar = fillchar_status(&attr, TRUE);
if (first_match == 0)
{
*buf = NUL;
len = 0;
}
else
{
STRCPY(buf, "< ");
len = 2;
}
clen = len;
i = first_match;
while ((long)(clen + status_match_len(xp, L_MATCH(i)) + 2) < Columns)
{
if (i == match)
{
selstart = buf + len;
selstart_col = clen;
}
s = L_MATCH(i);
/* Check for menu separators - replace with '|' */
#ifdef FEAT_MENU
emenu = (xp->xp_context == EXPAND_MENUS
|| xp->xp_context == EXPAND_MENUNAMES);
if (emenu && menu_is_separator(s))
{
STRCPY(buf + len, transchar('|'));
l = (int)STRLEN(buf + len);
len += l;
clen += l;
}
else
#endif
for ( ; *s != NUL; ++s)
{
s += skip_status_match_char(xp, s);
clen += ptr2cells(s);
#ifdef FEAT_MBYTE
if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1)
{
STRNCPY(buf + len, s, l);
s += l - 1;
len += l;
}
else
#endif
{
STRCPY(buf + len, transchar_byte(*s));
len += (int)STRLEN(buf + len);
}
}
if (i == match)
selend = buf + len;
*(buf + len++) = ' ';
*(buf + len++) = ' ';
clen += 2;
if (++i == num_matches)
break;
}
if (i != num_matches)
{
*(buf + len++) = '>';
++clen;
}
buf[len] = NUL;
row = cmdline_row - 1;
if (row >= 0)
{
if (wild_menu_showing == 0)
{
if (msg_scrolled > 0)
{
/* Put the wildmenu just above the command line. If there is
* no room, scroll the screen one line up. */
if (cmdline_row == Rows - 1)
{
screen_del_lines(0, 0, 1, (int)Rows, TRUE, NULL);
++msg_scrolled;
}
else
{
++cmdline_row;
++row;
}
wild_menu_showing = WM_SCROLLED;
}
else
{
/* Create status line if needed by setting 'laststatus' to 2.
* Set 'winminheight' to zero to avoid that the window is
* resized. */
if (lastwin->w_status_height == 0)
{
save_p_ls = p_ls;
save_p_wmh = p_wmh;
p_ls = 2;
p_wmh = 0;
last_status(FALSE);
}
wild_menu_showing = WM_SHOWN;
}
}
screen_puts(buf, row, 0, attr);
if (selstart != NULL && highlight)
{
*selend = NUL;
screen_puts(selstart, row, selstart_col, hl_attr(HLF_WM));
}
screen_fill(row, row + 1, clen, (int)Columns, fillchar, fillchar, attr);
}
#ifdef FEAT_VERTSPLIT
win_redraw_last_status(topframe);
#else
lastwin->w_redr_status = TRUE;
#endif
vim_free(buf);
}
#endif
#if defined(FEAT_WINDOWS) || defined(PROTO)
/*
* Redraw the status line of window wp.
*
* If inversion is possible we use it. Else '=' characters are used.
*/
void
win_redr_status(wp)
win_T *wp;
{
int row;
char_u *p;
int len;
int fillchar;
int attr;
int this_ru_col;
static int busy = FALSE;
/* It's possible to get here recursively when 'statusline' (indirectly)
* invokes ":redrawstatus". Simply ignore the call then. */
if (busy)
return;
busy = TRUE;
wp->w_redr_status = FALSE;
if (wp->w_status_height == 0)
{
/* no status line, can only be last window */
redraw_cmdline = TRUE;
}
else if (!redrawing()
#ifdef FEAT_INS_EXPAND
/* don't update status line when popup menu is visible and may be
* drawn over it */
|| pum_visible()
#endif
)
{
/* Don't redraw right now, do it later. */
wp->w_redr_status = TRUE;
}
#ifdef FEAT_STL_OPT
else if (*p_stl != NUL || *wp->w_p_stl != NUL)
{
/* redraw custom status line */
redraw_custom_statusline(wp);
}
#endif
else
{
fillchar = fillchar_status(&attr, wp == curwin);
get_trans_bufname(wp->w_buffer);
p = NameBuff;
len = (int)STRLEN(p);
if (wp->w_buffer->b_help
#ifdef FEAT_QUICKFIX
|| wp->w_p_pvw
#endif
|| bufIsChanged(wp->w_buffer)
|| wp->w_buffer->b_p_ro)
*(p + len++) = ' ';
if (wp->w_buffer->b_help)
{
STRCPY(p + len, _("[Help]"));
len += (int)STRLEN(p + len);
}
#ifdef FEAT_QUICKFIX
if (wp->w_p_pvw)
{
STRCPY(p + len, _("[Preview]"));
len += (int)STRLEN(p + len);
}
#endif
if (bufIsChanged(wp->w_buffer))
{
STRCPY(p + len, "[+]");
len += 3;
}
if (wp->w_buffer->b_p_ro)
{
STRCPY(p + len, "[RO]");
len += 4;
}
#ifndef FEAT_VERTSPLIT
this_ru_col = ru_col;
if (this_ru_col < (Columns + 1) / 2)
this_ru_col = (Columns + 1) / 2;
#else
this_ru_col = ru_col - (Columns - W_WIDTH(wp));
if (this_ru_col < (W_WIDTH(wp) + 1) / 2)
this_ru_col = (W_WIDTH(wp) + 1) / 2;
if (this_ru_col <= 1)
{
p = (char_u *)"<"; /* No room for file name! */
len = 1;
}
else
#endif
#ifdef FEAT_MBYTE
if (has_mbyte)
{
int clen = 0, i;
/* Count total number of display cells. */
clen = mb_string2cells(p, -1);
/* Find first character that will fit.
* Going from start to end is much faster for DBCS. */
for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;
i += (*mb_ptr2len)(p + i))
clen -= (*mb_ptr2cells)(p + i);
len = clen;
if (i > 0)
{
p = p + i - 1;
*p = '<';
++len;
}
}
else
#endif
if (len > this_ru_col - 1)
{
p += len - (this_ru_col - 1);
*p = '<';
len = this_ru_col - 1;
}
row = W_WINROW(wp) + wp->w_height;
screen_puts(p, row, W_WINCOL(wp), attr);
screen_fill(row, row + 1, len + W_WINCOL(wp),
this_ru_col + W_WINCOL(wp), fillchar, fillchar, attr);
if (get_keymap_str(wp, NameBuff, MAXPATHL)
&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))
screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)
- 1 + W_WINCOL(wp)), attr);
#ifdef FEAT_CMDL_INFO
win_redr_ruler(wp, TRUE);
#endif
}
#ifdef FEAT_VERTSPLIT
/*
* May need to draw the character below the vertical separator.
*/
if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())
{
if (stl_connected(wp))
fillchar = fillchar_status(&attr, wp == curwin);
else
fillchar = fillchar_vsep(&attr);
screen_putchar(fillchar, W_WINROW(wp) + wp->w_height, W_ENDCOL(wp),
attr);
}
#endif
busy = FALSE;
}
#ifdef FEAT_STL_OPT
/*
* Redraw the status line according to 'statusline' and take care of any
* errors encountered.
*/
static void
redraw_custom_statusline(wp)
win_T *wp;
{
static int entered = FALSE;
int save_called_emsg = called_emsg;
/* When called recursively return. This can happen when the statusline
* contains an expression that triggers a redraw. */
if (entered)
return;
entered = TRUE;
called_emsg = FALSE;
win_redr_custom(wp, FALSE);
if (called_emsg)
{
/* When there is an error disable the statusline, otherwise the
* display is messed up with errors and a redraw triggers the problem
* again and again. */
set_string_option_direct((char_u *)"statusline", -1,
(char_u *)"", OPT_FREE | (*wp->w_p_stl != NUL
? OPT_LOCAL : OPT_GLOBAL), SID_ERROR);
}
called_emsg |= save_called_emsg;
entered = FALSE;
}
#endif
# ifdef FEAT_VERTSPLIT
/*
* Return TRUE if the status line of window "wp" is connected to the status
* line of the window right of it. If not, then it's a vertical separator.
* Only call if (wp->w_vsep_width != 0).
*/
int
stl_connected(wp)
win_T *wp;
{
frame_T *fr;
fr = wp->w_frame;
while (fr->fr_parent != NULL)
{
if (fr->fr_parent->fr_layout == FR_COL)
{
if (fr->fr_next != NULL)
break;
}
else
{
if (fr->fr_next != NULL)
return TRUE;
}
fr = fr->fr_parent;
}
return FALSE;
}
# endif
#endif /* FEAT_WINDOWS */
#if defined(FEAT_WINDOWS) || defined(FEAT_STL_OPT) || defined(PROTO)
/*
* Get the value to show for the language mappings, active 'keymap'.
*/
int
get_keymap_str(wp, buf, len)
win_T *wp;
char_u *buf; /* buffer for the result */
int len; /* length of buffer */
{
char_u *p;
if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP)
return FALSE;
{
#ifdef FEAT_EVAL
buf_T *old_curbuf = curbuf;
win_T *old_curwin = curwin;
char_u *s;
curbuf = wp->w_buffer;
curwin = wp;
STRCPY(buf, "b:keymap_name"); /* must be writable */
++emsg_skip;
s = p = eval_to_string(buf, NULL, FALSE);
--emsg_skip;
curbuf = old_curbuf;
curwin = old_curwin;
if (p == NULL || *p == NUL)
#endif
{
#ifdef FEAT_KEYMAP
if (wp->w_buffer->b_kmap_state & KEYMAP_LOADED)
p = wp->w_buffer->b_p_keymap;
else
#endif
p = (char_u *)"lang";
}
if ((int)(STRLEN(p) + 3) < len)
sprintf((char *)buf, "<%s>", p);
else
buf[0] = NUL;
#ifdef FEAT_EVAL
vim_free(s);
#endif
}
return buf[0] != NUL;
}
#endif
#if defined(FEAT_STL_OPT) || defined(PROTO)
/*
* Redraw the status line or ruler of window "wp".
* When "wp" is NULL redraw the tab pages line from 'tabline'.
*/
static void
win_redr_custom(wp, draw_ruler)
win_T *wp;
int draw_ruler; /* TRUE or FALSE */
{
int attr;
int curattr;
int row;
int col = 0;
int maxwidth;
int width;
int n;
int len;
int fillchar;
char_u buf[MAXPATHL];
char_u *stl;
char_u *p;
struct stl_hlrec hltab[STL_MAX_ITEM];
struct stl_hlrec tabtab[STL_MAX_ITEM];
int use_sandbox = FALSE;
win_T *ewp;
int p_crb_save;
/* setup environment for the task at hand */
if (wp == NULL)
{
/* Use 'tabline'. Always at the first line of the screen. */
stl = p_tal;
row = 0;
fillchar = ' ';
attr = hl_attr(HLF_TPF);
maxwidth = Columns;
# ifdef FEAT_EVAL
use_sandbox = was_set_insecurely((char_u *)"tabline", 0);
# endif
}
else
{
row = W_WINROW(wp) + wp->w_height;
fillchar = fillchar_status(&attr, wp == curwin);
maxwidth = W_WIDTH(wp);
if (draw_ruler)
{
stl = p_ruf;
/* advance past any leading group spec - implicit in ru_col */
if (*stl == '%')
{
if (*++stl == '-')
stl++;
if (atoi((char *)stl))
while (VIM_ISDIGIT(*stl))
stl++;
if (*stl++ != '(')
stl = p_ruf;
}
#ifdef FEAT_VERTSPLIT
col = ru_col - (Columns - W_WIDTH(wp));
if (col < (W_WIDTH(wp) + 1) / 2)
col = (W_WIDTH(wp) + 1) / 2;
#else
col = ru_col;
if (col > (Columns + 1) / 2)
col = (Columns + 1) / 2;
#endif
maxwidth = W_WIDTH(wp) - col;
#ifdef FEAT_WINDOWS
if (!wp->w_status_height)
#endif
{
row = Rows - 1;
--maxwidth; /* writing in last column may cause scrolling */
fillchar = ' ';
attr = 0;
}
# ifdef FEAT_EVAL
use_sandbox = was_set_insecurely((char_u *)"rulerformat", 0);
# endif
}
else
{
if (*wp->w_p_stl != NUL)
stl = wp->w_p_stl;
else
stl = p_stl;
# ifdef FEAT_EVAL
use_sandbox = was_set_insecurely((char_u *)"statusline",
*wp->w_p_stl == NUL ? 0 : OPT_LOCAL);
# endif
}
#ifdef FEAT_VERTSPLIT
col += W_WINCOL(wp);
#endif
}
if (maxwidth <= 0)
return;
/* Temporarily reset 'cursorbind', we don't want a side effect from moving
* the cursor away and back. */
ewp = wp == NULL ? curwin : wp;
p_crb_save = ewp->w_p_crb;
ewp->w_p_crb = FALSE;
/* Make a copy, because the statusline may include a function call that
* might change the option value and free the memory. */
stl = vim_strsave(stl);
width = build_stl_str_hl(ewp, buf, sizeof(buf),
stl, use_sandbox,
fillchar, maxwidth, hltab, tabtab);
vim_free(stl);
ewp->w_p_crb = p_crb_save;
/* Make all characters printable. */
p = transstr(buf);
if (p != NULL)
{
vim_strncpy(buf, p, sizeof(buf) - 1);
vim_free(p);
}
/* fill up with "fillchar" */
len = (int)STRLEN(buf);
while (width < maxwidth && len < (int)sizeof(buf) - 1)
{
#ifdef FEAT_MBYTE
len += (*mb_char2bytes)(fillchar, buf + len);
#else
buf[len++] = fillchar;
#endif
++width;
}
buf[len] = NUL;
/*
* Draw each snippet with the specified highlighting.
*/
curattr = attr;
p = buf;
for (n = 0; hltab[n].start != NULL; n++)
{
len = (int)(hltab[n].start - p);
screen_puts_len(p, len, row, col, curattr);
col += vim_strnsize(p, len);
p = hltab[n].start;
if (hltab[n].userhl == 0)
curattr = attr;
else if (hltab[n].userhl < 0)
curattr = syn_id2attr(-hltab[n].userhl);
#ifdef FEAT_WINDOWS
else if (wp != NULL && wp != curwin && wp->w_status_height != 0)
curattr = highlight_stlnc[hltab[n].userhl - 1];
#endif
else
curattr = highlight_user[hltab[n].userhl - 1];
}
screen_puts(p, row, col, curattr);
if (wp == NULL)
{
/* Fill the TabPageIdxs[] array for clicking in the tab pagesline. */
col = 0;
len = 0;
p = buf;
fillchar = 0;
for (n = 0; tabtab[n].start != NULL; n++)
{
len += vim_strnsize(p, (int)(tabtab[n].start - p));
while (col < len)
TabPageIdxs[col++] = fillchar;
p = tabtab[n].start;
fillchar = tabtab[n].userhl;
}
while (col < Columns)
TabPageIdxs[col++] = fillchar;
}
}
#endif /* FEAT_STL_OPT */
/*
* Output a single character directly to the screen and update ScreenLines.
*/
void
screen_putchar(c, row, col, attr)
int c;
int row, col;
int attr;
{
char_u buf[MB_MAXBYTES + 1];
#ifdef FEAT_MBYTE
if (has_mbyte)
buf[(*mb_char2bytes)(c, buf)] = NUL;
else
#endif
{
buf[0] = c;
buf[1] = NUL;
}
screen_puts(buf, row, col, attr);
}
/*
* Get a single character directly from ScreenLines into "bytes[]".
* Also return its attribute in *attrp;
*/
void
screen_getbytes(row, col, bytes, attrp)
int row, col;
char_u *bytes;
int *attrp;
{
unsigned off;
/* safety check */
if (ScreenLines != NULL && row < screen_Rows && col < screen_Columns)
{
off = LineOffset[row] + col;
*attrp = ScreenAttrs[off];
bytes[0] = ScreenLines[off];
bytes[1] = NUL;
#ifdef FEAT_MBYTE
if (enc_utf8 && ScreenLinesUC[off] != 0)
bytes[utfc_char2bytes(off, bytes)] = NUL;
else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
{
bytes[0] = ScreenLines[off];
bytes[1] = ScreenLines2[off];
bytes[2] = NUL;
}
else if (enc_dbcs && MB_BYTE2LEN(bytes[0]) > 1)
{
bytes[1] = ScreenLines[off + 1];
bytes[2] = NUL;
}
#endif
}
}
#ifdef FEAT_MBYTE
static int screen_comp_differs __ARGS((int, int*));
/*
* Return TRUE if composing characters for screen posn "off" differs from
* composing characters in "u8cc".
* Only to be used when ScreenLinesUC[off] != 0.
*/
static int
screen_comp_differs(off, u8cc)
int off;
int *u8cc;
{
int i;
for (i = 0; i < Screen_mco; ++i)
{
if (ScreenLinesC[i][off] != (u8char_T)u8cc[i])
return TRUE;
if (u8cc[i] == 0)
break;
}
return FALSE;
}
#endif
/*
* Put string '*text' on the screen at position 'row' and 'col', with
* attributes 'attr', and update ScreenLines[] and ScreenAttrs[].
* Note: only outputs within one row, message is truncated at screen boundary!
* Note: if ScreenLines[], row and/or col is invalid, nothing is done.
*/
void
screen_puts(text, row, col, attr)
char_u *text;
int row;
int col;
int attr;
{
screen_puts_len(text, -1, row, col, attr);
}
/*
* Like screen_puts(), but output "text[len]". When "len" is -1 output up to
* a NUL.
*/
void
screen_puts_len(text, len, row, col, attr)
char_u *text;
int len;
int row;
int col;
int attr;
{
unsigned off;
char_u *ptr = text;
int c;
#ifdef FEAT_MBYTE
unsigned max_off;
int mbyte_blen = 1;
int mbyte_cells = 1;
int u8c = 0;
int u8cc[MAX_MCO];
int clear_next_cell = FALSE;
# ifdef FEAT_ARABIC
int prev_c = 0; /* previous Arabic character */
int pc, nc, nc1;
int pcc[MAX_MCO];
# endif
#endif
#if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
int force_redraw_this;
int force_redraw_next = FALSE;
#endif
int need_redraw;
if (ScreenLines == NULL || row >= screen_Rows) /* safety check */
return;
off = LineOffset[row] + col;
#ifdef FEAT_MBYTE
/* When drawing over the right halve of a double-wide char clear out the
* left halve. Only needed in a terminal. */
if (has_mbyte && col > 0 && col < screen_Columns
# ifdef FEAT_GUI
&& !gui.in_use
# endif
&& mb_fix_col(col, row) != col)
{
ScreenLines[off - 1] = ' ';
ScreenAttrs[off - 1] = 0;
if (enc_utf8)
{
ScreenLinesUC[off - 1] = 0;
ScreenLinesC[0][off - 1] = 0;
}
/* redraw the previous cell, make it empty */
screen_char(off - 1, row, col - 1);
/* force the cell at "col" to be redrawn */
force_redraw_next = TRUE;
}
#endif
#ifdef FEAT_MBYTE
max_off = LineOffset[row] + screen_Columns;
#endif
while (col < screen_Columns
&& (len < 0 || (int)(ptr - text) < len)
&& *ptr != NUL)
{
c = *ptr;
#ifdef FEAT_MBYTE
/* check if this is the first byte of a multibyte */
if (has_mbyte)
{
if (enc_utf8 && len > 0)
mbyte_blen = utfc_ptr2len_len(ptr, (int)((text + len) - ptr));
else
mbyte_blen = (*mb_ptr2len)(ptr);
if (enc_dbcs == DBCS_JPNU && c == 0x8e)
mbyte_cells = 1;
else if (enc_dbcs != 0)
mbyte_cells = mbyte_blen;
else /* enc_utf8 */
{
if (len >= 0)
u8c = utfc_ptr2char_len(ptr, u8cc,
(int)((text + len) - ptr));
else
u8c = utfc_ptr2char(ptr, u8cc);
mbyte_cells = utf_char2cells(u8c);
# ifdef UNICODE16
/* Non-BMP character: display as ? or fullwidth ?. */
if (u8c >= 0x10000)
{
u8c = (mbyte_cells == 2) ? 0xff1f : (int)'?';
if (attr == 0)
attr = hl_attr(HLF_8);
}
# endif
# ifdef FEAT_ARABIC
if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c))
{
/* Do Arabic shaping. */
if (len >= 0 && (int)(ptr - text) + mbyte_blen >= len)
{
/* Past end of string to be displayed. */
nc = NUL;
nc1 = NUL;
}
else
{
nc = utfc_ptr2char_len(ptr + mbyte_blen, pcc,
(int)((text + len) - ptr - mbyte_blen));
nc1 = pcc[0];
}
pc = prev_c;
prev_c = u8c;
u8c = arabic_shape(u8c, &c, &u8cc[0], nc, nc1, pc);
}
else
prev_c = u8c;
# endif
if (col + mbyte_cells > screen_Columns)
{
/* Only 1 cell left, but character requires 2 cells:
* display a '>' in the last column to avoid wrapping. */
c = '>';
mbyte_cells = 1;
}
}
}
#endif
#if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
force_redraw_this = force_redraw_next;
force_redraw_next = FALSE;
#endif
need_redraw = ScreenLines[off] != c
#ifdef FEAT_MBYTE
|| (mbyte_cells == 2
&& ScreenLines[off + 1] != (enc_dbcs ? ptr[1] : 0))
|| (enc_dbcs == DBCS_JPNU
&& c == 0x8e
&& ScreenLines2[off] != ptr[1])
|| (enc_utf8
&& (ScreenLinesUC[off] !=
(u8char_T)(c < 0x80 && u8cc[0] == 0 ? 0 : u8c)
|| (ScreenLinesUC[off] != 0
&& screen_comp_differs(off, u8cc))))
#endif
|| ScreenAttrs[off] != attr
|| exmode_active;
if (need_redraw
#if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
|| force_redraw_this
#endif
)
{
#if defined(FEAT_GUI) || defined(UNIX)
/* The bold trick makes a single row of pixels appear in the next
* character. When a bold character is removed, the next
* character should be redrawn too. This happens for our own GUI
* and for some xterms. */
if (need_redraw && ScreenLines[off] != ' ' && (
# ifdef FEAT_GUI
gui.in_use
# endif
# if defined(FEAT_GUI) && defined(UNIX)
||
# endif
# ifdef UNIX
term_is_xterm
# endif
))
{
int n = ScreenAttrs[off];
if (n > HL_ALL)
n = syn_attr2attr(n);
if (n & HL_BOLD)
force_redraw_next = TRUE;
}
#endif
#ifdef FEAT_MBYTE
/* When at the end of the text and overwriting a two-cell
* character with a one-cell character, need to clear the next
* cell. Also when overwriting the left halve of a two-cell char
* with the right halve of a two-cell char. Do this only once
* (mb_off2cells() may return 2 on the right halve). */
if (clear_next_cell)
clear_next_cell = FALSE;
else if (has_mbyte
&& (len < 0 ? ptr[mbyte_blen] == NUL
: ptr + mbyte_blen >= text + len)
&& ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
|| (mbyte_cells == 2
&& (*mb_off2cells)(off, max_off) == 1
&& (*mb_off2cells)(off + 1, max_off) > 1)))
clear_next_cell = TRUE;
/* Make sure we never leave a second byte of a double-byte behind,
* it confuses mb_off2cells(). */
if (enc_dbcs
&& ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
|| (mbyte_cells == 2
&& (*mb_off2cells)(off, max_off) == 1
&& (*mb_off2cells)(off + 1, max_off) > 1)))
ScreenLines[off + mbyte_blen] = 0;
#endif
ScreenLines[off] = c;
ScreenAttrs[off] = attr;
#ifdef FEAT_MBYTE
if (enc_utf8)
{
if (c < 0x80 && u8cc[0] == 0)
ScreenLinesUC[off] = 0;
else
{
int i;
ScreenLinesUC[off] = u8c;
for (i = 0; i < Screen_mco; ++i)
{
ScreenLinesC[i][off] = u8cc[i];
if (u8cc[i] == 0)
break;
}
}
if (mbyte_cells == 2)
{
ScreenLines[off + 1] = 0;
ScreenAttrs[off + 1] = attr;
}
screen_char(off, row, col);
}
else if (mbyte_cells == 2)
{
ScreenLines[off + 1] = ptr[1];
ScreenAttrs[off + 1] = attr;
screen_char_2(off, row, col);
}
else if (enc_dbcs == DBCS_JPNU && c == 0x8e)
{
ScreenLines2[off] = ptr[1];
screen_char(off, row, col);
}
else
#endif
screen_char(off, row, col);
}
#ifdef FEAT_MBYTE
if (has_mbyte)
{
off += mbyte_cells;
col += mbyte_cells;
ptr += mbyte_blen;
if (clear_next_cell)
ptr = (char_u *)" ";
}
else
#endif
{
++off;
++col;
++ptr;
}
}
#if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
/* If we detected the next character needs to be redrawn, but the text
* doesn't extend up to there, update the character here. */
if (force_redraw_next && col < screen_Columns)
{
# ifdef FEAT_MBYTE
if (enc_dbcs != 0 && dbcs_off2cells(off, max_off) > 1)
screen_char_2(off, row, col);
else
# endif
screen_char(off, row, col);
}
#endif
}
#ifdef FEAT_SEARCH_EXTRA
/*
* Prepare for 'hlsearch' highlighting.
*/
static void
start_search_hl()
{
if (p_hls && !no_hlsearch)
{
last_pat_prog(&search_hl.rm);
search_hl.attr = hl_attr(HLF_L);
# ifdef FEAT_RELTIME
/* Set the time limit to 'redrawtime'. */
profile_setlimit(p_rdt, &search_hl.tm);
# endif
}
}
/*
* Clean up for 'hlsearch' highlighting.
*/
static void
end_search_hl()
{
if (search_hl.rm.regprog != NULL)
{
vim_free(search_hl.rm.regprog);
search_hl.rm.regprog = NULL;
}
}
/*
* Init for calling prepare_search_hl().
*/
static void
init_search_hl(wp)
win_T *wp;
{
matchitem_T *cur;
/* Setup for match and 'hlsearch' highlighting. Disable any previous
* match */
cur = wp->w_match_head;
while (cur != NULL)
{
cur->hl.rm = cur->match;
if (cur->hlg_id == 0)
cur->hl.attr = 0;
else
cur->hl.attr = syn_id2attr(cur->hlg_id);
cur->hl.buf = wp->w_buffer;
cur->hl.lnum = 0;
cur->hl.first_lnum = 0;
# ifdef FEAT_RELTIME
/* Set the time limit to 'redrawtime'. */
profile_setlimit(p_rdt, &(cur->hl.tm));
# endif
cur = cur->next;
}
search_hl.buf = wp->w_buffer;
search_hl.lnum = 0;
search_hl.first_lnum = 0;
/* time limit is set at the toplevel, for all windows */
}
/*
* Advance to the match in window "wp" line "lnum" or past it.
*/
static void
prepare_search_hl(wp, lnum)
win_T *wp;
linenr_T lnum;
{
matchitem_T *cur; /* points to the match list */
match_T *shl; /* points to search_hl or a match */
int shl_flag; /* flag to indicate whether search_hl
has been processed or not */
int n;
/*
* When using a multi-line pattern, start searching at the top
* of the window or just after a closed fold.
* Do this both for search_hl and the match list.
*/
cur = wp->w_match_head;
shl_flag = FALSE;
while (cur != NULL || shl_flag == FALSE)
{
if (shl_flag == FALSE)
{
shl = &search_hl;
shl_flag = TRUE;
}
else
shl = &cur->hl;
if (shl->rm.regprog != NULL
&& shl->lnum == 0
&& re_multiline(shl->rm.regprog))
{
if (shl->first_lnum == 0)
{
# ifdef FEAT_FOLDING
for (shl->first_lnum = lnum;
shl->first_lnum > wp->w_topline; --shl->first_lnum)
if (hasFoldingWin(wp, shl->first_lnum - 1,
NULL, NULL, TRUE, NULL))
break;
# else
shl->first_lnum = wp->w_topline;
# endif
}
n = 0;
while (shl->first_lnum < lnum && shl->rm.regprog != NULL)
{
next_search_hl(wp, shl, shl->first_lnum, (colnr_T)n);
if (shl->lnum != 0)
{
shl->first_lnum = shl->lnum
+ shl->rm.endpos[0].lnum
- shl->rm.startpos[0].lnum;
n = shl->rm.endpos[0].col;
}
else
{
++shl->first_lnum;
n = 0;
}
}
}
if (shl != &search_hl && cur != NULL)
cur = cur->next;
}
}
/*
* Search for a next 'hlsearch' or match.
* Uses shl->buf.
* Sets shl->lnum and shl->rm contents.
* Note: Assumes a previous match is always before "lnum", unless
* shl->lnum is zero.
* Careful: Any pointers for buffer lines will become invalid.
*/
static void
next_search_hl(win, shl, lnum, mincol)
win_T *win;
match_T *shl; /* points to search_hl or a match */
linenr_T lnum;
colnr_T mincol; /* minimal column for a match */
{
linenr_T l;
colnr_T matchcol;
long nmatched;
if (shl->lnum != 0)
{
/* Check for three situations:
* 1. If the "lnum" is below a previous match, start a new search.
* 2. If the previous match includes "mincol", use it.
* 3. Continue after the previous match.
*/
l = shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum;
if (lnum > l)
shl->lnum = 0;
else if (lnum < l || shl->rm.endpos[0].col > mincol)
return;
}
/*
* Repeat searching for a match until one is found that includes "mincol"
* or none is found in this line.
*/
called_emsg = FALSE;
for (;;)
{
#ifdef FEAT_RELTIME
/* Stop searching after passing the time limit. */
if (profile_passed_limit(&(shl->tm)))
{
shl->lnum = 0; /* no match found in time */
break;
}
#endif
/* Three situations:
* 1. No useful previous match: search from start of line.
* 2. Not Vi compatible or empty match: continue at next character.
* Break the loop if this is beyond the end of the line.
* 3. Vi compatible searching: continue at end of previous match.
*/
if (shl->lnum == 0)
matchcol = 0;
else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL
|| (shl->rm.endpos[0].lnum == 0
&& shl->rm.endpos[0].col <= shl->rm.startpos[0].col))
{
char_u *ml;
matchcol = shl->rm.startpos[0].col;
ml = ml_get_buf(shl->buf, lnum, FALSE) + matchcol;
if (*ml == NUL)
{
++matchcol;
shl->lnum = 0;
break;
}
#ifdef FEAT_MBYTE
if (has_mbyte)
matchcol += mb_ptr2len(ml);
else
#endif
++matchcol;
}
else
matchcol = shl->rm.endpos[0].col;
shl->lnum = lnum;
nmatched = vim_regexec_multi(&shl->rm, win, shl->buf, lnum, matchcol,
#ifdef FEAT_RELTIME
&(shl->tm)
#else
NULL
#endif
);
if (called_emsg || got_int)
{
/* Error while handling regexp: stop using this regexp. */
if (shl == &search_hl)
{
/* don't free regprog in the match list, it's a copy */
vim_free(shl->rm.regprog);
no_hlsearch = TRUE;
}
shl->rm.regprog = NULL;
shl->lnum = 0;
got_int = FALSE; /* avoid the "Type :quit to exit Vim" message */
break;
}
if (nmatched == 0)
{
shl->lnum = 0; /* no match found */
break;
}
if (shl->rm.startpos[0].lnum > 0
|| shl->rm.startpos[0].col >= mincol
|| nmatched > 1
|| shl->rm.endpos[0].col > mincol)
{
shl->lnum += shl->rm.startpos[0].lnum;
break; /* useful match found */
}
}
}
#endif
static void
screen_start_highlight(attr)
int attr;
{
attrentry_T *aep = NULL;
screen_attr = attr;
if (full_screen
#ifdef WIN3264
&& termcap_active
#endif
)
{
#ifdef FEAT_GUI
if (gui.in_use)
{
char buf[20];
/* The GUI handles this internally. */
sprintf(buf, IF_EB("\033|%dh", ESC_STR "|%dh"), attr);
OUT_STR(buf);
}
else
#endif
{
if (attr > HL_ALL) /* special HL attr. */
{
if (t_colors > 1)
aep = syn_cterm_attr2entry(attr);
else
aep = syn_term_attr2entry(attr);
if (aep == NULL) /* did ":syntax clear" */
attr = 0;
else
attr = aep->ae_attr;
}
if ((attr & HL_BOLD) && T_MD != NULL) /* bold */
out_str(T_MD);
else if (aep != NULL && t_colors > 1 && aep->ae_u.cterm.fg_color
&& cterm_normal_fg_bold)
/* If the Normal FG color has BOLD attribute and the new HL
* has a FG color defined, clear BOLD. */
out_str(T_ME);
if ((attr & HL_STANDOUT) && T_SO != NULL) /* standout */
out_str(T_SO);
if ((attr & (HL_UNDERLINE | HL_UNDERCURL)) && T_US != NULL)
/* underline or undercurl */
out_str(T_US);
if ((attr & HL_ITALIC) && T_CZH != NULL) /* italic */
out_str(T_CZH);
if ((attr & HL_INVERSE) && T_MR != NULL) /* inverse (reverse) */
out_str(T_MR);
/*
* Output the color or start string after bold etc., in case the
* bold etc. override the color setting.
*/
if (aep != NULL)
{
if (t_colors > 1)
{
if (aep->ae_u.cterm.fg_color)
term_fg_color(aep->ae_u.cterm.fg_color - 1);
if (aep->ae_u.cterm.bg_color)
term_bg_color(aep->ae_u.cterm.bg_color - 1);
}
else
{
if (aep->ae_u.term.start != NULL)
out_str(aep->ae_u.term.start);
}
}
}
}
}
void
screen_stop_highlight()
{
int do_ME = FALSE; /* output T_ME code */
if (screen_attr != 0
#ifdef WIN3264
&& termcap_active
#endif
)
{
#ifdef FEAT_GUI
if (gui.in_use)
{
char buf[20];
/* use internal GUI code */
sprintf(buf, IF_EB("\033|%dH", ESC_STR "|%dH"), screen_attr);
OUT_STR(buf);
}
else
#endif
{
if (screen_attr > HL_ALL) /* special HL attr. */
{
attrentry_T *aep;
if (t_colors > 1)
{
/*
* Assume that t_me restores the original colors!
*/
aep = syn_cterm_attr2entry(screen_attr);
if (aep != NULL && (aep->ae_u.cterm.fg_color
|| aep->ae_u.cterm.bg_color))
do_ME = TRUE;
}
else
{
aep = syn_term_attr2entry(screen_attr);
if (aep != NULL && aep->ae_u.term.stop != NULL)
{
if (STRCMP(aep->ae_u.term.stop, T_ME) == 0)
do_ME = TRUE;
else
out_str(aep->ae_u.term.stop);
}
}
if (aep == NULL) /* did ":syntax clear" */
screen_attr = 0;
else
screen_attr = aep->ae_attr;
}
/*
* Often all ending-codes are equal to T_ME. Avoid outputting the
* same sequence several times.
*/
if (screen_attr & HL_STANDOUT)
{
if (STRCMP(T_SE, T_ME) == 0)
do_ME = TRUE;
else
out_str(T_SE);
}
if (screen_attr & (HL_UNDERLINE | HL_UNDERCURL))
{
if (STRCMP(T_UE, T_ME) == 0)
do_ME = TRUE;
else
out_str(T_UE);
}
if (screen_attr & HL_ITALIC)
{
if (STRCMP(T_CZR, T_ME) == 0)
do_ME = TRUE;
else
out_str(T_CZR);
}
if (do_ME || (screen_attr & (HL_BOLD | HL_INVERSE)))
out_str(T_ME);
if (t_colors > 1)
{
/* set Normal cterm colors */
if (cterm_normal_fg_color != 0)
term_fg_color(cterm_normal_fg_color - 1);
if (cterm_normal_bg_color != 0)
term_bg_color(cterm_normal_bg_color - 1);
if (cterm_normal_fg_bold)
out_str(T_MD);
}
}
}
screen_attr = 0;
}
/*
* Reset the colors for a cterm. Used when leaving Vim.
* The machine specific code may override this again.
*/
void
reset_cterm_colors()
{
if (t_colors > 1)
{
/* set Normal cterm colors */
if (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0)
{
out_str(T_OP);
screen_attr = -1;
}
if (cterm_normal_fg_bold)
{
out_str(T_ME);
screen_attr = -1;
}
}
}
/*
* Put character ScreenLines["off"] on the screen at position "row" and "col",
* using the attributes from ScreenAttrs["off"].
*/
static void
screen_char(off, row, col)
unsigned off;
int row;
int col;
{
int attr;
/* Check for illegal values, just in case (could happen just after
* resizing). */
if (row >= screen_Rows || col >= screen_Columns)
return;
/* Outputting the last character on the screen may scrollup the screen.
* Don't to it! Mark the character invalid (update it when scrolled up) */
if (row == screen_Rows - 1 && col == screen_Columns - 1
#ifdef FEAT_RIGHTLEFT
/* account for first command-line character in rightleft mode */
&& !cmdmsg_rl
#endif
)
{
ScreenAttrs[off] = (sattr_T)-1;
return;
}
/*
* Stop highlighting first, so it's easier to move the cursor.
*/
#if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT)
if (screen_char_attr != 0)
attr = screen_char_attr;
else
#endif
attr = ScreenAttrs[off];
if (screen_attr != attr)
screen_stop_highlight();
windgoto(row, col);
if (screen_attr != attr)
screen_start_highlight(attr);
#ifdef FEAT_MBYTE
if (enc_utf8 && ScreenLinesUC[off] != 0)
{
char_u buf[MB_MAXBYTES + 1];
/* Convert UTF-8 character to bytes and write it. */
buf[utfc_char2bytes(off, buf)] = NUL;
out_str(buf);
if (utf_char2cells(ScreenLinesUC[off]) > 1)
++screen_cur_col;
}
else
#endif
{
#ifdef FEAT_MBYTE
out_flush_check();
#endif
out_char(ScreenLines[off]);
#ifdef FEAT_MBYTE
/* double-byte character in single-width cell */
if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
out_char(ScreenLines2[off]);
#endif
}
screen_cur_col++;
}
#ifdef FEAT_MBYTE
/*
* Used for enc_dbcs only: Put one double-wide character at ScreenLines["off"]
* on the screen at position 'row' and 'col'.
* The attributes of the first byte is used for all. This is required to
* output the two bytes of a double-byte character with nothing in between.
*/
static void
screen_char_2(off, row, col)
unsigned off;
int row;
int col;
{
/* Check for illegal values (could be wrong when screen was resized). */
if (off + 1 >= (unsigned)(screen_Rows * screen_Columns))
return;
/* Outputting the last character on the screen may scrollup the screen.
* Don't to it! Mark the character invalid (update it when scrolled up) */
if (row == screen_Rows - 1 && col >= screen_Columns - 2)
{
ScreenAttrs[off] = (sattr_T)-1;
return;
}
/* Output the first byte normally (positions the cursor), then write the
* second byte directly. */
screen_char(off, row, col);
out_char(ScreenLines[off + 1]);
++screen_cur_col;
}
#endif
#if defined(FEAT_CLIPBOARD) || defined(FEAT_VERTSPLIT) || defined(PROTO)
/*
* Draw a rectangle of the screen, inverted when "invert" is TRUE.
* This uses the contents of ScreenLines[] and doesn't change it.
*/
void
screen_draw_rectangle(row, col, height, width, invert)
int row;
int col;
int height;
int width;
int invert;
{
int r, c;
int off;
#ifdef FEAT_MBYTE
int max_off;
#endif
/* Can't use ScreenLines unless initialized */
if (ScreenLines == NULL)
return;
if (invert)
screen_char_attr = HL_INVERSE;
for (r = row; r < row + height; ++r)
{
off = LineOffset[r];
#ifdef FEAT_MBYTE
max_off = off + screen_Columns;
#endif
for (c = col; c < col + width; ++c)
{
#ifdef FEAT_MBYTE
if (enc_dbcs != 0 && dbcs_off2cells(off + c, max_off) > 1)
{
screen_char_2(off + c, r, c);
++c;
}
else
#endif
{
screen_char(off + c, r, c);
#ifdef FEAT_MBYTE
if (utf_off2cells(off + c, max_off) > 1)
++c;
#endif
}
}
}
screen_char_attr = 0;
}
#endif
#ifdef FEAT_VERTSPLIT
/*
* Redraw the characters for a vertically split window.
*/
static void
redraw_block(row, end, wp)
int row;
int end;
win_T *wp;
{
int col;
int width;
# ifdef FEAT_CLIPBOARD
clip_may_clear_selection(row, end - 1);
# endif
if (wp == NULL)
{
col = 0;
width = Columns;
}
else
{
col = wp->w_wincol;
width = wp->w_width;
}
screen_draw_rectangle(row, col, end - row, width, FALSE);
}
#endif
/*
* Fill the screen from 'start_row' to 'end_row', from 'start_col' to 'end_col'
* with character 'c1' in first column followed by 'c2' in the other columns.
* Use attributes 'attr'.
*/
void
screen_fill(start_row, end_row, start_col, end_col, c1, c2, attr)
int start_row, end_row;
int start_col, end_col;
int c1, c2;
int attr;
{
int row;
int col;
int off;
int end_off;
int did_delete;
int c;
int norm_term;
#if defined(FEAT_GUI) || defined(UNIX)
int force_next = FALSE;
#endif
if (end_row > screen_Rows) /* safety check */
end_row = screen_Rows;
if (end_col > screen_Columns) /* safety check */
end_col = screen_Columns;
if (ScreenLines == NULL
|| start_row >= end_row
|| start_col >= end_col) /* nothing to do */
return;
/* it's a "normal" terminal when not in a GUI or cterm */
norm_term = (
#ifdef FEAT_GUI
!gui.in_use &&
#endif
t_colors <= 1);
for (row = start_row; row < end_row; ++row)
{
#ifdef FEAT_MBYTE
if (has_mbyte
# ifdef FEAT_GUI
&& !gui.in_use
# endif
)
{
/* When drawing over the right halve of a double-wide char clear
* out the left halve. When drawing over the left halve of a
* double wide-char clear out the right halve. Only needed in a
* terminal. */
if (start_col > 0 && mb_fix_col(start_col, row) != start_col)
screen_puts_len((char_u *)" ", 1, row, start_col - 1, 0);
if (end_col < screen_Columns && mb_fix_col(end_col, row) != end_col)
screen_puts_len((char_u *)" ", 1, row, end_col, 0);
}
#endif
/*
* Try to use delete-line termcap code, when no attributes or in a
* "normal" terminal, where a bold/italic space is just a
* space.
*/
did_delete = FALSE;
if (c2 == ' '
&& end_col == Columns
&& can_clear(T_CE)
&& (attr == 0
|| (norm_term
&& attr <= HL_ALL
&& ((attr & ~(HL_BOLD | HL_ITALIC)) == 0))))
{
/*
* check if we really need to clear something
*/
col = start_col;
if (c1 != ' ') /* don't clear first char */
++col;
off = LineOffset[row] + col;
end_off = LineOffset[row] + end_col;
/* skip blanks (used often, keep it fast!) */
#ifdef FEAT_MBYTE
if (enc_utf8)
while (off < end_off && ScreenLines[off] == ' '
&& ScreenAttrs[off] == 0 && ScreenLinesUC[off] == 0)
++off;
else
#endif
while (off < end_off && ScreenLines[off] == ' '
&& ScreenAttrs[off] == 0)
++off;
if (off < end_off) /* something to be cleared */
{
col = off - LineOffset[row];
screen_stop_highlight();
term_windgoto(row, col);/* clear rest of this screen line */
out_str(T_CE);
screen_start(); /* don't know where cursor is now */
col = end_col - col;
while (col--) /* clear chars in ScreenLines */
{
ScreenLines[off] = ' ';
#ifdef FEAT_MBYTE
if (enc_utf8)
ScreenLinesUC[off] = 0;
#endif
ScreenAttrs[off] = 0;
++off;
}
}
did_delete = TRUE; /* the chars are cleared now */
}
off = LineOffset[row] + start_col;
c = c1;
for (col = start_col; col < end_col; ++col)
{
if (ScreenLines[off] != c
#ifdef FEAT_MBYTE
|| (enc_utf8 && (int)ScreenLinesUC[off]
!= (c >= 0x80 ? c : 0))
#endif
|| ScreenAttrs[off] != attr
#if defined(FEAT_GUI) || defined(UNIX)
|| force_next
#endif
)
{
#if defined(FEAT_GUI) || defined(UNIX)
/* The bold trick may make a single row of pixels appear in
* the next character. When a bold character is removed, the
* next character should be redrawn too. This happens for our
* own GUI and for some xterms. */
if (
# ifdef FEAT_GUI
gui.in_use
# endif
# if defined(FEAT_GUI) && defined(UNIX)
||
# endif
# ifdef UNIX
term_is_xterm
# endif
)
{
if (ScreenLines[off] != ' '
&& (ScreenAttrs[off] > HL_ALL
|| ScreenAttrs[off] & HL_BOLD))
force_next = TRUE;
else
force_next = FALSE;
}
#endif
ScreenLines[off] = c;
#ifdef FEAT_MBYTE
if (enc_utf8)
{
if (c >= 0x80)
{
ScreenLinesUC[off] = c;
ScreenLinesC[0][off] = 0;
}
else
ScreenLinesUC[off] = 0;
}
#endif
ScreenAttrs[off] = attr;
if (!did_delete || c != ' ')
screen_char(off, row, col);
}
++off;
if (col == start_col)
{
if (did_delete)
break;
c = c2;
}
}
if (end_col == Columns)
LineWraps[row] = FALSE;
if (row == Rows - 1) /* overwritten the command line */
{
redraw_cmdline = TRUE;
if (c1 == ' ' && c2 == ' ')
clear_cmdline = FALSE; /* command line has been cleared */
if (start_col == 0)
mode_displayed = FALSE; /* mode cleared or overwritten */
}
}
}
/*
* Check if there should be a delay. Used before clearing or redrawing the
* screen or the command line.
*/
void
check_for_delay(check_msg_scroll)
int check_msg_scroll;
{
if ((emsg_on_display || (check_msg_scroll && msg_scroll))
&& !did_wait_return
&& emsg_silent == 0)
{
out_flush();
ui_delay(1000L, TRUE);
emsg_on_display = FALSE;
if (check_msg_scroll)
msg_scroll = FALSE;
}
}
/*
* screen_valid - allocate screen buffers if size changed
* If "doclear" is TRUE: clear screen if it has been resized.
* Returns TRUE if there is a valid screen to write to.
* Returns FALSE when starting up and screen not initialized yet.
*/
int
screen_valid(doclear)
int doclear;
{
screenalloc(doclear); /* allocate screen buffers if size changed */
return (ScreenLines != NULL);
}
/*
* Resize the shell to Rows and Columns.
* Allocate ScreenLines[] and associated items.
*
* There may be some time between setting Rows and Columns and (re)allocating
* ScreenLines[]. This happens when starting up and when (manually) changing
* the shell size. Always use screen_Rows and screen_Columns to access items
* in ScreenLines[]. Use Rows and Columns for positioning text etc. where the
* final size of the shell is needed.
*/
void
screenalloc(doclear)
int doclear;
{
int new_row, old_row;
#ifdef FEAT_GUI
int old_Rows;
#endif
win_T *wp;
int outofmem = FALSE;
int len;
schar_T *new_ScreenLines;
#ifdef FEAT_MBYTE
u8char_T *new_ScreenLinesUC = NULL;
u8char_T *new_ScreenLinesC[MAX_MCO];
schar_T *new_ScreenLines2 = NULL;
int i;
#endif
sattr_T *new_ScreenAttrs;
unsigned *new_LineOffset;
char_u *new_LineWraps;
#ifdef FEAT_WINDOWS
short *new_TabPageIdxs;
tabpage_T *tp;
#endif
static int entered = FALSE; /* avoid recursiveness */
static int done_outofmem_msg = FALSE; /* did outofmem message */
#ifdef FEAT_AUTOCMD
int retry_count = 0;
retry:
#endif
/*
* Allocation of the screen buffers is done only when the size changes and
* when Rows and Columns have been set and we have started doing full
* screen stuff.
*/
if ((ScreenLines != NULL
&& Rows == screen_Rows
&& Columns == screen_Columns
#ifdef FEAT_MBYTE
&& enc_utf8 == (ScreenLinesUC != NULL)
&& (enc_dbcs == DBCS_JPNU) == (ScreenLines2 != NULL)
&& p_mco == Screen_mco
#endif
)
|| Rows == 0
|| Columns == 0
|| (!full_screen && ScreenLines == NULL))
return;
/*
* It's possible that we produce an out-of-memory message below, which
* will cause this function to be called again. To break the loop, just
* return here.
*/
if (entered)
return;
entered = TRUE;
/*
* Note that the window sizes are updated before reallocating the arrays,
* thus we must not redraw here!
*/
++RedrawingDisabled;
win_new_shellsize(); /* fit the windows in the new sized shell */
comp_col(); /* recompute columns for shown command and ruler */
/*
* We're changing the size of the screen.
* - Allocate new arrays for ScreenLines and ScreenAttrs.
* - Move lines from the old arrays into the new arrays, clear extra
* lines (unless the screen is going to be cleared).
* - Free the old arrays.
*
* If anything fails, make ScreenLines NULL, so we don't do anything!
* Continuing with the old ScreenLines may result in a crash, because the
* size is wrong.
*/
FOR_ALL_TAB_WINDOWS(tp, wp)
win_free_lsize(wp);
#ifdef FEAT_AUTOCMD
if (aucmd_win != NULL)
win_free_lsize(aucmd_win);
#endif
new_ScreenLines = (schar_T *)lalloc((long_u)(
(Rows + 1) * Columns * sizeof(schar_T)), FALSE);
#ifdef FEAT_MBYTE
vim_memset(new_ScreenLinesC, 0, sizeof(u8char_T *) * MAX_MCO);
if (enc_utf8)
{
new_ScreenLinesUC = (u8char_T *)lalloc((long_u)(
(Rows + 1) * Columns * sizeof(u8char_T)), FALSE);
for (i = 0; i < p_mco; ++i)
new_ScreenLinesC[i] = (u8char_T *)lalloc_clear((long_u)(
(Rows + 1) * Columns * sizeof(u8char_T)), FALSE);
}
if (enc_dbcs == DBCS_JPNU)
new_ScreenLines2 = (schar_T *)lalloc((long_u)(
(Rows + 1) * Columns * sizeof(schar_T)), FALSE);
#endif
new_ScreenAttrs = (sattr_T *)lalloc((long_u)(
(Rows + 1) * Columns * sizeof(sattr_T)), FALSE);
new_LineOffset = (unsigned *)lalloc((long_u)(
Rows * sizeof(unsigned)), FALSE);
new_LineWraps = (char_u *)lalloc((long_u)(Rows * sizeof(char_u)), FALSE);
#ifdef FEAT_WINDOWS
new_TabPageIdxs = (short *)lalloc((long_u)(Columns * sizeof(short)), FALSE);
#endif
FOR_ALL_TAB_WINDOWS(tp, wp)
{
if (win_alloc_lines(wp) == FAIL)
{
outofmem = TRUE;
#ifdef FEAT_WINDOWS
goto give_up;
#endif
}
}
#ifdef FEAT_AUTOCMD
if (aucmd_win != NULL && aucmd_win->w_lines == NULL
&& win_alloc_lines(aucmd_win) == FAIL)
outofmem = TRUE;
#endif
#ifdef FEAT_WINDOWS
give_up:
#endif
#ifdef FEAT_MBYTE
for (i = 0; i < p_mco; ++i)
if (new_ScreenLinesC[i] == NULL)
break;
#endif
if (new_ScreenLines == NULL
#ifdef FEAT_MBYTE
|| (enc_utf8 && (new_ScreenLinesUC == NULL || i != p_mco))
|| (enc_dbcs == DBCS_JPNU && new_ScreenLines2 == NULL)
#endif
|| new_ScreenAttrs == NULL
|| new_LineOffset == NULL
|| new_LineWraps == NULL
#ifdef FEAT_WINDOWS
|| new_TabPageIdxs == NULL
#endif
|| outofmem)
{
if (ScreenLines != NULL || !done_outofmem_msg)
{
/* guess the size */
do_outofmem_msg((long_u)((Rows + 1) * Columns));
/* Remember we did this to avoid getting outofmem messages over
* and over again. */
done_outofmem_msg = TRUE;
}
vim_free(new_ScreenLines);
new_ScreenLines = NULL;
#ifdef FEAT_MBYTE
vim_free(new_ScreenLinesUC);
new_ScreenLinesUC = NULL;
for (i = 0; i < p_mco; ++i)
{
vim_free(new_ScreenLinesC[i]);
new_ScreenLinesC[i] = NULL;
}
vim_free(new_ScreenLines2);
new_ScreenLines2 = NULL;
#endif
vim_free(new_ScreenAttrs);
new_ScreenAttrs = NULL;
vim_free(new_LineOffset);
new_LineOffset = NULL;
vim_free(new_LineWraps);
new_LineWraps = NULL;
#ifdef FEAT_WINDOWS
vim_free(new_TabPageIdxs);
new_TabPageIdxs = NULL;
#endif
}
else
{
done_outofmem_msg = FALSE;
for (new_row = 0; new_row < Rows; ++new_row)
{
new_LineOffset[new_row] = new_row * Columns;
new_LineWraps[new_row] = FALSE;
/*
* If the screen is not going to be cleared, copy as much as
* possible from the old screen to the new one and clear the rest
* (used when resizing the window at the "--more--" prompt or when
* executing an external command, for the GUI).
*/
if (!doclear)
{
(void)vim_memset(new_ScreenLines + new_row * Columns,
' ', (size_t)Columns * sizeof(schar_T));
#ifdef FEAT_MBYTE
if (enc_utf8)
{
(void)vim_memset(new_ScreenLinesUC + new_row * Columns,
0, (size_t)Columns * sizeof(u8char_T));
for (i = 0; i < p_mco; ++i)
(void)vim_memset(new_ScreenLinesC[i]
+ new_row * Columns,
0, (size_t)Columns * sizeof(u8char_T));
}
if (enc_dbcs == DBCS_JPNU)
(void)vim_memset(new_ScreenLines2 + new_row * Columns,
0, (size_t)Columns * sizeof(schar_T));
#endif
(void)vim_memset(new_ScreenAttrs + new_row * Columns,
0, (size_t)Columns * sizeof(sattr_T));
old_row = new_row + (screen_Rows - Rows);
if (old_row >= 0 && ScreenLines != NULL)
{
if (screen_Columns < Columns)
len = screen_Columns;
else
len = Columns;
#ifdef FEAT_MBYTE
/* When switching to utf-8 don't copy characters, they
* may be invalid now. Also when p_mco changes. */
if (!(enc_utf8 && ScreenLinesUC == NULL)
&& p_mco == Screen_mco)
#endif
mch_memmove(new_ScreenLines + new_LineOffset[new_row],
ScreenLines + LineOffset[old_row],
(size_t)len * sizeof(schar_T));
#ifdef FEAT_MBYTE
if (enc_utf8 && ScreenLinesUC != NULL
&& p_mco == Screen_mco)
{
mch_memmove(new_ScreenLinesUC + new_LineOffset[new_row],
ScreenLinesUC + LineOffset[old_row],
(size_t)len * sizeof(u8char_T));
for (i = 0; i < p_mco; ++i)
mch_memmove(new_ScreenLinesC[i]
+ new_LineOffset[new_row],
ScreenLinesC[i] + LineOffset[old_row],
(size_t)len * sizeof(u8char_T));
}
if (enc_dbcs == DBCS_JPNU && ScreenLines2 != NULL)
mch_memmove(new_ScreenLines2 + new_LineOffset[new_row],
ScreenLines2 + LineOffset[old_row],
(size_t)len * sizeof(schar_T));
#endif
mch_memmove(new_ScreenAttrs + new_LineOffset[new_row],
ScreenAttrs + LineOffset[old_row],
(size_t)len * sizeof(sattr_T));
}
}
}
/* Use the last line of the screen for the current line. */
current_ScreenLine = new_ScreenLines + Rows * Columns;
}
free_screenlines();
ScreenLines = new_ScreenLines;
#ifdef FEAT_MBYTE
ScreenLinesUC = new_ScreenLinesUC;
for (i = 0; i < p_mco; ++i)
ScreenLinesC[i] = new_ScreenLinesC[i];
Screen_mco = p_mco;
ScreenLines2 = new_ScreenLines2;
#endif
ScreenAttrs = new_ScreenAttrs;
LineOffset = new_LineOffset;
LineWraps = new_LineWraps;
#ifdef FEAT_WINDOWS
TabPageIdxs = new_TabPageIdxs;
#endif
/* It's important that screen_Rows and screen_Columns reflect the actual
* size of ScreenLines[]. Set them before calling anything. */
#ifdef FEAT_GUI
old_Rows = screen_Rows;
#endif
screen_Rows = Rows;
screen_Columns = Columns;
must_redraw = CLEAR; /* need to clear the screen later */
if (doclear)
screenclear2();
#ifdef FEAT_GUI
else if (gui.in_use
&& !gui.starting
&& ScreenLines != NULL
&& old_Rows != Rows)
{
(void)gui_redraw_block(0, 0, (int)Rows - 1, (int)Columns - 1, 0);
/*
* Adjust the position of the cursor, for when executing an external
* command.
*/
if (msg_row >= Rows) /* Rows got smaller */
msg_row = Rows - 1; /* put cursor at last row */
else if (Rows > old_Rows) /* Rows got bigger */
msg_row += Rows - old_Rows; /* put cursor in same place */
if (msg_col >= Columns) /* Columns got smaller */
msg_col = Columns - 1; /* put cursor at last column */
}
#endif
entered = FALSE;
--RedrawingDisabled;
#ifdef FEAT_AUTOCMD
/*
* Do not apply autocommands more than 3 times to avoid an endless loop
* in case applying autocommands always changes Rows or Columns.
*/
if (starting == 0 && ++retry_count <= 3)
{
apply_autocmds(EVENT_VIMRESIZED, NULL, NULL, FALSE, curbuf);
/* In rare cases, autocommands may have altered Rows or Columns,
* jump back to check if we need to allocate the screen again. */
goto retry;
}
#endif
}
void
free_screenlines()
{
#ifdef FEAT_MBYTE
int i;
vim_free(ScreenLinesUC);
for (i = 0; i < Screen_mco; ++i)
vim_free(ScreenLinesC[i]);
vim_free(ScreenLines2);
#endif
vim_free(ScreenLines);
vim_free(ScreenAttrs);
vim_free(LineOffset);
vim_free(LineWraps);
#ifdef FEAT_WINDOWS
vim_free(TabPageIdxs);
#endif
}
void
screenclear()
{
check_for_delay(FALSE);
screenalloc(FALSE); /* allocate screen buffers if size changed */
screenclear2(); /* clear the screen */
}
static void
screenclear2()
{
int i;
if (starting == NO_SCREEN || ScreenLines == NULL
#ifdef FEAT_GUI
|| (gui.in_use && gui.starting)
#endif
)
return;
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
screen_attr = -1; /* force setting the Normal colors */
screen_stop_highlight(); /* don't want highlighting here */
#ifdef FEAT_CLIPBOARD
/* disable selection without redrawing it */
clip_scroll_selection(9999);
#endif
/* blank out ScreenLines */
for (i = 0; i < Rows; ++i)
{
lineclear(LineOffset[i], (int)Columns);
LineWraps[i] = FALSE;
}
if (can_clear(T_CL))
{
out_str(T_CL); /* clear the display */
clear_cmdline = FALSE;
mode_displayed = FALSE;
}
else
{
/* can't clear the screen, mark all chars with invalid attributes */
for (i = 0; i < Rows; ++i)
lineinvalid(LineOffset[i], (int)Columns);
clear_cmdline = TRUE;
}
screen_cleared = TRUE; /* can use contents of ScreenLines now */
win_rest_invalid(firstwin);
redraw_cmdline = TRUE;
#ifdef FEAT_WINDOWS
redraw_tabline = TRUE;
#endif
if (must_redraw == CLEAR) /* no need to clear again */
must_redraw = NOT_VALID;
compute_cmdrow();
msg_row = cmdline_row; /* put cursor on last line for messages */
msg_col = 0;
screen_start(); /* don't know where cursor is now */
msg_scrolled = 0; /* can't scroll back */
msg_didany = FALSE;
msg_didout = FALSE;
}
/*
* Clear one line in ScreenLines.
*/
static void
lineclear(off, width)
unsigned off;
int width;
{
(void)vim_memset(ScreenLines + off, ' ', (size_t)width * sizeof(schar_T));
#ifdef FEAT_MBYTE
if (enc_utf8)
(void)vim_memset(ScreenLinesUC + off, 0,
(size_t)width * sizeof(u8char_T));
#endif
(void)vim_memset(ScreenAttrs + off, 0, (size_t)width * sizeof(sattr_T));
}
/*
* Mark one line in ScreenLines invalid by setting the attributes to an
* invalid value.
*/
static void
lineinvalid(off, width)
unsigned off;
int width;
{
(void)vim_memset(ScreenAttrs + off, -1, (size_t)width * sizeof(sattr_T));
}
#ifdef FEAT_VERTSPLIT
/*
* Copy part of a Screenline for vertically split window "wp".
*/
static void
linecopy(to, from, wp)
int to;
int from;
win_T *wp;
{
unsigned off_to = LineOffset[to] + wp->w_wincol;
unsigned off_from = LineOffset[from] + wp->w_wincol;
mch_memmove(ScreenLines + off_to, ScreenLines + off_from,
wp->w_width * sizeof(schar_T));
# ifdef FEAT_MBYTE
if (enc_utf8)
{
int i;
mch_memmove(ScreenLinesUC + off_to, ScreenLinesUC + off_from,
wp->w_width * sizeof(u8char_T));
for (i = 0; i < p_mco; ++i)
mch_memmove(ScreenLinesC[i] + off_to, ScreenLinesC[i] + off_from,
wp->w_width * sizeof(u8char_T));
}
if (enc_dbcs == DBCS_JPNU)
mch_memmove(ScreenLines2 + off_to, ScreenLines2 + off_from,
wp->w_width * sizeof(schar_T));
# endif
mch_memmove(ScreenAttrs + off_to, ScreenAttrs + off_from,
wp->w_width * sizeof(sattr_T));
}
#endif
/*
* Return TRUE if clearing with term string "p" would work.
* It can't work when the string is empty or it won't set the right background.
*/
int
can_clear(p)
char_u *p;
{
return (*p != NUL && (t_colors <= 1
#ifdef FEAT_GUI
|| gui.in_use
#endif
|| cterm_normal_bg_color == 0 || *T_UT != NUL));
}
/*
* Reset cursor position. Use whenever cursor was moved because of outputting
* something directly to the screen (shell commands) or a terminal control
* code.
*/
void
screen_start()
{
screen_cur_row = screen_cur_col = 9999;
}
/*
* Move the cursor to position "row","col" in the screen.
* This tries to find the most efficient way to move, minimizing the number of
* characters sent to the terminal.
*/
void
windgoto(row, col)
int row;
int col;
{
sattr_T *p;
int i;
int plan;
int cost;
int wouldbe_col;
int noinvcurs;
char_u *bs;
int goto_cost;
int attr;
#define GOTO_COST 7 /* assume a term_windgoto() takes about 7 chars */
#define HIGHL_COST 5 /* assume unhighlight takes 5 chars */
#define PLAN_LE 1
#define PLAN_CR 2
#define PLAN_NL 3
#define PLAN_WRITE 4
/* Can't use ScreenLines unless initialized */
if (ScreenLines == NULL)
return;
if (col != screen_cur_col || row != screen_cur_row)
{
/* Check for valid position. */
if (row < 0) /* window without text lines? */
row = 0;
if (row >= screen_Rows)
row = screen_Rows - 1;
if (col >= screen_Columns)
col = screen_Columns - 1;
/* check if no cursor movement is allowed in highlight mode */
if (screen_attr && *T_MS == NUL)
noinvcurs = HIGHL_COST;
else
noinvcurs = 0;
goto_cost = GOTO_COST + noinvcurs;
/*
* Plan how to do the positioning:
* 1. Use CR to move it to column 0, same row.
* 2. Use T_LE to move it a few columns to the left.
* 3. Use NL to move a few lines down, column 0.
* 4. Move a few columns to the right with T_ND or by writing chars.
*
* Don't do this if the cursor went beyond the last column, the cursor
* position is unknown then (some terminals wrap, some don't )
*
* First check if the highlighting attributes allow us to write
* characters to move the cursor to the right.
*/
if (row >= screen_cur_row && screen_cur_col < Columns)
{
/*
* If the cursor is in the same row, bigger col, we can use CR
* or T_LE.
*/
bs = NULL; /* init for GCC */
attr = screen_attr;
if (row == screen_cur_row && col < screen_cur_col)
{
/* "le" is preferred over "bc", because "bc" is obsolete */
if (*T_LE)
bs = T_LE; /* "cursor left" */
else
bs = T_BC; /* "backspace character (old) */
if (*bs)
cost = (screen_cur_col - col) * (int)STRLEN(bs);
else
cost = 999;
if (col + 1 < cost) /* using CR is less characters */
{
plan = PLAN_CR;
wouldbe_col = 0;
cost = 1; /* CR is just one character */
}
else
{
plan = PLAN_LE;
wouldbe_col = col;
}
if (noinvcurs) /* will stop highlighting */
{
cost += noinvcurs;
attr = 0;
}
}
/*
* If the cursor is above where we want to be, we can use CR LF.
*/
else if (row > screen_cur_row)
{
plan = PLAN_NL;
wouldbe_col = 0;
cost = (row - screen_cur_row) * 2; /* CR LF */
if (noinvcurs) /* will stop highlighting */
{
cost += noinvcurs;
attr = 0;
}
}
/*
* If the cursor is in the same row, smaller col, just use write.
*/
else
{
plan = PLAN_WRITE;
wouldbe_col = screen_cur_col;
cost = 0;
}
/*
* Check if any characters that need to be written have the
* correct attributes. Also avoid UTF-8 characters.
*/
i = col - wouldbe_col;
if (i > 0)
cost += i;
if (cost < goto_cost && i > 0)
{
/*
* Check if the attributes are correct without additionally
* stopping highlighting.
*/
p = ScreenAttrs + LineOffset[row] + wouldbe_col;
while (i && *p++ == attr)
--i;
if (i != 0)
{
/*
* Try if it works when highlighting is stopped here.
*/
if (*--p == 0)
{
cost += noinvcurs;
while (i && *p++ == 0)
--i;
}
if (i != 0)
cost = 999; /* different attributes, don't do it */
}
#ifdef FEAT_MBYTE
if (enc_utf8)
{
/* Don't use an UTF-8 char for positioning, it's slow. */
for (i = wouldbe_col; i < col; ++i)
if (ScreenLinesUC[LineOffset[row] + i] != 0)
{
cost = 999;
break;
}
}
#endif
}
/*
* We can do it without term_windgoto()!
*/
if (cost < goto_cost)
{
if (plan == PLAN_LE)
{
if (noinvcurs)
screen_stop_highlight();
while (screen_cur_col > col)
{
out_str(bs);
--screen_cur_col;
}
}
else if (plan == PLAN_CR)
{
if (noinvcurs)
screen_stop_highlight();
out_char('\r');
screen_cur_col = 0;
}
else if (plan == PLAN_NL)
{
if (noinvcurs)
screen_stop_highlight();
while (screen_cur_row < row)
{
out_char('\n');
++screen_cur_row;
}
screen_cur_col = 0;
}
i = col - screen_cur_col;
if (i > 0)
{
/*
* Use cursor-right if it's one character only. Avoids
* removing a line of pixels from the last bold char, when
* using the bold trick in the GUI.
*/
if (T_ND[0] != NUL && T_ND[1] == NUL)
{
while (i-- > 0)
out_char(*T_ND);
}
else
{
int off;
off = LineOffset[row] + screen_cur_col;
while (i-- > 0)
{
if (ScreenAttrs[off] != screen_attr)
screen_stop_highlight();
#ifdef FEAT_MBYTE
out_flush_check();
#endif
out_char(ScreenLines[off]);
#ifdef FEAT_MBYTE
if (enc_dbcs == DBCS_JPNU
&& ScreenLines[off] == 0x8e)
out_char(ScreenLines2[off]);
#endif
++off;
}
}
}
}
}
else
cost = 999;
if (cost >= goto_cost)
{
if (noinvcurs)
screen_stop_highlight();
if (row == screen_cur_row && (col > screen_cur_col) &&
*T_CRI != NUL)
term_cursor_right(col - screen_cur_col);
else
term_windgoto(row, col);
}
screen_cur_row = row;
screen_cur_col = col;
}
}
/*
* Set cursor to its position in the current window.
*/
void
setcursor()
{
if (redrawing())
{
validate_cursor();
windgoto(W_WINROW(curwin) + curwin->w_wrow,
W_WINCOL(curwin) + (
#ifdef FEAT_RIGHTLEFT
/* With 'rightleft' set and the cursor on a double-wide
* character, position it on the leftmost column. */
curwin->w_p_rl ? ((int)W_WIDTH(curwin) - curwin->w_wcol - (
# ifdef FEAT_MBYTE
(has_mbyte
&& (*mb_ptr2cells)(ml_get_cursor()) == 2
&& vim_isprintc(gchar_cursor())) ? 2 :
# endif
1)) :
#endif
curwin->w_wcol));
}
}
/*
* insert 'line_count' lines at 'row' in window 'wp'
* if 'invalid' is TRUE the wp->w_lines[].wl_lnum is invalidated.
* if 'mayclear' is TRUE the screen will be cleared if it is faster than
* scrolling.
* Returns FAIL if the lines are not inserted, OK for success.
*/
int
win_ins_lines(wp, row, line_count, invalid, mayclear)
win_T *wp;
int row;
int line_count;
int invalid;
int mayclear;
{
int did_delete;
int nextrow;
int lastrow;
int retval;
if (invalid)
wp->w_lines_valid = 0;
if (wp->w_height < 5)
return FAIL;
if (line_count > wp->w_height - row)
line_count = wp->w_height - row;
retval = win_do_lines(wp, row, line_count, mayclear, FALSE);
if (retval != MAYBE)
return retval;
/*
* If there is a next window or a status line, we first try to delete the
* lines at the bottom to avoid messing what is after the window.
* If this fails and there are following windows, don't do anything to avoid
* messing up those windows, better just redraw.
*/
did_delete = FALSE;
#ifdef FEAT_WINDOWS
if (wp->w_next != NULL || wp->w_status_height)
{
if (screen_del_lines(0, W_WINROW(wp) + wp->w_height - line_count,
line_count, (int)Rows, FALSE, NULL) == OK)
did_delete = TRUE;
else if (wp->w_next)
return FAIL;
}
#endif
/*
* if no lines deleted, blank the lines that will end up below the window
*/
if (!did_delete)
{
#ifdef FEAT_WINDOWS
wp->w_redr_status = TRUE;
#endif
redraw_cmdline = TRUE;
nextrow = W_WINROW(wp) + wp->w_height + W_STATUS_HEIGHT(wp);
lastrow = nextrow + line_count;
if (lastrow > Rows)
lastrow = Rows;
screen_fill(nextrow - line_count, lastrow - line_count,
W_WINCOL(wp), (int)W_ENDCOL(wp),
' ', ' ', 0);
}
if (screen_ins_lines(0, W_WINROW(wp) + row, line_count, (int)Rows, NULL)
== FAIL)
{
/* deletion will have messed up other windows */
if (did_delete)
{
#ifdef FEAT_WINDOWS
wp->w_redr_status = TRUE;
#endif
win_rest_invalid(W_NEXT(wp));
}
return FAIL;
}
return OK;
}
/*
* delete "line_count" window lines at "row" in window "wp"
* If "invalid" is TRUE curwin->w_lines[] is invalidated.
* If "mayclear" is TRUE the screen will be cleared if it is faster than
* scrolling
* Return OK for success, FAIL if the lines are not deleted.
*/
int
win_del_lines(wp, row, line_count, invalid, mayclear)
win_T *wp;
int row;
int line_count;
int invalid;
int mayclear;
{
int retval;
if (invalid)
wp->w_lines_valid = 0;
if (line_count > wp->w_height - row)
line_count = wp->w_height - row;
retval = win_do_lines(wp, row, line_count, mayclear, TRUE);
if (retval != MAYBE)
return retval;
if (screen_del_lines(0, W_WINROW(wp) + row, line_count,
(int)Rows, FALSE, NULL) == FAIL)
return FAIL;
#ifdef FEAT_WINDOWS
/*
* If there are windows or status lines below, try to put them at the
* correct place. If we can't do that, they have to be redrawn.
*/
if (wp->w_next || wp->w_status_height || cmdline_row < Rows - 1)
{
if (screen_ins_lines(0, W_WINROW(wp) + wp->w_height - line_count,
line_count, (int)Rows, NULL) == FAIL)
{
wp->w_redr_status = TRUE;
win_rest_invalid(wp->w_next);
}
}
/*
* If this is the last window and there is no status line, redraw the
* command line later.
*/
else
#endif
redraw_cmdline = TRUE;
return OK;
}
/*
* Common code for win_ins_lines() and win_del_lines().
* Returns OK or FAIL when the work has been done.
* Returns MAYBE when not finished yet.
*/
static int
win_do_lines(wp, row, line_count, mayclear, del)
win_T *wp;
int row;
int line_count;
int mayclear;
int del;
{
int retval;
if (!redrawing() || line_count <= 0)
return FAIL;
/* only a few lines left: redraw is faster */
if (mayclear && Rows - line_count < 5
#ifdef FEAT_VERTSPLIT
&& wp->w_width == Columns
#endif
)
{
screenclear(); /* will set wp->w_lines_valid to 0 */
return FAIL;
}
/*
* Delete all remaining lines
*/
if (row + line_count >= wp->w_height)
{
screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
W_WINCOL(wp), (int)W_ENDCOL(wp),
' ', ' ', 0);
return OK;
}
/*
* when scrolling, the message on the command line should be cleared,
* otherwise it will stay there forever.
*/
clear_cmdline = TRUE;
/*
* If the terminal can set a scroll region, use that.
* Always do this in a vertically split window. This will redraw from
* ScreenLines[] when t_CV isn't defined. That's faster than using
* win_line().
* Don't use a scroll region when we are going to redraw the text, writing
* a character in the lower right corner of the scroll region causes a
* scroll-up in the DJGPP version.
*/
if (scroll_region
#ifdef FEAT_VERTSPLIT
|| W_WIDTH(wp) != Columns
#endif
)
{
#ifdef FEAT_VERTSPLIT
if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
#endif
scroll_region_set(wp, row);
if (del)
retval = screen_del_lines(W_WINROW(wp) + row, 0, line_count,
wp->w_height - row, FALSE, wp);
else
retval = screen_ins_lines(W_WINROW(wp) + row, 0, line_count,
wp->w_height - row, wp);
#ifdef FEAT_VERTSPLIT
if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
#endif
scroll_region_reset();
return retval;
}
#ifdef FEAT_WINDOWS
if (wp->w_next != NULL && p_tf) /* don't delete/insert on fast terminal */
return FAIL;
#endif
return MAYBE;
}
/*
* window 'wp' and everything after it is messed up, mark it for redraw
*/
static void
win_rest_invalid(wp)
win_T *wp;
{
#ifdef FEAT_WINDOWS
while (wp != NULL)
#else
if (wp != NULL)
#endif
{
redraw_win_later(wp, NOT_VALID);
#ifdef FEAT_WINDOWS
wp->w_redr_status = TRUE;
wp = wp->w_next;
#endif
}
redraw_cmdline = TRUE;
}
/*
* The rest of the routines in this file perform screen manipulations. The
* given operation is performed physically on the screen. The corresponding
* change is also made to the internal screen image. In this way, the editor
* anticipates the effect of editing changes on the appearance of the screen.
* That way, when we call screenupdate a complete redraw isn't usually
* necessary. Another advantage is that we can keep adding code to anticipate
* screen changes, and in the meantime, everything still works.
*/
/*
* types for inserting or deleting lines
*/
#define USE_T_CAL 1
#define USE_T_CDL 2
#define USE_T_AL 3
#define USE_T_CE 4
#define USE_T_DL 5
#define USE_T_SR 6
#define USE_NL 7
#define USE_T_CD 8
#define USE_REDRAW 9
/*
* insert lines on the screen and update ScreenLines[]
* 'end' is the line after the scrolled part. Normally it is Rows.
* When scrolling region used 'off' is the offset from the top for the region.
* 'row' and 'end' are relative to the start of the region.
*
* return FAIL for failure, OK for success.
*/
int
screen_ins_lines(off, row, line_count, end, wp)
int off;
int row;
int line_count;
int end;
win_T *wp; /* NULL or window to use width from */
{
int i;
int j;
unsigned temp;
int cursor_row;
int type;
int result_empty;
int can_ce = can_clear(T_CE);
/*
* FAIL if
* - there is no valid screen
* - the screen has to be redrawn completely
* - the line count is less than one
* - the line count is more than 'ttyscroll'
*/
if (!screen_valid(TRUE) || line_count <= 0 || line_count > p_ttyscroll)
return FAIL;
/*
* There are seven ways to insert lines:
* 0. When in a vertically split window and t_CV isn't set, redraw the
* characters from ScreenLines[].
* 1. Use T_CD (clear to end of display) if it exists and the result of
* the insert is just empty lines
* 2. Use T_CAL (insert multiple lines) if it exists and T_AL is not
* present or line_count > 1. It looks better if we do all the inserts
* at once.
* 3. Use T_CDL (delete multiple lines) if it exists and the result of the
* insert is just empty lines and T_CE is not present or line_count >
* 1.
* 4. Use T_AL (insert line) if it exists.
* 5. Use T_CE (erase line) if it exists and the result of the insert is
* just empty lines.
* 6. Use T_DL (delete line) if it exists and the result of the insert is
* just empty lines.
* 7. Use T_SR (scroll reverse) if it exists and inserting at row 0 and
* the 'da' flag is not set or we have clear line capability.
* 8. redraw the characters from ScreenLines[].
*
* Careful: In a hpterm scroll reverse doesn't work as expected, it moves
* the scrollbar for the window. It does have insert line, use that if it
* exists.
*/
result_empty = (row + line_count >= end);
#ifdef FEAT_VERTSPLIT
if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
type = USE_REDRAW;
else
#endif
if (can_clear(T_CD) && result_empty)
type = USE_T_CD;
else if (*T_CAL != NUL && (line_count > 1 || *T_AL == NUL))
type = USE_T_CAL;
else if (*T_CDL != NUL && result_empty && (line_count > 1 || !can_ce))
type = USE_T_CDL;
else if (*T_AL != NUL)
type = USE_T_AL;
else if (can_ce && result_empty)
type = USE_T_CE;
else if (*T_DL != NUL && result_empty)
type = USE_T_DL;
else if (*T_SR != NUL && row == 0 && (*T_DA == NUL || can_ce))
type = USE_T_SR;
else
return FAIL;
/*
* For clearing the lines screen_del_lines() is used. This will also take
* care of t_db if necessary.
*/
if (type == USE_T_CD || type == USE_T_CDL ||
type == USE_T_CE || type == USE_T_DL)
return screen_del_lines(off, row, line_count, end, FALSE, wp);
/*
* If text is retained below the screen, first clear or delete as many
* lines at the bottom of the window as are about to be inserted so that
* the deleted lines won't later surface during a screen_del_lines.
*/
if (*T_DB)
screen_del_lines(off, end - line_count, line_count, end, FALSE, wp);
#ifdef FEAT_CLIPBOARD
/* Remove a modeless selection when inserting lines halfway the screen
* or not the full width of the screen. */
if (off + row > 0
# ifdef FEAT_VERTSPLIT
|| (wp != NULL && wp->w_width != Columns)
# endif
)
clip_clear_selection();
else
clip_scroll_selection(-line_count);
#endif
#ifdef FEAT_GUI
/* Don't update the GUI cursor here, ScreenLines[] is invalid until the
* scrolling is actually carried out. */
gui_dont_update_cursor();
#endif
if (*T_CCS != NUL) /* cursor relative to region */
cursor_row = row;
else
cursor_row = row + off;
/*
* Shift LineOffset[] line_count down to reflect the inserted lines.
* Clear the inserted lines in ScreenLines[].
*/
row += off;
end += off;
for (i = 0; i < line_count; ++i)
{
#ifdef FEAT_VERTSPLIT
if (wp != NULL && wp->w_width != Columns)
{
/* need to copy part of a line */
j = end - 1 - i;
while ((j -= line_count) >= row)
linecopy(j + line_count, j, wp);
j += line_count;
if (can_clear((char_u *)" "))
lineclear(LineOffset[j] + wp->w_wincol, wp->w_width);
else
lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
LineWraps[j] = FALSE;
}
else
#endif
{
j = end - 1 - i;
temp = LineOffset[j];
while ((j -= line_count) >= row)
{
LineOffset[j + line_count] = LineOffset[j];
LineWraps[j + line_count] = LineWraps[j];
}
LineOffset[j + line_count] = temp;
LineWraps[j + line_count] = FALSE;
if (can_clear((char_u *)" "))
lineclear(temp, (int)Columns);
else
lineinvalid(temp, (int)Columns);
}
}
screen_stop_highlight();
windgoto(cursor_row, 0);
#ifdef FEAT_VERTSPLIT
/* redraw the characters */
if (type == USE_REDRAW)
redraw_block(row, end, wp);
else
#endif
if (type == USE_T_CAL)
{
term_append_lines(line_count);
screen_start(); /* don't know where cursor is now */
}
else
{
for (i = 0; i < line_count; i++)
{
if (type == USE_T_AL)
{
if (i && cursor_row != 0)
windgoto(cursor_row, 0);
out_str(T_AL);
}
else /* type == USE_T_SR */
out_str(T_SR);
screen_start(); /* don't know where cursor is now */
}
}
/*
* With scroll-reverse and 'da' flag set we need to clear the lines that
* have been scrolled down into the region.
*/
if (type == USE_T_SR && *T_DA)
{
for (i = 0; i < line_count; ++i)
{
windgoto(off + i, 0);
out_str(T_CE);
screen_start(); /* don't know where cursor is now */
}
}
#ifdef FEAT_GUI
gui_can_update_cursor();
if (gui.in_use)
out_flush(); /* always flush after a scroll */
#endif
return OK;
}
/*
* delete lines on the screen and update ScreenLines[]
* 'end' is the line after the scrolled part. Normally it is Rows.
* When scrolling region used 'off' is the offset from the top for the region.
* 'row' and 'end' are relative to the start of the region.
*
* Return OK for success, FAIL if the lines are not deleted.
*/
int
screen_del_lines(off, row, line_count, end, force, wp)
int off;
int row;
int line_count;
int end;
int force; /* even when line_count > p_ttyscroll */
win_T *wp UNUSED; /* NULL or window to use width from */
{
int j;
int i;
unsigned temp;
int cursor_row;
int cursor_end;
int result_empty; /* result is empty until end of region */
int can_delete; /* deleting line codes can be used */
int type;
/*
* FAIL if
* - there is no valid screen
* - the screen has to be redrawn completely
* - the line count is less than one
* - the line count is more than 'ttyscroll'
*/
if (!screen_valid(TRUE) || line_count <= 0 ||
(!force && line_count > p_ttyscroll))
return FAIL;
/*
* Check if the rest of the current region will become empty.
*/
result_empty = row + line_count >= end;
/*
* We can delete lines only when 'db' flag not set or when 'ce' option
* available.
*/
can_delete = (*T_DB == NUL || can_clear(T_CE));
/*
* There are six ways to delete lines:
* 0. When in a vertically split window and t_CV isn't set, redraw the
* characters from ScreenLines[].
* 1. Use T_CD if it exists and the result is empty.
* 2. Use newlines if row == 0 and count == 1 or T_CDL does not exist.
* 3. Use T_CDL (delete multiple lines) if it exists and line_count > 1 or
* none of the other ways work.
* 4. Use T_CE (erase line) if the result is empty.
* 5. Use T_DL (delete line) if it exists.
* 6. redraw the characters from ScreenLines[].
*/
#ifdef FEAT_VERTSPLIT
if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
type = USE_REDRAW;
else
#endif
if (can_clear(T_CD) && result_empty)
type = USE_T_CD;
#if defined(__BEOS__) && defined(BEOS_DR8)
/*
* USE_NL does not seem to work in Terminal of DR8 so we set T_DB="" in
* its internal termcap... this works okay for tests which test *T_DB !=
* NUL. It has the disadvantage that the user cannot use any :set t_*
* command to get T_DB (back) to empty_option, only :set term=... will do
* the trick...
* Anyway, this hack will hopefully go away with the next OS release.
* (Olaf Seibert)
*/
else if (row == 0 && T_DB == empty_option
&& (line_count == 1 || *T_CDL == NUL))
#else
else if (row == 0 && (
#ifndef AMIGA
/* On the Amiga, somehow '\n' on the last line doesn't always scroll
* up, so use delete-line command */
line_count == 1 ||
#endif
*T_CDL == NUL))
#endif
type = USE_NL;
else if (*T_CDL != NUL && line_count > 1 && can_delete)
type = USE_T_CDL;
else if (can_clear(T_CE) && result_empty
#ifdef FEAT_VERTSPLIT
&& (wp == NULL || wp->w_width == Columns)
#endif
)
type = USE_T_CE;
else if (*T_DL != NUL && can_delete)
type = USE_T_DL;
else if (*T_CDL != NUL && can_delete)
type = USE_T_CDL;
else
return FAIL;
#ifdef FEAT_CLIPBOARD
/* Remove a modeless selection when deleting lines halfway the screen or
* not the full width of the screen. */
if (off + row > 0
# ifdef FEAT_VERTSPLIT
|| (wp != NULL && wp->w_width != Columns)
# endif
)
clip_clear_selection();
else
clip_scroll_selection(line_count);
#endif
#ifdef FEAT_GUI
/* Don't update the GUI cursor here, ScreenLines[] is invalid until the
* scrolling is actually carried out. */
gui_dont_update_cursor();
#endif
if (*T_CCS != NUL) /* cursor relative to region */
{
cursor_row = row;
cursor_end = end;
}
else
{
cursor_row = row + off;
cursor_end = end + off;
}
/*
* Now shift LineOffset[] line_count up to reflect the deleted lines.
* Clear the inserted lines in ScreenLines[].
*/
row += off;
end += off;
for (i = 0; i < line_count; ++i)
{
#ifdef FEAT_VERTSPLIT
if (wp != NULL && wp->w_width != Columns)
{
/* need to copy part of a line */
j = row + i;
while ((j += line_count) <= end - 1)
linecopy(j - line_count, j, wp);
j -= line_count;
if (can_clear((char_u *)" "))
lineclear(LineOffset[j] + wp->w_wincol, wp->w_width);
else
lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
LineWraps[j] = FALSE;
}
else
#endif
{
/* whole width, moving the line pointers is faster */
j = row + i;
temp = LineOffset[j];
while ((j += line_count) <= end - 1)
{
LineOffset[j - line_count] = LineOffset[j];
LineWraps[j - line_count] = LineWraps[j];
}
LineOffset[j - line_count] = temp;
LineWraps[j - line_count] = FALSE;
if (can_clear((char_u *)" "))
lineclear(temp, (int)Columns);
else
lineinvalid(temp, (int)Columns);
}
}
screen_stop_highlight();
#ifdef FEAT_VERTSPLIT
/* redraw the characters */
if (type == USE_REDRAW)
redraw_block(row, end, wp);
else
#endif
if (type == USE_T_CD) /* delete the lines */
{
windgoto(cursor_row, 0);
out_str(T_CD);
screen_start(); /* don't know where cursor is now */
}
else if (type == USE_T_CDL)
{
windgoto(cursor_row, 0);
term_delete_lines(line_count);
screen_start(); /* don't know where cursor is now */
}
/*
* Deleting lines at top of the screen or scroll region: Just scroll
* the whole screen (scroll region) up by outputting newlines on the
* last line.
*/
else if (type == USE_NL)
{
windgoto(cursor_end - 1, 0);
for (i = line_count; --i >= 0; )
out_char('\n'); /* cursor will remain on same line */
}
else
{
for (i = line_count; --i >= 0; )
{
if (type == USE_T_DL)
{
windgoto(cursor_row, 0);
out_str(T_DL); /* delete a line */
}
else /* type == USE_T_CE */
{
windgoto(cursor_row + i, 0);
out_str(T_CE); /* erase a line */
}
screen_start(); /* don't know where cursor is now */
}
}
/*
* If the 'db' flag is set, we need to clear the lines that have been
* scrolled up at the bottom of the region.
*/
if (*T_DB && (type == USE_T_DL || type == USE_T_CDL))
{
for (i = line_count; i > 0; --i)
{
windgoto(cursor_end - i, 0);
out_str(T_CE); /* erase a line */
screen_start(); /* don't know where cursor is now */
}
}
#ifdef FEAT_GUI
gui_can_update_cursor();
if (gui.in_use)
out_flush(); /* always flush after a scroll */
#endif
return OK;
}
/*
* show the current mode and ruler
*
* If clear_cmdline is TRUE, clear the rest of the cmdline.
* If clear_cmdline is FALSE there may be a message there that needs to be
* cleared only if a mode is shown.
* Return the length of the message (0 if no message).
*/
int
showmode()
{
int need_clear;
int length = 0;
int do_mode;
int attr;
int nwr_save;
#ifdef FEAT_INS_EXPAND
int sub_attr;
#endif
do_mode = ((p_smd && msg_silent == 0)
&& ((State & INSERT)
|| restart_edit
#ifdef FEAT_VISUAL
|| VIsual_active
#endif
));
if (do_mode || Recording)
{
/*
* Don't show mode right now, when not redrawing or inside a mapping.
* Call char_avail() only when we are going to show something, because
* it takes a bit of time.
*/
if (!redrawing() || (char_avail() && !KeyTyped) || msg_silent != 0)
{
redraw_cmdline = TRUE; /* show mode later */
return 0;
}
nwr_save = need_wait_return;
/* wait a bit before overwriting an important message */
check_for_delay(FALSE);
/* if the cmdline is more than one line high, erase top lines */
need_clear = clear_cmdline;
if (clear_cmdline && cmdline_row < Rows - 1)
msg_clr_cmdline(); /* will reset clear_cmdline */
/* Position on the last line in the window, column 0 */
msg_pos_mode();
cursor_off();
attr = hl_attr(HLF_CM); /* Highlight mode */
if (do_mode)
{
MSG_PUTS_ATTR("--", attr);
#if defined(FEAT_XIM)
if (
# ifdef FEAT_GUI_GTK
preedit_get_status()
# else
im_get_status()
# endif
)
# ifdef FEAT_GUI_GTK /* most of the time, it's not XIM being used */
MSG_PUTS_ATTR(" IM", attr);
# else
MSG_PUTS_ATTR(" XIM", attr);
# endif
#endif
#if defined(FEAT_HANGULIN) && defined(FEAT_GUI)
if (gui.in_use)
{
if (hangul_input_state_get())
MSG_PUTS_ATTR(" \307\321\261\333", attr); /* HANGUL */
}
#endif
#ifdef FEAT_INS_EXPAND
if (edit_submode != NULL) /* CTRL-X in Insert mode */
{
/* These messages can get long, avoid a wrap in a narrow
* window. Prefer showing edit_submode_extra. */
length = (Rows - msg_row) * Columns - 3;
if (edit_submode_extra != NULL)
length -= vim_strsize(edit_submode_extra);
if (length > 0)
{
if (edit_submode_pre != NULL)
length -= vim_strsize(edit_submode_pre);
if (length - vim_strsize(edit_submode) > 0)
{
if (edit_submode_pre != NULL)
msg_puts_attr(edit_submode_pre, attr);
msg_puts_attr(edit_submode, attr);
}
if (edit_submode_extra != NULL)
{
MSG_PUTS_ATTR(" ", attr); /* add a space in between */
if ((int)edit_submode_highl < (int)HLF_COUNT)
sub_attr = hl_attr(edit_submode_highl);
else
sub_attr = attr;
msg_puts_attr(edit_submode_extra, sub_attr);
}
}
length = 0;
}
else
#endif
{
#ifdef FEAT_VREPLACE
if (State & VREPLACE_FLAG)
MSG_PUTS_ATTR(_(" VREPLACE"), attr);
else
#endif
if (State & REPLACE_FLAG)
MSG_PUTS_ATTR(_(" REPLACE"), attr);
else if (State & INSERT)
{
#ifdef FEAT_RIGHTLEFT
if (p_ri)
MSG_PUTS_ATTR(_(" REVERSE"), attr);
#endif
MSG_PUTS_ATTR(_(" INSERT"), attr);
}
else if (restart_edit == 'I')
MSG_PUTS_ATTR(_(" (insert)"), attr);
else if (restart_edit == 'R')
MSG_PUTS_ATTR(_(" (replace)"), attr);
else if (restart_edit == 'V')
MSG_PUTS_ATTR(_(" (vreplace)"), attr);
#ifdef FEAT_RIGHTLEFT
if (p_hkmap)
MSG_PUTS_ATTR(_(" Hebrew"), attr);
# ifdef FEAT_FKMAP
if (p_fkmap)
MSG_PUTS_ATTR(farsi_text_5, attr);
# endif
#endif
#ifdef FEAT_KEYMAP
if (State & LANGMAP)
{
# ifdef FEAT_ARABIC
if (curwin->w_p_arab)
MSG_PUTS_ATTR(_(" Arabic"), attr);
else
# endif
MSG_PUTS_ATTR(_(" (lang)"), attr);
}
#endif
if ((State & INSERT) && p_paste)
MSG_PUTS_ATTR(_(" (paste)"), attr);
#ifdef FEAT_VISUAL
if (VIsual_active)
{
char *p;
/* Don't concatenate separate words to avoid translation
* problems. */
switch ((VIsual_select ? 4 : 0)
+ (VIsual_mode == Ctrl_V) * 2
+ (VIsual_mode == 'V'))
{
case 0: p = N_(" VISUAL"); break;
case 1: p = N_(" VISUAL LINE"); break;
case 2: p = N_(" VISUAL BLOCK"); break;
case 4: p = N_(" SELECT"); break;
case 5: p = N_(" SELECT LINE"); break;
default: p = N_(" SELECT BLOCK"); break;
}
MSG_PUTS_ATTR(_(p), attr);
}
#endif
MSG_PUTS_ATTR(" --", attr);
}
need_clear = TRUE;
}
if (Recording
#ifdef FEAT_INS_EXPAND
&& edit_submode == NULL /* otherwise it gets too long */
#endif
)
{
MSG_PUTS_ATTR(_("recording"), attr);
need_clear = TRUE;
}
mode_displayed = TRUE;
if (need_clear || clear_cmdline)
msg_clr_eos();
msg_didout = FALSE; /* overwrite this message */
length = msg_col;
msg_col = 0;
need_wait_return = nwr_save; /* never ask for hit-return for this */
}
else if (clear_cmdline && msg_silent == 0)
/* Clear the whole command line. Will reset "clear_cmdline". */
msg_clr_cmdline();
#ifdef FEAT_CMDL_INFO
# ifdef FEAT_VISUAL
/* In Visual mode the size of the selected area must be redrawn. */
if (VIsual_active)
clear_showcmd();
# endif
/* If the last window has no status line, the ruler is after the mode
* message and must be redrawn */
if (redrawing()
# ifdef FEAT_WINDOWS
&& lastwin->w_status_height == 0
# endif
)
win_redr_ruler(lastwin, TRUE);
#endif
redraw_cmdline = FALSE;
clear_cmdline = FALSE;
return length;
}
/*
* Position for a mode message.
*/
static void
msg_pos_mode()
{
msg_col = 0;
msg_row = Rows - 1;
}
/*
* Delete mode message. Used when ESC is typed which is expected to end
* Insert mode (but Insert mode didn't end yet!).
* Caller should check "mode_displayed".
*/
void
unshowmode(force)
int force;
{
/*
* Don't delete it right now, when not redrawing or inside a mapping.
*/
if (!redrawing() || (!force && char_avail() && !KeyTyped))
redraw_cmdline = TRUE; /* delete mode later */
else
{
msg_pos_mode();
if (Recording)
MSG_PUTS_ATTR(_("recording"), hl_attr(HLF_CM));
msg_clr_eos();
}
}
#if defined(FEAT_WINDOWS)
/*
* Draw the tab pages line at the top of the Vim window.
*/
static void
draw_tabline()
{
int tabcount = 0;
tabpage_T *tp;
int tabwidth;
int col = 0;
int scol = 0;
int attr;
win_T *wp;
win_T *cwp;
int wincount;
int modified;
int c;
int len;
int attr_sel = hl_attr(HLF_TPS);
int attr_nosel = hl_attr(HLF_TP);
int attr_fill = hl_attr(HLF_TPF);
char_u *p;
int room;
int use_sep_chars = (t_colors < 8
#ifdef FEAT_GUI
&& !gui.in_use
#endif
);
redraw_tabline = FALSE;
#ifdef FEAT_GUI_TABLINE
/* Take care of a GUI tabline. */
if (gui_use_tabline())
{
gui_update_tabline();
return;
}
#endif
if (tabline_height() < 1)
return;
#if defined(FEAT_STL_OPT)
/* Init TabPageIdxs[] to zero: Clicking outside of tabs has no effect. */
for (scol = 0; scol < Columns; ++scol)
TabPageIdxs[scol] = 0;
/* Use the 'tabline' option if it's set. */
if (*p_tal != NUL)
{
int save_called_emsg = called_emsg;
/* Check for an error. If there is one we would loop in redrawing the
* screen. Avoid that by making 'tabline' empty. */
called_emsg = FALSE;
win_redr_custom(NULL, FALSE);
if (called_emsg)
set_string_option_direct((char_u *)"tabline", -1,
(char_u *)"", OPT_FREE, SID_ERROR);
called_emsg |= save_called_emsg;
}
else
#endif
{
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
++tabcount;
tabwidth = (Columns - 1 + tabcount / 2) / tabcount;
if (tabwidth < 6)
tabwidth = 6;
attr = attr_nosel;
tabcount = 0;
scol = 0;
for (tp = first_tabpage; tp != NULL && col < Columns - 4;
tp = tp->tp_next)
{
scol = col;
if (tp->tp_topframe == topframe)
attr = attr_sel;
if (use_sep_chars && col > 0)
screen_putchar('|', 0, col++, attr);
if (tp->tp_topframe != topframe)
attr = attr_nosel;
screen_putchar(' ', 0, col++, attr);
if (tp == curtab)
{
cwp = curwin;
wp = firstwin;
}
else
{
cwp = tp->tp_curwin;
wp = tp->tp_firstwin;
}
modified = FALSE;
for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
if (bufIsChanged(wp->w_buffer))
modified = TRUE;
if (modified || wincount > 1)
{
if (wincount > 1)
{
vim_snprintf((char *)NameBuff, MAXPATHL, "%d", wincount);
len = (int)STRLEN(NameBuff);
if (col + len >= Columns - 3)
break;
screen_puts_len(NameBuff, len, 0, col,
#if defined(FEAT_SYN_HL)
hl_combine_attr(attr, hl_attr(HLF_T))
#else
attr
#endif
);
col += len;
}
if (modified)
screen_puts_len((char_u *)"+", 1, 0, col++, attr);
screen_putchar(' ', 0, col++, attr);
}
room = scol - col + tabwidth - 1;
if (room > 0)
{
/* Get buffer name in NameBuff[] */
get_trans_bufname(cwp->w_buffer);
shorten_dir(NameBuff);
len = vim_strsize(NameBuff);
p = NameBuff;
#ifdef FEAT_MBYTE
if (has_mbyte)
while (len > room)
{
len -= ptr2cells(p);
mb_ptr_adv(p);
}
else
#endif
if (len > room)
{
p += len - room;
len = room;
}
if (len > Columns - col - 1)
len = Columns - col - 1;
screen_puts_len(p, (int)STRLEN(p), 0, col, attr);
col += len;
}
screen_putchar(' ', 0, col++, attr);
/* Store the tab page number in TabPageIdxs[], so that
* jump_to_mouse() knows where each one is. */
++tabcount;
while (scol < col)
TabPageIdxs[scol++] = tabcount;
}
if (use_sep_chars)
c = '_';
else
c = ' ';
screen_fill(0, 1, col, (int)Columns, c, c, attr_fill);
/* Put an "X" for closing the current tab if there are several. */
if (first_tabpage->tp_next != NULL)
{
screen_putchar('X', 0, (int)Columns - 1, attr_nosel);
TabPageIdxs[Columns - 1] = -999;
}
}
/* Reset the flag here again, in case evaluating 'tabline' causes it to be
* set. */
redraw_tabline = FALSE;
}
/*
* Get buffer name for "buf" into NameBuff[].
* Takes care of special buffer names and translates special characters.
*/
void
get_trans_bufname(buf)
buf_T *buf;
{
if (buf_spname(buf) != NULL)
STRCPY(NameBuff, buf_spname(buf));
else
home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE);
trans_characters(NameBuff, MAXPATHL);
}
#endif
#if defined(FEAT_WINDOWS) || defined(FEAT_WILDMENU) || defined(FEAT_STL_OPT)
/*
* Get the character to use in a status line. Get its attributes in "*attr".
*/
static int
fillchar_status(attr, is_curwin)
int *attr;
int is_curwin;
{
int fill;
if (is_curwin)
{
*attr = hl_attr(HLF_S);
fill = fill_stl;
}
else
{
*attr = hl_attr(HLF_SNC);
fill = fill_stlnc;
}
/* Use fill when there is highlighting, and highlighting of current
* window differs, or the fillchars differ, or this is not the
* current window */
if (*attr != 0 && ((hl_attr(HLF_S) != hl_attr(HLF_SNC)
|| !is_curwin || firstwin == lastwin)
|| (fill_stl != fill_stlnc)))
return fill;
if (is_curwin)
return '^';
return '=';
}
#endif
#ifdef FEAT_VERTSPLIT
/*
* Get the character to use in a separator between vertically split windows.
* Get its attributes in "*attr".
*/
static int
fillchar_vsep(attr)
int *attr;
{
*attr = hl_attr(HLF_C);
if (*attr == 0 && fill_vert == ' ')
return '|';
else
return fill_vert;
}
#endif
/*
* Return TRUE if redrawing should currently be done.
*/
int
redrawing()
{
return (!RedrawingDisabled
&& !(p_lz && char_avail() && !KeyTyped && !do_redraw));
}
/*
* Return TRUE if printing messages should currently be done.
*/
int
messaging()
{
return (!(p_lz && char_avail() && !KeyTyped));
}
/*
* Show current status info in ruler and various other places
* If always is FALSE, only show ruler if position has changed.
*/
void
showruler(always)
int always;
{
if (!always && !redrawing())
return;
#ifdef FEAT_INS_EXPAND
if (pum_visible())
{
# ifdef FEAT_WINDOWS
/* Don't redraw right now, do it later. */
curwin->w_redr_status = TRUE;
# endif
return;
}
#endif
#if defined(FEAT_STL_OPT) && defined(FEAT_WINDOWS)
if ((*p_stl != NUL || *curwin->w_p_stl != NUL) && curwin->w_status_height)
{
redraw_custom_statusline(curwin);
}
else
#endif
#ifdef FEAT_CMDL_INFO
win_redr_ruler(curwin, always);
#endif
#ifdef FEAT_TITLE
if (need_maketitle
# ifdef FEAT_STL_OPT
|| (p_icon && (stl_syntax & STL_IN_ICON))
|| (p_title && (stl_syntax & STL_IN_TITLE))
# endif
)
maketitle();
#endif
#ifdef FEAT_WINDOWS
/* Redraw the tab pages line if needed. */
if (redraw_tabline)
draw_tabline();
#endif
}
#ifdef FEAT_CMDL_INFO
static void
win_redr_ruler(wp, always)
win_T *wp;
int always;
{
#define RULER_BUF_LEN 70
char_u buffer[RULER_BUF_LEN];
int row;
int fillchar;
int attr;
int empty_line = FALSE;
colnr_T virtcol;
int i;
size_t len;
int o;
#ifdef FEAT_VERTSPLIT
int this_ru_col;
int off = 0;
int width = Columns;
# define WITH_OFF(x) x
# define WITH_WIDTH(x) x
#else
# define WITH_OFF(x) 0
# define WITH_WIDTH(x) Columns
# define this_ru_col ru_col
#endif
/* If 'ruler' off or redrawing disabled, don't do anything */
if (!p_ru)
return;
/*
* Check if cursor.lnum is valid, since win_redr_ruler() may be called
* after deleting lines, before cursor.lnum is corrected.
*/
if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count)
return;
#ifdef FEAT_INS_EXPAND
/* Don't draw the ruler while doing insert-completion, it might overwrite
* the (long) mode message. */
# ifdef FEAT_WINDOWS
if (wp == lastwin && lastwin->w_status_height == 0)
# endif
if (edit_submode != NULL)
return;
/* Don't draw the ruler when the popup menu is visible, it may overlap. */
if (pum_visible())
return;
#endif
#ifdef FEAT_STL_OPT
if (*p_ruf)
{
int save_called_emsg = called_emsg;
called_emsg = FALSE;
win_redr_custom(wp, TRUE);
if (called_emsg)
set_string_option_direct((char_u *)"rulerformat", -1,
(char_u *)"", OPT_FREE, SID_ERROR);
called_emsg |= save_called_emsg;
return;
}
#endif
/*
* Check if not in Insert mode and the line is empty (will show "0-1").
*/
if (!(State & INSERT)
&& *ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE) == NUL)
empty_line = TRUE;
/*
* Only draw the ruler when something changed.
*/
validate_virtcol_win(wp);
if ( redraw_cmdline
|| always
|| wp->w_cursor.lnum != wp->w_ru_cursor.lnum
|| wp->w_cursor.col != wp->w_ru_cursor.col
|| wp->w_virtcol != wp->w_ru_virtcol
#ifdef FEAT_VIRTUALEDIT
|| wp->w_cursor.coladd != wp->w_ru_cursor.coladd
#endif
|| wp->w_topline != wp->w_ru_topline
|| wp->w_buffer->b_ml.ml_line_count != wp->w_ru_line_count
#ifdef FEAT_DIFF
|| wp->w_topfill != wp->w_ru_topfill
#endif
|| empty_line != wp->w_ru_empty)
{
cursor_off();
#ifdef FEAT_WINDOWS
if (wp->w_status_height)
{
row = W_WINROW(wp) + wp->w_height;
fillchar = fillchar_status(&attr, wp == curwin);
# ifdef FEAT_VERTSPLIT
off = W_WINCOL(wp);
width = W_WIDTH(wp);
# endif
}
else
#endif
{
row = Rows - 1;
fillchar = ' ';
attr = 0;
#ifdef FEAT_VERTSPLIT
width = Columns;
off = 0;
#endif
}
/* 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;
getvvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL);
wp->w_p_list = TRUE;
}
/*
* Some sprintfs return the length, some return a pointer.
* To avoid portability problems we use strlen() here.
*/
vim_snprintf((char *)buffer, RULER_BUF_LEN, "%ld,",
(wp->w_buffer->b_ml.ml_flags & ML_EMPTY)
? 0L
: (long)(wp->w_cursor.lnum));
len = STRLEN(buffer);
col_print(buffer + len, RULER_BUF_LEN - len,
empty_line ? 0 : (int)wp->w_cursor.col + 1,
(int)virtcol + 1);
/*
* Add a "50%" if there is room for it.
* On the last line, don't print in the last column (scrolls the
* screen up on some terminals).
*/
i = (int)STRLEN(buffer);
get_rel_pos(wp, buffer + i + 1, RULER_BUF_LEN - i - 1);
o = i + vim_strsize(buffer + i + 1);
#ifdef FEAT_WINDOWS
if (wp->w_status_height == 0) /* can't use last char of screen */
#endif
++o;
#ifdef FEAT_VERTSPLIT
this_ru_col = ru_col - (Columns - width);
if (this_ru_col < 0)
this_ru_col = 0;
#endif
/* Never use more than half the window/screen width, leave the other
* half for the filename. */
if (this_ru_col < (WITH_WIDTH(width) + 1) / 2)
this_ru_col = (WITH_WIDTH(width) + 1) / 2;
if (this_ru_col + o < WITH_WIDTH(width))
{
while (this_ru_col + o < WITH_WIDTH(width))
{
#ifdef FEAT_MBYTE
if (has_mbyte)
i += (*mb_char2bytes)(fillchar, buffer + i);
else
#endif
buffer[i++] = fillchar;
++o;
}
get_rel_pos(wp, buffer + i, RULER_BUF_LEN - i);
}
/* Truncate at window boundary. */
#ifdef FEAT_MBYTE
if (has_mbyte)
{
o = 0;
for (i = 0; buffer[i] != NUL; i += (*mb_ptr2len)(buffer + i))
{
o += (*mb_ptr2cells)(buffer + i);
if (this_ru_col + o > WITH_WIDTH(width))
{
buffer[i] = NUL;
break;
}
}
}
else
#endif
if (this_ru_col + (int)STRLEN(buffer) > WITH_WIDTH(width))
buffer[WITH_WIDTH(width) - this_ru_col] = NUL;
screen_puts(buffer, row, this_ru_col + WITH_OFF(off), attr);
i = redraw_cmdline;
screen_fill(row, row + 1,
this_ru_col + WITH_OFF(off) + (int)STRLEN(buffer),
(int)(WITH_OFF(off) + WITH_WIDTH(width)),
fillchar, fillchar, attr);
/* don't redraw the cmdline because of showing the ruler */
redraw_cmdline = i;
wp->w_ru_cursor = wp->w_cursor;
wp->w_ru_virtcol = wp->w_virtcol;
wp->w_ru_empty = empty_line;
wp->w_ru_topline = wp->w_topline;
wp->w_ru_line_count = wp->w_buffer->b_ml.ml_line_count;
#ifdef FEAT_DIFF
wp->w_ru_topfill = wp->w_topfill;
#endif
}
}
#endif
#if defined(FEAT_LINEBREAK) || defined(PROTO)
/*
* Return the width of the 'number' and 'relativenumber' column.
* Caller may need to check if 'number' or 'relativenumber' is set.
* Otherwise it depends on 'numberwidth' and the line count.
*/
int
number_width(wp)
win_T *wp;
{
int n;
linenr_T lnum;
if (wp->w_p_nu)
/* 'number' */
lnum = wp->w_buffer->b_ml.ml_line_count;
else
/* 'relativenumber' */
lnum = wp->w_height;
if (lnum == wp->w_nrwidth_line_count)
return wp->w_nrwidth_width;
wp->w_nrwidth_line_count = lnum;
n = 0;
do
{
lnum /= 10;
++n;
} while (lnum > 0);
/* 'numberwidth' gives the minimal width plus one */
if (n < wp->w_p_nuw - 1)
n = wp->w_p_nuw - 1;
wp->w_nrwidth_width = n;
return n;
}
#endif
| zyz2011-vim | src/screen.c | C | gpl2 | 252,981 |
/* 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.
*/
/*
* farsi.c: functions for Farsi language
*
* Included by main.c, when FEAT_FKMAP is defined.
*/
static int toF_Xor_X_ __ARGS((int c));
static int F_is_TyE __ARGS((int c));
static int F_is_TyC_TyD __ARGS((int c));
static int F_is_TyB_TyC_TyD __ARGS((int src, int offset));
static int toF_TyB __ARGS((int c));
static void put_curr_and_l_to_X __ARGS((int c));
static void put_and_redo __ARGS((int c));
static void chg_c_toX_orX __ARGS((void));
static void chg_c_to_X_orX_ __ARGS((void));
static void chg_c_to_X_or_X __ARGS((void));
static void chg_l_to_X_orX_ __ARGS((void));
static void chg_l_toXor_X __ARGS((void));
static void chg_r_to_Xor_X_ __ARGS((void));
static int toF_leading __ARGS((int c));
static int toF_Rjoin __ARGS((int c));
static int canF_Ljoin __ARGS((int c));
static int canF_Rjoin __ARGS((int c));
static int F_isterm __ARGS((int c));
static int toF_ending __ARGS((int c));
static void lrswapbuf __ARGS((char_u *buf, int len));
/*
** Convert the given Farsi character into a _X or _X_ type
*/
static int
toF_Xor_X_(c)
int c;
{
int tempc;
switch (c)
{
case BE:
return _BE;
case PE:
return _PE;
case TE:
return _TE;
case SE:
return _SE;
case JIM:
return _JIM;
case CHE:
return _CHE;
case HE_J:
return _HE_J;
case XE:
return _XE;
case SIN:
return _SIN;
case SHIN:
return _SHIN;
case SAD:
return _SAD;
case ZAD:
return _ZAD;
case AYN:
return _AYN;
case AYN_:
return _AYN_;
case GHAYN:
return _GHAYN;
case GHAYN_:
return _GHAYN_;
case FE:
return _FE;
case GHAF:
return _GHAF;
case KAF:
return _KAF;
case GAF:
return _GAF;
case LAM:
return _LAM;
case MIM:
return _MIM;
case NOON:
return _NOON;
case YE:
case YE_:
return _YE;
case YEE:
case YEE_:
return _YEE;
case IE:
case IE_:
return _IE;
case F_HE:
tempc = _HE;
if (p_ri && (curwin->w_cursor.col + 1
< (colnr_T)STRLEN(ml_get_curline())))
{
inc_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = _HE_;
dec_cursor();
}
if (!p_ri && STRLEN(ml_get_curline()))
{
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = _HE_;
inc_cursor();
}
return tempc;
}
return 0;
}
/*
** Convert the given Farsi character into Farsi capital character .
*/
int
toF_TyA(c)
int c ;
{
switch (c)
{
case ALEF_:
return ALEF;
case ALEF_U_H_:
return ALEF_U_H;
case _BE:
return BE;
case _PE:
return PE;
case _TE:
return TE;
case _SE:
return SE;
case _JIM:
return JIM;
case _CHE:
return CHE;
case _HE_J:
return HE_J;
case _XE:
return XE;
case _SIN:
return SIN;
case _SHIN:
return SHIN;
case _SAD:
return SAD;
case _ZAD:
return ZAD;
case _AYN:
case AYN_:
case _AYN_:
return AYN;
case _GHAYN:
case GHAYN_:
case _GHAYN_:
return GHAYN;
case _FE:
return FE;
case _GHAF:
return GHAF;
/* I am not sure what it is !!! case _KAF_H: */
case _KAF:
return KAF;
case _GAF:
return GAF;
case _LAM:
return LAM;
case _MIM:
return MIM;
case _NOON:
return NOON;
case _YE:
case YE_:
return YE;
case _YEE:
case YEE_:
return YEE;
case TEE_:
return TEE;
case _IE:
case IE_:
return IE;
case _HE:
case _HE_:
return F_HE;
}
return c;
}
/*
** Is the character under the cursor+offset in the given buffer a join type.
** That is a character that is combined with the others.
** Note: the offset is used only for command line buffer.
*/
static int
F_is_TyB_TyC_TyD(src, offset)
int src, offset;
{
int c;
if (src == SRC_EDT)
c = gchar_cursor();
else
c = cmd_gchar(AT_CURSOR+offset);
switch (c)
{
case _LAM:
case _BE:
case _PE:
case _TE:
case _SE:
case _JIM:
case _CHE:
case _HE_J:
case _XE:
case _SIN:
case _SHIN:
case _SAD:
case _ZAD:
case _TA:
case _ZA:
case _AYN:
case _AYN_:
case _GHAYN:
case _GHAYN_:
case _FE:
case _GHAF:
case _KAF:
case _KAF_H:
case _GAF:
case _MIM:
case _NOON:
case _YE:
case _YEE:
case _IE:
case _HE_:
case _HE:
return TRUE;
}
return FALSE;
}
/*
** Is the Farsi character one of the terminating only type.
*/
static int
F_is_TyE(c)
int c;
{
switch (c)
{
case ALEF_A:
case ALEF_D_H:
case DAL:
case ZAL:
case RE:
case ZE:
case JE:
case WAW:
case WAW_H:
case HAMZE:
return TRUE;
}
return FALSE;
}
/*
** Is the Farsi character one of the none leading type.
*/
static int
F_is_TyC_TyD(c)
int c;
{
switch (c)
{
case ALEF_:
case ALEF_U_H_:
case _AYN_:
case AYN_:
case _GHAYN_:
case GHAYN_:
case _HE_:
case YE_:
case IE_:
case TEE_:
case YEE_:
return TRUE;
}
return FALSE;
}
/*
** Convert a none leading Farsi char into a leading type.
*/
static int
toF_TyB(c)
int c;
{
switch (c)
{
case ALEF_: return ALEF;
case ALEF_U_H_: return ALEF_U_H;
case _AYN_: return _AYN;
case AYN_: return AYN; /* exception - there are many of them */
case _GHAYN_: return _GHAYN;
case GHAYN_: return GHAYN; /* exception - there are many of them */
case _HE_: return _HE;
case YE_: return YE;
case IE_: return IE;
case TEE_: return TEE;
case YEE_: return YEE;
}
return c;
}
/*
** Overwrite the current redo and cursor characters + left adjust
*/
static void
put_curr_and_l_to_X(c)
int c;
{
int tempc;
if (curwin->w_p_rl && p_ri)
return;
if ((curwin->w_cursor.col < (colnr_T)STRLEN(ml_get_curline())))
{
if ((p_ri && curwin->w_cursor.col) || !p_ri)
{
if (p_ri)
dec_cursor();
else
inc_cursor();
if (F_is_TyC_TyD((tempc = gchar_cursor())))
{
pchar_cursor(toF_TyB(tempc));
AppendCharToRedobuff(K_BS);
AppendCharToRedobuff(tempc);
}
if (p_ri)
inc_cursor();
else
dec_cursor();
}
}
put_and_redo(c);
}
static void
put_and_redo(c)
int c;
{
pchar_cursor(c);
AppendCharToRedobuff(K_BS);
AppendCharToRedobuff(c);
}
/*
** Change the char. under the cursor to a X_ or X type
*/
static void
chg_c_toX_orX()
{
int tempc, curc;
switch ((curc = gchar_cursor()))
{
case _BE:
tempc = BE;
break;
case _PE:
tempc = PE;
break;
case _TE:
tempc = TE;
break;
case _SE:
tempc = SE;
break;
case _JIM:
tempc = JIM;
break;
case _CHE:
tempc = CHE;
break;
case _HE_J:
tempc = HE_J;
break;
case _XE:
tempc = XE;
break;
case _SIN:
tempc = SIN;
break;
case _SHIN:
tempc = SHIN;
break;
case _SAD:
tempc = SAD;
break;
case _ZAD:
tempc = ZAD;
break;
case _FE:
tempc = FE;
break;
case _GHAF:
tempc = GHAF;
break;
case _KAF_H:
case _KAF:
tempc = KAF;
break;
case _GAF:
tempc = GAF;
break;
case _AYN:
tempc = AYN;
break;
case _AYN_:
tempc = AYN_;
break;
case _GHAYN:
tempc = GHAYN;
break;
case _GHAYN_:
tempc = GHAYN_;
break;
case _LAM:
tempc = LAM;
break;
case _MIM:
tempc = MIM;
break;
case _NOON:
tempc = NOON;
break;
case _HE:
case _HE_:
tempc = F_HE;
break;
case _YE:
case _IE:
case _YEE:
if (p_ri)
{
inc_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = (curc == _YE ? YE_ :
(curc == _IE ? IE_ : YEE_));
else
tempc = (curc == _YE ? YE :
(curc == _IE ? IE : YEE));
dec_cursor();
}
else
{
if (curwin->w_cursor.col)
{
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = (curc == _YE ? YE_ :
(curc == _IE ? IE_ : YEE_));
else
tempc = (curc == _YE ? YE :
(curc == _IE ? IE : YEE));
inc_cursor();
}
else
tempc = (curc == _YE ? YE :
(curc == _IE ? IE : YEE));
}
break;
default:
tempc = 0;
}
if (tempc)
put_and_redo(tempc);
}
/*
** Change the char. under the cursor to a _X_ or X_ type
*/
static void
chg_c_to_X_orX_()
{
int tempc;
switch (gchar_cursor())
{
case ALEF:
tempc = ALEF_;
break;
case ALEF_U_H:
tempc = ALEF_U_H_;
break;
case _AYN:
tempc = _AYN_;
break;
case AYN:
tempc = AYN_;
break;
case _GHAYN:
tempc = _GHAYN_;
break;
case GHAYN:
tempc = GHAYN_;
break;
case _HE:
tempc = _HE_;
break;
case YE:
tempc = YE_;
break;
case IE:
tempc = IE_;
break;
case TEE:
tempc = TEE_;
break;
case YEE:
tempc = YEE_;
break;
default:
tempc = 0;
}
if (tempc)
put_and_redo(tempc);
}
/*
** Change the char. under the cursor to a _X_ or _X type
*/
static void
chg_c_to_X_or_X ()
{
int tempc;
tempc = gchar_cursor();
if (curwin->w_cursor.col + 1 < (colnr_T)STRLEN(ml_get_curline()))
{
inc_cursor();
if ((tempc == F_HE) && (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR)))
{
tempc = _HE_;
dec_cursor();
put_and_redo(tempc);
return;
}
dec_cursor();
}
if ((tempc = toF_Xor_X_(tempc)) != 0)
put_and_redo(tempc);
}
/*
** Change the character left to the cursor to a _X_ or X_ type
*/
static void
chg_l_to_X_orX_ ()
{
int tempc;
if (curwin->w_cursor.col != 0 &&
(curwin->w_cursor.col + 1 == (colnr_T)STRLEN(ml_get_curline())))
return;
if (!curwin->w_cursor.col && p_ri)
return;
if (p_ri)
dec_cursor();
else
inc_cursor();
switch (gchar_cursor())
{
case ALEF:
tempc = ALEF_;
break;
case ALEF_U_H:
tempc = ALEF_U_H_;
break;
case _AYN:
tempc = _AYN_;
break;
case AYN:
tempc = AYN_;
break;
case _GHAYN:
tempc = _GHAYN_;
break;
case GHAYN:
tempc = GHAYN_;
break;
case _HE:
tempc = _HE_;
break;
case YE:
tempc = YE_;
break;
case IE:
tempc = IE_;
break;
case TEE:
tempc = TEE_;
break;
case YEE:
tempc = YEE_;
break;
default:
tempc = 0;
}
if (tempc)
put_and_redo(tempc);
if (p_ri)
inc_cursor();
else
dec_cursor();
}
/*
** Change the character left to the cursor to a X or _X type
*/
static void
chg_l_toXor_X ()
{
int tempc;
if (curwin->w_cursor.col != 0 &&
(curwin->w_cursor.col + 1 == (colnr_T)STRLEN(ml_get_curline())))
return;
if (!curwin->w_cursor.col && p_ri)
return;
if (p_ri)
dec_cursor();
else
inc_cursor();
switch (gchar_cursor())
{
case ALEF_:
tempc = ALEF;
break;
case ALEF_U_H_:
tempc = ALEF_U_H;
break;
case _AYN_:
tempc = _AYN;
break;
case AYN_:
tempc = AYN;
break;
case _GHAYN_:
tempc = _GHAYN;
break;
case GHAYN_:
tempc = GHAYN;
break;
case _HE_:
tempc = _HE;
break;
case YE_:
tempc = YE;
break;
case IE_:
tempc = IE;
break;
case TEE_:
tempc = TEE;
break;
case YEE_:
tempc = YEE;
break;
default:
tempc = 0;
}
if (tempc)
put_and_redo(tempc);
if (p_ri)
inc_cursor();
else
dec_cursor();
}
/*
** Change the character right to the cursor to a _X or _X_ type
*/
static void
chg_r_to_Xor_X_()
{
int tempc, c;
if (curwin->w_cursor.col)
{
if (!p_ri)
dec_cursor();
tempc = gchar_cursor();
if ((c = toF_Xor_X_(tempc)) != 0)
put_and_redo(c);
if (!p_ri)
inc_cursor();
}
}
/*
** Map Farsi keyboard when in fkmap mode.
*/
int
fkmap(c)
int c;
{
int tempc;
static int revins;
if (IS_SPECIAL(c))
return c;
if (VIM_ISDIGIT(c) || ((c == '.' || c == '+' || c == '-' ||
c == '^' || c == '%' || c == '#' || c == '=') && revins))
{
if (!revins)
{
if (curwin->w_cursor.col)
{
if (!p_ri)
dec_cursor();
chg_c_toX_orX ();
chg_l_toXor_X ();
if (!p_ri)
inc_cursor();
}
}
arrow_used = TRUE;
(void)stop_arrow();
if (!curwin->w_p_rl && revins)
inc_cursor();
++revins;
p_ri=1;
}
else
{
if (revins)
{
arrow_used = TRUE;
(void)stop_arrow();
revins = 0;
if (curwin->w_p_rl)
{
while ((F_isdigit(gchar_cursor())
|| (gchar_cursor() == F_PERIOD
|| gchar_cursor() == F_PLUS
|| gchar_cursor() == F_MINUS
|| gchar_cursor() == F_MUL
|| gchar_cursor() == F_DIVIDE
|| gchar_cursor() == F_PERCENT
|| gchar_cursor() == F_EQUALS))
&& gchar_cursor() != NUL)
++curwin->w_cursor.col;
}
else
{
if (curwin->w_cursor.col)
while ((F_isdigit(gchar_cursor())
|| (gchar_cursor() == F_PERIOD
|| gchar_cursor() == F_PLUS
|| gchar_cursor() == F_MINUS
|| gchar_cursor() == F_MUL
|| gchar_cursor() == F_DIVIDE
|| gchar_cursor() == F_PERCENT
|| gchar_cursor() == F_EQUALS))
&& --curwin->w_cursor.col)
;
if (!F_isdigit(gchar_cursor()))
++curwin->w_cursor.col;
}
}
}
if (!revins)
{
if (curwin->w_p_rl)
p_ri=0;
if (!curwin->w_p_rl)
p_ri=1;
}
if ((c < 0x100) && (isalpha(c) || c == '&' || c == '^' || c == ';' ||
c == '\''|| c == ',' || c == '[' ||
c == ']' || c == '{' || c == '}' ))
chg_r_to_Xor_X_();
tempc = 0;
switch (c)
{
case '`':
case ' ':
case '.':
case '!':
case '"':
case '$':
case '%':
case '^':
case '&':
case '/':
case '(':
case ')':
case '=':
case '\\':
case '?':
case '+':
case '-':
case '_':
case '*':
case ':':
case '#':
case '~':
case '@':
case '<':
case '>':
case '{':
case '}':
case '|':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'B':
case 'E':
case 'F':
case 'H':
case 'I':
case 'K':
case 'L':
case 'M':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'W':
case 'Y':
case NL:
case TAB:
if (p_ri && c == NL && curwin->w_cursor.col)
{
/*
** If the char before the cursor is _X_ or X_ do not change
** the one under the cursor with X type.
*/
dec_cursor();
if (F_isalpha(gchar_cursor()))
{
inc_cursor();
return NL;
}
inc_cursor();
}
if (!p_ri)
if (!curwin->w_cursor.col)
{
switch (c)
{
case '0': return FARSI_0;
case '1': return FARSI_1;
case '2': return FARSI_2;
case '3': return FARSI_3;
case '4': return FARSI_4;
case '5': return FARSI_5;
case '6': return FARSI_6;
case '7': return FARSI_7;
case '8': return FARSI_8;
case '9': return FARSI_9;
case 'B': return F_PSP;
case 'E': return JAZR_N;
case 'F': return ALEF_D_H;
case 'H': return ALEF_A;
case 'I': return TASH;
case 'K': return F_LQUOT;
case 'L': return F_RQUOT;
case 'M': return HAMZE;
case 'O': return '[';
case 'P': return ']';
case 'Q': return OO;
case 'R': return MAD_N;
case 'T': return OW;
case 'U': return MAD;
case 'W': return OW_OW;
case 'Y': return JAZR;
case '`': return F_PCN;
case '!': return F_EXCL;
case '@': return F_COMMA;
case '#': return F_DIVIDE;
case '$': return F_CURRENCY;
case '%': return F_PERCENT;
case '^': return F_MUL;
case '&': return F_BCOMMA;
case '*': return F_STAR;
case '(': return F_LPARENT;
case ')': return F_RPARENT;
case '-': return F_MINUS;
case '_': return F_UNDERLINE;
case '=': return F_EQUALS;
case '+': return F_PLUS;
case '\\': return F_BSLASH;
case '|': return F_PIPE;
case ':': return F_DCOLON;
case '"': return F_SEMICOLON;
case '.': return F_PERIOD;
case '/': return F_SLASH;
case '<': return F_LESS;
case '>': return F_GREATER;
case '?': return F_QUESTION;
case ' ': return F_BLANK;
}
break;
}
if (!p_ri)
dec_cursor();
switch ((tempc = gchar_cursor()))
{
case _BE:
case _PE:
case _TE:
case _SE:
case _JIM:
case _CHE:
case _HE_J:
case _XE:
case _SIN:
case _SHIN:
case _SAD:
case _ZAD:
case _FE:
case _GHAF:
case _KAF:
case _KAF_H:
case _GAF:
case _LAM:
case _MIM:
case _NOON:
case _HE:
case _HE_:
case _TA:
case _ZA:
put_curr_and_l_to_X(toF_TyA(tempc));
break;
case _AYN:
case _AYN_:
if (!p_ri)
if (!curwin->w_cursor.col)
{
put_curr_and_l_to_X(AYN);
break;
}
if (p_ri)
inc_cursor();
else
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = AYN_;
else
tempc = AYN;
if (p_ri)
dec_cursor();
else
inc_cursor();
put_curr_and_l_to_X(tempc);
break;
case _GHAYN:
case _GHAYN_:
if (!p_ri)
if (!curwin->w_cursor.col)
{
put_curr_and_l_to_X(GHAYN);
break;
}
if (p_ri)
inc_cursor();
else
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = GHAYN_;
else
tempc = GHAYN;
if (p_ri)
dec_cursor();
else
inc_cursor();
put_curr_and_l_to_X(tempc);
break;
case _YE:
case _IE:
case _YEE:
if (!p_ri)
if (!curwin->w_cursor.col)
{
put_curr_and_l_to_X((tempc == _YE ? YE :
(tempc == _IE ? IE : YEE)));
break;
}
if (p_ri)
inc_cursor();
else
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = (tempc == _YE ? YE_ :
(tempc == _IE ? IE_ : YEE_));
else
tempc = (tempc == _YE ? YE :
(tempc == _IE ? IE : YEE));
if (p_ri)
dec_cursor();
else
inc_cursor();
put_curr_and_l_to_X(tempc);
break;
}
if (!p_ri)
inc_cursor();
tempc = 0;
switch (c)
{
case '0': return FARSI_0;
case '1': return FARSI_1;
case '2': return FARSI_2;
case '3': return FARSI_3;
case '4': return FARSI_4;
case '5': return FARSI_5;
case '6': return FARSI_6;
case '7': return FARSI_7;
case '8': return FARSI_8;
case '9': return FARSI_9;
case 'B': return F_PSP;
case 'E': return JAZR_N;
case 'F': return ALEF_D_H;
case 'H': return ALEF_A;
case 'I': return TASH;
case 'K': return F_LQUOT;
case 'L': return F_RQUOT;
case 'M': return HAMZE;
case 'O': return '[';
case 'P': return ']';
case 'Q': return OO;
case 'R': return MAD_N;
case 'T': return OW;
case 'U': return MAD;
case 'W': return OW_OW;
case 'Y': return JAZR;
case '`': return F_PCN;
case '!': return F_EXCL;
case '@': return F_COMMA;
case '#': return F_DIVIDE;
case '$': return F_CURRENCY;
case '%': return F_PERCENT;
case '^': return F_MUL;
case '&': return F_BCOMMA;
case '*': return F_STAR;
case '(': return F_LPARENT;
case ')': return F_RPARENT;
case '-': return F_MINUS;
case '_': return F_UNDERLINE;
case '=': return F_EQUALS;
case '+': return F_PLUS;
case '\\': return F_BSLASH;
case '|': return F_PIPE;
case ':': return F_DCOLON;
case '"': return F_SEMICOLON;
case '.': return F_PERIOD;
case '/': return F_SLASH;
case '<': return F_LESS;
case '>': return F_GREATER;
case '?': return F_QUESTION;
case ' ': return F_BLANK;
}
break;
case 'a':
tempc = _SHIN;
break;
case 'A':
tempc = WAW_H;
break;
case 'b':
tempc = ZAL;
break;
case 'c':
tempc = ZE;
break;
case 'C':
tempc = JE;
break;
case 'd':
tempc = _YE;
break;
case 'D':
tempc = _YEE;
break;
case 'e':
tempc = _SE;
break;
case 'f':
tempc = _BE;
break;
case 'g':
tempc = _LAM;
break;
case 'G':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (gchar_cursor() == _LAM)
chg_c_toX_orX ();
else
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri)
if (!curwin->w_cursor.col)
return ALEF_U_H;
if (!p_ri)
dec_cursor();
if (gchar_cursor() == _LAM)
{
chg_c_toX_orX ();
chg_l_toXor_X ();
tempc = ALEF_U_H;
}
else
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
{
tempc = ALEF_U_H_;
chg_l_toXor_X ();
}
else
tempc = ALEF_U_H;
if (!p_ri)
inc_cursor();
return tempc;
case 'h':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri)
if (!curwin->w_cursor.col)
return ALEF;
if (!p_ri)
dec_cursor();
if (gchar_cursor() == _LAM)
{
chg_l_toXor_X();
del_char(FALSE);
AppendCharToRedobuff(K_BS);
if (!p_ri)
dec_cursor();
tempc = LA;
}
else
{
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
{
tempc = ALEF_;
chg_l_toXor_X ();
}
else
tempc = ALEF;
}
if (!p_ri)
inc_cursor();
return tempc;
case 'i':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (!p_ri && !F_is_TyE(tempc))
chg_c_to_X_orX_ ();
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri && !curwin->w_cursor.col)
return _HE;
if (!p_ri)
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = _HE_;
else
tempc = _HE;
if (!p_ri)
inc_cursor();
break;
case 'j':
tempc = _TE;
break;
case 'J':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri)
if (!curwin->w_cursor.col)
return TEE;
if (!p_ri)
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
{
tempc = TEE_;
chg_l_toXor_X ();
}
else
tempc = TEE;
if (!p_ri)
inc_cursor();
return tempc;
case 'k':
tempc = _NOON;
break;
case 'l':
tempc = _MIM;
break;
case 'm':
tempc = _PE;
break;
case 'n':
case 'N':
tempc = DAL;
break;
case 'o':
tempc = _XE;
break;
case 'p':
tempc = _HE_J;
break;
case 'q':
tempc = _ZAD;
break;
case 'r':
tempc = _GHAF;
break;
case 's':
tempc = _SIN;
break;
case 'S':
tempc = _IE;
break;
case 't':
tempc = _FE;
break;
case 'u':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (!p_ri && !F_is_TyE(tempc))
chg_c_to_X_orX_ ();
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri && !curwin->w_cursor.col)
return _AYN;
if (!p_ri)
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = _AYN_;
else
tempc = _AYN;
if (!p_ri)
inc_cursor();
break;
case 'v':
case 'V':
tempc = RE;
break;
case 'w':
tempc = _SAD;
break;
case 'x':
case 'X':
tempc = _TA;
break;
case 'y':
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (!p_ri && !F_is_TyE(tempc))
chg_c_to_X_orX_ ();
if (p_ri)
chg_c_to_X_or_X ();
}
if (!p_ri && !curwin->w_cursor.col)
return _GHAYN;
if (!p_ri)
dec_cursor();
if (F_is_TyB_TyC_TyD(SRC_EDT, AT_CURSOR))
tempc = _GHAYN_;
else
tempc = _GHAYN;
if (!p_ri)
inc_cursor();
break;
case 'z':
tempc = _ZA;
break;
case 'Z':
tempc = _KAF_H;
break;
case ';':
tempc = _KAF;
break;
case '\'':
tempc = _GAF;
break;
case ',':
tempc = WAW;
break;
case '[':
tempc = _JIM;
break;
case ']':
tempc = _CHE;
break;
}
if ((F_isalpha(tempc) || F_isdigit(tempc)))
{
if (!curwin->w_cursor.col && STRLEN(ml_get_curline()))
{
if (!p_ri && !F_is_TyE(tempc))
chg_c_to_X_orX_ ();
if (p_ri)
chg_c_to_X_or_X ();
}
if (curwin->w_cursor.col)
{
if (!p_ri)
dec_cursor();
if (F_is_TyE(tempc))
chg_l_toXor_X ();
else
chg_l_to_X_orX_ ();
if (!p_ri)
inc_cursor();
}
}
if (tempc)
return tempc;
return c;
}
/*
** Convert a none leading Farsi char into a leading type.
*/
static int
toF_leading(c)
int c;
{
switch (c)
{
case ALEF_: return ALEF;
case ALEF_U_H_: return ALEF_U_H;
case BE: return _BE;
case PE: return _PE;
case TE: return _TE;
case SE: return _SE;
case JIM: return _JIM;
case CHE: return _CHE;
case HE_J: return _HE_J;
case XE: return _XE;
case SIN: return _SIN;
case SHIN: return _SHIN;
case SAD: return _SAD;
case ZAD: return _ZAD;
case AYN:
case AYN_:
case _AYN_: return _AYN;
case GHAYN:
case GHAYN_:
case _GHAYN_: return _GHAYN;
case FE: return _FE;
case GHAF: return _GHAF;
case KAF: return _KAF;
case GAF: return _GAF;
case LAM: return _LAM;
case MIM: return _MIM;
case NOON: return _NOON;
case _HE_:
case F_HE: return _HE;
case YE:
case YE_: return _YE;
case IE_:
case IE: return _IE;
case YEE:
case YEE_: return _YEE;
}
return c;
}
/*
** Convert a given Farsi char into right joining type.
*/
static int
toF_Rjoin(c)
int c;
{
switch (c)
{
case ALEF: return ALEF_;
case ALEF_U_H: return ALEF_U_H_;
case BE: return _BE;
case PE: return _PE;
case TE: return _TE;
case SE: return _SE;
case JIM: return _JIM;
case CHE: return _CHE;
case HE_J: return _HE_J;
case XE: return _XE;
case SIN: return _SIN;
case SHIN: return _SHIN;
case SAD: return _SAD;
case ZAD: return _ZAD;
case AYN:
case AYN_:
case _AYN: return _AYN_;
case GHAYN:
case GHAYN_:
case _GHAYN_: return _GHAYN_;
case FE: return _FE;
case GHAF: return _GHAF;
case KAF: return _KAF;
case GAF: return _GAF;
case LAM: return _LAM;
case MIM: return _MIM;
case NOON: return _NOON;
case _HE:
case F_HE: return _HE_;
case YE:
case YE_: return _YE;
case IE_:
case IE: return _IE;
case TEE: return TEE_;
case YEE:
case YEE_: return _YEE;
}
return c;
}
/*
** Can a given Farsi character join via its left edj.
*/
static int
canF_Ljoin(c)
int c;
{
switch (c)
{
case _BE:
case BE:
case PE:
case _PE:
case TE:
case _TE:
case SE:
case _SE:
case JIM:
case _JIM:
case CHE:
case _CHE:
case HE_J:
case _HE_J:
case XE:
case _XE:
case SIN:
case _SIN:
case SHIN:
case _SHIN:
case SAD:
case _SAD:
case ZAD:
case _ZAD:
case _TA:
case _ZA:
case AYN:
case _AYN:
case _AYN_:
case AYN_:
case GHAYN:
case GHAYN_:
case _GHAYN_:
case _GHAYN:
case FE:
case _FE:
case GHAF:
case _GHAF:
case _KAF_H:
case KAF:
case _KAF:
case GAF:
case _GAF:
case LAM:
case _LAM:
case MIM:
case _MIM:
case NOON:
case _NOON:
case IE:
case _IE:
case IE_:
case YE:
case _YE:
case YE_:
case YEE:
case _YEE:
case YEE_:
case F_HE:
case _HE:
case _HE_:
return TRUE;
}
return FALSE;
}
/*
** Can a given Farsi character join via its right edj.
*/
static int
canF_Rjoin(c)
int c;
{
switch (c)
{
case ALEF:
case ALEF_:
case ALEF_U_H:
case ALEF_U_H_:
case DAL:
case ZAL:
case RE:
case JE:
case ZE:
case TEE:
case TEE_:
case WAW:
case WAW_H:
return TRUE;
}
return canF_Ljoin(c);
}
/*
** is a given Farsi character a terminating type.
*/
static int
F_isterm(c)
int c;
{
switch (c)
{
case ALEF:
case ALEF_:
case ALEF_U_H:
case ALEF_U_H_:
case DAL:
case ZAL:
case RE:
case JE:
case ZE:
case WAW:
case WAW_H:
case TEE:
case TEE_:
return TRUE;
}
return FALSE;
}
/*
** Convert the given Farsi character into a ending type .
*/
static int
toF_ending(c)
int c;
{
switch (c)
{
case _BE:
return BE;
case _PE:
return PE;
case _TE:
return TE;
case _SE:
return SE;
case _JIM:
return JIM;
case _CHE:
return CHE;
case _HE_J:
return HE_J;
case _XE:
return XE;
case _SIN:
return SIN;
case _SHIN:
return SHIN;
case _SAD:
return SAD;
case _ZAD:
return ZAD;
case _AYN:
return AYN;
case _AYN_:
return AYN_;
case _GHAYN:
return GHAYN;
case _GHAYN_:
return GHAYN_;
case _FE:
return FE;
case _GHAF:
return GHAF;
case _KAF_H:
case _KAF:
return KAF;
case _GAF:
return GAF;
case _LAM:
return LAM;
case _MIM:
return MIM;
case _NOON:
return NOON;
case _YE:
return YE_;
case YE_:
return YE;
case _YEE:
return YEE_;
case YEE_:
return YEE;
case TEE:
return TEE_;
case _IE:
return IE_;
case IE_:
return IE;
case _HE:
case _HE_:
return F_HE;
}
return c;
}
/*
** Convert the Farsi 3342 standard into Farsi VIM.
*/
void
conv_to_pvim()
{
char_u *ptr;
int lnum, llen, i;
for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
{
ptr = ml_get((linenr_T)lnum);
llen = (int)STRLEN(ptr);
for ( i = 0; i < llen-1; i++)
{
if (canF_Ljoin(ptr[i]) && canF_Rjoin(ptr[i+1]))
{
ptr[i] = toF_leading(ptr[i]);
++i;
while(canF_Rjoin(ptr[i]) && (i < llen))
{
ptr[i] = toF_Rjoin(ptr[i]);
if (F_isterm(ptr[i]) || !F_isalpha(ptr[i]))
break;
++i;
}
if (!F_isalpha(ptr[i]) || !canF_Rjoin(ptr[i]))
ptr[i-1] = toF_ending(ptr[i-1]);
}
else
ptr[i] = toF_TyA(ptr[i]);
}
}
/*
* Following lines contains Farsi encoded character.
*/
do_cmdline_cmd((char_u *)"%s/\202\231/\232/g");
do_cmdline_cmd((char_u *)"%s/\201\231/\370\334/g");
/* Assume the screen has been messed up: clear it and redraw. */
redraw_later(CLEAR);
MSG_ATTR(farsi_text_1, hl_attr(HLF_S));
}
/*
* Convert the Farsi VIM into Farsi 3342 standad.
*/
void
conv_to_pstd()
{
char_u *ptr;
int lnum, llen, i;
/*
* Following line contains Farsi encoded character.
*/
do_cmdline_cmd((char_u *)"%s/\232/\202\231/g");
for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
{
ptr = ml_get((linenr_T)lnum);
llen = (int)STRLEN(ptr);
for ( i = 0; i < llen; i++)
{
ptr[i] = toF_TyA(ptr[i]);
}
}
/* Assume the screen has been messed up: clear it and redraw. */
redraw_later(CLEAR);
MSG_ATTR(farsi_text_2, hl_attr(HLF_S));
}
/*
* left-right swap the characters in buf[len].
*/
static void
lrswapbuf(buf, len)
char_u *buf;
int len;
{
char_u *s, *e;
int c;
s = buf;
e = buf + len - 1;
while (e > s)
{
c = *s;
*s = *e;
*e = c;
++s;
--e;
}
}
/*
* swap all the characters in reverse direction
*/
char_u *
lrswap(ibuf)
char_u *ibuf;
{
if (ibuf != NULL && *ibuf != NUL)
lrswapbuf(ibuf, (int)STRLEN(ibuf));
return ibuf;
}
/*
* swap all the Farsi characters in reverse direction
*/
char_u *
lrFswap(cmdbuf, len)
char_u *cmdbuf;
int len;
{
int i, cnt;
if (cmdbuf == NULL)
return cmdbuf;
if (len == 0 && (len = (int)STRLEN(cmdbuf)) == 0)
return cmdbuf;
for (i = 0; i < len; i++)
{
for (cnt = 0; i + cnt < len
&& (F_isalpha(cmdbuf[i + cnt])
|| F_isdigit(cmdbuf[i + cnt])
|| cmdbuf[i + cnt] == ' '); ++cnt)
;
lrswapbuf(cmdbuf + i, cnt);
i += cnt;
}
return cmdbuf;
}
/*
* Reverse the characters in the search path and substitute section
* accordingly.
* TODO: handle different separator characters. Use skip_regexp().
*/
char_u *
lrF_sub(ibuf)
char_u *ibuf;
{
char_u *p, *ep;
int i, cnt;
p = ibuf;
/* Find the boundary of the search path */
while (((p = vim_strchr(p + 1, '/')) != NULL) && p[-1] == '\\')
;
if (p == NULL)
return ibuf;
/* Reverse the Farsi characters in the search path. */
lrFswap(ibuf, (int)(p-ibuf));
/* Now find the boundary of the substitute section */
if ((ep = (char_u *)strrchr((char *)++p, '/')) != NULL)
cnt = (int)(ep - p);
else
cnt = (int)STRLEN(p);
/* Reverse the characters in the substitute section and take care of '\' */
for (i = 0; i < cnt-1; i++)
if (p[i] == '\\')
{
p[i] = p[i+1] ;
p[++i] = '\\';
}
lrswapbuf(p, cnt);
return ibuf;
}
/*
* Map Farsi keyboard when in cmd_fkmap mode.
*/
int
cmdl_fkmap(c)
int c;
{
int tempc;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '`':
case ' ':
case '.':
case '!':
case '"':
case '$':
case '%':
case '^':
case '&':
case '/':
case '(':
case ')':
case '=':
case '\\':
case '?':
case '+':
case '-':
case '_':
case '*':
case ':':
case '#':
case '~':
case '@':
case '<':
case '>':
case '{':
case '}':
case '|':
case 'B':
case 'E':
case 'F':
case 'H':
case 'I':
case 'K':
case 'L':
case 'M':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'W':
case 'Y':
case NL:
case TAB:
switch ((tempc = cmd_gchar(AT_CURSOR)))
{
case _BE:
case _PE:
case _TE:
case _SE:
case _JIM:
case _CHE:
case _HE_J:
case _XE:
case _SIN:
case _SHIN:
case _SAD:
case _ZAD:
case _AYN:
case _GHAYN:
case _FE:
case _GHAF:
case _KAF:
case _GAF:
case _LAM:
case _MIM:
case _NOON:
case _HE:
case _HE_:
cmd_pchar(toF_TyA(tempc), AT_CURSOR);
break;
case _AYN_:
cmd_pchar(AYN_, AT_CURSOR);
break;
case _GHAYN_:
cmd_pchar(GHAYN_, AT_CURSOR);
break;
case _IE:
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR+1))
cmd_pchar(IE_, AT_CURSOR);
else
cmd_pchar(IE, AT_CURSOR);
break;
case _YEE:
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR+1))
cmd_pchar(YEE_, AT_CURSOR);
else
cmd_pchar(YEE, AT_CURSOR);
break;
case _YE:
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR+1))
cmd_pchar(YE_, AT_CURSOR);
else
cmd_pchar(YE, AT_CURSOR);
}
switch (c)
{
case '0': return FARSI_0;
case '1': return FARSI_1;
case '2': return FARSI_2;
case '3': return FARSI_3;
case '4': return FARSI_4;
case '5': return FARSI_5;
case '6': return FARSI_6;
case '7': return FARSI_7;
case '8': return FARSI_8;
case '9': return FARSI_9;
case 'B': return F_PSP;
case 'E': return JAZR_N;
case 'F': return ALEF_D_H;
case 'H': return ALEF_A;
case 'I': return TASH;
case 'K': return F_LQUOT;
case 'L': return F_RQUOT;
case 'M': return HAMZE;
case 'O': return '[';
case 'P': return ']';
case 'Q': return OO;
case 'R': return MAD_N;
case 'T': return OW;
case 'U': return MAD;
case 'W': return OW_OW;
case 'Y': return JAZR;
case '`': return F_PCN;
case '!': return F_EXCL;
case '@': return F_COMMA;
case '#': return F_DIVIDE;
case '$': return F_CURRENCY;
case '%': return F_PERCENT;
case '^': return F_MUL;
case '&': return F_BCOMMA;
case '*': return F_STAR;
case '(': return F_LPARENT;
case ')': return F_RPARENT;
case '-': return F_MINUS;
case '_': return F_UNDERLINE;
case '=': return F_EQUALS;
case '+': return F_PLUS;
case '\\': return F_BSLASH;
case '|': return F_PIPE;
case ':': return F_DCOLON;
case '"': return F_SEMICOLON;
case '.': return F_PERIOD;
case '/': return F_SLASH;
case '<': return F_LESS;
case '>': return F_GREATER;
case '?': return F_QUESTION;
case ' ': return F_BLANK;
}
break;
case 'a': return _SHIN;
case 'A': return WAW_H;
case 'b': return ZAL;
case 'c': return ZE;
case 'C': return JE;
case 'd': return _YE;
case 'D': return _YEE;
case 'e': return _SE;
case 'f': return _BE;
case 'g': return _LAM;
case 'G':
if (cmd_gchar(AT_CURSOR) == _LAM )
{
cmd_pchar(LAM, AT_CURSOR);
return ALEF_U_H;
}
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return ALEF_U_H_;
else
return ALEF_U_H;
case 'h':
if (cmd_gchar(AT_CURSOR) == _LAM )
{
cmd_pchar(LA, AT_CURSOR);
redrawcmdline();
return K_IGNORE;
}
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return ALEF_;
else
return ALEF;
case 'i':
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return _HE_;
else
return _HE;
case 'j': return _TE;
case 'J':
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return TEE_;
else
return TEE;
case 'k': return _NOON;
case 'l': return _MIM;
case 'm': return _PE;
case 'n':
case 'N': return DAL;
case 'o': return _XE;
case 'p': return _HE_J;
case 'q': return _ZAD;
case 'r': return _GHAF;
case 's': return _SIN;
case 'S': return _IE;
case 't': return _FE;
case 'u':
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return _AYN_;
else
return _AYN;
case 'v':
case 'V': return RE;
case 'w': return _SAD;
case 'x':
case 'X': return _TA;
case 'y':
if (F_is_TyB_TyC_TyD(SRC_CMD, AT_CURSOR))
return _GHAYN_;
else
return _GHAYN;
case 'z':
case 'Z': return _ZA;
case ';': return _KAF;
case '\'': return _GAF;
case ',': return WAW;
case '[': return _JIM;
case ']': return _CHE;
}
return c;
}
/*
* F_isalpha returns TRUE if 'c' is a Farsi alphabet
*/
int
F_isalpha(c)
int c;
{
return (( c >= TEE_ && c <= _YE)
|| (c >= ALEF_A && c <= YE)
|| (c >= _IE && c <= YE_));
}
/*
* F_isdigit returns TRUE if 'c' is a Farsi digit
*/
int
F_isdigit(c)
int c;
{
return (c >= FARSI_0 && c <= FARSI_9);
}
/*
* F_ischar returns TRUE if 'c' is a Farsi character.
*/
int
F_ischar(c)
int c;
{
return (c >= TEE_ && c <= YE_);
}
void
farsi_fkey(cap)
cmdarg_T *cap;
{
int c = cap->cmdchar;
if (c == K_F8)
{
if (p_altkeymap)
{
if (curwin->w_farsi & W_R_L)
{
p_fkmap = 0;
do_cmdline_cmd((char_u *)"set norl");
MSG("");
}
else
{
p_fkmap = 1;
do_cmdline_cmd((char_u *)"set rl");
MSG("");
}
curwin->w_farsi = curwin->w_farsi ^ W_R_L;
}
}
if (c == K_F9)
{
if (p_altkeymap && curwin->w_p_rl)
{
curwin->w_farsi = curwin->w_farsi ^ W_CONV;
if (curwin->w_farsi & W_CONV)
conv_to_pvim();
else
conv_to_pstd();
}
}
}
| zyz2011-vim | src/farsi.c | C | gpl2 | 37,757 |
; Thomas Leonard
; 24/5/98
ar0 rn 0
ar1 rn 1
ar2 rn 2
ar3 rn 3
ar4 rn 4
ar5 rn 5
ar6 rn 6
ar7 rn 7
ar10 rn 10
ar11 rn 11
lk rn 14
ar15 rn 15
AREA DATA
align 4
export |r0|
r0: dcd 0
export |r1|
r1: dcd 0
export |r2|
r2: dcd 0
export |r3|
r3: dcd 0
export |r4|
r4: dcd 0
export |r5|
r5: dcd 0
export |r6|
r6: dcd 0
export |r7|
r7: dcd 0
export |time_of_last_poll|
time_of_last_poll: dcd 0
AREA CODE, READONLY
align 4
import |r0|
export |swi|
= "swi"
align 4
swi:
; r0 = swi number
stmfd sp!,{ar4-ar10,lk}
orr ar10,ar0,#1<<17 ;always use the X form
mov ar0,ar1
mov ar1,ar2
mov ar2,ar3
add ar3,sp,#4*8
ldmia ar3,{ar3-ar7}
swi 0x6f ; OS_CallASWI
ldr ar10,regs_addr
stmia ar10,{ar0-ar7}
ldmvcfd sp!,{ar4-ar10,pc}^
; report the error and quit on Cancel
mov r1,#0x17
adr r2,s_title
swi 0x400df ; Wimp_ReportError
cmp r1,#1 ;OK selected?
ldmeqfd sp!,{ar4-ar10,pc}^ ;yes - try to continue
swi 0x11 ;no - die (OS_Exit)
s_title:
= "Nasty error - Cancel to quit"
= 0
align 4
export |xswi|
= "xswi"
align 4
xswi:
; r0 = swi number
stmfd sp!,{ar4-ar10,lk}
orr ar10,ar0,#1<<17 ;always use the X form
mov ar0,ar1
mov ar1,ar2
mov ar2,ar3
add ar3,sp,#4*8
ldmia ar3,{ar3-ar7}
swi 0x6f ; OS_CallASWI
ldr ar10,regs_addr
stmia ar10,{ar0-ar7}
mov ar0,#0
orr ar0,ar0,ar15
ldmfd sp!,{ar4-ar10,pc}^
regs_addr:
dcd r0
; The Wimp_Poll swis have to be done specially because,
; for some reason, r13 sometimes gets corrupted by Wimp_Poll
; (eg when running FileFind)
AREA CODE, READONLY
align 4
import |time_of_last_poll|
export |wimp_poll|
= "wimp_poll"
align 4
wimp_poll:
mov ar3,sp
swi 0x400c7 ; Wimp_Poll
mov sp,ar3
mov ar3,ar0
swi 0x42 ; OS_ReadMonotonicTime
ldr ar2,addr_time
str ar0,[ar2]
mov ar0,ar3
mov ar2,#0
wfs ar2 ; Write floating point status. Needed?
movs pc,lk
align 4
export |wimp_pollidle|
= "wimp_pollidle"
align 4
wimp_pollidle:
mov ar3,sp
swi 0x400e1 ; Wimp_PollIdle
mov sp,ar3
mov ar3,ar0
swi 0x42 ; OS_ReadMonotonicTime
ldr ar2,addr_time
str ar0,[ar2]
mov ar0,ar3
mov ar2,#0
wfs ar2 ; Write floating point status. Needed?
movs pc,lk
addr_time: dcd time_of_last_poll
| zyz2011-vim | src/swis.s | Unix Assembly | gpl2 | 2,189 |
/* 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) 1998,1999 by Marcin Dalecki <martin@dalecki.de>
*
* Support for GTK+ 2 was added by:
*
* (C) 2002,2003 Jason Hildebrand <jason@peaceworks.ca>
* Daniel Elstner <daniel.elstner@gmx.net>
*
* This is a special purpose container widget, which manages arbitrary
* children at arbitrary positions width arbitrary sizes. This finally puts
* an end on our resize problems with which we where struggling for such a
* long time.
*/
#include "vim.h"
#include <gtk/gtk.h> /* without this it compiles, but gives errors at
runtime! */
#include "gui_gtk_f.h"
#include <gtk/gtksignal.h>
#ifdef WIN3264
# include <gdk/gdkwin32.h>
#else
# include <gdk/gdkx.h>
#endif
typedef struct _GtkFormChild GtkFormChild;
struct _GtkFormChild
{
GtkWidget *widget;
GdkWindow *window;
gint x; /* relative subwidget x position */
gint y; /* relative subwidget y position */
gint mapped;
};
static void gtk_form_class_init(GtkFormClass *klass);
static void gtk_form_init(GtkForm *form);
static void gtk_form_realize(GtkWidget *widget);
static void gtk_form_unrealize(GtkWidget *widget);
static void gtk_form_map(GtkWidget *widget);
static void gtk_form_size_request(GtkWidget *widget,
GtkRequisition *requisition);
static void gtk_form_size_allocate(GtkWidget *widget,
GtkAllocation *allocation);
static gint gtk_form_expose(GtkWidget *widget,
GdkEventExpose *event);
static void gtk_form_remove(GtkContainer *container,
GtkWidget *widget);
static void gtk_form_forall(GtkContainer *container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data);
static void gtk_form_attach_child_window(GtkForm *form,
GtkFormChild *child);
static void gtk_form_realize_child(GtkForm *form,
GtkFormChild *child);
static void gtk_form_position_child(GtkForm *form,
GtkFormChild *child,
gboolean force_allocate);
static void gtk_form_position_children(GtkForm *form);
static GdkFilterReturn gtk_form_filter(GdkXEvent *gdk_xevent,
GdkEvent *event,
gpointer data);
static GdkFilterReturn gtk_form_main_filter(GdkXEvent *gdk_xevent,
GdkEvent *event,
gpointer data);
static void gtk_form_set_static_gravity(GdkWindow *window,
gboolean use_static);
static void gtk_form_send_configure(GtkForm *form);
static void gtk_form_child_map(GtkWidget *widget, gpointer user_data);
static void gtk_form_child_unmap(GtkWidget *widget, gpointer user_data);
static GtkWidgetClass *parent_class = NULL;
/* Public interface
*/
GtkWidget *
gtk_form_new(void)
{
GtkForm *form;
form = gtk_type_new(gtk_form_get_type());
return GTK_WIDGET(form);
}
void
gtk_form_put(GtkForm *form,
GtkWidget *child_widget,
gint x,
gint y)
{
GtkFormChild *child;
g_return_if_fail(GTK_IS_FORM(form));
/* LINTED: avoid warning: conversion to 'unsigned long' */
child = g_new(GtkFormChild, 1);
child->widget = child_widget;
child->window = NULL;
child->x = x;
child->y = y;
child->widget->requisition.width = 0;
child->widget->requisition.height = 0;
child->mapped = FALSE;
form->children = g_list_append(form->children, child);
/* child->window must be created and attached to the widget _before_
* it has been realized, or else things will break with GTK2. Note
* that gtk_widget_set_parent() realizes the widget if it's visible
* and its parent is mapped.
*/
if (GTK_WIDGET_REALIZED(form))
gtk_form_attach_child_window(form, child);
gtk_widget_set_parent(child_widget, GTK_WIDGET(form));
gtk_widget_size_request(child->widget, NULL);
if (GTK_WIDGET_REALIZED(form) && !GTK_WIDGET_REALIZED(child_widget))
gtk_form_realize_child(form, child);
gtk_form_position_child(form, child, TRUE);
}
void
gtk_form_move(GtkForm *form,
GtkWidget *child_widget,
gint x,
gint y)
{
GList *tmp_list;
GtkFormChild *child;
g_return_if_fail(GTK_IS_FORM(form));
for (tmp_list = form->children; tmp_list; tmp_list = tmp_list->next)
{
child = tmp_list->data;
if (child->widget == child_widget)
{
child->x = x;
child->y = y;
gtk_form_position_child(form, child, TRUE);
return;
}
}
}
void
gtk_form_freeze(GtkForm *form)
{
g_return_if_fail(GTK_IS_FORM(form));
++form->freeze_count;
}
void
gtk_form_thaw(GtkForm *form)
{
g_return_if_fail(GTK_IS_FORM(form));
if (form->freeze_count)
{
if (!(--form->freeze_count))
{
gtk_form_position_children(form);
gtk_widget_queue_draw(GTK_WIDGET(form));
}
}
}
/* Basic Object handling procedures
*/
GtkType
gtk_form_get_type(void)
{
static GtkType form_type = 0;
if (!form_type)
{
GtkTypeInfo form_info;
vim_memset(&form_info, 0, sizeof(form_info));
form_info.type_name = "GtkForm";
form_info.object_size = sizeof(GtkForm);
form_info.class_size = sizeof(GtkFormClass);
form_info.class_init_func = (GtkClassInitFunc)gtk_form_class_init;
form_info.object_init_func = (GtkObjectInitFunc)gtk_form_init;
form_type = gtk_type_unique(GTK_TYPE_CONTAINER, &form_info);
}
return form_type;
}
static void
gtk_form_class_init(GtkFormClass *klass)
{
GtkWidgetClass *widget_class;
GtkContainerClass *container_class;
widget_class = (GtkWidgetClass *) klass;
container_class = (GtkContainerClass *) klass;
parent_class = gtk_type_class(gtk_container_get_type());
widget_class->realize = gtk_form_realize;
widget_class->unrealize = gtk_form_unrealize;
widget_class->map = gtk_form_map;
widget_class->size_request = gtk_form_size_request;
widget_class->size_allocate = gtk_form_size_allocate;
widget_class->expose_event = gtk_form_expose;
container_class->remove = gtk_form_remove;
container_class->forall = gtk_form_forall;
}
static void
gtk_form_init(GtkForm *form)
{
form->children = NULL;
form->width = 1;
form->height = 1;
form->bin_window = NULL;
form->configure_serial = 0;
form->visibility = GDK_VISIBILITY_PARTIAL;
form->freeze_count = 0;
}
/*
* Widget methods
*/
static void
gtk_form_realize(GtkWidget *widget)
{
GList *tmp_list;
GtkForm *form;
GdkWindowAttr attributes;
gint attributes_mask;
g_return_if_fail(GTK_IS_FORM(widget));
form = GTK_FORM(widget);
GTK_WIDGET_SET_FLAGS(form, GTK_REALIZED);
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = widget->allocation.x;
attributes.y = widget->allocation.y;
attributes.width = widget->allocation.width;
attributes.height = widget->allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
&attributes, attributes_mask);
gdk_window_set_user_data(widget->window, widget);
attributes.x = 0;
attributes.y = 0;
attributes.event_mask = gtk_widget_get_events(widget);
form->bin_window = gdk_window_new(widget->window,
&attributes, attributes_mask);
gdk_window_set_user_data(form->bin_window, widget);
gtk_form_set_static_gravity(form->bin_window, TRUE);
widget->style = gtk_style_attach(widget->style, widget->window);
gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);
gtk_style_set_background(widget->style, form->bin_window, GTK_STATE_NORMAL);
gdk_window_add_filter(widget->window, gtk_form_main_filter, form);
gdk_window_add_filter(form->bin_window, gtk_form_filter, form);
for (tmp_list = form->children; tmp_list; tmp_list = tmp_list->next)
{
GtkFormChild *child = tmp_list->data;
gtk_form_attach_child_window(form, child);
if (GTK_WIDGET_VISIBLE(child->widget))
gtk_form_realize_child(form, child);
}
}
/* After reading the documentation at
* http://developer.gnome.org/doc/API/2.0/gtk/gtk-changes-2-0.html
* I think it should be possible to remove this function when compiling
* against gtk-2.0. It doesn't seem to cause problems, though.
*
* Well, I reckon at least the gdk_window_show(form->bin_window)
* is necessary. GtkForm is anything but a usual container widget.
*/
static void
gtk_form_map(GtkWidget *widget)
{
GList *tmp_list;
GtkForm *form;
g_return_if_fail(GTK_IS_FORM(widget));
form = GTK_FORM(widget);
GTK_WIDGET_SET_FLAGS(widget, GTK_MAPPED);
gdk_window_show(widget->window);
gdk_window_show(form->bin_window);
for (tmp_list = form->children; tmp_list; tmp_list = tmp_list->next)
{
GtkFormChild *child = tmp_list->data;
if (GTK_WIDGET_VISIBLE(child->widget)
&& !GTK_WIDGET_MAPPED(child->widget))
gtk_widget_map(child->widget);
}
}
static void
gtk_form_unrealize(GtkWidget *widget)
{
GList *tmp_list;
GtkForm *form;
g_return_if_fail(GTK_IS_FORM(widget));
form = GTK_FORM(widget);
tmp_list = form->children;
gdk_window_set_user_data(form->bin_window, NULL);
gdk_window_destroy(form->bin_window);
form->bin_window = NULL;
while (tmp_list)
{
GtkFormChild *child = tmp_list->data;
if (child->window != NULL)
{
gtk_signal_disconnect_by_func(GTK_OBJECT(child->widget),
GTK_SIGNAL_FUNC(gtk_form_child_map),
child);
gtk_signal_disconnect_by_func(GTK_OBJECT(child->widget),
GTK_SIGNAL_FUNC(gtk_form_child_unmap),
child);
gdk_window_set_user_data(child->window, NULL);
gdk_window_destroy(child->window);
child->window = NULL;
}
tmp_list = tmp_list->next;
}
if (GTK_WIDGET_CLASS (parent_class)->unrealize)
(* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
}
static void
gtk_form_size_request(GtkWidget *widget, GtkRequisition *requisition)
{
GList *tmp_list;
GtkForm *form;
g_return_if_fail(GTK_IS_FORM(widget));
form = GTK_FORM(widget);
requisition->width = form->width;
requisition->height = form->height;
tmp_list = form->children;
while (tmp_list)
{
GtkFormChild *child = tmp_list->data;
gtk_widget_size_request(child->widget, NULL);
tmp_list = tmp_list->next;
}
}
static void
gtk_form_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
{
GList *tmp_list;
GtkForm *form;
gboolean need_reposition;
g_return_if_fail(GTK_IS_FORM(widget));
if (widget->allocation.x == allocation->x
&& widget->allocation.y == allocation->y
&& widget->allocation.width == allocation->width
&& widget->allocation.height == allocation->height)
return;
need_reposition = widget->allocation.width != allocation->width
|| widget->allocation.height != allocation->height;
form = GTK_FORM(widget);
if (need_reposition)
{
tmp_list = form->children;
while (tmp_list)
{
GtkFormChild *child = tmp_list->data;
gtk_form_position_child(form, child, TRUE);
tmp_list = tmp_list->next;
}
}
if (GTK_WIDGET_REALIZED(widget))
{
gdk_window_move_resize(widget->window,
allocation->x, allocation->y,
allocation->width, allocation->height);
gdk_window_move_resize(GTK_FORM(widget)->bin_window,
0, 0,
allocation->width, allocation->height);
}
widget->allocation = *allocation;
if (need_reposition)
gtk_form_send_configure(form);
}
static gint
gtk_form_expose(GtkWidget *widget, GdkEventExpose *event)
{
GList *tmp_list;
GtkForm *form;
g_return_val_if_fail(GTK_IS_FORM(widget), FALSE);
form = GTK_FORM(widget);
if (event->window == form->bin_window)
return FALSE;
for (tmp_list = form->children; tmp_list; tmp_list = tmp_list->next)
{
GtkFormChild *formchild = tmp_list->data;
GtkWidget *child = formchild->widget;
/*
* The following chunk of code is taken from gtkcontainer.c. The
* gtk1.x code synthesized expose events directly on the child widgets,
* which can't be done in gtk2
*/
if (GTK_WIDGET_DRAWABLE(child) && GTK_WIDGET_NO_WINDOW(child)
&& child->window == event->window)
{
GdkEventExpose child_event;
child_event = *event;
child_event.region = gtk_widget_region_intersect(child, event->region);
if (!gdk_region_empty(child_event.region))
{
gdk_region_get_clipbox(child_event.region, &child_event.area);
gtk_widget_send_expose(child, (GdkEvent *)&child_event);
}
}
}
return FALSE;
}
/* Container method
*/
static void
gtk_form_remove(GtkContainer *container, GtkWidget *widget)
{
GList *tmp_list;
GtkForm *form;
GtkFormChild *child = NULL; /* init for gcc */
g_return_if_fail(GTK_IS_FORM(container));
form = GTK_FORM(container);
tmp_list = form->children;
while (tmp_list)
{
child = tmp_list->data;
if (child->widget == widget)
break;
tmp_list = tmp_list->next;
}
if (tmp_list)
{
if (child->window)
{
gtk_signal_disconnect_by_func(GTK_OBJECT(child->widget),
GTK_SIGNAL_FUNC(>k_form_child_map), child);
gtk_signal_disconnect_by_func(GTK_OBJECT(child->widget),
GTK_SIGNAL_FUNC(>k_form_child_unmap), child);
/* FIXME: This will cause problems for reparenting NO_WINDOW
* widgets out of a GtkForm
*/
gdk_window_set_user_data(child->window, NULL);
gdk_window_destroy(child->window);
}
gtk_widget_unparent(widget);
form->children = g_list_remove_link(form->children, tmp_list);
g_list_free_1(tmp_list);
g_free(child);
}
}
static void
gtk_form_forall(GtkContainer *container,
gboolean include_internals UNUSED,
GtkCallback callback,
gpointer callback_data)
{
GtkForm *form;
GtkFormChild *child;
GList *tmp_list;
g_return_if_fail(GTK_IS_FORM(container));
g_return_if_fail(callback != NULL);
form = GTK_FORM(container);
tmp_list = form->children;
while (tmp_list)
{
child = tmp_list->data;
tmp_list = tmp_list->next;
(*callback) (child->widget, callback_data);
}
}
/* Operations on children
*/
static void
gtk_form_attach_child_window(GtkForm *form, GtkFormChild *child)
{
if (child->window != NULL)
return; /* been there, done that */
if (GTK_WIDGET_NO_WINDOW(child->widget))
{
GtkWidget *widget;
GdkWindowAttr attributes;
gint attributes_mask;
widget = GTK_WIDGET(form);
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = child->x;
attributes.y = child->y;
attributes.width = child->widget->requisition.width;
attributes.height = child->widget->requisition.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes.event_mask = GDK_EXPOSURE_MASK;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
child->window = gdk_window_new(form->bin_window,
&attributes, attributes_mask);
gdk_window_set_user_data(child->window, widget);
gtk_style_set_background(widget->style,
child->window,
GTK_STATE_NORMAL);
gtk_widget_set_parent_window(child->widget, child->window);
gtk_form_set_static_gravity(child->window, TRUE);
/*
* Install signal handlers to map/unmap child->window
* alongside with the actual widget.
*/
gtk_signal_connect(GTK_OBJECT(child->widget), "map",
GTK_SIGNAL_FUNC(>k_form_child_map), child);
gtk_signal_connect(GTK_OBJECT(child->widget), "unmap",
GTK_SIGNAL_FUNC(>k_form_child_unmap), child);
}
else if (!GTK_WIDGET_REALIZED(child->widget))
{
gtk_widget_set_parent_window(child->widget, form->bin_window);
}
}
static void
gtk_form_realize_child(GtkForm *form, GtkFormChild *child)
{
gtk_form_attach_child_window(form, child);
gtk_widget_realize(child->widget);
if (child->window == NULL) /* might be already set, see above */
gtk_form_set_static_gravity(child->widget->window, TRUE);
}
static void
gtk_form_position_child(GtkForm *form, GtkFormChild *child,
gboolean force_allocate)
{
gint x;
gint y;
x = child->x;
y = child->y;
if ((x >= G_MINSHORT) && (x <= G_MAXSHORT) &&
(y >= G_MINSHORT) && (y <= G_MAXSHORT))
{
if (!child->mapped)
{
if (GTK_WIDGET_MAPPED(form) && GTK_WIDGET_VISIBLE(child->widget))
{
if (!GTK_WIDGET_MAPPED(child->widget))
gtk_widget_map(child->widget);
child->mapped = TRUE;
force_allocate = TRUE;
}
}
if (force_allocate)
{
GtkAllocation allocation;
if (GTK_WIDGET_NO_WINDOW(child->widget))
{
if (child->window)
{
gdk_window_move_resize(child->window,
x, y,
child->widget->requisition.width,
child->widget->requisition.height);
}
allocation.x = 0;
allocation.y = 0;
}
else
{
allocation.x = x;
allocation.y = y;
}
allocation.width = child->widget->requisition.width;
allocation.height = child->widget->requisition.height;
gtk_widget_size_allocate(child->widget, &allocation);
}
}
else
{
if (child->mapped)
{
child->mapped = FALSE;
if (GTK_WIDGET_MAPPED(child->widget))
gtk_widget_unmap(child->widget);
}
}
}
static void
gtk_form_position_children(GtkForm *form)
{
GList *tmp_list;
for (tmp_list = form->children; tmp_list; tmp_list = tmp_list->next)
gtk_form_position_child(form, tmp_list->data, FALSE);
}
/* Callbacks */
/* The main event filter. Actually, we probably don't really need
* to install this as a filter at all, since we are calling it
* directly above in the expose-handling hack.
*
* This routine identifies expose events that are generated when
* we've temporarily moved the bin_window_origin, and translates
* them or discards them, depending on whether we are obscured
* or not.
*/
static GdkFilterReturn
gtk_form_filter(GdkXEvent *gdk_xevent, GdkEvent *event UNUSED, gpointer data)
{
XEvent *xevent;
GtkForm *form;
xevent = (XEvent *) gdk_xevent;
form = GTK_FORM(data);
switch (xevent->type)
{
case Expose:
if (xevent->xexpose.serial == form->configure_serial)
{
if (form->visibility == GDK_VISIBILITY_UNOBSCURED)
return GDK_FILTER_REMOVE;
else
break;
}
break;
case ConfigureNotify:
if ((xevent->xconfigure.x != 0) || (xevent->xconfigure.y != 0))
form->configure_serial = xevent->xconfigure.serial;
break;
}
return GDK_FILTER_CONTINUE;
}
/* Although GDK does have a GDK_VISIBILITY_NOTIFY event,
* there is no corresponding event in GTK, so we have
* to get the events from a filter
*/
static GdkFilterReturn
gtk_form_main_filter(GdkXEvent *gdk_xevent,
GdkEvent *event UNUSED,
gpointer data)
{
XEvent *xevent;
GtkForm *form;
xevent = (XEvent *) gdk_xevent;
form = GTK_FORM(data);
if (xevent->type == VisibilityNotify)
{
switch (xevent->xvisibility.state)
{
case VisibilityFullyObscured:
form->visibility = GDK_VISIBILITY_FULLY_OBSCURED;
break;
case VisibilityPartiallyObscured:
form->visibility = GDK_VISIBILITY_PARTIAL;
break;
case VisibilityUnobscured:
form->visibility = GDK_VISIBILITY_UNOBSCURED;
break;
}
return GDK_FILTER_REMOVE;
}
return GDK_FILTER_CONTINUE;
}
static void
gtk_form_set_static_gravity(GdkWindow *window, gboolean use_static)
{
/* We don't check if static gravity is actually supported, because it
* results in an annoying assertion error message. */
gdk_window_set_static_gravities(window, use_static);
}
void
gtk_form_move_resize(GtkForm *form, GtkWidget *widget,
gint x, gint y, gint w, gint h)
{
widget->requisition.width = w;
widget->requisition.height = h;
gtk_form_move(form, widget, x, y);
}
static void
gtk_form_send_configure(GtkForm *form)
{
GtkWidget *widget;
GdkEventConfigure event;
widget = GTK_WIDGET(form);
event.type = GDK_CONFIGURE;
event.window = widget->window;
event.x = widget->allocation.x;
event.y = widget->allocation.y;
event.width = widget->allocation.width;
event.height = widget->allocation.height;
gtk_main_do_event((GdkEvent*)&event);
}
static void
gtk_form_child_map(GtkWidget *widget UNUSED, gpointer user_data)
{
GtkFormChild *child;
child = (GtkFormChild *)user_data;
child->mapped = TRUE;
gdk_window_show(child->window);
}
static void
gtk_form_child_unmap(GtkWidget *widget UNUSED, gpointer user_data)
{
GtkFormChild *child;
child = (GtkFormChild *)user_data;
child->mapped = FALSE;
gdk_window_hide(child->window);
}
| zyz2011-vim | src/gui_gtk_f.c | C | gpl2 | 21,057 |
#
# Makefile for VIM on the Amiga, using Aztec/Manx C 5.0 or later
#
# Note: Not all dependencies are included. This was done to avoid having
# to compile everything when a global variable or function is added.
# Careful when changing a global struct or variable!
#
#>>>>> choose options:
### See feature.h for a list of optionals.
### Any other defines can be included here.
DEFINES =
#>>>>> if HAVE_TGETENT is defined obj/termlib.o has to be used
#TERMLIB = obj/termlib.o
TERMLIB =
#>>>>> choose between debugging (-bs) or optimizing (-so)
OPTIONS = -so
#OPTIONS = -bs
#>>>>> end of choices
###########################################################################
CFLAGS = $(OPTIONS) -wapruq -ps -qf -Iproto $(DEFINES) -DAMIGA
LIBS = -lc16
SYMS = vim.syms
CC = cc
LN = ln
LNFLAGS = +q
SHELL = csh
REN = $(SHELL) -c mv -f
DEL = $(SHELL) -c rm -f
SRC = blowfish.c \
buffer.c \
charset.c \
diff.c \
digraph.c \
edit.c \
eval.c \
ex_cmds.c \
ex_cmds2.c \
ex_docmd.c \
ex_eval.c \
ex_getln.c \
fileio.c \
fold.c \
getchar.c \
hardcopy.c \
hashtab.c \
main.c \
mark.c \
memfile.c \
memline.c \
menu.c \
message.c \
misc1.c \
misc2.c \
move.c \
mbyte.c \
normal.c \
ops.c \
option.c \
os_amiga.c \
popupmnu.c \
quickfix.c \
regexp.c \
screen.c \
search.c \
sha256.c \
spell.c \
syntax.c \
tag.c \
term.c \
ui.c \
undo.c \
window.c \
version.c
INCL = vim.h feature.h keymap.h macros.h ascii.h term.h structs.h os_amiga.h
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_amiga.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)
PRO = 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/fold.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_amiga.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/termlib.pro \
proto/ui.pro \
proto/undo.pro \
proto/window.pro
all: Vim xxd/Xxd
Vim: obj $(OBJ) version.c version.h
$(CC) $(CFLAGS) version.c -o obj/version.o
$(LN) $(LNFLAGS) -m -o Vim $(OBJ) obj/version.o $(LIBS)
debug: obj $(OBJ) version.c version.h
$(CC) $(CFLAGS) version.c -o obj/version.o
$(LN) $(LNFLAGS) -m -g -o Vim $(OBJ) obj/version.o $(LIBS)
xxd/Xxd: xxd/xxd.c
$(SHELL) -c cd xxd; make -f Make_amiga.mak; cd ..
# Making prototypes with Manx has been removed, because it caused too many
# problems.
#proto: $(SYMS) $(PRO)
obj:
makedir obj
tags: $(SRC) $(INCL)
$(SHELL) -c ctags $(SRC) *.h
# can't use delete here, too many file names
clean:
$(DEL) $(OBJ) obj/version.o \
obj/termlib.o Vim $(SYMS) xxd/Xxd
test:
$(SHELL) -c cd testdir; make -f Make_amiga.mak; cd ..
$(SYMS): $(INCL) $(PRO)
$(CC) $(CFLAGS) -ho$(SYMS) vim.h
###########################################################################
# Unfortunately, Manx's make doesn't understand a .c.o rule, so each
# compilation command has to be given explicitly.
CCSYM = $(CC) $(CFLAGS) -hi$(SYMS) -o
CCNOSYM = $(CC) $(CFLAGS) -o
$(OBJ): $(SYMS)
obj/blowfish.o: blowfish.c
$(CCSYM) $@ blowfish.c
obj/buffer.o: buffer.c
$(CCSYM) $@ buffer.c
obj/charset.o: charset.c
$(CCSYM) $@ charset.c
obj/diff.o: diff.c
$(CCSYM) $@ diff.c
obj/digraph.o: digraph.c
$(CCSYM) $@ digraph.c
obj/edit.o: edit.c
$(CCSYM) $@ edit.c
obj/eval.o: eval.c
$(CCSYM) $@ eval.c
obj/ex_cmds.o: ex_cmds.c
$(CCSYM) $@ ex_cmds.c
obj/ex_cmds2.o: ex_cmds2.c
$(CCSYM) $@ ex_cmds2.c
# Don't use $(SYMS) here, because ex_docmd.c defines DO_DECLARE_EXCMD
obj/ex_docmd.o: ex_docmd.c ex_cmds.h
$(CCNOSYM) $@ ex_docmd.c
obj/ex_eval.o: ex_eval.c ex_cmds.h
$(CCSYM) $@ ex_eval.c
obj/ex_getln.o: ex_getln.c
$(CCSYM) $@ ex_getln.c
obj/fileio.o: fileio.c
$(CCSYM) $@ fileio.c
obj/fold.o: fold.c
$(CCSYM) $@ fold.c
obj/getchar.o: getchar.c
$(CCSYM) $@ getchar.c
obj/hardcopy.o: hardcopy.c
$(CCSYM) $@ hardcopy.c
obj/hashtab.o: hashtab.c
$(CCSYM) $@ hashtab.c
# Don't use $(SYMS) here, because main.c defines EXTERN
obj/main.o: main.c option.h globals.h
$(CCNOSYM) $@ main.c
obj/mark.o: mark.c
$(CCSYM) $@ mark.c
obj/memfile.o: memfile.c
$(CCSYM) $@ memfile.c
obj/memline.o: memline.c
$(CCSYM) $@ memline.c
obj/menu.o: menu.c
$(CCSYM) $@ menu.c
# Don't use $(SYMS) here, because message.c defines MESSAGE_FILE
obj/message.o: message.c
$(CCNOSYM) $@ message.c
obj/misc1.o: misc1.c
$(CCSYM) $@ misc1.c
obj/misc2.o: misc2.c
$(CCSYM) $@ misc2.c
obj/move.o: move.c
$(CCSYM) $@ move.c
obj/mbyte.o: mbyte.c
$(CCSYM) $@ mbyte.c
obj/normal.o: normal.c
$(CCSYM) $@ normal.c
obj/ops.o: ops.c
$(CCSYM) $@ ops.c
# Don't use $(SYMS) here, because option.h defines variables here
obj/option.o: option.c
$(CCNOSYM) $@ option.c
obj/os_amiga.o: os_amiga.c
$(CCSYM) $@ os_amiga.c
obj/popupmnu.o: popupmnu.c
$(CCSYM) $@ popupmnu.c
obj/quickfix.o: quickfix.c
$(CCSYM) $@ quickfix.c
obj/regexp.o: regexp.c
$(CCSYM) $@ regexp.c
obj/screen.o: screen.c
$(CCSYM) $@ screen.c
obj/search.o: search.c
$(CCSYM) $@ search.c
obj/sha256.o: sha256.c
$(CCSYM) $@ sha256.c
obj/spell.o: spell.c
$(CCSYM) $@ spell.c
obj/syntax.o: syntax.c
$(CCSYM) $@ syntax.c
obj/tag.o: tag.c
$(CCSYM) $@ tag.c
obj/term.o: term.c term.h
$(CCSYM) $@ term.c
obj/termlib.o: termlib.c
$(CCSYM) $@ termlib.c
obj/ui.o: ui.c
$(CCSYM) $@ ui.c
obj/undo.o: undo.c
$(CCSYM) $@ undo.c
obj/window.o: window.c
$(CCSYM) $@ window.c
| zyz2011-vim | src/Make_manx.mak | Makefile | gpl2 | 6,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.
*
* FIPS-180-2 compliant SHA-256 implementation
* GPL by Christophe Devine.
* Modified for md5deep, in public domain.
* Modified For Vim, Mohsin Ahmed, http://www.cs.albany.edu/~mosh
*
* Vim specific notes:
* Functions exported by this file:
* 1. sha256_key() hashes the password to 64 bytes char string.
* 2. sha2_seed() generates a random header.
* sha256_self_test() is implicitly called once.
*/
#include "vim.h"
#if defined(FEAT_CRYPT) || defined(FEAT_PERSISTENT_UNDO)
static void sha256_process __ARGS((context_sha256_T *ctx, char_u data[64]));
#define GET_UINT32(n, b, i) \
{ \
(n) = ( (UINT32_T)(b)[(i) ] << 24) \
| ( (UINT32_T)(b)[(i) + 1] << 16) \
| ( (UINT32_T)(b)[(i) + 2] << 8) \
| ( (UINT32_T)(b)[(i) + 3] ); \
}
#define PUT_UINT32(n,b,i) \
{ \
(b)[(i) ] = (char_u)((n) >> 24); \
(b)[(i) + 1] = (char_u)((n) >> 16); \
(b)[(i) + 2] = (char_u)((n) >> 8); \
(b)[(i) + 3] = (char_u)((n) ); \
}
void
sha256_start(ctx)
context_sha256_T *ctx;
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
ctx->state[2] = 0x3C6EF372;
ctx->state[3] = 0xA54FF53A;
ctx->state[4] = 0x510E527F;
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
}
static void
sha256_process(ctx, data)
context_sha256_T *ctx;
char_u data[64];
{
UINT32_T temp1, temp2, W[64];
UINT32_T A, B, C, D, E, F, G, H;
GET_UINT32(W[0], data, 0);
GET_UINT32(W[1], data, 4);
GET_UINT32(W[2], data, 8);
GET_UINT32(W[3], data, 12);
GET_UINT32(W[4], data, 16);
GET_UINT32(W[5], data, 20);
GET_UINT32(W[6], data, 24);
GET_UINT32(W[7], data, 28);
GET_UINT32(W[8], data, 32);
GET_UINT32(W[9], data, 36);
GET_UINT32(W[10], data, 40);
GET_UINT32(W[11], data, 44);
GET_UINT32(W[12], data, 48);
GET_UINT32(W[13], data, 52);
GET_UINT32(W[14], data, 56);
GET_UINT32(W[15], data, 60);
#define SHR(x, n) ((x & 0xFFFFFFFF) >> n)
#define ROTR(x, n) (SHR(x, n) | (x << (32 - n)))
#define S0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))
#define S1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))
#define S2(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define S3(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define F0(x, y, z) ((x & y) | (z & (x | y)))
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define R(t) \
( \
W[t] = S1(W[t - 2]) + W[t - 7] + \
S0(W[t - 15]) + W[t - 16] \
)
#define P(a,b,c,d,e,f,g,h,x,K) \
{ \
temp1 = h + S3(e) + F1(e, f, g) + K + x; \
temp2 = S2(a) + F0(a, b, c); \
d += temp1; h = temp1 + temp2; \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
E = ctx->state[4];
F = ctx->state[5];
G = ctx->state[6];
H = ctx->state[7];
P( A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98);
P( H, A, B, C, D, E, F, G, W[ 1], 0x71374491);
P( G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF);
P( F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5);
P( E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B);
P( D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1);
P( C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4);
P( B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5);
P( A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98);
P( H, A, B, C, D, E, F, G, W[ 9], 0x12835B01);
P( G, H, A, B, C, D, E, F, W[10], 0x243185BE);
P( F, G, H, A, B, C, D, E, W[11], 0x550C7DC3);
P( E, F, G, H, A, B, C, D, W[12], 0x72BE5D74);
P( D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE);
P( C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7);
P( B, C, D, E, F, G, H, A, W[15], 0xC19BF174);
P( A, B, C, D, E, F, G, H, R(16), 0xE49B69C1);
P( H, A, B, C, D, E, F, G, R(17), 0xEFBE4786);
P( G, H, A, B, C, D, E, F, R(18), 0x0FC19DC6);
P( F, G, H, A, B, C, D, E, R(19), 0x240CA1CC);
P( E, F, G, H, A, B, C, D, R(20), 0x2DE92C6F);
P( D, E, F, G, H, A, B, C, R(21), 0x4A7484AA);
P( C, D, E, F, G, H, A, B, R(22), 0x5CB0A9DC);
P( B, C, D, E, F, G, H, A, R(23), 0x76F988DA);
P( A, B, C, D, E, F, G, H, R(24), 0x983E5152);
P( H, A, B, C, D, E, F, G, R(25), 0xA831C66D);
P( G, H, A, B, C, D, E, F, R(26), 0xB00327C8);
P( F, G, H, A, B, C, D, E, R(27), 0xBF597FC7);
P( E, F, G, H, A, B, C, D, R(28), 0xC6E00BF3);
P( D, E, F, G, H, A, B, C, R(29), 0xD5A79147);
P( C, D, E, F, G, H, A, B, R(30), 0x06CA6351);
P( B, C, D, E, F, G, H, A, R(31), 0x14292967);
P( A, B, C, D, E, F, G, H, R(32), 0x27B70A85);
P( H, A, B, C, D, E, F, G, R(33), 0x2E1B2138);
P( G, H, A, B, C, D, E, F, R(34), 0x4D2C6DFC);
P( F, G, H, A, B, C, D, E, R(35), 0x53380D13);
P( E, F, G, H, A, B, C, D, R(36), 0x650A7354);
P( D, E, F, G, H, A, B, C, R(37), 0x766A0ABB);
P( C, D, E, F, G, H, A, B, R(38), 0x81C2C92E);
P( B, C, D, E, F, G, H, A, R(39), 0x92722C85);
P( A, B, C, D, E, F, G, H, R(40), 0xA2BFE8A1);
P( H, A, B, C, D, E, F, G, R(41), 0xA81A664B);
P( G, H, A, B, C, D, E, F, R(42), 0xC24B8B70);
P( F, G, H, A, B, C, D, E, R(43), 0xC76C51A3);
P( E, F, G, H, A, B, C, D, R(44), 0xD192E819);
P( D, E, F, G, H, A, B, C, R(45), 0xD6990624);
P( C, D, E, F, G, H, A, B, R(46), 0xF40E3585);
P( B, C, D, E, F, G, H, A, R(47), 0x106AA070);
P( A, B, C, D, E, F, G, H, R(48), 0x19A4C116);
P( H, A, B, C, D, E, F, G, R(49), 0x1E376C08);
P( G, H, A, B, C, D, E, F, R(50), 0x2748774C);
P( F, G, H, A, B, C, D, E, R(51), 0x34B0BCB5);
P( E, F, G, H, A, B, C, D, R(52), 0x391C0CB3);
P( D, E, F, G, H, A, B, C, R(53), 0x4ED8AA4A);
P( C, D, E, F, G, H, A, B, R(54), 0x5B9CCA4F);
P( B, C, D, E, F, G, H, A, R(55), 0x682E6FF3);
P( A, B, C, D, E, F, G, H, R(56), 0x748F82EE);
P( H, A, B, C, D, E, F, G, R(57), 0x78A5636F);
P( G, H, A, B, C, D, E, F, R(58), 0x84C87814);
P( F, G, H, A, B, C, D, E, R(59), 0x8CC70208);
P( E, F, G, H, A, B, C, D, R(60), 0x90BEFFFA);
P( D, E, F, G, H, A, B, C, R(61), 0xA4506CEB);
P( C, D, E, F, G, H, A, B, R(62), 0xBEF9A3F7);
P( B, C, D, E, F, G, H, A, R(63), 0xC67178F2);
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
ctx->state[4] += E;
ctx->state[5] += F;
ctx->state[6] += G;
ctx->state[7] += H;
}
void
sha256_update(ctx, input, length)
context_sha256_T *ctx;
char_u *input;
UINT32_T length;
{
UINT32_T left, fill;
if (length == 0)
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += length;
ctx->total[0] &= 0xFFFFFFFF;
if (ctx->total[0] < length)
ctx->total[1]++;
if (left && length >= fill)
{
memcpy((void *)(ctx->buffer + left), (void *)input, fill);
sha256_process(ctx, ctx->buffer);
length -= fill;
input += fill;
left = 0;
}
while (length >= 64)
{
sha256_process(ctx, input);
length -= 64;
input += 64;
}
if (length)
memcpy((void *)(ctx->buffer + left), (void *)input, length);
}
static char_u sha256_padding[64] = {
0x80, 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
};
void
sha256_finish(ctx, digest)
context_sha256_T *ctx;
char_u digest[32];
{
UINT32_T last, padn;
UINT32_T high, low;
char_u msglen[8];
high = (ctx->total[0] >> 29) | (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
PUT_UINT32(high, msglen, 0);
PUT_UINT32(low, msglen, 4);
last = ctx->total[0] & 0x3F;
padn = (last < 56) ? (56 - last) : (120 - last);
sha256_update(ctx, sha256_padding, padn);
sha256_update(ctx, msglen, 8);
PUT_UINT32(ctx->state[0], digest, 0);
PUT_UINT32(ctx->state[1], digest, 4);
PUT_UINT32(ctx->state[2], digest, 8);
PUT_UINT32(ctx->state[3], digest, 12);
PUT_UINT32(ctx->state[4], digest, 16);
PUT_UINT32(ctx->state[5], digest, 20);
PUT_UINT32(ctx->state[6], digest, 24);
PUT_UINT32(ctx->state[7], digest, 28);
}
#endif /* FEAT_CRYPT || FEAT_PERSISTENT_UNDO */
#if defined(FEAT_CRYPT) || defined(PROTO)
static char_u *sha256_bytes __ARGS((char_u *buf, int buf_len, char_u *salt, int salt_len));
static unsigned int get_some_time __ARGS((void));
/*
* Returns hex digest of "buf[buf_len]" in a static array.
* if "salt" is not NULL also do "salt[salt_len]".
*/
static char_u *
sha256_bytes(buf, buf_len, salt, salt_len)
char_u *buf;
int buf_len;
char_u *salt;
int salt_len;
{
char_u sha256sum[32];
static char_u hexit[65];
int j;
context_sha256_T ctx;
sha256_self_test();
sha256_start(&ctx);
sha256_update(&ctx, buf, buf_len);
if (salt != NULL)
sha256_update(&ctx, salt, salt_len);
sha256_finish(&ctx, sha256sum);
for (j = 0; j < 32; j++)
sprintf((char *)hexit + j * 2, "%02x", sha256sum[j]);
hexit[sizeof(hexit) - 1] = '\0';
return hexit;
}
/*
* Returns sha256(buf) as 64 hex chars in static array.
*/
char_u *
sha256_key(buf, salt, salt_len)
char_u *buf;
char_u *salt;
int salt_len;
{
/* No passwd means don't encrypt */
if (buf == NULL || *buf == NUL)
return (char_u *)"";
return sha256_bytes(buf, (int)STRLEN(buf), salt, salt_len);
}
/*
* These are the standard FIPS-180-2 test vectors
*/
static char *sha_self_test_msg[] = {
"abc",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
NULL
};
static char *sha_self_test_vector[] = {
"ba7816bf8f01cfea414140de5dae2223" \
"b00361a396177a9cb410ff61f20015ad",
"248d6a61d20638b8e5c026930c3e6039" \
"a33ce45964ff2167f6ecedd419db06c1",
"cdc76e5c9914fb9281a1c7e284d73e67" \
"f1809a48a497200e046d39ccc7112cd0"
};
/*
* Perform a test on the SHA256 algorithm.
* Return FAIL or OK.
*/
int
sha256_self_test()
{
int i, j;
char output[65];
context_sha256_T ctx;
char_u buf[1000];
char_u sha256sum[32];
static int failures = 0;
char_u *hexit;
static int sha256_self_tested = 0;
if (sha256_self_tested > 0)
return failures > 0 ? FAIL : OK;
sha256_self_tested = 1;
for (i = 0; i < 3; i++)
{
if (i < 2)
{
hexit = sha256_bytes((char_u *)sha_self_test_msg[i],
(int)STRLEN(sha_self_test_msg[i]),
NULL, 0);
STRCPY(output, hexit);
}
else
{
sha256_start(&ctx);
vim_memset(buf, 'a', 1000);
for (j = 0; j < 1000; j++)
sha256_update(&ctx, (char_u *)buf, 1000);
sha256_finish(&ctx, sha256sum);
for (j = 0; j < 32; j++)
sprintf(output + j * 2, "%02x", sha256sum[j]);
}
if (memcmp(output, sha_self_test_vector[i], 64))
{
failures++;
output[sizeof(output) - 1] = '\0';
/* printf("sha256_self_test %d failed %s\n", i, output); */
}
}
return failures > 0 ? FAIL : OK;
}
static unsigned int
get_some_time()
{
# ifdef HAVE_GETTIMEOFDAY
struct timeval tv;
/* Using usec makes it less predictable. */
gettimeofday(&tv, NULL);
return (unsigned int)(tv.tv_sec + tv.tv_usec);
# else
return (unsigned int)time(NULL);
# endif
}
/*
* Fill "header[header_len]" with random_data.
* Also "salt[salt_len]" when "salt" is not NULL.
*/
void
sha2_seed(header, header_len, salt, salt_len)
char_u *header;
int header_len;
char_u *salt;
int salt_len;
{
int i;
static char_u random_data[1000];
char_u sha256sum[32];
context_sha256_T ctx;
srand(get_some_time());
for (i = 0; i < (int)sizeof(random_data) - 1; i++)
random_data[i] = (char_u)((get_some_time() ^ rand()) & 0xff);
sha256_start(&ctx);
sha256_update(&ctx, (char_u *)random_data, sizeof(random_data));
sha256_finish(&ctx, sha256sum);
/* put first block into header. */
for (i = 0; i < header_len; i++)
header[i] = sha256sum[i % sizeof(sha256sum)];
/* put remaining block into salt. */
if (salt != NULL)
for (i = 0; i < salt_len; i++)
salt[i] = sha256sum[(i + header_len) % sizeof(sha256sum)];
}
#endif /* FEAT_CRYPT */
| zyz2011-vim | src/sha256.c | C | gpl2 | 12,518 |
#
# Makefile for VIM, using DICE 3
#
#>>>>> choose options:
### See feature.h for a list of optionals.
### Any other defines can be included here.
DEFINES = -DHAVE_TGETENT -DUP_BC_PC_EXTERN -DOSPEED_EXTERN
#>>>>> if HAVE_TGETENT is defined o/termlib.o has to be used
TERMLIB = o/termlib.o
#TERMLIB =
#>>>>> end of choices
###########################################################################
CFLAGS = -c -DAMIGA -Iproto $(DEFINES)
SYMS = vim.syms
PRE = -H${SYMS}=vim.h
LIBS = -la
CC = dcc
LD = dcc
.c.o:
${CC} ${PRE} ${CFLAGS} $< -o $@
SRC = \
blowfish.c \
buffer.c \
charset.c \
diff.c \
digraph.c \
edit.c \
eval.c \
ex_cmds.c \
ex_cmds2.c \
ex_docmd.c \
ex_eval.c \
ex_getln.c \
fileio.c \
fold.c \
getchar.c \
hardcopy.c \
hashtab.c \
main.c \
mark.c \
memfile.c \
memline.c \
menu.c \
message.c \
misc1.c \
misc2.c \
move.c \
mbyte.c \
normal.c \
ops.c \
option.c \
os_amiga.c \
popupmnu.c \
quickfix.c \
regexp.c \
screen.c \
search.c \
sha256.c \
spell.c \
syntax.c \
tag.c \
term.c \
ui.c \
undo.c \
window.c \
version.c
OBJ = o/blowfish.o \
o/buffer.o \
o/charset.o \
o/diff.o \
o/digraph.o \
o/edit.o \
o/eval.o \
o/ex_cmds.o \
o/ex_cmds2.o \
o/ex_docmd.o \
o/ex_eval.o \
o/ex_getln.o \
o/fileio.o \
o/fold.o \
o/getchar.o \
o/hardcopy.o \
o/hashtab.o \
o/main.o \
o/mark.o \
o/memfile.o \
o/memline.o \
o/menu.o \
o/message.o \
o/misc1.o \
o/misc2.o \
o/move.o \
o/mbyte.o \
o/normal.o \
o/ops.o \
o/option.o \
o/os_amiga.o \
o/popupmnu.o \
o/quickfix.o \
o/regexp.o \
o/screen.o \
o/search.o \
o/sha256.o \
o/spell.o \
o/syntax.o \
o/tag.o \
o/term.o \
o/ui.o \
o/undo.o \
o/window.o \
$(TERMLIB)
Vim: $(OBJ) version.c version.h
${CC} $(CFLAGS) version.c -o o/version.o
${LD} -o Vim $(OBJ) o/version.o $(LIBS)
debug: $(OBJ) version.c version.h
${CC} $(CFLAGS) version.c -o o/version.o
${LD} -s -o Vim $(OBJ) o/version.o $(LIBS)
tags:
csh -c ctags $(SRC) *.h
clean:
delete o/*.o Vim $(SYMS)
$(SYMS) : vim.h globals.h keymap.h macros.h ascii.h term.h os_amiga.h structs.h
delete $(SYMS)
###########################################################################
o/blowfish.o: blowfish.c $(SYMS)
o/buffer.o: buffer.c $(SYMS)
o/charset.o: charset.c $(SYMS)
o/diff.o: diff.c $(SYMS)
o/digraph.o: digraph.c $(SYMS)
o/edit.o: edit.c $(SYMS)
o/eval.o: eval.c $(SYMS)
o/ex_cmds.o: ex_cmds.c $(SYMS)
o/ex_cmds2.o: ex_cmds2.c $(SYMS)
o/ex_docmd.o: ex_docmd.c $(SYMS) ex_cmds.h
o/ex_eval.o: ex_eval.c $(SYMS) ex_cmds.h
o/ex_getln.o: ex_getln.c $(SYMS)
o/fileio.o: fileio.c $(SYMS)
o/fold.o: fold.c $(SYMS)
o/getchar.o: getchar.c $(SYMS)
o/hardcopy.o: hardcopy.c $(SYMS)
o/hashtab.o: hashtab.c $(SYMS)
o/main.o: main.c $(SYMS)
o/mark.o: mark.c $(SYMS)
o/memfile.o: memfile.c $(SYMS)
o/memline.o: memline.c $(SYMS)
o/menu.o: menu.c $(SYMS)
o/message.o: message.c $(SYMS)
o/misc1.o: misc1.c $(SYMS)
o/misc2.o: misc2.c $(SYMS)
o/move.o: move.c $(SYMS)
o/mbyte.o: mbyte.c $(SYMS)
o/normal.o: normal.c $(SYMS)
o/ops.o: ops.c $(SYMS)
o/option.o: option.c $(SYMS)
# Because of a bug in DC1 2.06.40, initialisation of unions does not
# work correctly. dc1-21 is DC1 2.06.21 which does work.
# rename dc1-21 dc1
${CC} ${CFLAGS} option.c -o o/option.o
# rename dc1 dc1-21
o/os_amiga.o: os_amiga.c $(SYMS) os_amiga.h
o/popupmnu.o: popupmnu.c $(SYMS)
o/quickfix.o: quickfix.c $(SYMS)
o/regexp.o: regexp.c $(SYMS) regexp.h
o/screen.o: screen.c $(SYMS)
o/search.o: search.c $(SYMS) regexp.h
o/sha256.o: sha256.c $(SYMS)
o/spell.o: spell.c $(SYMS)
o/syntax.o: syntax.c $(SYMS)
o/tag.o: tag.c $(SYMS)
o/term.o: term.c $(SYMS) term.h
o/termlib.o: termlib.c $(SYMS)
o/ui.o: ui.c $(SYMS)
o/undo.o: undo.c $(SYMS)
o/window.o: window.c $(SYMS)
| zyz2011-vim | src/Make_dice.mak | Makefile | gpl2 | 3,821 |
/* vi:set ts=8 sts=4 sw=4:
*
* VIM - Vi IMproved by Bram Moolenaar
* BeBox port by Olaf Seibert
*
* 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_beos.h
*/
#undef USE_SYSTEM
#define USE_THREAD_FOR_INPUT_WITH_TIMEOUT 1
#define USE_TERM_CONSOLE
#define HAVE_DROP_FILE
#undef BEOS_DR8
#define BEOS_PR_OR_BETTER
/* select emulation */
#include <net/socket.h> /* for typedefs and #defines only */
| zyz2011-vim | src/os_beos.h | C | gpl2 | 508 |
// Stdafx.cpp : source file that includes just the standard includes
// VisEmacs.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
#include "atlimpl.cpp"
| zyz2011-vim | src/VisVim/StdAfx.cpp | C++ | gpl2 | 222 |
// VisVim.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include <initguid.h>
#include "VisVim.h"
#include "DSAddIn.h"
#include "Commands.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CComModule _Module;
BEGIN_OBJECT_MAP (ObjectMap)
OBJECT_ENTRY (CLSID_DSAddIn, CDSAddIn)
END_OBJECT_MAP ()
class CVisVimApp : public CWinApp
{
public:
CVisVimApp ();
//{{AFX_VIRTUAL(CVisVimApp)
public:
virtual BOOL InitInstance ();
virtual int ExitInstance ();
//}}AFX_VIRTUAL
//{{AFX_MSG(CVisVimApp)
//}}AFX_MSG
DECLARE_MESSAGE_MAP ()
};
BEGIN_MESSAGE_MAP (CVisVimApp, CWinApp)
//{{AFX_MSG_MAP(CVisVimApp)
//}}AFX_MSG_MAP
END_MESSAGE_MAP ()
// The one and only CVisVimApp object
CVisVimApp theApp;
CVisVimApp::CVisVimApp ()
{
}
BOOL CVisVimApp::InitInstance ()
{
_Module.Init (ObjectMap, m_hInstance);
return CWinApp::InitInstance ();
}
int CVisVimApp::ExitInstance ()
{
_Module.Term ();
return CWinApp::ExitInstance ();
}
// Special entry points required for inproc servers
//
STDAPI DllGetClassObject (REFCLSID rclsid, REFIID riid, LPVOID * ppv)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
return _Module.GetClassObject (rclsid, riid, ppv);
}
STDAPI DllCanUnloadNow (void)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
return (AfxDllCanUnloadNow () == S_OK && _Module.GetLockCount () == 0)
? S_OK : S_FALSE;
}
// By exporting DllRegisterServer, you can use regsvr32.exe
//
STDAPI DllRegisterServer (void)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
HRESULT hRes;
// Registers object, typelib and all interfaces in typelib
hRes = _Module.RegisterServer (TRUE);
if (FAILED (hRes))
// Hack: When this fails we might be a normal user, while the
// admin already registered the module. Returning S_OK then
// makes it work. When the module was never registered it
// will soon fail in another way.
// old code: return hRes;
return S_OK;
_ATL_OBJMAP_ENTRY *pEntry = _Module.m_pObjMap;
CRegKey key;
LONG lRes = key.Open (HKEY_CLASSES_ROOT, _T ("CLSID"));
if (lRes == ERROR_SUCCESS)
{
USES_CONVERSION;
LPOLESTR lpOleStr;
StringFromCLSID (*pEntry->pclsid, &lpOleStr);
LPTSTR lpsz = OLE2T (lpOleStr);
lRes = key.Open (key, lpsz);
if (lRes == ERROR_SUCCESS)
{
CString strDescription;
strDescription.LoadString (IDS_VISVIM_DESCRIPTION);
key.SetKeyValue (_T ("Description"), strDescription);
}
CoTaskMemFree (lpOleStr);
}
if (lRes != ERROR_SUCCESS)
hRes = HRESULT_FROM_WIN32 (lRes);
return hRes;
}
// DllUnregisterServer - Removes entries from the system registry
//
STDAPI DllUnregisterServer (void)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
HRESULT hRes = S_OK;
_Module.UnregisterServer ();
return hRes;
}
// Debugging support
// GetLastErrorDescription is used in the implementation of the VERIFY_OK
// macro, defined in stdafx.h.
#ifdef _DEBUG
void GetLastErrorDescription (CComBSTR & bstr)
{
CComPtr < IErrorInfo > pErrorInfo;
if (GetErrorInfo (0, &pErrorInfo) == S_OK)
pErrorInfo->GetDescription (&bstr);
}
#endif //_DEBUG
| zyz2011-vim | src/VisVim/VisVim.cpp | C++ | gpl2 | 3,132 |
#include "stdafx.h"
// Returns key for HKEY_CURRENT_USER\"Software"\Company\AppName
// creating it if it doesn't exist
// responsibility of the caller to call RegCloseKey() on the returned HKEY
//
HKEY GetAppKey (char* AppName)
{
HKEY hAppKey = NULL;
HKEY hSoftKey = NULL;
if (RegOpenKeyEx (HKEY_CURRENT_USER, "Software", 0, KEY_WRITE | KEY_READ,
&hSoftKey) == ERROR_SUCCESS)
{
DWORD Dummy;
RegCreateKeyEx (hSoftKey, AppName, 0, REG_NONE,
REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL,
&hAppKey, &Dummy);
}
if (hSoftKey)
RegCloseKey (hSoftKey);
return hAppKey;
}
// Returns key for
// HKEY_CURRENT_USER\"Software"\RegistryKey\AppName\Section
// creating it if it doesn't exist.
// responsibility of the caller to call RegCloseKey () on the returned HKEY
//
HKEY GetSectionKey (HKEY hAppKey, LPCTSTR Section)
{
HKEY hSectionKey = NULL;
DWORD Dummy;
RegCreateKeyEx (hAppKey, Section, 0, REG_NONE,
REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
&hSectionKey, &Dummy);
return hSectionKey;
}
int GetRegistryInt (HKEY hSectionKey, LPCTSTR Entry, int Default)
{
DWORD Value;
DWORD Type;
DWORD Count = sizeof (DWORD);
if (RegQueryValueEx (hSectionKey, (LPTSTR) Entry, NULL, &Type,
(LPBYTE) &Value, &Count) == ERROR_SUCCESS)
return Value;
return Default;
}
bool WriteRegistryInt (HKEY hSectionKey, char* Entry, int nValue)
{
return RegSetValueEx (hSectionKey, Entry, NULL, REG_DWORD,
(LPBYTE) &nValue, sizeof (nValue)) == ERROR_SUCCESS;
}
| zyz2011-vim | src/VisVim/Reg.cpp | C++ | gpl2 | 1,493 |
#ifndef __OLEAUT_H__
#define __OLEAUT_H__
class COleAutomationControl : public CObject
{
public:
COleAutomationControl ();
~COleAutomationControl ();
bool CreateObject (char* ProgId);
DISPID GetDispatchId (char* Name);
bool GetProperty (char* Name);
bool GetProperty (DISPID DispatchId);
bool PutProperty (char* Name, LPCTSTR Format, ...);
bool PutProperty (DISPID DispatchId, LPCTSTR Format, ...);
bool Method (char* Name, LPCTSTR Format = NULL, ...);
bool Method (DISPID DispatchId, LPCTSTR Format = NULL, ...);
void DeleteObject ();
void ErrDiag ();
bool IsCreated ()
{
return m_pDispatch ? true : false;
}
bool IsAlive ();
HRESULT GetResult ()
{
return m_hResult;
}
UINT GetErrArgNr ()
{
return m_nErrArg;
}
EXCEPINFO* GetExceptionInfo ()
{
return &m_ExceptionInfo;
}
LPVARIANT GetResultVariant ()
{
return &m_VariantResult;
}
protected:
bool Invoke (WORD Flags, char* Name, LPCTSTR Format, va_list ArgList);
bool Invoke (WORD Flags, DISPID DispatchId, LPCTSTR Format, va_list ArgList);
protected:
IDispatch* m_pDispatch;
HRESULT m_hResult;
UINT m_nErrArg;
EXCEPINFO m_ExceptionInfo;
VARIANTARG m_VariantResult;
};
#ifdef UNICODE
#define FROM_OLE_STRING(str) str
#define FROM_OLE_STRING_BUF(str,buf) str
#define TO_OLE_STR(str) str
#define TO_OLE_STR_BUF(str,buf) str
#define MAX_OLE_STR 1
#else
#define FROM_OLE_STR(str) ConvertToAnsi(str)
#define FROM_OLE_STR_BUF(str,buf) ConvertToAnsiBuf(str,buf)
char* ConvertToAnsi (OLECHAR* sUnicode);
char* ConvertToAnsiBuf (OLECHAR* sUnicode, char* Buf);
#define TO_OLE_STR(str) ConvertToUnicode(str)
#define TO_OLE_STR_BUF(str,buf) ConvertToUnicodeBuf(str,buf)
OLECHAR* ConvertToUnicode (char* sAscii);
OLECHAR* ConvertToUnicodeBuf (char* sAscii, OLECHAR* Buf);
// Maximum length of string that can be converted between Ansi & Unicode
#define MAX_OLE_STR 500
#endif
#endif // __OLEAUT_H__
| zyz2011-vim | src/VisVim/OleAut.h | C++ | gpl2 | 1,979 |
regsvr32.exe visvim.dll
| zyz2011-vim | src/VisVim/Register.bat | Batchfile | gpl2 | 24 |
#include "stdafx.h"
#include <comdef.h> // For _bstr_t
#include "VisVim.h"
#include "Commands.h"
#include "OleAut.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Change directory before opening file?
#define CD_SOURCE 0 // Cd to source path
#define CD_SOURCE_PARENT 1 // Cd to parent directory of source path
#define CD_NONE 2 // No cd
static BOOL g_bEnableVim = TRUE; // Vim enabled
static BOOL g_bDevStudioEditor = FALSE; // Open file in Dev Studio editor simultaneously
static BOOL g_bNewTabs = FALSE;
static int g_ChangeDir = CD_NONE; // CD after file open?
static void VimSetEnableState(BOOL bEnableState);
static BOOL VimOpenFile(BSTR& FileName, long LineNr);
static DISPID VimGetDispatchId(COleAutomationControl& VimOle, char* Method);
static void VimErrDiag(COleAutomationControl& VimOle);
static void VimChangeDir(COleAutomationControl& VimOle, DISPID DispatchId, BSTR& FileName);
static void DebugMsg(char* Msg, char* Arg = NULL);
/////////////////////////////////////////////////////////////////////////////
// CCommands
CCommands::CCommands()
{
// m_pApplication == NULL; M$ Code generation bug!!!
m_pApplication = NULL;
m_pApplicationEventsObj = NULL;
m_pDebuggerEventsObj = NULL;
}
CCommands::~CCommands()
{
ASSERT(m_pApplication != NULL);
if (m_pApplication)
{
m_pApplication->Release();
m_pApplication = NULL;
}
}
void CCommands::SetApplicationObject(IApplication * pApplication)
{
// This function assumes pApplication has already been AddRef'd
// for us, which CDSAddIn did in it's QueryInterface call
// just before it called us.
m_pApplication = pApplication;
if (! m_pApplication)
return;
// Create Application event handlers
XApplicationEventsObj::CreateInstance(&m_pApplicationEventsObj);
if (! m_pApplicationEventsObj)
{
ReportInternalError("XApplicationEventsObj::CreateInstance");
return;
}
m_pApplicationEventsObj->AddRef();
m_pApplicationEventsObj->Connect(m_pApplication);
m_pApplicationEventsObj->m_pCommands = this;
#ifdef NEVER
// Create Debugger event handler
CComPtr < IDispatch > pDebugger;
if (SUCCEEDED(m_pApplication->get_Debugger(&pDebugger))
&& pDebugger != NULL)
{
XDebuggerEventsObj::CreateInstance(&m_pDebuggerEventsObj);
m_pDebuggerEventsObj->AddRef();
m_pDebuggerEventsObj->Connect(pDebugger);
m_pDebuggerEventsObj->m_pCommands = this;
}
#endif
// Get settings from registry HKEY_CURRENT_USER\Software\Vim\VisVim
HKEY hAppKey = GetAppKey("Vim");
if (hAppKey)
{
HKEY hSectionKey = GetSectionKey(hAppKey, "VisVim");
if (hSectionKey)
{
g_bEnableVim = GetRegistryInt(hSectionKey, "EnableVim",
g_bEnableVim);
g_bDevStudioEditor = GetRegistryInt(hSectionKey,
"DevStudioEditor", g_bDevStudioEditor);
g_bNewTabs = GetRegistryInt(hSectionKey, "NewTabs",
g_bNewTabs);
g_ChangeDir = GetRegistryInt(hSectionKey, "ChangeDir",
g_ChangeDir);
RegCloseKey(hSectionKey);
}
RegCloseKey(hAppKey);
}
}
void CCommands::UnadviseFromEvents()
{
ASSERT(m_pApplicationEventsObj != NULL);
if (m_pApplicationEventsObj)
{
m_pApplicationEventsObj->Disconnect(m_pApplication);
m_pApplicationEventsObj->Release();
m_pApplicationEventsObj = NULL;
}
#ifdef NEVER
if (m_pDebuggerEventsObj)
{
// Since we were able to connect to the Debugger events, we
// should be able to access the Debugger object again to
// unadvise from its events (thus the VERIFY_OK below--see
// stdafx.h).
CComPtr < IDispatch > pDebugger;
VERIFY_OK(m_pApplication->get_Debugger(&pDebugger));
ASSERT(pDebugger != NULL);
m_pDebuggerEventsObj->Disconnect(pDebugger);
m_pDebuggerEventsObj->Release();
m_pDebuggerEventsObj = NULL;
}
#endif
}
/////////////////////////////////////////////////////////////////////////////
// Event handlers
// Application events
HRESULT CCommands::XApplicationEvents::BeforeBuildStart()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::BuildFinish(long nNumErrors, long nNumWarnings)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::BeforeApplicationShutDown()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
// The open document event handle is the place where the real interface work
// is done.
// Vim gets called from here.
//
HRESULT CCommands::XApplicationEvents::DocumentOpen(IDispatch * theDocument)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (! g_bEnableVim)
// Vim not enabled or empty command line entered
return S_OK;
// First get the current file name and line number
// Get the document object
CComQIPtr < ITextDocument, &IID_ITextDocument > pDoc(theDocument);
if (! pDoc)
return S_OK;
BSTR FileName;
long LineNr = -1;
// Get the document name
if (FAILED(pDoc->get_FullName(&FileName)))
return S_OK;
LPDISPATCH pDispSel;
// Get a selection object dispatch pointer
if (SUCCEEDED(pDoc->get_Selection(&pDispSel)))
{
// Get the selection object
CComQIPtr < ITextSelection, &IID_ITextSelection > pSel(pDispSel);
if (pSel)
// Get the selection line number
pSel->get_CurrentLine(&LineNr);
pDispSel->Release();
}
// Open the file in Vim and position to the current line
if (VimOpenFile(FileName, LineNr))
{
if (! g_bDevStudioEditor)
{
// Close the document in developer studio
CComVariant vSaveChanges = dsSaveChangesPrompt;
DsSaveStatus Saved;
pDoc->Close(vSaveChanges, &Saved);
}
}
// We're done here
SysFreeString(FileName);
return S_OK;
}
HRESULT CCommands::XApplicationEvents::BeforeDocumentClose(IDispatch * theDocument)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::DocumentSave(IDispatch * theDocument)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::NewDocument(IDispatch * theDocument)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (! g_bEnableVim)
// Vim not enabled or empty command line entered
return S_OK;
// First get the current file name and line number
CComQIPtr < ITextDocument, &IID_ITextDocument > pDoc(theDocument);
if (! pDoc)
return S_OK;
BSTR FileName;
HRESULT hr;
hr = pDoc->get_FullName(&FileName);
if (FAILED(hr))
return S_OK;
// Open the file in Vim and position to the current line
if (VimOpenFile(FileName, 0))
{
if (! g_bDevStudioEditor)
{
// Close the document in developer studio
CComVariant vSaveChanges = dsSaveChangesPrompt;
DsSaveStatus Saved;
pDoc->Close(vSaveChanges, &Saved);
}
}
SysFreeString(FileName);
return S_OK;
}
HRESULT CCommands::XApplicationEvents::WindowActivate(IDispatch * theWindow)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::WindowDeactivate(IDispatch * theWindow)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::WorkspaceOpen()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::WorkspaceClose()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
HRESULT CCommands::XApplicationEvents::NewWorkspace()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
// Debugger event
HRESULT CCommands::XDebuggerEvents::BreakpointHit(IDispatch * pBreakpoint)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// VisVim dialog
class CMainDialog : public CDialog
{
public:
CMainDialog(CWnd * pParent = NULL); // Standard constructor
//{{AFX_DATA(CMainDialog)
enum { IDD = IDD_ADDINMAIN };
int m_ChangeDir;
BOOL m_bDevStudioEditor;
BOOL m_bNewTabs;
//}}AFX_DATA
//{{AFX_VIRTUAL(CMainDialog)
protected:
virtual void DoDataExchange(CDataExchange * pDX); // DDX/DDV support
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(CMainDialog)
afx_msg void OnEnable();
afx_msg void OnDisable();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CMainDialog::CMainDialog(CWnd * pParent /* =NULL */ )
: CDialog(CMainDialog::IDD, pParent)
{
//{{AFX_DATA_INIT(CMainDialog)
m_ChangeDir = -1;
m_bDevStudioEditor = FALSE;
m_bNewTabs = FALSE;
//}}AFX_DATA_INIT
}
void CMainDialog::DoDataExchange(CDataExchange * pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMainDialog)
DDX_Radio(pDX, IDC_CD_SOURCE_PATH, m_ChangeDir);
DDX_Check(pDX, IDC_DEVSTUDIO_EDITOR, m_bDevStudioEditor);
DDX_Check(pDX, IDC_NEW_TABS, m_bNewTabs);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMainDialog, CDialog)
//{{AFX_MSG_MAP(CMainDialog)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCommands methods
STDMETHODIMP CCommands::VisVimDialog()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// Use m_pApplication to access the Developer Studio Application
// object,
// and VERIFY_OK to see error strings in DEBUG builds of your add-in
// (see stdafx.h)
VERIFY_OK(m_pApplication->EnableModeless(VARIANT_FALSE));
CMainDialog Dlg;
Dlg.m_bDevStudioEditor = g_bDevStudioEditor;
Dlg.m_bNewTabs = g_bNewTabs;
Dlg.m_ChangeDir = g_ChangeDir;
if (Dlg.DoModal() == IDOK)
{
g_bDevStudioEditor = Dlg.m_bDevStudioEditor;
g_bNewTabs = Dlg.m_bNewTabs;
g_ChangeDir = Dlg.m_ChangeDir;
// Save settings to registry HKEY_CURRENT_USER\Software\Vim\VisVim
HKEY hAppKey = GetAppKey("Vim");
if (hAppKey)
{
HKEY hSectionKey = GetSectionKey(hAppKey, "VisVim");
if (hSectionKey)
{
WriteRegistryInt(hSectionKey, "DevStudioEditor",
g_bDevStudioEditor);
WriteRegistryInt(hSectionKey, "NewTabs",
g_bNewTabs);
WriteRegistryInt(hSectionKey, "ChangeDir", g_ChangeDir);
RegCloseKey(hSectionKey);
}
RegCloseKey(hAppKey);
}
}
VERIFY_OK(m_pApplication->EnableModeless(VARIANT_TRUE));
return S_OK;
}
STDMETHODIMP CCommands::VisVimEnable()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
VimSetEnableState(true);
return S_OK;
}
STDMETHODIMP CCommands::VisVimDisable()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
VimSetEnableState(false);
return S_OK;
}
STDMETHODIMP CCommands::VisVimToggle()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
VimSetEnableState(! g_bEnableVim);
return S_OK;
}
STDMETHODIMP CCommands::VisVimLoad()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// Use m_pApplication to access the Developer Studio Application object,
// and VERIFY_OK to see error strings in DEBUG builds of your add-in
// (see stdafx.h)
CComBSTR bStr;
// Define dispatch pointers for document and selection objects
CComPtr < IDispatch > pDispDoc, pDispSel;
// Get a document object dispatch pointer
VERIFY_OK(m_pApplication->get_ActiveDocument(&pDispDoc));
if (! pDispDoc)
return S_OK;
BSTR FileName;
long LineNr = -1;
// Get the document object
CComQIPtr < ITextDocument, &IID_ITextDocument > pDoc(pDispDoc);
if (! pDoc)
return S_OK;
// Get the document name
if (FAILED(pDoc->get_FullName(&FileName)))
return S_OK;
// Get a selection object dispatch pointer
if (SUCCEEDED(pDoc->get_Selection(&pDispSel)))
{
// Get the selection object
CComQIPtr < ITextSelection, &IID_ITextSelection > pSel(pDispSel);
if (pSel)
// Get the selection line number
pSel->get_CurrentLine(&LineNr);
}
// Open the file in Vim
VimOpenFile(FileName, LineNr);
SysFreeString(FileName);
return S_OK;
}
//
// Here we do the actual processing and communication with Vim
//
// Set the enable state and save to registry
//
static void VimSetEnableState(BOOL bEnableState)
{
g_bEnableVim = bEnableState;
HKEY hAppKey = GetAppKey("Vim");
if (hAppKey)
{
HKEY hSectionKey = GetSectionKey(hAppKey, "VisVim");
if (hSectionKey)
WriteRegistryInt(hSectionKey, "EnableVim", g_bEnableVim);
RegCloseKey(hAppKey);
}
}
// Open the file 'FileName' in Vim and goto line 'LineNr'
// 'FileName' is expected to contain an absolute DOS path including the drive
// letter.
// 'LineNr' must contain a valid line number or 0, e. g. for a new file
//
static BOOL VimOpenFile(BSTR& FileName, long LineNr)
{
// OLE automation object for com. with Vim
// When the object goes out of scope, it's destructor destroys the OLE
// connection;
// This is important to avoid blocking the object
// (in this memory corruption would be likely when terminating Vim
// while still running DevStudio).
// So keep this object local!
COleAutomationControl VimOle;
// :cd D:/Src2/VisVim/
//
// Get a dispatch id for the SendKeys method of Vim;
// enables connection to Vim if necessary
DISPID DispatchId;
DispatchId = VimGetDispatchId(VimOle, "SendKeys");
if (! DispatchId)
// OLE error, can't obtain dispatch id
goto OleError;
OLECHAR Buf[MAX_OLE_STR];
char FileNameTmp[MAX_OLE_STR];
char VimCmd[MAX_OLE_STR];
char *s, *p;
// Prepend CTRL-\ CTRL-N to exit insert mode
VimCmd[0] = 0x1c;
VimCmd[1] = 0x0e;
VimCmd[2] = 0;
#ifdef SINGLE_WINDOW
// Update the current file in Vim if it has been modified.
// Disabled, because it could write the file when you don't want to.
sprintf(VimCmd + 2, ":up\n");
#endif
if (! VimOle.Method(DispatchId, "s", TO_OLE_STR_BUF(VimCmd, Buf)))
goto OleError;
// Change Vim working directory to where the file is if desired
if (g_ChangeDir != CD_NONE)
VimChangeDir(VimOle, DispatchId, FileName);
// Make Vim open the file.
// In the filename convert all \ to /, put a \ before a space.
if (g_bNewTabs)
{
sprintf(VimCmd, ":tab drop ");
s = VimCmd + 10;
}
else
{
sprintf(VimCmd, ":drop ");
s = VimCmd + 6;
}
sprintf(FileNameTmp, "%S", (char *)FileName);
for (p = FileNameTmp; *p != '\0' && s < VimCmd + MAX_OLE_STR - 4; ++p)
if (*p == '\\')
*s++ = '/';
else
{
if (*p == ' ')
*s++ = '\\';
*s++ = *p;
}
*s++ = '\n';
*s = '\0';
if (! VimOle.Method(DispatchId, "s", TO_OLE_STR_BUF(VimCmd, Buf)))
goto OleError;
if (LineNr > 0)
{
// Goto line
sprintf(VimCmd, ":%d\n", LineNr);
if (! VimOle.Method(DispatchId, "s", TO_OLE_STR_BUF(VimCmd, Buf)))
goto OleError;
}
// Make Vim come to the foreground
if (! VimOle.Method("SetForeground"))
VimOle.ErrDiag();
// We're done
return true;
OleError:
// There was an OLE error
// Check if it's the "unknown class string" error
VimErrDiag(VimOle);
return false;
}
// Return the dispatch id for the Vim method 'Method'
// Create the Vim OLE object if necessary
// Returns a valid dispatch id or null on error
//
static DISPID VimGetDispatchId(COleAutomationControl& VimOle, char* Method)
{
// Initialize Vim OLE connection if not already done
if (! VimOle.IsCreated())
{
if (! VimOle.CreateObject("Vim.Application"))
return NULL;
}
// Get the dispatch id for the SendKeys method.
// By doing this, we are checking if Vim is still there...
DISPID DispatchId = VimOle.GetDispatchId("SendKeys");
if (! DispatchId)
{
// We can't get a dispatch id.
// This means that probably Vim has been terminated.
// Don't issue an error message here, instead
// destroy the OLE object and try to connect once more
//
// In fact, this should never happen, because the OLE aut. object
// should not be kept long enough to allow the user to terminate Vim
// to avoid memory corruption (why the heck is there no system garbage
// collection for those damned OLE memory chunks???).
VimOle.DeleteObject();
if (! VimOle.CreateObject("Vim.Application"))
// If this create fails, it's time for an error msg
return NULL;
if (! (DispatchId = VimOle.GetDispatchId("SendKeys")))
// There is something wrong...
return NULL;
}
return DispatchId;
}
// Output an error message for an OLE error
// Check on the classstring error, which probably means Vim wasn't registered.
//
static void VimErrDiag(COleAutomationControl& VimOle)
{
SCODE sc = GetScode(VimOle.GetResult());
if (sc == CO_E_CLASSSTRING)
{
char Buf[256];
sprintf(Buf, "There is no registered OLE automation server named "
"\"Vim.Application\".\n"
"Use the OLE-enabled version of Vim with VisVim and "
"make sure to register Vim by running \"vim -register\".");
MessageBox(NULL, Buf, "OLE Error", MB_OK);
}
else
VimOle.ErrDiag();
}
// Change directory to the directory the file 'FileName' is in or it's parent
// directory according to the setting of the global 'g_ChangeDir':
// 'FileName' is expected to contain an absolute DOS path including the drive
// letter.
// CD_NONE
// CD_SOURCE_PATH
// CD_SOURCE_PARENT
//
static void VimChangeDir(COleAutomationControl& VimOle, DISPID DispatchId, BSTR& FileName)
{
// Do a :cd first
// Get the path name of the file ("dir/")
CString StrFileName = FileName;
char Drive[_MAX_DRIVE];
char Dir[_MAX_DIR];
char DirUnix[_MAX_DIR * 2];
char *s, *t;
_splitpath(StrFileName, Drive, Dir, NULL, NULL);
// Convert to Unix path name format, escape spaces.
t = DirUnix;
for (s = Dir; *s; ++s)
if (*s == '\\')
*t++ = '/';
else
{
if (*s == ' ')
*t++ = '\\';
*t++ = *s;
}
*t = '\0';
// Construct the cd command; append /.. if cd to parent
// directory and not in root directory
OLECHAR Buf[MAX_OLE_STR];
char VimCmd[MAX_OLE_STR];
sprintf(VimCmd, ":cd %s%s%s\n", Drive, DirUnix,
g_ChangeDir == CD_SOURCE_PARENT && DirUnix[1] ? ".." : "");
VimOle.Method(DispatchId, "s", TO_OLE_STR_BUF(VimCmd, Buf));
}
#ifdef _DEBUG
// Print out a debug message
//
static void DebugMsg(char* Msg, char* Arg)
{
char Buf[400];
sprintf(Buf, Msg, Arg);
AfxMessageBox(Buf);
}
#endif
| zyz2011-vim | src/VisVim/Commands.cpp | C++ | gpl2 | 17,594 |
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by VisVim.rc
//
#define IDS_VISVIM_LONGNAME 1
#define IDS_VISVIM_DESCRIPTION 2
#define IDS_CMD_DIALOG 3
#define IDS_CMD_ENABLE 4
#define IDS_CMD_DISABLE 5
#define IDS_CMD_TOGGLE 6
#define IDS_CMD_LOAD 7
#define IDR_TOOLBAR_MEDIUM 128
#define IDR_TOOLBAR_LARGE 129
#define IDD_ADDINMAIN 130
#define IDC_DEVSTUDIO_EDITOR 1000
#define IDC_CD_SOURCE_PATH 1001
#define IDC_CD_SOURCE_PARENT 1002
#define IDC_CD_NONE 1003
#define IDC_NEW_TABS 1004
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 131
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1004
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| zyz2011-vim | src/VisVim/Resource.h | C | gpl2 | 812 |
regsvr32.exe -unregister visvim.dll
| zyz2011-vim | src/VisVim/UnRegist.bat | Batchfile | gpl2 | 36 |
// DSAddIn.h : header file
//
#if !defined(AFX_DSADDIN_H__AC726715_2977_11D1_B2F3_006008040780__INCLUDED_)
#define AFX_DSADDIN_H__AC726715_2977_11D1_B2F3_006008040780__INCLUDED_
#include "commands.h"
// {4F9E01C0-406B-11d2-8006-00001C405077}
DEFINE_GUID (CLSID_DSAddIn,
0x4f9e01c0, 0x406b, 0x11d2, 0x80, 0x6, 0x0, 0x0, 0x1c, 0x40, 0x50, 0x77);
/////////////////////////////////////////////////////////////////////////////
// CDSAddIn
class CDSAddIn :
public IDSAddIn,
public CComObjectRoot,
public CComCoClass < CDSAddIn,
&CLSID_DSAddIn >
{
public:
DECLARE_REGISTRY (CDSAddIn, "VisVim.DSAddIn.1",
"VisVim Developer Studio Add-in", IDS_VISVIM_LONGNAME,
THREADFLAGS_BOTH)
CDSAddIn ()
{
}
BEGIN_COM_MAP (CDSAddIn)
COM_INTERFACE_ENTRY (IDSAddIn)
END_COM_MAP ()
DECLARE_NOT_AGGREGATABLE (CDSAddIn)
// IDSAddIns
public:
STDMETHOD (OnConnection) (THIS_ IApplication * pApp, VARIANT_BOOL bFirstTime,
long dwCookie, VARIANT_BOOL * OnConnection);
STDMETHOD (OnDisconnection) (THIS_ VARIANT_BOOL bLastTime);
protected:
bool AddCommand (IApplication* pApp, char* MethodName, char* CmdName,
UINT StrResId, UINT GlyphIndex, VARIANT_BOOL bFirstTime);
protected:
CCommandsObj * m_pCommands;
DWORD m_dwCookie;
};
//{{AFX_INSERT_LOCATION}}
#endif // !defined(AFX_DSADDIN_H__AC726715_2977_11D1_B2F3_006008040780__INCLUDED)
| zyz2011-vim | src/VisVim/DSAddIn.h | C++ | gpl2 | 1,379 |
// VisVIM.h : main header file for the VisVim DLL
//
#if !defined(AFX_VISVIM_H__AC72670B_2977_11D1_B2F3_006008040780__INCLUDED_)
#define AFX_VISVIM_H__AC72670B_2977_11D1_B2F3_006008040780__INCLUDED_
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // Main symbols
#include <ObjModel\addguid.h>
#include <ObjModel\appguid.h>
#include <ObjModel\bldguid.h>
#include <ObjModel\textguid.h>
#include <ObjModel\dbgguid.h>
//
// Prototypes
//
HKEY GetAppKey (char* AppName);
HKEY GetSectionKey (HKEY hAppKey, LPCTSTR Section);
int GetRegistryInt (HKEY hSectionKey, LPCTSTR Entry, int Default);
bool WriteRegistryInt (HKEY hSectionKey, char* Entry, int nValue);
void ReportLastError (HRESULT Err);
void ReportInternalError (char* Fct);
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_VISVIM_H__AC72670B_2977_11D1_B2F3_006008040780__INCLUDED)
| zyz2011-vim | src/VisVim/VisVim.h | C | gpl2 | 1,009 |
//
// Class for creating OLE automation controllers.
//
// CreateObject() creates an automation object
// Invoke() will call a property or method of the automation object.
// GetProperty() returns a property
// SetProperty() changes a property
// Method() invokes a method
//
// For example, the following VB code will control Microsoft Word:
//
// Private Sub Form_Load()
// Dim wb As Object
// Set wb = CreateObject("Word.Basic")
// wb.AppShow
// wb.FileNewDefault
// wb.Insert "This is a test"
// wb.FileSaveAs "c:\sample.doc)"
// End Sub
//
// A C++ automation controller that does the same can be written as follows:
// the helper functions:
//
// Void FormLoad ()
// {
// COleAutomationControl Aut;
// Aut.CreateObject("Word.Basic");
// Aut.Method ("AppShow");
// Aut.Method ("FileNewDefault");
// Aut.Method ("Insert", "s", (LPOLESTR) OLESTR ("This is a test"));
// Aut.Method ("FileSaveAs", "s", OLESTR ("c:\\sample.doc"));
// }
//
//
#include "stdafx.h"
#include <stdarg.h>
#include "oleaut.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static bool CountArgsInFormat (LPCTSTR Format, UINT* nArgs);
static LPCTSTR GetNextVarType (LPCTSTR Format, VARTYPE* pVarType);
COleAutomationControl::COleAutomationControl ()
{
m_pDispatch = NULL;
m_hResult = NOERROR;
m_nErrArg = 0;
VariantInit (&m_VariantResult);
}
COleAutomationControl::~COleAutomationControl ()
{
DeleteObject ();
}
void COleAutomationControl::DeleteObject ()
{
if (m_pDispatch)
{
m_pDispatch->Release ();
m_pDispatch = NULL;
}
}
// Creates an instance of the Automation object and
// obtains it's IDispatch interface.
//
// Parameters:
// ProgId ProgID of Automation object
//
bool COleAutomationControl::CreateObject (char* ProgId)
{
CLSID ClsId; // CLSID of automation object
LPUNKNOWN pUnknown = NULL; // IUnknown of automation object
// Retrieve CLSID from the progID that the user specified
LPOLESTR OleProgId = TO_OLE_STR (ProgId);
m_hResult = CLSIDFromProgID (OleProgId, &ClsId);
if (FAILED (m_hResult))
goto error;
// Create an instance of the automation object and ask for the
// IDispatch interface
m_hResult = CoCreateInstance (ClsId, NULL, CLSCTX_SERVER,
IID_IUnknown, (void**) &pUnknown);
if (FAILED (m_hResult))
goto error;
m_hResult = pUnknown->QueryInterface (IID_IDispatch, (void**) &m_pDispatch);
if (FAILED (m_hResult))
goto error;
pUnknown->Release ();
return true;
error:
if (pUnknown)
pUnknown->Release ();
if (m_pDispatch)
m_pDispatch->Release ();
return false;
}
// Return the dispatch id of a named service
// This id can be used in subsequent calls to GetProperty (), SetProperty () and
// Method (). This is the preferred method when performance is important.
//
DISPID COleAutomationControl::GetDispatchId (char* Name)
{
DISPID DispatchId;
ASSERT (m_pDispatch);
// Get DISPID of property/method
LPOLESTR OleName = TO_OLE_STR (Name);
m_hResult = m_pDispatch->GetIDsOfNames (IID_NULL, &OleName, 1,
LOCALE_USER_DEFAULT, &DispatchId);
if (FAILED (m_hResult))
return NULL;
return DispatchId;
}
// The following functions use these parameters:
//
// Parameters:
//
// Name Name of property or method.
//
// Format Format string that describes the variable list of parameters that
// follows. The format string can contain the following characters.
// & = mark the following format character as VT_BYREF
// B = VT_BOOL
// i = VT_I2
// I = VT_I4
// r = VT_R2
// R = VT_R4
// c = VT_CY
// s = VT_BSTR (string pointer can be passed,
// BSTR will be allocated by this function).
// e = VT_ERROR
// d = VT_DATE
// v = VT_VARIANT. Use this to pass data types that are not described
// in the format string. (For example SafeArrays).
// D = VT_DISPATCH
// U = VT_UNKNOWN
//
// ... Arguments of the property or method.
// Arguments are described by Format.
//
bool COleAutomationControl::GetProperty (char* Name)
{
return Invoke (DISPATCH_PROPERTYGET, Name, NULL, NULL);
}
bool COleAutomationControl::GetProperty (DISPID DispatchId)
{
return Invoke (DISPATCH_PROPERTYGET, DispatchId, NULL, NULL);
}
bool COleAutomationControl::PutProperty (char* Name, LPCTSTR Format, ...)
{
va_list ArgList;
va_start (ArgList, Format);
bool bRet = Invoke (DISPATCH_PROPERTYPUT, Name, Format, ArgList);
va_end (ArgList);
return bRet;
}
bool COleAutomationControl::PutProperty (DISPID DispatchId, LPCTSTR Format, ...)
{
va_list ArgList;
va_start (ArgList, Format);
bool bRet = Invoke (DISPATCH_PROPERTYPUT, DispatchId, Format, ArgList);
va_end (ArgList);
return bRet;
}
bool COleAutomationControl::Method (char* Name, LPCTSTR Format, ...)
{
va_list ArgList;
va_start (ArgList, Format);
bool bRet = Invoke (DISPATCH_METHOD, Name, Format, ArgList);
va_end (ArgList);
return bRet;
}
bool COleAutomationControl::Method (DISPID DispatchId, LPCTSTR Format, ...)
{
va_list ArgList;
va_start (ArgList, Format);
bool bRet = Invoke (DISPATCH_METHOD, DispatchId, Format, ArgList);
va_end (ArgList);
return bRet;
}
bool COleAutomationControl::Invoke (WORD Flags, char* Name,
LPCTSTR Format, va_list ArgList)
{
DISPID DispatchId = GetDispatchId (Name);
if (! DispatchId)
return false;
return Invoke (Flags, DispatchId, Format, ArgList);
}
bool COleAutomationControl::Invoke (WORD Flags, DISPID DispatchId,
LPCTSTR Format, va_list ArgList)
{
UINT ArgCount = 0;
VARIANTARG* ArgVector = NULL;
ASSERT (m_pDispatch);
DISPPARAMS DispatchParams;
memset (&DispatchParams, 0, sizeof (DispatchParams));
// Determine number of arguments
if (Format)
CountArgsInFormat (Format, &ArgCount);
// Property puts have a named argument that represents the value that
// the property is being assigned.
DISPID DispIdNamed = DISPID_PROPERTYPUT;
if (Flags & DISPATCH_PROPERTYPUT)
{
if (ArgCount == 0)
{
m_hResult = ResultFromScode (E_INVALIDARG);
return false;
}
DispatchParams.cNamedArgs = 1;
DispatchParams.rgdispidNamedArgs = &DispIdNamed;
}
if (ArgCount)
{
// Allocate memory for all VARIANTARG parameters
ArgVector = (VARIANTARG*) CoTaskMemAlloc (
ArgCount * sizeof (VARIANTARG));
if (! ArgVector)
{
m_hResult = ResultFromScode (E_OUTOFMEMORY);
return false;
}
memset (ArgVector, 0, sizeof (VARIANTARG) * ArgCount);
// Get ready to walk vararg list
LPCTSTR s = Format;
VARIANTARG *p = ArgVector + ArgCount - 1; // Params go in opposite order
for (;;)
{
VariantInit (p);
if (! (s = GetNextVarType (s, &p->vt)))
break;
if (p < ArgVector)
{
m_hResult = ResultFromScode (E_INVALIDARG);
goto Cleanup;
}
switch (p->vt)
{
case VT_I2:
V_I2 (p) = va_arg (ArgList, short);
break;
case VT_I4:
V_I4 (p) = va_arg (ArgList, long);
break;
case VT_R4:
V_R4 (p) = va_arg (ArgList, float);
break;
case VT_DATE:
case VT_R8:
V_R8 (p) = va_arg (ArgList, double);
break;
case VT_CY:
V_CY (p) = va_arg (ArgList, CY);
break;
case VT_BSTR:
V_BSTR (p) = SysAllocString (va_arg (ArgList,
OLECHAR*));
if (! p->bstrVal)
{
m_hResult = ResultFromScode (E_OUTOFMEMORY);
p->vt = VT_EMPTY;
goto Cleanup;
}
break;
case VT_DISPATCH:
V_DISPATCH (p) = va_arg (ArgList, LPDISPATCH);
break;
case VT_ERROR:
V_ERROR (p) = va_arg (ArgList, SCODE);
break;
case VT_BOOL:
V_BOOL (p) = va_arg (ArgList, BOOL) ? -1 : 0;
break;
case VT_VARIANT:
*p = va_arg (ArgList, VARIANTARG);
break;
case VT_UNKNOWN:
V_UNKNOWN (p) = va_arg (ArgList, LPUNKNOWN);
break;
case VT_I2 | VT_BYREF:
V_I2REF (p) = va_arg (ArgList, short*);
break;
case VT_I4 | VT_BYREF:
V_I4REF (p) = va_arg (ArgList, long*);
break;
case VT_R4 | VT_BYREF:
V_R4REF (p) = va_arg (ArgList, float*);
break;
case VT_R8 | VT_BYREF:
V_R8REF (p) = va_arg (ArgList, double*);
break;
case VT_DATE | VT_BYREF:
V_DATEREF (p) = va_arg (ArgList, DATE*);
break;
case VT_CY | VT_BYREF:
V_CYREF (p) = va_arg (ArgList, CY*);
break;
case VT_BSTR | VT_BYREF:
V_BSTRREF (p) = va_arg (ArgList, BSTR*);
break;
case VT_DISPATCH | VT_BYREF:
V_DISPATCHREF (p) = va_arg (ArgList, LPDISPATCH*);
break;
case VT_ERROR | VT_BYREF:
V_ERRORREF (p) = va_arg (ArgList, SCODE*);
break;
case VT_BOOL | VT_BYREF:
{
BOOL* pBool = va_arg (ArgList, BOOL*);
*pBool = 0;
V_BOOLREF (p) = (VARIANT_BOOL*) pBool;
}
break;
case VT_VARIANT | VT_BYREF:
V_VARIANTREF (p) = va_arg (ArgList, VARIANTARG*);
break;
case VT_UNKNOWN | VT_BYREF:
V_UNKNOWNREF (p) = va_arg (ArgList, LPUNKNOWN*);
break;
default:
{
m_hResult = ResultFromScode (E_INVALIDARG);
goto Cleanup;
}
break;
}
--p; // Get ready to fill next argument
}
}
DispatchParams.cArgs = ArgCount;
DispatchParams.rgvarg = ArgVector;
// Initialize return variant, in case caller forgot. Caller can pass
// NULL if return value is not expected.
VariantInit (&m_VariantResult);
// Make the call
m_hResult = m_pDispatch->Invoke (DispatchId, IID_NULL, LOCALE_USER_DEFAULT,
Flags, &DispatchParams, &m_VariantResult,
&m_ExceptionInfo, &m_nErrArg);
Cleanup:
// Cleanup any arguments that need cleanup
if (ArgCount)
{
VARIANTARG* p = ArgVector;
while (ArgCount--)
{
switch (p->vt)
{
case VT_BSTR:
VariantClear (p);
break;
}
++p;
}
CoTaskMemFree (ArgVector);
}
return FAILED (m_hResult) ? false : true;
}
#define CASE_SCODE(sc) \
case sc: \
lstrcpy((char*)ErrName, (char*)#sc); \
break;
void COleAutomationControl::ErrDiag ()
{
char ErrName[200];
SCODE sc = GetScode (m_hResult);
switch (sc)
{
// SCODE's defined in SCODE.H
CASE_SCODE (S_OK)
CASE_SCODE (S_FALSE)
CASE_SCODE (E_UNEXPECTED)
CASE_SCODE (E_OUTOFMEMORY)
CASE_SCODE (E_INVALIDARG)
CASE_SCODE (E_NOINTERFACE)
CASE_SCODE (E_POINTER)
CASE_SCODE (E_HANDLE)
CASE_SCODE (E_ABORT)
CASE_SCODE (E_FAIL)
CASE_SCODE (E_ACCESSDENIED)
// SCODE's defined in OLE2.H
CASE_SCODE (OLE_E_OLEVERB)
CASE_SCODE (OLE_E_ADVF)
CASE_SCODE (OLE_E_ENUM_NOMORE)
CASE_SCODE (OLE_E_ADVISENOTSUPPORTED)
CASE_SCODE (OLE_E_NOCONNECTION)
CASE_SCODE (OLE_E_NOTRUNNING)
CASE_SCODE (OLE_E_NOCACHE)
CASE_SCODE (OLE_E_BLANK)
CASE_SCODE (OLE_E_CLASSDIFF)
CASE_SCODE (OLE_E_CANT_GETMONIKER)
CASE_SCODE (OLE_E_CANT_BINDTOSOURCE)
CASE_SCODE (OLE_E_STATIC)
CASE_SCODE (OLE_E_PROMPTSAVECANCELLED)
CASE_SCODE (OLE_E_INVALIDRECT)
CASE_SCODE (OLE_E_WRONGCOMPOBJ)
CASE_SCODE (OLE_E_INVALIDHWND)
CASE_SCODE (OLE_E_NOT_INPLACEACTIVE)
CASE_SCODE (OLE_E_CANTCONVERT)
CASE_SCODE (OLE_E_NOSTORAGE)
CASE_SCODE (DV_E_FORMATETC)
CASE_SCODE (DV_E_DVTARGETDEVICE)
CASE_SCODE (DV_E_STGMEDIUM)
CASE_SCODE (DV_E_STATDATA)
CASE_SCODE (DV_E_LINDEX)
CASE_SCODE (DV_E_TYMED)
CASE_SCODE (DV_E_CLIPFORMAT)
CASE_SCODE (DV_E_DVASPECT)
CASE_SCODE (DV_E_DVTARGETDEVICE_SIZE)
CASE_SCODE (DV_E_NOIVIEWOBJECT)
CASE_SCODE (OLE_S_USEREG)
CASE_SCODE (OLE_S_STATIC)
CASE_SCODE (OLE_S_MAC_CLIPFORMAT)
CASE_SCODE (CONVERT10_E_OLESTREAM_GET)
CASE_SCODE (CONVERT10_E_OLESTREAM_PUT)
CASE_SCODE (CONVERT10_E_OLESTREAM_FMT)
CASE_SCODE (CONVERT10_E_OLESTREAM_BITMAP_TO_DIB)
CASE_SCODE (CONVERT10_E_STG_FMT)
CASE_SCODE (CONVERT10_E_STG_NO_STD_STREAM)
CASE_SCODE (CONVERT10_E_STG_DIB_TO_BITMAP)
CASE_SCODE (CONVERT10_S_NO_PRESENTATION)
CASE_SCODE (CLIPBRD_E_CANT_OPEN)
CASE_SCODE (CLIPBRD_E_CANT_EMPTY)
CASE_SCODE (CLIPBRD_E_CANT_SET)
CASE_SCODE (CLIPBRD_E_BAD_DATA)
CASE_SCODE (CLIPBRD_E_CANT_CLOSE)
CASE_SCODE (DRAGDROP_E_NOTREGISTERED)
CASE_SCODE (DRAGDROP_E_ALREADYREGISTERED)
CASE_SCODE (DRAGDROP_E_INVALIDHWND)
CASE_SCODE (DRAGDROP_S_DROP)
CASE_SCODE (DRAGDROP_S_CANCEL)
CASE_SCODE (DRAGDROP_S_USEDEFAULTCURSORS)
CASE_SCODE (OLEOBJ_E_NOVERBS)
CASE_SCODE (OLEOBJ_E_INVALIDVERB)
CASE_SCODE (OLEOBJ_S_INVALIDVERB)
CASE_SCODE (OLEOBJ_S_CANNOT_DOVERB_NOW)
CASE_SCODE (OLEOBJ_S_INVALIDHWND)
CASE_SCODE (INPLACE_E_NOTUNDOABLE)
CASE_SCODE (INPLACE_E_NOTOOLSPACE)
CASE_SCODE (INPLACE_S_TRUNCATED)
// SCODE's defined in COMPOBJ.H
CASE_SCODE (CO_E_NOTINITIALIZED)
CASE_SCODE (CO_E_ALREADYINITIALIZED)
CASE_SCODE (CO_E_CANTDETERMINECLASS)
CASE_SCODE (CO_E_CLASSSTRING)
CASE_SCODE (CO_E_IIDSTRING)
CASE_SCODE (CO_E_APPNOTFOUND)
CASE_SCODE (CO_E_APPSINGLEUSE)
CASE_SCODE (CO_E_ERRORINAPP)
CASE_SCODE (CO_E_DLLNOTFOUND)
CASE_SCODE (CO_E_ERRORINDLL)
CASE_SCODE (CO_E_WRONGOSFORAPP)
CASE_SCODE (CO_E_OBJNOTREG)
CASE_SCODE (CO_E_OBJISREG)
CASE_SCODE (CO_E_OBJNOTCONNECTED)
CASE_SCODE (CO_E_APPDIDNTREG)
CASE_SCODE (CLASS_E_NOAGGREGATION)
CASE_SCODE (CLASS_E_CLASSNOTAVAILABLE)
CASE_SCODE (REGDB_E_READREGDB)
CASE_SCODE (REGDB_E_WRITEREGDB)
CASE_SCODE (REGDB_E_KEYMISSING)
CASE_SCODE (REGDB_E_INVALIDVALUE)
CASE_SCODE (REGDB_E_CLASSNOTREG)
CASE_SCODE (REGDB_E_IIDNOTREG)
CASE_SCODE (RPC_E_CALL_REJECTED)
CASE_SCODE (RPC_E_CALL_CANCELED)
CASE_SCODE (RPC_E_CANTPOST_INSENDCALL)
CASE_SCODE (RPC_E_CANTCALLOUT_INASYNCCALL)
CASE_SCODE (RPC_E_CANTCALLOUT_INEXTERNALCALL)
CASE_SCODE (RPC_E_CONNECTION_TERMINATED)
CASE_SCODE (RPC_E_SERVER_DIED)
CASE_SCODE (RPC_E_CLIENT_DIED)
CASE_SCODE (RPC_E_INVALID_DATAPACKET)
CASE_SCODE (RPC_E_CANTTRANSMIT_CALL)
CASE_SCODE (RPC_E_CLIENT_CANTMARSHAL_DATA)
CASE_SCODE (RPC_E_CLIENT_CANTUNMARSHAL_DATA)
CASE_SCODE (RPC_E_SERVER_CANTMARSHAL_DATA)
CASE_SCODE (RPC_E_SERVER_CANTUNMARSHAL_DATA)
CASE_SCODE (RPC_E_INVALID_DATA)
CASE_SCODE (RPC_E_INVALID_PARAMETER)
CASE_SCODE (RPC_E_CANTCALLOUT_AGAIN)
CASE_SCODE (RPC_E_UNEXPECTED)
// SCODE's defined in DVOBJ.H
CASE_SCODE (DATA_S_SAMEFORMATETC)
CASE_SCODE (VIEW_E_DRAW)
CASE_SCODE (VIEW_S_ALREADY_FROZEN)
CASE_SCODE (CACHE_E_NOCACHE_UPDATED)
CASE_SCODE (CACHE_S_FORMATETC_NOTSUPPORTED)
CASE_SCODE (CACHE_S_SAMECACHE)
CASE_SCODE (CACHE_S_SOMECACHES_NOTUPDATED)
// SCODE's defined in STORAGE.H
CASE_SCODE (STG_E_INVALIDFUNCTION)
CASE_SCODE (STG_E_FILENOTFOUND)
CASE_SCODE (STG_E_PATHNOTFOUND)
CASE_SCODE (STG_E_TOOMANYOPENFILES)
CASE_SCODE (STG_E_ACCESSDENIED)
CASE_SCODE (STG_E_INVALIDHANDLE)
CASE_SCODE (STG_E_INSUFFICIENTMEMORY)
CASE_SCODE (STG_E_INVALIDPOINTER)
CASE_SCODE (STG_E_NOMOREFILES)
CASE_SCODE (STG_E_DISKISWRITEPROTECTED)
CASE_SCODE (STG_E_SEEKERROR)
CASE_SCODE (STG_E_WRITEFAULT)
CASE_SCODE (STG_E_READFAULT)
CASE_SCODE (STG_E_SHAREVIOLATION)
CASE_SCODE (STG_E_LOCKVIOLATION)
CASE_SCODE (STG_E_FILEALREADYEXISTS)
CASE_SCODE (STG_E_INVALIDPARAMETER)
CASE_SCODE (STG_E_MEDIUMFULL)
CASE_SCODE (STG_E_ABNORMALAPIEXIT)
CASE_SCODE (STG_E_INVALIDHEADER)
CASE_SCODE (STG_E_INVALIDNAME)
CASE_SCODE (STG_E_UNKNOWN)
CASE_SCODE (STG_E_UNIMPLEMENTEDFUNCTION)
CASE_SCODE (STG_E_INVALIDFLAG)
CASE_SCODE (STG_E_INUSE)
CASE_SCODE (STG_E_NOTCURRENT)
CASE_SCODE (STG_E_REVERTED)
CASE_SCODE (STG_E_CANTSAVE)
CASE_SCODE (STG_E_OLDFORMAT)
CASE_SCODE (STG_E_OLDDLL)
CASE_SCODE (STG_E_SHAREREQUIRED)
CASE_SCODE (STG_E_NOTFILEBASEDSTORAGE)
CASE_SCODE (STG_E_EXTANTMARSHALLINGS)
CASE_SCODE (STG_S_CONVERTED)
// SCODE's defined in STORAGE.H
CASE_SCODE (MK_E_CONNECTMANUALLY)
CASE_SCODE (MK_E_EXCEEDEDDEADLINE)
CASE_SCODE (MK_E_NEEDGENERIC)
CASE_SCODE (MK_E_UNAVAILABLE)
CASE_SCODE (MK_E_SYNTAX)
CASE_SCODE (MK_E_NOOBJECT)
CASE_SCODE (MK_E_INVALIDEXTENSION)
CASE_SCODE (MK_E_INTERMEDIATEINTERFACENOTSUPPORTED)
CASE_SCODE (MK_E_NOTBINDABLE)
CASE_SCODE (MK_E_NOTBOUND)
CASE_SCODE (MK_E_CANTOPENFILE)
CASE_SCODE (MK_E_MUSTBOTHERUSER)
CASE_SCODE (MK_E_NOINVERSE)
CASE_SCODE (MK_E_NOSTORAGE)
CASE_SCODE (MK_E_NOPREFIX)
CASE_SCODE (MK_S_REDUCED_TO_SELF)
CASE_SCODE (MK_S_ME)
CASE_SCODE (MK_S_HIM)
CASE_SCODE (MK_S_US)
CASE_SCODE (MK_S_MONIKERALREADYREGISTERED)
// SCODE's defined in DISPATCH.H
CASE_SCODE (DISP_E_UNKNOWNINTERFACE)
CASE_SCODE (DISP_E_MEMBERNOTFOUND)
CASE_SCODE (DISP_E_PARAMNOTFOUND)
CASE_SCODE (DISP_E_TYPEMISMATCH)
CASE_SCODE (DISP_E_UNKNOWNNAME)
CASE_SCODE (DISP_E_NONAMEDARGS)
CASE_SCODE (DISP_E_BADVARTYPE)
CASE_SCODE (DISP_E_EXCEPTION)
CASE_SCODE (DISP_E_OVERFLOW)
CASE_SCODE (DISP_E_BADINDEX)
CASE_SCODE (DISP_E_UNKNOWNLCID)
CASE_SCODE (DISP_E_ARRAYISLOCKED)
CASE_SCODE (DISP_E_BADPARAMCOUNT)
CASE_SCODE (DISP_E_PARAMNOTOPTIONAL)
CASE_SCODE (DISP_E_BADCALLEE)
CASE_SCODE (DISP_E_NOTACOLLECTION)
CASE_SCODE (TYPE_E_BUFFERTOOSMALL)
CASE_SCODE (TYPE_E_INVDATAREAD)
CASE_SCODE (TYPE_E_UNSUPFORMAT)
CASE_SCODE (TYPE_E_REGISTRYACCESS)
CASE_SCODE (TYPE_E_LIBNOTREGISTERED)
CASE_SCODE (TYPE_E_UNDEFINEDTYPE)
CASE_SCODE (TYPE_E_QUALIFIEDNAMEDISALLOWED)
CASE_SCODE (TYPE_E_INVALIDSTATE)
CASE_SCODE (TYPE_E_WRONGTYPEKIND)
CASE_SCODE (TYPE_E_ELEMENTNOTFOUND)
CASE_SCODE (TYPE_E_AMBIGUOUSNAME)
CASE_SCODE (TYPE_E_NAMECONFLICT)
CASE_SCODE (TYPE_E_UNKNOWNLCID)
CASE_SCODE (TYPE_E_DLLFUNCTIONNOTFOUND)
CASE_SCODE (TYPE_E_BADMODULEKIND)
CASE_SCODE (TYPE_E_SIZETOOBIG)
CASE_SCODE (TYPE_E_DUPLICATEID)
CASE_SCODE (TYPE_E_TYPEMISMATCH)
CASE_SCODE (TYPE_E_OUTOFBOUNDS)
CASE_SCODE (TYPE_E_IOERROR)
CASE_SCODE (TYPE_E_CANTCREATETMPFILE)
CASE_SCODE (TYPE_E_CANTLOADLIBRARY)
CASE_SCODE (TYPE_E_INCONSISTENTPROPFUNCS)
CASE_SCODE (TYPE_E_CIRCULARTYPE)
default:
lstrcpy (ErrName, "UNKNOWN SCODE");
}
char Buf[256];
sprintf (Buf, "An OLE error occured:\r\nCode = %s\r\nResult = %lx.",
(char*) ErrName, m_hResult);
MessageBox (NULL, Buf, "OLE Error", MB_OK);
}
static bool CountArgsInFormat (LPCTSTR Format, UINT* pArgCount)
{
*pArgCount = 0;
if (! Format)
return true;
while (*Format)
{
if (*Format == '&')
Format++;
switch (*Format)
{
case 'b':
case 'i':
case 'I':
case 'r':
case 'R':
case 'c':
case 's':
case 'e':
case 'd':
case 'v':
case 'D':
case 'U':
++ (*pArgCount);
Format++;
break;
case '\0':
default:
return false;
}
}
return true;
}
static LPCTSTR GetNextVarType (LPCTSTR Format, VARTYPE* pVarType)
{
*pVarType = 0;
if (*Format == '&')
{
*pVarType = VT_BYREF;
Format++;
if (!*Format)
return NULL;
}
switch (*Format)
{
case 'b':
*pVarType |= VT_BOOL;
break;
case 'i':
*pVarType |= VT_I2;
break;
case 'I':
*pVarType |= VT_I4;
break;
case 'r':
*pVarType |= VT_R4;
break;
case 'R':
*pVarType |= VT_R8;
break;
case 'c':
*pVarType |= VT_CY;
break;
case 's':
*pVarType |= VT_BSTR;
break;
case 'e':
*pVarType |= VT_ERROR;
break;
case 'd':
*pVarType |= VT_DATE;
break;
case 'v':
*pVarType |= VT_VARIANT;
break;
case 'U':
*pVarType |= VT_UNKNOWN;
break;
case 'D':
*pVarType |= VT_DISPATCH;
break;
case '\0':
return NULL; // End of Format string
default:
return NULL;
}
return ++Format;
}
#ifndef UNICODE
char* ConvertToAnsi (OLECHAR* sUnicode)
{
static char BufAscii[MAX_OLE_STR];
return ConvertToAnsiBuf (sUnicode, BufAscii);
}
char* ConvertToAnsiBuf (OLECHAR* sUnicode, char* BufAscii)
{
WideCharToMultiByte (CP_ACP, 0, sUnicode, -1, BufAscii, MAX_OLE_STR, NULL, NULL);
return BufAscii;
}
OLECHAR* ConvertToUnicode (char* sAscii)
{
static OLECHAR BufUnicode[MAX_OLE_STR];
return ConvertToUnicodeBuf (sAscii, BufUnicode);
}
OLECHAR* ConvertToUnicodeBuf (char* sAscii, OLECHAR* BufUnicode)
{
MultiByteToWideChar (CP_ACP, 0, sAscii, -1, BufUnicode, MAX_OLE_STR);
return BufUnicode;
}
#endif
| zyz2011-vim | src/VisVim/OleAut.cpp | C++ | gpl2 | 20,547 |
// Stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__AC72670E_2977_11D1_B2F3_006008040780__INCLUDED_)
#define AFX_STDAFX_H__AC72670E_2977_11D1_B2F3_006008040780__INCLUDED_
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxdisp.h>
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
// Developer Studio Object Model
#include <ObjModel\addauto.h>
#include <ObjModel\appdefs.h>
#include <ObjModel\appauto.h>
#include <ObjModel\blddefs.h>
#include <ObjModel\bldauto.h>
#include <ObjModel\textdefs.h>
#include <ObjModel\textauto.h>
#include <ObjModel\dbgdefs.h>
#include <ObjModel\dbgauto.h>
/////////////////////////////////////////////////////////////////////////////
// Debugging support
// Use VERIFY_OK around all calls to the Developer Studio objects which
// you expect to return S_OK.
// In DEBUG builds of your add-in, VERIFY_OK displays an ASSERT dialog box
// if the expression returns an HRESULT other than S_OK. If the HRESULT
// is a success code, the ASSERT box will display that HRESULT. If it
// is a failure code, the ASSERT box will display that HRESULT plus the
// error description string provided by the object which raised the error.
// In RETAIL builds of your add-in, VERIFY_OK just evaluates the expression
// and ignores the returned HRESULT.
#ifdef _DEBUG
void GetLastErrorDescription (CComBSTR & bstr); // Defined in VisVim.cpp
#define VERIFY_OK(f) \
{ \
HRESULT hr = (f); \
if (hr != S_OK) \
{ \
if (FAILED(hr)) \
{ \
CComBSTR bstr; \
GetLastErrorDescription(bstr); \
_RPTF2(_CRT_ASSERT, "Object call returned %lx\n\n%S", hr, (BSTR) bstr); \
} \
else \
_RPTF1(_CRT_ASSERT, "Object call returned %lx", hr); \
} \
}
#else //_DEBUG
#define VERIFY_OK(f) (f);
#endif //_DEBUG
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__AC72670E_2977_11D1_B2F3_006008040780__INCLUDED)
| zyz2011-vim | src/VisVim/StdAfx.h | C | gpl2 | 2,346 |
#include "stdafx.h"
#include "VisVim.h"
#include "DSAddIn.h"
#include "Commands.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// This is called when the user first loads the add-in, and on start-up
// of each subsequent Developer Studio session
STDMETHODIMP CDSAddIn::OnConnection (IApplication * pApp, VARIANT_BOOL bFirstTime,
long dwCookie, VARIANT_BOOL * OnConnection)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
*OnConnection = VARIANT_FALSE;
// Store info passed to us
IApplication *pApplication = NULL;
HRESULT hr;
hr = pApp->QueryInterface (IID_IApplication, (void **) &pApplication);
if (FAILED (hr))
{
ReportLastError (hr);
return E_UNEXPECTED;
}
if (pApplication == NULL)
{
ReportInternalError ("IApplication::QueryInterface");
return E_UNEXPECTED;
}
m_dwCookie = dwCookie;
// Create command dispatch, send info back to DevStudio
CCommandsObj::CreateInstance (&m_pCommands);
if (! m_pCommands)
{
ReportInternalError ("CCommandsObj::CreateInstance");
return E_UNEXPECTED;
}
m_pCommands->AddRef ();
// The QueryInterface above AddRef'd the Application object. It will
// be Release'd in CCommand's destructor.
m_pCommands->SetApplicationObject (pApplication);
hr = pApplication->SetAddInInfo ((long) AfxGetInstanceHandle (),
(LPDISPATCH) m_pCommands, IDR_TOOLBAR_MEDIUM, IDR_TOOLBAR_LARGE,
m_dwCookie);
if (FAILED (hr))
{
ReportLastError (hr);
return E_UNEXPECTED;
}
// Inform DevStudio of the commands we implement
if (! AddCommand (pApplication, "VisVimDialog", "VisVimDialogCmd",
IDS_CMD_DIALOG, 0, bFirstTime))
return E_UNEXPECTED;
if (! AddCommand (pApplication, "VisVimEnable", "VisVimEnableCmd",
IDS_CMD_ENABLE, 1, bFirstTime))
return E_UNEXPECTED;
if (! AddCommand (pApplication, "VisVimDisable", "VisVimDisableCmd",
IDS_CMD_DISABLE, 2, bFirstTime))
return E_UNEXPECTED;
if (! AddCommand (pApplication, "VisVimToggle", "VisVimToggleCmd",
IDS_CMD_TOGGLE, 3, bFirstTime))
return E_UNEXPECTED;
if (! AddCommand (pApplication, "VisVimLoad", "VisVimLoadCmd",
IDS_CMD_LOAD, 4, bFirstTime))
return E_UNEXPECTED;
*OnConnection = VARIANT_TRUE;
return S_OK;
}
// This is called on shut-down, and also when the user unloads the add-in
STDMETHODIMP CDSAddIn::OnDisconnection (VARIANT_BOOL bLastTime)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState ());
m_pCommands->UnadviseFromEvents ();
m_pCommands->Release ();
m_pCommands = NULL;
return S_OK;
}
// Add a command to DevStudio
// Creates a toolbar button for the command also.
// 'MethodName' is the name of the method specified in the .odl file
// 'StrResId' the resource id of the descriptive string
// 'GlyphIndex' the image index into the command buttons bitmap
// Return true on success
//
bool CDSAddIn::AddCommand (IApplication* pApp, char* MethodName, char* CmdName,
UINT StrResId, UINT GlyphIndex, VARIANT_BOOL bFirstTime)
{
CString CmdString;
CString CmdText;
CmdText.LoadString (StrResId);
CmdString = CmdName;
CmdString += CmdText;
CComBSTR bszCmdString (CmdString);
CComBSTR bszMethod (MethodName);
CComBSTR bszCmdName (CmdName);
// (see stdafx.h for the definition of VERIFY_OK)
VARIANT_BOOL bRet;
VERIFY_OK (pApp->AddCommand (bszCmdString, bszMethod, GlyphIndex,
m_dwCookie, &bRet));
if (bRet == VARIANT_FALSE)
{
// AddCommand failed because a command with this name already exists.
ReportInternalError ("IApplication::AddCommand");
return FALSE;
}
// Add toolbar buttons only if this is the first time the add-in
// is being loaded. Toolbar buttons are automatically remembered
// by Developer Studio from session to session, so we should only
// add the toolbar buttons once.
if (bFirstTime == VARIANT_TRUE)
VERIFY_OK (pApp->AddCommandBarButton (dsGlyph, bszCmdName, m_dwCookie));
return TRUE;
}
void ReportLastError (HRESULT Err)
{
char *Buf = NULL;
char Msg[512];
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, Err,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
Buf, 400, NULL);
sprintf (Msg, "Unexpected error (Error code: %lx)\n%s", Err, Buf);
::MessageBox (NULL, Msg, "VisVim", MB_OK | MB_ICONSTOP);
if (Buf)
LocalFree (Buf);
}
void ReportInternalError (char* Fct)
{
char Msg[512];
sprintf (Msg, "Unexpected error\n%s failed", Fct);
::MessageBox (NULL, Msg, "VisVim", MB_OK | MB_ICONSTOP);
}
| zyz2011-vim | src/VisVim/DSAddIn.cpp | C++ | gpl2 | 4,471 |
// Commands.h : header file
//
#if !defined(AFX_COMMANDS_H__AC726717_2977_11D1_B2F3_006008040780__INCLUDED_)
#define AFX_COMMANDS_H__AC726717_2977_11D1_B2F3_006008040780__INCLUDED_
#include "vsvtypes.h"
class CCommands :
public CComDualImpl < ICommands,
&IID_ICommands,
&LIBID_VisVim >,
public CComObjectRoot,
public CComCoClass < CCommands,
&CLSID_Commands >
{
protected:
IApplication * m_pApplication;
public:
CCommands ();
~CCommands ();
void SetApplicationObject (IApplication * m_pApplication);
IApplication *GetApplicationObject ()
{
return m_pApplication;
}
void UnadviseFromEvents ();
BEGIN_COM_MAP (CCommands)
COM_INTERFACE_ENTRY (IDispatch)
COM_INTERFACE_ENTRY (ICommands)
END_COM_MAP ()
DECLARE_NOT_AGGREGATABLE (CCommands)
protected:
// This class template is used as the base class for the Application
// event handler object and the Debugger event handler object,
// which are declared below.
template < class IEvents,
const IID * piidEvents,
const GUID * plibid,
class XEvents,
const CLSID * pClsidEvents >
class XEventHandler :
public CComDualImpl < IEvents,
piidEvents,
plibid >,
public CComObjectRoot,
public CComCoClass < XEvents,
pClsidEvents >
{
public:
BEGIN_COM_MAP (XEvents)
COM_INTERFACE_ENTRY (IDispatch)
COM_INTERFACE_ENTRY_IID (*piidEvents, IEvents)
END_COM_MAP ()
DECLARE_NOT_AGGREGATABLE (XEvents)
void Connect (IUnknown * pUnk)
{
VERIFY (SUCCEEDED (AtlAdvise (pUnk, this, *piidEvents,
&m_dwAdvise)));
}
void Disconnect (IUnknown * pUnk)
{
AtlUnadvise (pUnk, *piidEvents, m_dwAdvise);
}
CCommands *m_pCommands;
protected:
DWORD m_dwAdvise;
};
// This object handles events fired by the Application object
class XApplicationEvents : public XEventHandler < IApplicationEvents,
&IID_IApplicationEvents,
&LIBID_VisVim,
XApplicationEvents,
&CLSID_ApplicationEvents >
{
public:
// IApplicationEvents methods
STDMETHOD (BeforeBuildStart) (THIS);
STDMETHOD (BuildFinish) (THIS_ long nNumErrors, long nNumWarnings);
STDMETHOD (BeforeApplicationShutDown) (THIS);
STDMETHOD (DocumentOpen) (THIS_ IDispatch * theDocument);
STDMETHOD (BeforeDocumentClose) (THIS_ IDispatch * theDocument);
STDMETHOD (DocumentSave) (THIS_ IDispatch * theDocument);
STDMETHOD (NewDocument) (THIS_ IDispatch * theDocument);
STDMETHOD (WindowActivate) (THIS_ IDispatch * theWindow);
STDMETHOD (WindowDeactivate) (THIS_ IDispatch * theWindow);
STDMETHOD (WorkspaceOpen) (THIS);
STDMETHOD (WorkspaceClose) (THIS);
STDMETHOD (NewWorkspace) (THIS);
};
typedef CComObject < XApplicationEvents > XApplicationEventsObj;
XApplicationEventsObj *m_pApplicationEventsObj;
// This object handles events fired by the Application object
class XDebuggerEvents : public XEventHandler < IDebuggerEvents,
&IID_IDebuggerEvents,
&LIBID_VisVim,
XDebuggerEvents,
&CLSID_DebuggerEvents >
{
public:
// IDebuggerEvents method
STDMETHOD (BreakpointHit) (THIS_ IDispatch * pBreakpoint);
};
typedef CComObject < XDebuggerEvents > XDebuggerEventsObj;
XDebuggerEventsObj *m_pDebuggerEventsObj;
public:
// ICommands methods
STDMETHOD (VisVimDialog) (THIS);
STDMETHOD (VisVimEnable) (THIS);
STDMETHOD (VisVimDisable) (THIS);
STDMETHOD (VisVimToggle) (THIS);
STDMETHOD (VisVimLoad) (THIS);
};
typedef CComObject < CCommands > CCommandsObj;
//{{AFX_INSERT_LOCATION}}
#endif // !defined(AFX_COMMANDS_H__AC726717_2977_11D1_B2F3_006008040780__INCLUDED)
| zyz2011-vim | src/VisVim/Commands.h | C++ | gpl2 | 3,584 |
/* 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_cmds.c: some functions for command line commands
*/
#include "vim.h"
#include "version.h"
#ifdef FEAT_EX_EXTRA
static int linelen __ARGS((int *has_tab));
#endif
static void do_filter __ARGS((linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, int do_in, int do_out));
#ifdef FEAT_VIMINFO
static char_u *viminfo_filename __ARGS((char_u *));
static void do_viminfo __ARGS((FILE *fp_in, FILE *fp_out, int flags));
static int viminfo_encoding __ARGS((vir_T *virp));
static int read_viminfo_up_to_marks __ARGS((vir_T *virp, int forceit, int writing));
#endif
static int check_readonly __ARGS((int *forceit, buf_T *buf));
#ifdef FEAT_AUTOCMD
static void delbuf_msg __ARGS((char_u *name));
#endif
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
help_compare __ARGS((const void *s1, const void *s2));
/*
* ":ascii" and "ga".
*/
void
do_ascii(eap)
exarg_T *eap UNUSED;
{
int c;
int cval;
char buf1[20];
char buf2[20];
char_u buf3[7];
#ifdef FEAT_MBYTE
int cc[MAX_MCO];
int ci = 0;
int len;
if (enc_utf8)
c = utfc_ptr2char(ml_get_cursor(), cc);
else
#endif
c = gchar_cursor();
if (c == NUL)
{
MSG("NUL");
return;
}
#ifdef FEAT_MBYTE
IObuff[0] = NUL;
if (!has_mbyte || (enc_dbcs != 0 && c < 0x100) || c < 0x80)
#endif
{
if (c == NL) /* NUL is stored as NL */
c = NUL;
if (c == CAR && get_fileformat(curbuf) == EOL_MAC)
cval = NL; /* NL is stored as CR */
else
cval = c;
if (vim_isprintc_strict(c) && (c < ' '
#ifndef EBCDIC
|| c > '~'
#endif
))
{
transchar_nonprint(buf3, c);
vim_snprintf(buf1, sizeof(buf1), " <%s>", (char *)buf3);
}
else
buf1[0] = NUL;
#ifndef EBCDIC
if (c >= 0x80)
vim_snprintf(buf2, sizeof(buf2), " <M-%s>",
(char *)transchar(c & 0x7f));
else
#endif
buf2[0] = NUL;
vim_snprintf((char *)IObuff, IOSIZE,
_("<%s>%s%s %d, Hex %02x, Octal %03o"),
transchar(c), buf1, buf2, cval, cval, cval);
#ifdef FEAT_MBYTE
if (enc_utf8)
c = cc[ci++];
else
c = 0;
#endif
}
#ifdef FEAT_MBYTE
/* Repeat for combining characters. */
while (has_mbyte && (c >= 0x100 || (enc_utf8 && c >= 0x80)))
{
len = (int)STRLEN(IObuff);
/* This assumes every multi-byte char is printable... */
if (len > 0)
IObuff[len++] = ' ';
IObuff[len++] = '<';
if (enc_utf8 && utf_iscomposing(c)
# ifdef USE_GUI
&& !gui.in_use
# endif
)
IObuff[len++] = ' '; /* draw composing char on top of a space */
len += (*mb_char2bytes)(c, IObuff + len);
vim_snprintf((char *)IObuff + len, IOSIZE - len,
c < 0x10000 ? _("> %d, Hex %04x, Octal %o")
: _("> %d, Hex %08x, Octal %o"), c, c, c);
if (ci == MAX_MCO)
break;
if (enc_utf8)
c = cc[ci++];
else
c = 0;
}
#endif
msg(IObuff);
}
#if defined(FEAT_EX_EXTRA) || defined(PROTO)
/*
* ":left", ":center" and ":right": align text.
*/
void
ex_align(eap)
exarg_T *eap;
{
pos_T save_curpos;
int len;
int indent = 0;
int new_indent;
int has_tab;
int width;
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl)
{
/* switch left and right aligning */
if (eap->cmdidx == CMD_right)
eap->cmdidx = CMD_left;
else if (eap->cmdidx == CMD_left)
eap->cmdidx = CMD_right;
}
#endif
width = atoi((char *)eap->arg);
save_curpos = curwin->w_cursor;
if (eap->cmdidx == CMD_left) /* width is used for new indent */
{
if (width >= 0)
indent = width;
}
else
{
/*
* if 'textwidth' set, use it
* else if 'wrapmargin' set, use it
* if invalid value, use 80
*/
if (width <= 0)
width = curbuf->b_p_tw;
if (width == 0 && curbuf->b_p_wm > 0)
width = W_WIDTH(curwin) - curbuf->b_p_wm;
if (width <= 0)
width = 80;
}
if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
return;
for (curwin->w_cursor.lnum = eap->line1;
curwin->w_cursor.lnum <= eap->line2; ++curwin->w_cursor.lnum)
{
if (eap->cmdidx == CMD_left) /* left align */
new_indent = indent;
else
{
has_tab = FALSE; /* avoid uninit warnings */
len = linelen(eap->cmdidx == CMD_right ? &has_tab
: NULL) - get_indent();
if (len <= 0) /* skip blank lines */
continue;
if (eap->cmdidx == CMD_center)
new_indent = (width - len) / 2;
else
{
new_indent = width - len; /* right align */
/*
* Make sure that embedded TABs don't make the text go too far
* to the right.
*/
if (has_tab)
while (new_indent > 0)
{
(void)set_indent(new_indent, 0);
if (linelen(NULL) <= width)
{
/*
* Now try to move the line as much as possible to
* the right. Stop when it moves too far.
*/
do
(void)set_indent(++new_indent, 0);
while (linelen(NULL) <= width);
--new_indent;
break;
}
--new_indent;
}
}
}
if (new_indent < 0)
new_indent = 0;
(void)set_indent(new_indent, 0); /* set indent */
}
changed_lines(eap->line1, 0, eap->line2 + 1, 0L);
curwin->w_cursor = save_curpos;
beginline(BL_WHITE | BL_FIX);
}
/*
* Get the length of the current line, excluding trailing white space.
*/
static int
linelen(has_tab)
int *has_tab;
{
char_u *line;
char_u *first;
char_u *last;
int save;
int len;
/* find the first non-blank character */
line = ml_get_curline();
first = skipwhite(line);
/* find the character after the last non-blank character */
for (last = first + STRLEN(first);
last > first && vim_iswhite(last[-1]); --last)
;
save = *last;
*last = NUL;
len = linetabsize(line); /* get line length */
if (has_tab != NULL) /* check for embedded TAB */
*has_tab = (vim_strrchr(first, TAB) != NULL);
*last = save;
return len;
}
/* Buffer for two lines used during sorting. They are allocated to
* contain the longest line being sorted. */
static char_u *sortbuf1;
static char_u *sortbuf2;
static int sort_ic; /* ignore case */
static int sort_nr; /* sort on number */
static int sort_rx; /* sort on regex instead of skipping it */
static int sort_abort; /* flag to indicate if sorting has been interrupted */
/* Struct to store info to be sorted. */
typedef struct
{
linenr_T lnum; /* line number */
long start_col_nr; /* starting column number or number */
long end_col_nr; /* ending column number */
} sorti_T;
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;
{
sorti_T l1 = *(sorti_T *)s1;
sorti_T l2 = *(sorti_T *)s2;
int result = 0;
/* If the user interrupts, there's no way to stop qsort() immediately, but
* if we return 0 every time, qsort will assume it's done sorting and
* exit. */
if (sort_abort)
return 0;
fast_breakcheck();
if (got_int)
sort_abort = TRUE;
/* When sorting numbers "start_col_nr" is the number, not the column
* number. */
if (sort_nr)
result = l1.start_col_nr == l2.start_col_nr ? 0
: l1.start_col_nr > l2.start_col_nr ? 1 : -1;
else
{
/* We need to copy one line into "sortbuf1", because there is no
* guarantee that the first pointer becomes invalid when obtaining the
* second one. */
STRNCPY(sortbuf1, ml_get(l1.lnum) + l1.start_col_nr,
l1.end_col_nr - l1.start_col_nr + 1);
sortbuf1[l1.end_col_nr - l1.start_col_nr] = 0;
STRNCPY(sortbuf2, ml_get(l2.lnum) + l2.start_col_nr,
l2.end_col_nr - l2.start_col_nr + 1);
sortbuf2[l2.end_col_nr - l2.start_col_nr] = 0;
result = sort_ic ? STRICMP(sortbuf1, sortbuf2)
: STRCMP(sortbuf1, sortbuf2);
}
/* If two lines have the same value, preserve the original line order. */
if (result == 0)
return (int)(l1.lnum - l2.lnum);
return result;
}
/*
* ":sort".
*/
void
ex_sort(eap)
exarg_T *eap;
{
regmatch_T regmatch;
int len;
linenr_T lnum;
long maxlen = 0;
sorti_T *nrs;
size_t count = (size_t)(eap->line2 - eap->line1 + 1);
size_t i;
char_u *p;
char_u *s;
char_u *s2;
char_u c; /* temporary character storage */
int unique = FALSE;
long deleted;
colnr_T start_col;
colnr_T end_col;
int sort_oct; /* sort on octal number */
int sort_hex; /* sort on hex number */
/* Sorting one line is really quick! */
if (count <= 1)
return;
if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
return;
sortbuf1 = NULL;
sortbuf2 = NULL;
regmatch.regprog = NULL;
nrs = (sorti_T *)lalloc((long_u)(count * sizeof(sorti_T)), TRUE);
if (nrs == NULL)
goto sortend;
sort_abort = sort_ic = sort_rx = sort_nr = sort_oct = sort_hex = 0;
for (p = eap->arg; *p != NUL; ++p)
{
if (vim_iswhite(*p))
;
else if (*p == 'i')
sort_ic = TRUE;
else if (*p == 'r')
sort_rx = TRUE;
else if (*p == 'n')
sort_nr = 2;
else if (*p == 'o')
sort_oct = 2;
else if (*p == 'x')
sort_hex = 2;
else if (*p == 'u')
unique = TRUE;
else if (*p == '"') /* comment start */
break;
else if (check_nextcmd(p) != NULL)
{
eap->nextcmd = check_nextcmd(p);
break;
}
else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL)
{
s = skip_regexp(p + 1, *p, TRUE, NULL);
if (*s != *p)
{
EMSG(_(e_invalpat));
goto sortend;
}
*s = NUL;
/* Use last search pattern if sort pattern is empty. */
if (s == p + 1 && last_search_pat() != NULL)
regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
else
regmatch.regprog = vim_regcomp(p + 1, RE_MAGIC);
if (regmatch.regprog == NULL)
goto sortend;
p = s; /* continue after the regexp */
regmatch.rm_ic = p_ic;
}
else
{
EMSG2(_(e_invarg2), p);
goto sortend;
}
}
/* Can only have one of 'n', 'o' and 'x'. */
if (sort_nr + sort_oct + sort_hex > 2)
{
EMSG(_(e_invarg));
goto sortend;
}
/* From here on "sort_nr" is used as a flag for any number sorting. */
sort_nr += sort_oct + sort_hex;
/*
* Make an array with all line numbers. This avoids having to copy all
* the lines into allocated memory.
* When sorting on strings "start_col_nr" is the offset in the line, for
* numbers sorting it's the number to sort on. This means the pattern
* matching and number conversion only has to be done once per line.
* Also get the longest line length for allocating "sortbuf".
*/
for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
{
s = ml_get(lnum);
len = (int)STRLEN(s);
if (maxlen < len)
maxlen = len;
start_col = 0;
end_col = len;
if (regmatch.regprog != NULL && vim_regexec(®match, s, 0))
{
if (sort_rx)
{
start_col = (colnr_T)(regmatch.startp[0] - s);
end_col = (colnr_T)(regmatch.endp[0] - s);
}
else
start_col = (colnr_T)(regmatch.endp[0] - s);
}
else
if (regmatch.regprog != NULL)
end_col = 0;
if (sort_nr)
{
/* Make sure vim_str2nr doesn't read any digits past the end
* of the match, by temporarily terminating the string there */
s2 = s + end_col;
c = *s2;
*s2 = NUL;
/* Sorting on number: Store the number itself. */
p = s + start_col;
if (sort_hex)
s = skiptohex(p);
else
s = skiptodigit(p);
if (s > p && s[-1] == '-')
--s; /* include preceding negative sign */
if (*s == NUL)
/* empty line should sort before any number */
nrs[lnum - eap->line1].start_col_nr = -MAXLNUM;
else
vim_str2nr(s, NULL, NULL, sort_oct, sort_hex,
&nrs[lnum - eap->line1].start_col_nr, NULL);
*s2 = c;
}
else
{
/* Store the column to sort at. */
nrs[lnum - eap->line1].start_col_nr = start_col;
nrs[lnum - eap->line1].end_col_nr = end_col;
}
nrs[lnum - eap->line1].lnum = lnum;
if (regmatch.regprog != NULL)
fast_breakcheck();
if (got_int)
goto sortend;
}
/* Allocate a buffer that can hold the longest line. */
sortbuf1 = alloc((unsigned)maxlen + 1);
if (sortbuf1 == NULL)
goto sortend;
sortbuf2 = alloc((unsigned)maxlen + 1);
if (sortbuf2 == NULL)
goto sortend;
/* Sort the array of line numbers. Note: can't be interrupted! */
qsort((void *)nrs, count, sizeof(sorti_T), sort_compare);
if (sort_abort)
goto sortend;
/* Insert the lines in the sorted order below the last one. */
lnum = eap->line2;
for (i = 0; i < count; ++i)
{
s = ml_get(nrs[eap->forceit ? count - i - 1 : i].lnum);
if (!unique || i == 0
|| (sort_ic ? STRICMP(s, sortbuf1) : STRCMP(s, sortbuf1)) != 0)
{
if (ml_append(lnum++, s, (colnr_T)0, FALSE) == FAIL)
break;
if (unique)
STRCPY(sortbuf1, s);
}
fast_breakcheck();
if (got_int)
goto sortend;
}
/* delete the original lines if appending worked */
if (i == count)
for (i = 0; i < count; ++i)
ml_delete(eap->line1, FALSE);
else
count = 0;
/* Adjust marks for deleted (or added) lines and prepare for displaying. */
deleted = (long)(count - (lnum - eap->line2));
if (deleted > 0)
mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted);
else if (deleted < 0)
mark_adjust(eap->line2, MAXLNUM, -deleted, 0L);
changed_lines(eap->line1, 0, eap->line2 + 1, -deleted);
curwin->w_cursor.lnum = eap->line1;
beginline(BL_WHITE | BL_FIX);
sortend:
vim_free(nrs);
vim_free(sortbuf1);
vim_free(sortbuf2);
vim_free(regmatch.regprog);
if (got_int)
EMSG(_(e_interr));
}
/*
* ":retab".
*/
void
ex_retab(eap)
exarg_T *eap;
{
linenr_T lnum;
int got_tab = FALSE;
long num_spaces = 0;
long num_tabs;
long len;
long col;
long vcol;
long start_col = 0; /* For start of white-space string */
long start_vcol = 0; /* For start of white-space string */
int temp;
long old_len;
char_u *ptr;
char_u *new_line = (char_u *)1; /* init to non-NULL */
int did_undo; /* called u_save for current line */
int new_ts;
int save_list;
linenr_T first_line = 0; /* first changed line */
linenr_T last_line = 0; /* last changed line */
save_list = curwin->w_p_list;
curwin->w_p_list = 0; /* don't want list mode here */
new_ts = getdigits(&(eap->arg));
if (new_ts < 0)
{
EMSG(_(e_positive));
return;
}
if (new_ts == 0)
new_ts = curbuf->b_p_ts;
for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)
{
ptr = ml_get(lnum);
col = 0;
vcol = 0;
did_undo = FALSE;
for (;;)
{
if (vim_iswhite(ptr[col]))
{
if (!got_tab && num_spaces == 0)
{
/* First consecutive white-space */
start_vcol = vcol;
start_col = col;
}
if (ptr[col] == ' ')
num_spaces++;
else
got_tab = TRUE;
}
else
{
if (got_tab || (eap->forceit && num_spaces > 1))
{
/* Retabulate this string of white-space */
/* len is virtual length of white string */
len = num_spaces = vcol - start_vcol;
num_tabs = 0;
if (!curbuf->b_p_et)
{
temp = new_ts - (start_vcol % new_ts);
if (num_spaces >= temp)
{
num_spaces -= temp;
num_tabs++;
}
num_tabs += num_spaces / new_ts;
num_spaces -= (num_spaces / new_ts) * new_ts;
}
if (curbuf->b_p_et || got_tab ||
(num_spaces + num_tabs < len))
{
if (did_undo == FALSE)
{
did_undo = TRUE;
if (u_save((linenr_T)(lnum - 1),
(linenr_T)(lnum + 1)) == FAIL)
{
new_line = NULL; /* flag out-of-memory */
break;
}
}
/* len is actual number of white characters used */
len = num_spaces + num_tabs;
old_len = (long)STRLEN(ptr);
new_line = lalloc(old_len - col + start_col + len + 1,
TRUE);
if (new_line == NULL)
break;
if (start_col > 0)
mch_memmove(new_line, ptr, (size_t)start_col);
mch_memmove(new_line + start_col + len,
ptr + col, (size_t)(old_len - col + 1));
ptr = new_line + start_col;
for (col = 0; col < len; col++)
ptr[col] = (col < num_tabs) ? '\t' : ' ';
ml_replace(lnum, new_line, FALSE);
if (first_line == 0)
first_line = lnum;
last_line = lnum;
ptr = new_line;
col = start_col + len;
}
}
got_tab = FALSE;
num_spaces = 0;
}
if (ptr[col] == NUL)
break;
vcol += chartabsize(ptr + col, (colnr_T)vcol);
#ifdef FEAT_MBYTE
if (has_mbyte)
col += (*mb_ptr2len)(ptr + col);
else
#endif
++col;
}
if (new_line == NULL) /* out of memory */
break;
line_breakcheck();
}
if (got_int)
EMSG(_(e_interr));
if (curbuf->b_p_ts != new_ts)
redraw_curbuf_later(NOT_VALID);
if (first_line != 0)
changed_lines(first_line, 0, last_line + 1, 0L);
curwin->w_p_list = save_list; /* restore 'list' */
curbuf->b_p_ts = new_ts;
coladvance(curwin->w_curswant);
u_clearline();
}
#endif
/*
* :move command - move lines line1-line2 to line dest
*
* return FAIL for failure, OK otherwise
*/
int
do_move(line1, line2, dest)
linenr_T line1;
linenr_T line2;
linenr_T dest;
{
char_u *str;
linenr_T l;
linenr_T extra; /* Num lines added before line1 */
linenr_T num_lines; /* Num lines moved */
linenr_T last_line; /* Last line in file after adding new text */
if (dest >= line1 && dest < line2)
{
EMSG(_("E134: Move lines into themselves"));
return FAIL;
}
num_lines = line2 - line1 + 1;
/*
* First we copy the old text to its new location -- webb
* Also copy the flag that ":global" command uses.
*/
if (u_save(dest, dest + 1) == FAIL)
return FAIL;
for (extra = 0, l = line1; l <= line2; l++)
{
str = vim_strsave(ml_get(l + extra));
if (str != NULL)
{
ml_append(dest + l - line1, str, (colnr_T)0, FALSE);
vim_free(str);
if (dest < line1)
extra++;
}
}
/*
* Now we must be careful adjusting our marks so that we don't overlap our
* mark_adjust() calls.
*
* We adjust the marks within the old text so that they refer to the
* last lines of the file (temporarily), because we know no other marks
* will be set there since these line numbers did not exist until we added
* our new lines.
*
* Then we adjust the marks on lines between the old and new text positions
* (either forwards or backwards).
*
* And Finally we adjust the marks we put at the end of the file back to
* their final destination at the new text position -- webb
*/
last_line = curbuf->b_ml.ml_line_count;
mark_adjust(line1, line2, last_line - line2, 0L);
if (dest >= line2)
{
mark_adjust(line2 + 1, dest, -num_lines, 0L);
curbuf->b_op_start.lnum = dest - num_lines + 1;
curbuf->b_op_end.lnum = dest;
}
else
{
mark_adjust(dest + 1, line1 - 1, num_lines, 0L);
curbuf->b_op_start.lnum = dest + 1;
curbuf->b_op_end.lnum = dest + num_lines;
}
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
mark_adjust(last_line - num_lines + 1, last_line,
-(last_line - dest - extra), 0L);
/*
* Now we delete the original text -- webb
*/
if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL)
return FAIL;
for (l = line1; l <= line2; l++)
ml_delete(line1 + extra, TRUE);
if (!global_busy && num_lines > p_report)
{
if (num_lines == 1)
MSG(_("1 line moved"));
else
smsg((char_u *)_("%ld lines moved"), num_lines);
}
/*
* Leave the cursor on the last of the moved lines.
*/
if (dest >= line1)
curwin->w_cursor.lnum = dest;
else
curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
if (line1 < dest)
{
dest += num_lines + 1;
last_line = curbuf->b_ml.ml_line_count;
if (dest > last_line + 1)
dest = last_line + 1;
changed_lines(line1, 0, dest, 0L);
}
else
changed_lines(dest + 1, 0, line1 + num_lines, 0L);
return OK;
}
/*
* ":copy"
*/
void
ex_copy(line1, line2, n)
linenr_T line1;
linenr_T line2;
linenr_T n;
{
linenr_T count;
char_u *p;
count = line2 - line1 + 1;
curbuf->b_op_start.lnum = n + 1;
curbuf->b_op_end.lnum = n + count;
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
/*
* there are three situations:
* 1. destination is above line1
* 2. destination is between line1 and line2
* 3. destination is below line2
*
* n = destination (when starting)
* curwin->w_cursor.lnum = destination (while copying)
* line1 = start of source (while copying)
* line2 = end of source (while copying)
*/
if (u_save(n, n + 1) == FAIL)
return;
curwin->w_cursor.lnum = n;
while (line1 <= line2)
{
/* need to use vim_strsave() because the line will be unlocked within
* ml_append() */
p = vim_strsave(ml_get(line1));
if (p != NULL)
{
ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
vim_free(p);
}
/* situation 2: skip already copied lines */
if (line1 == n)
line1 = curwin->w_cursor.lnum;
++line1;
if (curwin->w_cursor.lnum < line1)
++line1;
if (curwin->w_cursor.lnum < line2)
++line2;
++curwin->w_cursor.lnum;
}
appended_lines_mark(n, count);
msgmore((long)count);
}
static char_u *prevcmd = NULL; /* the previous command */
#if defined(EXITFREE) || defined(PROTO)
void
free_prev_shellcmd()
{
vim_free(prevcmd);
}
#endif
/*
* Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd"
* Bangs in the argument are replaced with the previously entered command.
* Remember the argument.
*/
void
do_bang(addr_count, eap, forceit, do_in, do_out)
int addr_count;
exarg_T *eap;
int forceit;
int do_in, do_out;
{
char_u *arg = eap->arg; /* command */
linenr_T line1 = eap->line1; /* start of range */
linenr_T line2 = eap->line2; /* end of range */
char_u *newcmd = NULL; /* the new command */
int free_newcmd = FALSE; /* need to free() newcmd */
int ins_prevcmd;
char_u *t;
char_u *p;
char_u *trailarg;
int len;
int scroll_save = msg_scroll;
/*
* Disallow shell commands for "rvim".
* Disallow shell commands from .exrc and .vimrc in current directory for
* security reasons.
*/
if (check_restricted() || check_secure())
return;
if (addr_count == 0) /* :! */
{
msg_scroll = FALSE; /* don't scroll here */
autowrite_all();
msg_scroll = scroll_save;
}
/*
* Try to find an embedded bang, like in :!<cmd> ! [args]
* (:!! is indicated by the 'forceit' variable)
*/
ins_prevcmd = forceit;
trailarg = arg;
do
{
len = (int)STRLEN(trailarg) + 1;
if (newcmd != NULL)
len += (int)STRLEN(newcmd);
if (ins_prevcmd)
{
if (prevcmd == NULL)
{
EMSG(_(e_noprev));
vim_free(newcmd);
return;
}
len += (int)STRLEN(prevcmd);
}
if ((t = alloc((unsigned)len)) == NULL)
{
vim_free(newcmd);
return;
}
*t = NUL;
if (newcmd != NULL)
STRCAT(t, newcmd);
if (ins_prevcmd)
STRCAT(t, prevcmd);
p = t + STRLEN(t);
STRCAT(t, trailarg);
vim_free(newcmd);
newcmd = t;
/*
* Scan the rest of the argument for '!', which is replaced by the
* previous command. "\!" is replaced by "!" (this is vi compatible).
*/
trailarg = NULL;
while (*p)
{
if (*p == '!')
{
if (p > newcmd && p[-1] == '\\')
STRMOVE(p - 1, p);
else
{
trailarg = p;
*trailarg++ = NUL;
ins_prevcmd = TRUE;
break;
}
}
++p;
}
} while (trailarg != NULL);
vim_free(prevcmd);
prevcmd = newcmd;
if (bangredo) /* put cmd in redo buffer for ! command */
{
AppendToRedobuffLit(prevcmd, -1);
AppendToRedobuff((char_u *)"\n");
bangredo = FALSE;
}
/*
* Add quotes around the command, for shells that need them.
*/
if (*p_shq != NUL)
{
newcmd = alloc((unsigned)(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1));
if (newcmd == NULL)
return;
STRCPY(newcmd, p_shq);
STRCAT(newcmd, prevcmd);
STRCAT(newcmd, p_shq);
free_newcmd = TRUE;
}
if (addr_count == 0) /* :! */
{
/* echo the command */
msg_start();
msg_putchar(':');
msg_putchar('!');
msg_outtrans(newcmd);
msg_clr_eos();
windgoto(msg_row, msg_col);
do_shell(newcmd, 0);
}
else /* :range! */
{
/* Careful: This may recursively call do_bang() again! (because of
* autocommands) */
do_filter(line1, line2, eap, newcmd, do_in, do_out);
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_SHELLFILTERPOST, NULL, NULL, FALSE, curbuf);
#endif
}
if (free_newcmd)
vim_free(newcmd);
}
/*
* do_filter: filter lines through a command given by the user
*
* We mostly use temp files and the call_shell() routine here. This would
* normally be done using pipes on a UNIX machine, but this is more portable
* to non-unix machines. The call_shell() routine needs to be able
* to deal with redirection somehow, and should handle things like looking
* at the PATH env. variable, and adding reasonable extensions to the
* command name given by the user. All reasonable versions of call_shell()
* do this.
* Alternatively, if on Unix and redirecting input or output, but not both,
* and the 'shelltemp' option isn't set, use pipes.
* We use input redirection if do_in is TRUE.
* We use output redirection if do_out is TRUE.
*/
static void
do_filter(line1, line2, eap, cmd, do_in, do_out)
linenr_T line1, line2;
exarg_T *eap; /* for forced 'ff' and 'fenc' */
char_u *cmd;
int do_in, do_out;
{
char_u *itmp = NULL;
char_u *otmp = NULL;
linenr_T linecount;
linenr_T read_linecount;
pos_T cursor_save;
char_u *cmd_buf;
#ifdef FEAT_AUTOCMD
buf_T *old_curbuf = curbuf;
#endif
int shell_flags = 0;
if (*cmd == NUL) /* no filter command */
return;
#ifdef WIN3264
/*
* Check if external commands are allowed now.
*/
if (can_end_termcap_mode(TRUE) == FALSE)
return;
#endif
cursor_save = curwin->w_cursor;
linecount = line2 - line1 + 1;
curwin->w_cursor.lnum = line1;
curwin->w_cursor.col = 0;
changed_line_abv_curs();
invalidate_botline();
/*
* When using temp files:
* 1. * Form temp file names
* 2. * Write the lines to a temp file
* 3. Run the filter command on the temp file
* 4. * Read the output of the command into the buffer
* 5. * Delete the original lines to be filtered
* 6. * Remove the temp files
*
* When writing the input with a pipe or when catching the output with a
* pipe only need to do 3.
*/
if (do_out)
shell_flags |= SHELL_DOOUT;
#ifdef FEAT_FILTERPIPE
if (!do_in && do_out && !p_stmp)
{
/* Use a pipe to fetch stdout of the command, do not use a temp file. */
shell_flags |= SHELL_READ;
curwin->w_cursor.lnum = line2;
}
else if (do_in && !do_out && !p_stmp)
{
/* Use a pipe to write stdin of the command, do not use a temp file. */
shell_flags |= SHELL_WRITE;
curbuf->b_op_start.lnum = line1;
curbuf->b_op_end.lnum = line2;
}
else if (do_in && do_out && !p_stmp)
{
/* Use a pipe to write stdin and fetch stdout of the command, do not
* use a temp file. */
shell_flags |= SHELL_READ|SHELL_WRITE;
curbuf->b_op_start.lnum = line1;
curbuf->b_op_end.lnum = line2;
curwin->w_cursor.lnum = line2;
}
else
#endif
if ((do_in && (itmp = vim_tempname('i')) == NULL)
|| (do_out && (otmp = vim_tempname('o')) == NULL))
{
EMSG(_(e_notmp));
goto filterend;
}
/*
* The writing and reading of temp files will not be shown.
* Vi also doesn't do this and the messages are not very informative.
*/
++no_wait_return; /* don't call wait_return() while busy */
if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
FALSE, FALSE, FALSE, TRUE) == FAIL)
{
msg_putchar('\n'); /* keep message from buf_write() */
--no_wait_return;
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!aborting())
#endif
(void)EMSG2(_(e_notcreate), itmp); /* will call wait_return */
goto filterend;
}
#ifdef FEAT_AUTOCMD
if (curbuf != old_curbuf)
goto filterend;
#endif
if (!do_out)
msg_putchar('\n');
/* Create the shell command in allocated memory. */
cmd_buf = make_filter_cmd(cmd, itmp, otmp);
if (cmd_buf == NULL)
goto filterend;
windgoto((int)Rows - 1, 0);
cursor_on();
/*
* When not redirecting the output the command can write anything to the
* screen. If 'shellredir' is equal to ">", screen may be messed up by
* stderr output of external command. Clear the screen later.
* If do_in is FALSE, this could be something like ":r !cat", which may
* also mess up the screen, clear it later.
*/
if (!do_out || STRCMP(p_srr, ">") == 0 || !do_in)
redraw_later_clear();
if (do_out)
{
if (u_save((linenr_T)(line2), (linenr_T)(line2 + 1)) == FAIL)
{
vim_free(cmd_buf);
goto error;
}
redraw_curbuf_later(VALID);
}
read_linecount = curbuf->b_ml.ml_line_count;
/*
* When call_shell() fails wait_return() is called to give the user a
* chance to read the error messages. Otherwise errors are ignored, so you
* can see the error messages from the command that appear on stdout; use
* 'u' to fix the text
* Switch to cooked mode when not redirecting stdin, avoids that something
* like ":r !cat" hangs.
* Pass on the SHELL_DOOUT flag when the output is being redirected.
*/
if (call_shell(cmd_buf, SHELL_FILTER | SHELL_COOKED | shell_flags))
{
redraw_later_clear();
wait_return(FALSE);
}
vim_free(cmd_buf);
did_check_timestamps = FALSE;
need_check_timestamps = TRUE;
/* When interrupting the shell command, it may still have produced some
* useful output. Reset got_int here, so that readfile() won't cancel
* reading. */
ui_breakcheck();
got_int = FALSE;
if (do_out)
{
if (otmp != NULL)
{
if (readfile(otmp, NULL, line2, (linenr_T)0, (linenr_T)MAXLNUM,
eap, READ_FILTER) == FAIL)
{
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!aborting())
#endif
{
msg_putchar('\n');
EMSG2(_(e_notread), otmp);
}
goto error;
}
#ifdef FEAT_AUTOCMD
if (curbuf != old_curbuf)
goto filterend;
#endif
}
read_linecount = curbuf->b_ml.ml_line_count - read_linecount;
if (shell_flags & SHELL_READ)
{
curbuf->b_op_start.lnum = line2 + 1;
curbuf->b_op_end.lnum = curwin->w_cursor.lnum;
appended_lines_mark(line2, read_linecount);
}
if (do_in)
{
if (cmdmod.keepmarks || vim_strchr(p_cpo, CPO_REMMARK) == NULL)
{
if (read_linecount >= linecount)
/* move all marks from old lines to new lines */
mark_adjust(line1, line2, linecount, 0L);
else
{
/* move marks from old lines to new lines, delete marks
* that are in deleted lines */
mark_adjust(line1, line1 + read_linecount - 1,
linecount, 0L);
mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L);
}
}
/*
* Put cursor on first filtered line for ":range!cmd".
* Adjust '[ and '] (set by buf_write()).
*/
curwin->w_cursor.lnum = line1;
del_lines(linecount, TRUE);
curbuf->b_op_start.lnum -= linecount; /* adjust '[ */
curbuf->b_op_end.lnum -= linecount; /* adjust '] */
write_lnum_adjust(-linecount); /* adjust last line
for next write */
#ifdef FEAT_FOLDING
foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
#endif
}
else
{
/*
* Put cursor on last new line for ":r !cmd".
*/
linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
}
beginline(BL_WHITE | BL_FIX); /* cursor on first non-blank */
--no_wait_return;
if (linecount > p_report)
{
if (do_in)
{
vim_snprintf((char *)msg_buf, sizeof(msg_buf),
_("%ld lines filtered"), (long)linecount);
if (msg(msg_buf) && !msg_scroll)
/* save message to display it after redraw */
set_keep_msg(msg_buf, 0);
}
else
msgmore((long)linecount);
}
}
else
{
error:
/* put cursor back in same position for ":w !cmd" */
curwin->w_cursor = cursor_save;
--no_wait_return;
wait_return(FALSE);
}
filterend:
#ifdef FEAT_AUTOCMD
if (curbuf != old_curbuf)
{
--no_wait_return;
EMSG(_("E135: *Filter* Autocommands must not change current buffer"));
}
#endif
if (itmp != NULL)
mch_remove(itmp);
if (otmp != NULL)
mch_remove(otmp);
vim_free(itmp);
vim_free(otmp);
}
/*
* Call a shell to execute a command.
* When "cmd" is NULL start an interactive shell.
*/
void
do_shell(cmd, flags)
char_u *cmd;
int flags; /* may be SHELL_DOOUT when output is redirected */
{
buf_T *buf;
#ifndef FEAT_GUI_MSWIN
int save_nwr;
#endif
#ifdef MSWIN
int winstart = FALSE;
#endif
/*
* Disallow shell commands for "rvim".
* Disallow shell commands from .exrc and .vimrc in current directory for
* security reasons.
*/
if (check_restricted() || check_secure())
{
msg_end();
return;
}
#ifdef MSWIN
/*
* Check if external commands are allowed now.
*/
if (can_end_termcap_mode(TRUE) == FALSE)
return;
/*
* Check if ":!start" is used.
*/
if (cmd != NULL)
winstart = (STRNICMP(cmd, "start ", 6) == 0);
#endif
/*
* For autocommands we want to get the output on the current screen, to
* avoid having to type return below.
*/
msg_putchar('\r'); /* put cursor at start of line */
#ifdef FEAT_AUTOCMD
if (!autocmd_busy)
#endif
{
#ifdef MSWIN
if (!winstart)
#endif
stoptermcap();
}
#ifdef MSWIN
if (!winstart)
#endif
msg_putchar('\n'); /* may shift screen one line up */
/* warning message before calling the shell */
if (p_warn
#ifdef FEAT_AUTOCMD
&& !autocmd_busy
#endif
&& msg_silent == 0)
for (buf = firstbuf; buf; buf = buf->b_next)
if (bufIsChanged(buf))
{
#ifdef FEAT_GUI_MSWIN
if (!winstart)
starttermcap(); /* don't want a message box here */
#endif
MSG_PUTS(_("[No write since last change]\n"));
#ifdef FEAT_GUI_MSWIN
if (!winstart)
stoptermcap();
#endif
break;
}
/* This windgoto is required for when the '\n' resulted in a "delete line
* 1" command to the terminal. */
if (!swapping_screen())
windgoto(msg_row, msg_col);
cursor_on();
(void)call_shell(cmd, SHELL_COOKED | flags);
did_check_timestamps = FALSE;
need_check_timestamps = TRUE;
/*
* put the message cursor at the end of the screen, avoids wait_return()
* to overwrite the text that the external command showed
*/
if (!swapping_screen())
{
msg_row = Rows - 1;
msg_col = 0;
}
#ifdef FEAT_AUTOCMD
if (autocmd_busy)
{
if (msg_silent == 0)
redraw_later_clear();
}
else
#endif
{
/*
* For ":sh" there is no need to call wait_return(), just redraw.
* Also for the Win32 GUI (the output is in a console window).
* Otherwise there is probably text on the screen that the user wants
* to read before redrawing, so call wait_return().
*/
#ifndef FEAT_GUI_MSWIN
if (cmd == NULL
# ifdef WIN3264
|| (winstart && !need_wait_return)
# endif
)
{
if (msg_silent == 0)
redraw_later_clear();
need_wait_return = FALSE;
}
else
{
/*
* If we switch screens when starttermcap() is called, we really
* want to wait for "hit return to continue".
*/
save_nwr = no_wait_return;
if (swapping_screen())
no_wait_return = FALSE;
# ifdef AMIGA
wait_return(term_console ? -1 : msg_silent == 0); /* see below */
# else
wait_return(msg_silent == 0);
# endif
no_wait_return = save_nwr;
}
#endif /* FEAT_GUI_W32 */
#ifdef MSWIN
if (!winstart) /* if winstart==TRUE, never stopped termcap! */
#endif
starttermcap(); /* start termcap if not done by wait_return() */
/*
* In an Amiga window redrawing is caused by asking the window size.
* If we got an interrupt this will not work. The chance that the
* window size is wrong is very small, but we need to redraw the
* screen. Don't do this if ':' hit in wait_return(). THIS IS UGLY
* but it saves an extra redraw.
*/
#ifdef AMIGA
if (skip_redraw) /* ':' hit in wait_return() */
{
if (msg_silent == 0)
redraw_later_clear();
}
else if (term_console)
{
OUT_STR(IF_EB("\033[0 q", ESC_STR "[0 q")); /* get window size */
if (got_int && msg_silent == 0)
redraw_later_clear(); /* if got_int is TRUE, redraw needed */
else
must_redraw = 0; /* no extra redraw needed */
}
#endif
}
/* display any error messages now */
display_errors();
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_SHELLCMDPOST, NULL, NULL, FALSE, curbuf);
#endif
}
/*
* Create a shell command from a command string, input redirection file and
* output redirection file.
* Returns an allocated string with the shell command, or NULL for failure.
*/
char_u *
make_filter_cmd(cmd, itmp, otmp)
char_u *cmd; /* command */
char_u *itmp; /* NULL or name of input file */
char_u *otmp; /* NULL or name of output file */
{
char_u *buf;
long_u len;
len = (long_u)STRLEN(cmd) + 3; /* "()" + NUL */
if (itmp != NULL)
len += (long_u)STRLEN(itmp) + 9; /* " { < " + " } " */
if (otmp != NULL)
len += (long_u)STRLEN(otmp) + (long_u)STRLEN(p_srr) + 2; /* " " */
buf = lalloc(len, TRUE);
if (buf == NULL)
return NULL;
#if (defined(UNIX) && !defined(ARCHIE)) || defined(OS2)
/*
* Put braces around the command (for concatenated commands) when
* redirecting input and/or output.
*/
if (itmp != NULL || otmp != NULL)
vim_snprintf((char *)buf, len, "(%s)", (char *)cmd);
else
STRCPY(buf, cmd);
if (itmp != NULL)
{
STRCAT(buf, " < ");
STRCAT(buf, itmp);
}
#else
/*
* for shells that don't understand braces around commands, at least allow
* the use of commands in a pipe.
*/
STRCPY(buf, cmd);
if (itmp != NULL)
{
char_u *p;
/*
* If there is a pipe, we have to put the '<' in front of it.
* Don't do this when 'shellquote' is not empty, otherwise the
* redirection would be inside the quotes.
*/
if (*p_shq == NUL)
{
p = vim_strchr(buf, '|');
if (p != NULL)
*p = NUL;
}
STRCAT(buf, " <"); /* " < " causes problems on Amiga */
STRCAT(buf, itmp);
if (*p_shq == NUL)
{
p = vim_strchr(cmd, '|');
if (p != NULL)
{
STRCAT(buf, " "); /* insert a space before the '|' for DOS */
STRCAT(buf, p);
}
}
}
#endif
if (otmp != NULL)
append_redir(buf, (int)len, p_srr, otmp);
return buf;
}
/*
* Append output redirection for file "fname" to the end of string buffer
* "buf[buflen]"
* Works with the 'shellredir' and 'shellpipe' options.
* The caller should make sure that there is enough room:
* STRLEN(opt) + STRLEN(fname) + 3
*/
void
append_redir(buf, buflen, opt, fname)
char_u *buf;
int buflen;
char_u *opt;
char_u *fname;
{
char_u *p;
char_u *end;
end = buf + STRLEN(buf);
/* find "%s", skipping "%%" */
for (p = opt; (p = vim_strchr(p, '%')) != NULL; ++p)
if (p[1] == 's')
break;
if (p != NULL)
{
*end = ' '; /* not really needed? Not with sh, ksh or bash */
vim_snprintf((char *)end + 1, (size_t)(buflen - (end + 1 - buf)),
(char *)opt, (char *)fname);
}
else
vim_snprintf((char *)end, (size_t)(buflen - (end - buf)),
#ifdef FEAT_QUICKFIX
" %s %s",
#else
" %s%s", /* " > %s" causes problems on Amiga */
#endif
(char *)opt, (char *)fname);
}
#ifdef FEAT_VIMINFO
static int no_viminfo __ARGS((void));
static int viminfo_errcnt;
static int
no_viminfo()
{
/* "vim -i NONE" does not read or write a viminfo file */
return (use_viminfo != NULL && STRCMP(use_viminfo, "NONE") == 0);
}
/*
* Report an error for reading a viminfo file.
* Count the number of errors. When there are more than 10, return TRUE.
*/
int
viminfo_error(errnum, message, line)
char *errnum;
char *message;
char_u *line;
{
vim_snprintf((char *)IObuff, IOSIZE, _("%sviminfo: %s in line: "),
errnum, message);
STRNCAT(IObuff, line, IOSIZE - STRLEN(IObuff) - 1);
if (IObuff[STRLEN(IObuff) - 1] == '\n')
IObuff[STRLEN(IObuff) - 1] = NUL;
emsg(IObuff);
if (++viminfo_errcnt >= 10)
{
EMSG(_("E136: viminfo: Too many errors, skipping rest of file"));
return TRUE;
}
return FALSE;
}
/*
* read_viminfo() -- Read the viminfo file. Registers etc. which are already
* set are not over-written unless "flags" includes VIF_FORCEIT. -- webb
*/
int
read_viminfo(file, flags)
char_u *file; /* file name or NULL to use default name */
int flags; /* VIF_WANT_INFO et al. */
{
FILE *fp;
char_u *fname;
if (no_viminfo())
return FAIL;
fname = viminfo_filename(file); /* get file name in allocated buffer */
if (fname == NULL)
return FAIL;
fp = mch_fopen((char *)fname, READBIN);
if (p_verbose > 0)
{
verbose_enter();
smsg((char_u *)_("Reading viminfo file \"%s\"%s%s%s"),
fname,
(flags & VIF_WANT_INFO) ? _(" info") : "",
(flags & VIF_WANT_MARKS) ? _(" marks") : "",
(flags & VIF_GET_OLDFILES) ? _(" oldfiles") : "",
fp == NULL ? _(" FAILED") : "");
verbose_leave();
}
vim_free(fname);
if (fp == NULL)
return FAIL;
viminfo_errcnt = 0;
do_viminfo(fp, NULL, flags);
fclose(fp);
return OK;
}
/*
* write_viminfo() -- Write the viminfo file. The old one is read in first so
* that effectively a merge of current info and old info is done. This allows
* multiple vims to run simultaneously, without losing any marks etc. If
* forceit is TRUE, then the old file is not read in, and only internal info is
* written to the file. -- webb
*/
void
write_viminfo(file, forceit)
char_u *file;
int forceit;
{
char_u *fname;
FILE *fp_in = NULL; /* input viminfo file, if any */
FILE *fp_out = NULL; /* output viminfo file */
char_u *tempname = NULL; /* name of temp viminfo file */
struct stat st_new; /* mch_stat() of potential new file */
char_u *wp;
#if defined(UNIX) || defined(VMS)
mode_t umask_save;
#endif
#ifdef UNIX
int shortname = FALSE; /* use 8.3 file name */
struct stat st_old; /* mch_stat() of existing viminfo file */
#endif
#ifdef WIN3264
long perm = -1;
#endif
if (no_viminfo())
return;
fname = viminfo_filename(file); /* may set to default if NULL */
if (fname == NULL)
return;
fp_in = mch_fopen((char *)fname, READBIN);
if (fp_in == NULL)
{
/* if it does exist, but we can't read it, don't try writing */
if (mch_stat((char *)fname, &st_new) == 0)
goto end;
#if defined(UNIX) || defined(VMS)
/*
* For Unix we create the .viminfo non-accessible for others,
* because it may contain text from non-accessible documents.
*/
umask_save = umask(077);
#endif
fp_out = mch_fopen((char *)fname, WRITEBIN);
#if defined(UNIX) || defined(VMS)
(void)umask(umask_save);
#endif
}
else
{
/*
* There is an existing viminfo file. Create a temporary file to
* write the new viminfo into, in the same directory as the
* existing viminfo file, which will be renamed later.
*/
#ifdef UNIX
/*
* For Unix we check the owner of the file. It's not very nice to
* overwrite a user's viminfo file after a "su root", with a
* viminfo file that the user can't read.
*/
st_old.st_dev = (dev_t)0;
st_old.st_ino = 0;
st_old.st_mode = 0600;
if (mch_stat((char *)fname, &st_old) == 0
&& getuid() != ROOT_UID
&& !(st_old.st_uid == getuid()
? (st_old.st_mode & 0200)
: (st_old.st_gid == getgid()
? (st_old.st_mode & 0020)
: (st_old.st_mode & 0002))))
{
int tt = msg_didany;
/* avoid a wait_return for this message, it's annoying */
EMSG2(_("E137: Viminfo file is not writable: %s"), fname);
msg_didany = tt;
fclose(fp_in);
goto end;
}
#endif
#ifdef WIN3264
/* Get the file attributes of the existing viminfo file. */
perm = mch_getperm(fname);
#endif
/*
* Make tempname.
* May try twice: Once normal and once with shortname set, just in
* case somebody puts his viminfo file in an 8.3 filesystem.
*/
for (;;)
{
tempname = buf_modname(
#ifdef UNIX
shortname,
#else
# ifdef SHORT_FNAME
TRUE,
# else
# ifdef FEAT_GUI_W32
gui_is_win32s(),
# else
FALSE,
# endif
# endif
#endif
fname,
#ifdef VMS
(char_u *)"-tmp",
#else
(char_u *)".tmp",
#endif
FALSE);
if (tempname == NULL) /* out of memory */
break;
/*
* Check if tempfile already exists. Never overwrite an
* existing file!
*/
if (mch_stat((char *)tempname, &st_new) == 0)
{
#ifdef UNIX
/*
* Check if tempfile is same as original file. May happen
* when modname() gave the same file back. E.g. silly
* link, or file name-length reached. Try again with
* shortname set.
*/
if (!shortname && st_new.st_dev == st_old.st_dev
&& st_new.st_ino == st_old.st_ino)
{
vim_free(tempname);
tempname = NULL;
shortname = TRUE;
continue;
}
#endif
/*
* Try another name. Change one character, just before
* the extension. This should also work for an 8.3
* file name, when after adding the extension it still is
* the same file as the original.
*/
wp = tempname + STRLEN(tempname) - 5;
if (wp < gettail(tempname)) /* empty file name? */
wp = gettail(tempname);
for (*wp = 'z'; mch_stat((char *)tempname, &st_new) == 0;
--*wp)
{
/*
* They all exist? Must be something wrong! Don't
* write the viminfo file then.
*/
if (*wp == 'a')
{
vim_free(tempname);
tempname = NULL;
break;
}
}
}
break;
}
if (tempname != NULL)
{
#ifdef VMS
/* fdopen() fails for some reason */
umask_save = umask(077);
fp_out = mch_fopen((char *)tempname, WRITEBIN);
(void)umask(umask_save);
#else
int fd;
/* Use mch_open() to be able to use O_NOFOLLOW and set file
* protection:
* Unix: same as original file, but strip s-bit. Reset umask to
* avoid it getting in the way.
* Others: r&w for user only. */
# ifdef UNIX
umask_save = umask(0);
fd = mch_open((char *)tempname,
O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW,
(int)((st_old.st_mode & 0777) | 0600));
(void)umask(umask_save);
# else
fd = mch_open((char *)tempname,
O_CREAT|O_EXTRA|O_EXCL|O_WRONLY|O_NOFOLLOW, 0600);
# endif
if (fd < 0)
fp_out = NULL;
else
fp_out = fdopen(fd, WRITEBIN);
#endif /* VMS */
/*
* If we can't create in the same directory, try creating a
* "normal" temp file.
*/
if (fp_out == NULL)
{
vim_free(tempname);
if ((tempname = vim_tempname('o')) != NULL)
fp_out = mch_fopen((char *)tempname, WRITEBIN);
}
#if defined(UNIX) && defined(HAVE_FCHOWN)
/*
* Make sure the owner can read/write it. This only works for
* root.
*/
if (fp_out != NULL)
ignored = fchown(fileno(fp_out), st_old.st_uid, st_old.st_gid);
#endif
}
}
/*
* Check if the new viminfo file can be written to.
*/
if (fp_out == NULL)
{
EMSG2(_("E138: Can't write viminfo file %s!"),
(fp_in == NULL || tempname == NULL) ? fname : tempname);
if (fp_in != NULL)
fclose(fp_in);
goto end;
}
if (p_verbose > 0)
{
verbose_enter();
smsg((char_u *)_("Writing viminfo file \"%s\""), fname);
verbose_leave();
}
viminfo_errcnt = 0;
do_viminfo(fp_in, fp_out, forceit ? 0 : (VIF_WANT_INFO | VIF_WANT_MARKS));
fclose(fp_out); /* errors are ignored !? */
if (fp_in != NULL)
{
fclose(fp_in);
/*
* In case of an error keep the original viminfo file.
* Otherwise rename the newly written file.
*/
if (viminfo_errcnt || vim_rename(tempname, fname) == -1)
mch_remove(tempname);
#ifdef WIN3264
/* If the viminfo file was hidden then also hide the new file. */
if (perm > 0 && (perm & FILE_ATTRIBUTE_HIDDEN))
mch_hide(fname);
#endif
}
end:
vim_free(fname);
vim_free(tempname);
}
/*
* Get the viminfo file name to use.
* If "file" is given and not empty, use it (has already been expanded by
* cmdline functions).
* Otherwise use "-i file_name", value from 'viminfo' or the default, and
* expand environment variables.
* Returns an allocated string. NULL when out of memory.
*/
static char_u *
viminfo_filename(file)
char_u *file;
{
if (file == NULL || *file == NUL)
{
if (use_viminfo != NULL)
file = use_viminfo;
else if ((file = find_viminfo_parameter('n')) == NULL || *file == NUL)
{
#ifdef VIMINFO_FILE2
/* don't use $HOME when not defined (turned into "c:/"!). */
# ifdef VMS
if (mch_getenv((char_u *)"SYS$LOGIN") == NULL)
# else
if (mch_getenv((char_u *)"HOME") == NULL)
# endif
{
/* don't use $VIM when not available. */
expand_env((char_u *)"$VIM", NameBuff, MAXPATHL);
if (STRCMP("$VIM", NameBuff) != 0) /* $VIM was expanded */
file = (char_u *)VIMINFO_FILE2;
else
file = (char_u *)VIMINFO_FILE;
}
else
#endif
file = (char_u *)VIMINFO_FILE;
}
expand_env(file, NameBuff, MAXPATHL);
file = NameBuff;
}
return vim_strsave(file);
}
/*
* do_viminfo() -- Should only be called from read_viminfo() & write_viminfo().
*/
static void
do_viminfo(fp_in, fp_out, flags)
FILE *fp_in;
FILE *fp_out;
int flags;
{
int count = 0;
int eof = FALSE;
vir_T vir;
if ((vir.vir_line = alloc(LSIZE)) == NULL)
return;
vir.vir_fd = fp_in;
#ifdef FEAT_MBYTE
vir.vir_conv.vc_type = CONV_NONE;
#endif
if (fp_in != NULL)
{
if (flags & VIF_WANT_INFO)
eof = read_viminfo_up_to_marks(&vir,
flags & VIF_FORCEIT, fp_out != NULL);
else
/* Skip info, find start of marks */
while (!(eof = viminfo_readline(&vir))
&& vir.vir_line[0] != '>')
;
}
if (fp_out != NULL)
{
/* Write the info: */
fprintf(fp_out, _("# This viminfo file was generated by Vim %s.\n"),
VIM_VERSION_MEDIUM);
fputs(_("# You may edit it if you're careful!\n\n"), fp_out);
#ifdef FEAT_MBYTE
fputs(_("# Value of 'encoding' when this file was written\n"), fp_out);
fprintf(fp_out, "*encoding=%s\n\n", p_enc);
#endif
write_viminfo_search_pattern(fp_out);
write_viminfo_sub_string(fp_out);
#ifdef FEAT_CMDHIST
write_viminfo_history(fp_out);
#endif
write_viminfo_registers(fp_out);
#ifdef FEAT_EVAL
write_viminfo_varlist(fp_out);
#endif
write_viminfo_filemarks(fp_out);
write_viminfo_bufferlist(fp_out);
count = write_viminfo_marks(fp_out);
}
if (fp_in != NULL
&& (flags & (VIF_WANT_MARKS | VIF_GET_OLDFILES | VIF_FORCEIT)))
copy_viminfo_marks(&vir, fp_out, count, eof, flags);
vim_free(vir.vir_line);
#ifdef FEAT_MBYTE
if (vir.vir_conv.vc_type != CONV_NONE)
convert_setup(&vir.vir_conv, NULL, NULL);
#endif
}
/*
* read_viminfo_up_to_marks() -- Only called from do_viminfo(). Reads in the
* first part of the viminfo file which contains everything but the marks that
* are local to a file. Returns TRUE when end-of-file is reached. -- webb
*/
static int
read_viminfo_up_to_marks(virp, forceit, writing)
vir_T *virp;
int forceit;
int writing;
{
int eof;
buf_T *buf;
#ifdef FEAT_CMDHIST
prepare_viminfo_history(forceit ? 9999 : 0);
#endif
eof = viminfo_readline(virp);
while (!eof && virp->vir_line[0] != '>')
{
switch (virp->vir_line[0])
{
/* Characters reserved for future expansion, ignored now */
case '+': /* "+40 /path/dir file", for running vim without args */
case '|': /* to be defined */
case '^': /* to be defined */
case '<': /* long line - ignored */
/* A comment or empty line. */
case NUL:
case '\r':
case '\n':
case '#':
eof = viminfo_readline(virp);
break;
case '*': /* "*encoding=value" */
eof = viminfo_encoding(virp);
break;
case '!': /* global variable */
#ifdef FEAT_EVAL
eof = read_viminfo_varlist(virp, writing);
#else
eof = viminfo_readline(virp);
#endif
break;
case '%': /* entry for buffer list */
eof = read_viminfo_bufferlist(virp, writing);
break;
case '"':
eof = read_viminfo_register(virp, forceit);
break;
case '/': /* Search string */
case '&': /* Substitute search string */
case '~': /* Last search string, followed by '/' or '&' */
eof = read_viminfo_search_pattern(virp, forceit);
break;
case '$':
eof = read_viminfo_sub_string(virp, forceit);
break;
case ':':
case '?':
case '=':
case '@':
#ifdef FEAT_CMDHIST
eof = read_viminfo_history(virp);
#else
eof = viminfo_readline(virp);
#endif
break;
case '-':
case '\'':
eof = read_viminfo_filemark(virp, forceit);
break;
default:
if (viminfo_error("E575: ", _("Illegal starting char"),
virp->vir_line))
eof = TRUE;
else
eof = viminfo_readline(virp);
break;
}
}
#ifdef FEAT_CMDHIST
/* Finish reading history items. */
finish_viminfo_history();
#endif
/* Change file names to buffer numbers for fmarks. */
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
fmarks_check_names(buf);
return eof;
}
/*
* Compare the 'encoding' value in the viminfo file with the current value of
* 'encoding'. If different and the 'c' flag is in 'viminfo', setup for
* conversion of text with iconv() in viminfo_readstring().
*/
static int
viminfo_encoding(virp)
vir_T *virp;
{
#ifdef FEAT_MBYTE
char_u *p;
int i;
if (get_viminfo_parameter('c') != 0)
{
p = vim_strchr(virp->vir_line, '=');
if (p != NULL)
{
/* remove trailing newline */
++p;
for (i = 0; vim_isprintc(p[i]); ++i)
;
p[i] = NUL;
convert_setup(&virp->vir_conv, p, p_enc);
}
}
#endif
return viminfo_readline(virp);
}
/*
* Read a line from the viminfo file.
* Returns TRUE for end-of-file;
*/
int
viminfo_readline(virp)
vir_T *virp;
{
return vim_fgets(virp->vir_line, LSIZE, virp->vir_fd);
}
/*
* check string read from viminfo file
* remove '\n' at the end of the line
* - replace CTRL-V CTRL-V with CTRL-V
* - replace CTRL-V 'n' with '\n'
*
* Check for a long line as written by viminfo_writestring().
*
* Return the string in allocated memory (NULL when out of memory).
*/
char_u *
viminfo_readstring(virp, off, convert)
vir_T *virp;
int off; /* offset for virp->vir_line */
int convert UNUSED; /* convert the string */
{
char_u *retval;
char_u *s, *d;
long len;
if (virp->vir_line[off] == Ctrl_V && vim_isdigit(virp->vir_line[off + 1]))
{
len = atol((char *)virp->vir_line + off + 1);
retval = lalloc(len, TRUE);
if (retval == NULL)
{
/* Line too long? File messed up? Skip next line. */
(void)vim_fgets(virp->vir_line, 10, virp->vir_fd);
return NULL;
}
(void)vim_fgets(retval, (int)len, virp->vir_fd);
s = retval + 1; /* Skip the leading '<' */
}
else
{
retval = vim_strsave(virp->vir_line + off);
if (retval == NULL)
return NULL;
s = retval;
}
/* Change CTRL-V CTRL-V to CTRL-V and CTRL-V n to \n in-place. */
d = retval;
while (*s != NUL && *s != '\n')
{
if (s[0] == Ctrl_V && s[1] != NUL)
{
if (s[1] == 'n')
*d++ = '\n';
else
*d++ = Ctrl_V;
s += 2;
}
else
*d++ = *s++;
}
*d = NUL;
#ifdef FEAT_MBYTE
if (convert && virp->vir_conv.vc_type != CONV_NONE && *retval != NUL)
{
d = string_convert(&virp->vir_conv, retval, NULL);
if (d != NULL)
{
vim_free(retval);
retval = d;
}
}
#endif
return retval;
}
/*
* write string to viminfo file
* - replace CTRL-V with CTRL-V CTRL-V
* - replace '\n' with CTRL-V 'n'
* - add a '\n' at the end
*
* For a long line:
* - write " CTRL-V <length> \n " in first line
* - write " < <string> \n " in second line
*/
void
viminfo_writestring(fd, p)
FILE *fd;
char_u *p;
{
int c;
char_u *s;
int len = 0;
for (s = p; *s != NUL; ++s)
{
if (*s == Ctrl_V || *s == '\n')
++len;
++len;
}
/* If the string will be too long, write its length and put it in the next
* line. Take into account that some room is needed for what comes before
* the string (e.g., variable name). Add something to the length for the
* '<', NL and trailing NUL. */
if (len > LSIZE / 2)
fprintf(fd, IF_EB("\026%d\n<", CTRL_V_STR "%d\n<"), len + 3);
while ((c = *p++) != NUL)
{
if (c == Ctrl_V || c == '\n')
{
putc(Ctrl_V, fd);
if (c == '\n')
c = 'n';
}
putc(c, fd);
}
putc('\n', fd);
}
#endif /* FEAT_VIMINFO */
/*
* Implementation of ":fixdel", also used by get_stty().
* <BS> resulting <Del>
* ^? ^H
* not ^? ^?
*/
void
do_fixdel(eap)
exarg_T *eap UNUSED;
{
char_u *p;
p = find_termcode((char_u *)"kb");
add_termcode((char_u *)"kD", p != NULL
&& *p == DEL ? (char_u *)CTRL_H_STR : DEL_STR, FALSE);
}
void
print_line_no_prefix(lnum, use_number, list)
linenr_T lnum;
int use_number;
int list;
{
char_u numbuf[30];
if (curwin->w_p_nu || use_number)
{
vim_snprintf((char *)numbuf, sizeof(numbuf),
"%*ld ", number_width(curwin), (long)lnum);
msg_puts_attr(numbuf, hl_attr(HLF_N)); /* Highlight line nrs */
}
msg_prt_line(ml_get(lnum), list);
}
/*
* Print a text line. Also in silent mode ("ex -s").
*/
void
print_line(lnum, use_number, list)
linenr_T lnum;
int use_number;
int list;
{
int save_silent = silent_mode;
msg_start();
silent_mode = FALSE;
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
print_line_no_prefix(lnum, use_number, list);
if (save_silent)
{
msg_putchar('\n');
cursor_on(); /* msg_start() switches it off */
out_flush();
silent_mode = save_silent;
}
info_message = FALSE;
}
/*
* ":file[!] [fname]".
*/
void
ex_file(eap)
exarg_T *eap;
{
char_u *fname, *sfname, *xfname;
buf_T *buf;
/* ":0file" removes the file name. Check for illegal uses ":3file",
* "0file name", etc. */
if (eap->addr_count > 0
&& (*eap->arg != NUL
|| eap->line2 > 0
|| eap->addr_count > 1))
{
EMSG(_(e_invarg));
return;
}
if (*eap->arg != NUL || eap->addr_count == 1)
{
#ifdef FEAT_AUTOCMD
buf = curbuf;
apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
/* buffer changed, don't change name now */
if (buf != curbuf)
return;
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return;
# endif
#endif
/*
* The name of the current buffer will be changed.
* A new (unlisted) buffer entry needs to be made to hold the old file
* name, which will become the alternate file name.
* But don't set the alternate file name if the buffer didn't have a
* name.
*/
fname = curbuf->b_ffname;
sfname = curbuf->b_sfname;
xfname = curbuf->b_fname;
curbuf->b_ffname = NULL;
curbuf->b_sfname = NULL;
if (setfname(curbuf, eap->arg, NULL, TRUE) == FAIL)
{
curbuf->b_ffname = fname;
curbuf->b_sfname = sfname;
return;
}
curbuf->b_flags |= BF_NOTEDITED;
if (xfname != NULL && *xfname != NUL)
{
buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
if (buf != NULL && !cmdmod.keepalt)
curwin->w_alt_fnum = buf->b_fnum;
}
vim_free(fname);
vim_free(sfname);
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
#endif
/* Change directories when the 'acd' option is set. */
DO_AUTOCHDIR
}
/* print full file name if :cd used */
fileinfo(FALSE, FALSE, eap->forceit);
}
/*
* ":update".
*/
void
ex_update(eap)
exarg_T *eap;
{
if (curbufIsChanged())
(void)do_write(eap);
}
/*
* ":write" and ":saveas".
*/
void
ex_write(eap)
exarg_T *eap;
{
if (eap->usefilter) /* input lines to shell command */
do_bang(1, eap, FALSE, TRUE, FALSE);
else
(void)do_write(eap);
}
/*
* write current buffer to file 'eap->arg'
* if 'eap->append' is TRUE, append to the file
*
* if *eap->arg == NUL write to current file
*
* return FAIL for failure, OK otherwise
*/
int
do_write(eap)
exarg_T *eap;
{
int other;
char_u *fname = NULL; /* init to shut up gcc */
char_u *ffname;
int retval = FAIL;
char_u *free_fname = NULL;
#ifdef FEAT_BROWSE
char_u *browse_file = NULL;
#endif
buf_T *alt_buf = NULL;
if (not_writing()) /* check 'write' option */
return FAIL;
ffname = eap->arg;
#ifdef FEAT_BROWSE
if (cmdmod.browse)
{
browse_file = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), ffname,
NULL, NULL, NULL, curbuf);
if (browse_file == NULL)
goto theend;
ffname = browse_file;
}
#endif
if (*ffname == NUL)
{
if (eap->cmdidx == CMD_saveas)
{
EMSG(_(e_argreq));
goto theend;
}
other = FALSE;
}
else
{
fname = ffname;
free_fname = fix_fname(ffname);
/*
* When out-of-memory, keep unexpanded file name, because we MUST be
* able to write the file in this situation.
*/
if (free_fname != NULL)
ffname = free_fname;
other = otherfile(ffname);
}
/*
* If we have a new file, put its name in the list of alternate file names.
*/
if (other)
{
if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
|| eap->cmdidx == CMD_saveas)
alt_buf = setaltfname(ffname, fname, (linenr_T)1);
else
alt_buf = buflist_findname(ffname);
if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL)
{
/* Overwriting a file that is loaded in another buffer is not a
* good idea. */
EMSG(_(e_bufloaded));
goto theend;
}
}
/*
* Writing to the current file is not allowed in readonly mode
* and a file name is required.
* "nofile" and "nowrite" buffers cannot be written implicitly either.
*/
if (!other && (
#ifdef FEAT_QUICKFIX
bt_dontwrite_msg(curbuf) ||
#endif
check_fname() == FAIL || check_readonly(&eap->forceit, curbuf)))
goto theend;
if (!other)
{
ffname = curbuf->b_ffname;
fname = curbuf->b_fname;
/*
* Not writing the whole file is only allowed with '!'.
*/
if ( (eap->line1 != 1
|| eap->line2 != curbuf->b_ml.ml_line_count)
&& !eap->forceit
&& !eap->append
&& !p_wa)
{
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if (p_confirm || cmdmod.confirm)
{
if (vim_dialog_yesno(VIM_QUESTION, NULL,
(char_u *)_("Write partial file?"), 2) != VIM_YES)
goto theend;
eap->forceit = TRUE;
}
else
#endif
{
EMSG(_("E140: Use ! to write partial buffer"));
goto theend;
}
}
}
if (check_overwrite(eap, curbuf, fname, ffname, other) == OK)
{
if (eap->cmdidx == CMD_saveas && alt_buf != NULL)
{
#ifdef FEAT_AUTOCMD
buf_T *was_curbuf = curbuf;
apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf);
# ifdef FEAT_EVAL
if (curbuf != was_curbuf || aborting())
# else
if (curbuf != was_curbuf)
# endif
{
/* buffer changed, don't change name now */
retval = FAIL;
goto theend;
}
#endif
/* Exchange the file names for the current and the alternate
* buffer. This makes it look like we are now editing the buffer
* under the new name. Must be done before buf_write(), because
* if there is no file name and 'cpo' contains 'F', it will set
* the file name. */
fname = alt_buf->b_fname;
alt_buf->b_fname = curbuf->b_fname;
curbuf->b_fname = fname;
fname = alt_buf->b_ffname;
alt_buf->b_ffname = curbuf->b_ffname;
curbuf->b_ffname = fname;
fname = alt_buf->b_sfname;
alt_buf->b_sfname = curbuf->b_sfname;
curbuf->b_sfname = fname;
buf_name_changed(curbuf);
#ifdef FEAT_AUTOCMD
apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, alt_buf);
if (!alt_buf->b_p_bl)
{
alt_buf->b_p_bl = TRUE;
apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf);
}
# ifdef FEAT_EVAL
if (curbuf != was_curbuf || aborting())
# else
if (curbuf != was_curbuf)
# endif
{
/* buffer changed, don't write the file */
retval = FAIL;
goto theend;
}
/* If 'filetype' was empty try detecting it now. */
if (*curbuf->b_p_ft == NUL)
{
if (au_has_group((char_u *)"filetypedetect"))
(void)do_doautocmd((char_u *)"filetypedetect BufRead",
TRUE);
do_modelines(0);
}
/* Autocommands may have changed buffer names, esp. when
* 'autochdir' is set. */
fname = curbuf->b_sfname;
#endif
}
retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
eap, eap->append, eap->forceit, TRUE, FALSE);
/* After ":saveas fname" reset 'readonly'. */
if (eap->cmdidx == CMD_saveas)
{
if (retval == OK)
{
curbuf->b_p_ro = FALSE;
#ifdef FEAT_WINDOWS
redraw_tabline = TRUE;
#endif
}
/* Change directories when the 'acd' option is set. */
DO_AUTOCHDIR
}
}
theend:
#ifdef FEAT_BROWSE
vim_free(browse_file);
#endif
vim_free(free_fname);
return retval;
}
/*
* Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED,
* BF_NEW or BF_READERR, check for overwriting current file.
* May set eap->forceit if a dialog says it's OK to overwrite.
* Return OK if it's OK, FAIL if it is not.
*/
int
check_overwrite(eap, buf, fname, ffname, other)
exarg_T *eap;
buf_T *buf;
char_u *fname; /* file name to be used (can differ from
buf->ffname) */
char_u *ffname; /* full path version of fname */
int other; /* writing under other name */
{
/*
* write to other file or b_flags set or not writing the whole file:
* overwriting only allowed with '!'
*/
if ( (other
|| (buf->b_flags & BF_NOTEDITED)
|| ((buf->b_flags & BF_NEW)
&& vim_strchr(p_cpo, CPO_OVERNEW) == NULL)
|| (buf->b_flags & BF_READERR))
&& !p_wa
#ifdef FEAT_QUICKFIX
&& !bt_nofile(buf)
#endif
&& vim_fexists(ffname))
{
if (!eap->forceit && !eap->append)
{
#ifdef UNIX
/* with UNIX it is possible to open a directory */
if (mch_isdir(ffname))
{
EMSG2(_(e_isadir2), ffname);
return FAIL;
}
#endif
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if (p_confirm || cmdmod.confirm)
{
char_u buff[DIALOG_MSG_SIZE];
dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname);
if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES)
return FAIL;
eap->forceit = TRUE;
}
else
#endif
{
EMSG(_(e_exists));
return FAIL;
}
}
/* For ":w! filename" check that no swap file exists for "filename". */
if (other && !emsg_silent)
{
char_u *dir;
char_u *p;
int r;
char_u *swapname;
/* We only try the first entry in 'directory', without checking if
* it's writable. If the "." directory is not writable the write
* will probably fail anyway.
* Use 'shortname' of the current buffer, since there is no buffer
* for the written file. */
if (*p_dir == NUL)
{
dir = alloc(5);
if (dir == NULL)
return FAIL;
STRCPY(dir, ".");
}
else
{
dir = alloc(MAXPATHL);
if (dir == NULL)
return FAIL;
p = p_dir;
copy_option_part(&p, dir, MAXPATHL, ",");
}
swapname = makeswapname(fname, ffname, curbuf, dir);
vim_free(dir);
r = vim_fexists(swapname);
if (r)
{
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if (p_confirm || cmdmod.confirm)
{
char_u buff[DIALOG_MSG_SIZE];
dialog_msg(buff,
_("Swap file \"%s\" exists, overwrite anyway?"),
swapname);
if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2)
!= VIM_YES)
{
vim_free(swapname);
return FAIL;
}
eap->forceit = TRUE;
}
else
#endif
{
EMSG2(_("E768: Swap file exists: %s (:silent! overrides)"),
swapname);
vim_free(swapname);
return FAIL;
}
}
vim_free(swapname);
}
}
return OK;
}
/*
* Handle ":wnext", ":wNext" and ":wprevious" commands.
*/
void
ex_wnext(eap)
exarg_T *eap;
{
int i;
if (eap->cmd[1] == 'n')
i = curwin->w_arg_idx + (int)eap->line2;
else
i = curwin->w_arg_idx - (int)eap->line2;
eap->line1 = 1;
eap->line2 = curbuf->b_ml.ml_line_count;
if (do_write(eap) != FAIL)
do_argfile(eap, i);
}
/*
* ":wall", ":wqall" and ":xall": Write all changed files (and exit).
*/
void
do_wqall(eap)
exarg_T *eap;
{
buf_T *buf;
int error = 0;
int save_forceit = eap->forceit;
if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall)
exiting = TRUE;
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
{
if (bufIsChanged(buf))
{
/*
* Check if there is a reason the buffer cannot be written:
* 1. if the 'write' option is set
* 2. if there is no file name (even after browsing)
* 3. if the 'readonly' is set (even after a dialog)
* 4. if overwriting is allowed (even after a dialog)
*/
if (not_writing())
{
++error;
break;
}
#ifdef FEAT_BROWSE
/* ":browse wall": ask for file name if there isn't one */
if (buf->b_ffname == NULL && cmdmod.browse)
browse_save_fname(buf);
#endif
if (buf->b_ffname == NULL)
{
EMSGN(_("E141: No file name for buffer %ld"), (long)buf->b_fnum);
++error;
}
else if (check_readonly(&eap->forceit, buf)
|| check_overwrite(eap, buf, buf->b_fname, buf->b_ffname,
FALSE) == FAIL)
{
++error;
}
else
{
if (buf_write_all(buf, eap->forceit) == FAIL)
++error;
#ifdef FEAT_AUTOCMD
/* an autocommand may have deleted the buffer */
if (!buf_valid(buf))
buf = firstbuf;
#endif
}
eap->forceit = save_forceit; /* check_overwrite() may set it */
}
}
if (exiting)
{
if (!error)
getout(0); /* exit Vim */
not_exiting();
}
}
/*
* Check the 'write' option.
* Return TRUE and give a message when it's not st.
*/
int
not_writing()
{
if (p_write)
return FALSE;
EMSG(_("E142: File not written: Writing is disabled by 'write' option"));
return TRUE;
}
/*
* Check if a buffer is read-only (either 'readonly' option is set or file is
* read-only). Ask for overruling in a dialog. Return TRUE and give an error
* message when the buffer is readonly.
*/
static int
check_readonly(forceit, buf)
int *forceit;
buf_T *buf;
{
struct stat st;
/* Handle a file being readonly when the 'readonly' option is set or when
* the file exists and permissions are read-only.
* We will send 0777 to check_file_readonly(), as the "perm" variable is
* important for device checks but not here. */
if (!*forceit && (buf->b_p_ro
|| (mch_stat((char *)buf->b_ffname, &st) >= 0
&& check_file_readonly(buf->b_ffname, 0777))))
{
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if ((p_confirm || cmdmod.confirm) && buf->b_fname != NULL)
{
char_u buff[DIALOG_MSG_SIZE];
if (buf->b_p_ro)
dialog_msg(buff, _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
buf->b_fname);
else
dialog_msg(buff, _("File permissions of \"%s\" are read-only.\nIt may still be possible to write it.\nDo you wish to try?"),
buf->b_fname);
if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES)
{
/* Set forceit, to force the writing of a readonly file */
*forceit = TRUE;
return FALSE;
}
else
return TRUE;
}
else
#endif
if (buf->b_p_ro)
EMSG(_(e_readonly));
else
EMSG2(_("E505: \"%s\" is read-only (add ! to override)"),
buf->b_fname);
return TRUE;
}
return FALSE;
}
/*
* Try to abandon current file and edit a new or existing file.
* 'fnum' is the number of the file, if zero use ffname/sfname.
*
* Return 1 for "normal" error, 2 for "not written" error, 0 for success
* -1 for successfully opening another file.
* 'lnum' is the line number for the cursor in the new file (if non-zero).
*/
int
getfile(fnum, ffname, sfname, setpm, lnum, forceit)
int fnum;
char_u *ffname;
char_u *sfname;
int setpm;
linenr_T lnum;
int forceit;
{
int other;
int retval;
char_u *free_me = NULL;
if (text_locked())
return 1;
#ifdef FEAT_AUTOCMD
if (curbuf_locked())
return 1;
#endif
if (fnum == 0)
{
/* make ffname full path, set sfname */
fname_expand(curbuf, &ffname, &sfname);
other = otherfile(ffname);
free_me = ffname; /* has been allocated, free() later */
}
else
other = (fnum != curbuf->b_fnum);
if (other)
++no_wait_return; /* don't wait for autowrite message */
if (other && !forceit && curbuf->b_nwindows == 1 && !P_HID(curbuf)
&& curbufIsChanged() && autowrite(curbuf, forceit) == FAIL)
{
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
if (p_confirm && p_write)
dialog_changed(curbuf, FALSE);
if (curbufIsChanged())
#endif
{
if (other)
--no_wait_return;
EMSG(_(e_nowrtmsg));
retval = 2; /* file has been changed */
goto theend;
}
}
if (other)
--no_wait_return;
if (setpm)
setpcmark();
if (!other)
{
if (lnum != 0)
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_SOL | BL_FIX);
retval = 0; /* it's in the same file */
}
else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
(P_HID(curbuf) ? ECMD_HIDE : 0) + (forceit ? ECMD_FORCEIT : 0),
curwin) == OK)
retval = -1; /* opened another file */
else
retval = 1; /* error encountered */
theend:
vim_free(free_me);
return retval;
}
/*
* start editing a new file
*
* fnum: file number; if zero use ffname/sfname
* ffname: the file name
* - full path if sfname used,
* - any file name if sfname is NULL
* - empty string to re-edit with the same file name (but may be
* in a different directory)
* - NULL to start an empty buffer
* sfname: the short file name (or NULL)
* eap: contains the command to be executed after loading the file and
* forced 'ff' and 'fenc'
* newlnum: if > 0: put cursor on this line number (if possible)
* if ECMD_LASTL: use last position in loaded file
* if ECMD_LAST: use last position in all files
* if ECMD_ONE: use first line
* flags:
* ECMD_HIDE: if TRUE don't free the current buffer
* ECMD_SET_HELP: set b_help flag of (new) buffer before opening file
* ECMD_OLDBUF: use existing buffer if it exists
* ECMD_FORCEIT: ! used for Ex command
* ECMD_ADDBUF: don't edit, just add to buffer list
* oldwin: Should be "curwin" when editing a new buffer in the current
* window, NULL when splitting the window first. When not NULL info
* of the previous buffer for "oldwin" is stored.
*
* return FAIL for failure, OK otherwise
*/
int
do_ecmd(fnum, ffname, sfname, eap, newlnum, flags, oldwin)
int fnum;
char_u *ffname;
char_u *sfname;
exarg_T *eap; /* can be NULL! */
linenr_T newlnum;
int flags;
win_T *oldwin;
{
int other_file; /* TRUE if editing another file */
int oldbuf; /* TRUE if using existing buffer */
#ifdef FEAT_AUTOCMD
int auto_buf = FALSE; /* TRUE if autocommands brought us
into the buffer unexpectedly */
char_u *new_name = NULL;
int did_set_swapcommand = FALSE;
#endif
buf_T *buf;
#if defined(FEAT_AUTOCMD) || defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
buf_T *old_curbuf = curbuf;
#endif
char_u *free_fname = NULL;
#ifdef FEAT_BROWSE
char_u *browse_file = NULL;
#endif
int retval = FAIL;
long n;
linenr_T lnum;
linenr_T topline = 0;
int newcol = -1;
int solcol = -1;
pos_T *pos;
#ifdef FEAT_SUN_WORKSHOP
char_u *cp;
#endif
char_u *command = NULL;
#ifdef FEAT_SPELL
int did_get_winopts = FALSE;
#endif
int readfile_flags = 0;
if (eap != NULL)
command = eap->do_ecmd_cmd;
if (fnum != 0)
{
if (fnum == curbuf->b_fnum) /* file is already being edited */
return OK; /* nothing to do */
other_file = TRUE;
}
else
{
#ifdef FEAT_BROWSE
if (cmdmod.browse)
{
# 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 (ffname == NULL || !mch_isdir(ffname))
ffname = (char_u *)".";
}
else
# endif
{
browse_file = do_browse(0, (char_u *)_("Edit File"), ffname,
NULL, NULL, NULL, curbuf);
if (browse_file == NULL)
goto theend;
ffname = browse_file;
}
}
#endif
/* if no short name given, use ffname for short name */
if (sfname == NULL)
sfname = ffname;
#ifdef USE_FNAME_CASE
# ifdef USE_LONG_FNAME
if (USE_LONG_FNAME)
# endif
if (sfname != NULL)
fname_case(sfname, 0); /* set correct case for sfname */
#endif
#ifdef FEAT_LISTCMDS
if ((flags & ECMD_ADDBUF) && (ffname == NULL || *ffname == NUL))
goto theend;
#endif
if (ffname == NULL)
other_file = TRUE;
/* there is no file name */
else if (*ffname == NUL && curbuf->b_ffname == NULL)
other_file = FALSE;
else
{
if (*ffname == NUL) /* re-edit with same file name */
{
ffname = curbuf->b_ffname;
sfname = curbuf->b_fname;
}
free_fname = fix_fname(ffname); /* may expand to full path name */
if (free_fname != NULL)
ffname = free_fname;
other_file = otherfile(ffname);
#ifdef FEAT_SUN_WORKSHOP
if (usingSunWorkShop && p_acd
&& (cp = vim_strrchr(sfname, '/')) != NULL)
sfname = ++cp;
#endif
}
}
/*
* if the file was changed we may not be allowed to abandon it
* - if we are going to re-edit the same file
* - or if we are the only window on this file and if ECMD_HIDE is FALSE
*/
if ( ((!other_file && !(flags & ECMD_OLDBUF))
|| (curbuf->b_nwindows == 1
&& !(flags & (ECMD_HIDE | ECMD_ADDBUF))))
&& check_changed(curbuf, p_awa, !other_file,
(flags & ECMD_FORCEIT), FALSE))
{
if (fnum == 0 && other_file && ffname != NULL)
(void)setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
goto theend;
}
#ifdef FEAT_VISUAL
/*
* End Visual mode before switching to another buffer, so the text can be
* copied into the GUI selection buffer.
*/
reset_VIsual();
#endif
#ifdef FEAT_AUTOCMD
if ((command != NULL || newlnum > (linenr_T)0)
&& *get_vim_var_str(VV_SWAPCOMMAND) == NUL)
{
int len;
char_u *p;
/* Set v:swapcommand for the SwapExists autocommands. */
if (command != NULL)
len = (int)STRLEN(command) + 3;
else
len = 30;
p = alloc((unsigned)len);
if (p != NULL)
{
if (command != NULL)
vim_snprintf((char *)p, len, ":%s\r", command);
else
vim_snprintf((char *)p, len, "%ldG", (long)newlnum);
set_vim_var_string(VV_SWAPCOMMAND, p, -1);
did_set_swapcommand = TRUE;
vim_free(p);
}
}
#endif
/*
* If we are starting to edit another file, open a (new) buffer.
* Otherwise we re-use the current buffer.
*/
if (other_file)
{
#ifdef FEAT_LISTCMDS
if (!(flags & ECMD_ADDBUF))
#endif
{
if (!cmdmod.keepalt)
curwin->w_alt_fnum = curbuf->b_fnum;
if (oldwin != NULL)
buflist_altfpos(oldwin);
}
if (fnum)
buf = buflist_findnr(fnum);
else
{
#ifdef FEAT_LISTCMDS
if (flags & ECMD_ADDBUF)
{
linenr_T tlnum = 1L;
if (command != NULL)
{
tlnum = atol((char *)command);
if (tlnum <= 0)
tlnum = 1L;
}
(void)buflist_new(ffname, sfname, tlnum, BLN_LISTED);
goto theend;
}
#endif
buf = buflist_new(ffname, sfname, 0L,
BLN_CURBUF | ((flags & ECMD_SET_HELP) ? 0 : BLN_LISTED));
}
if (buf == NULL)
goto theend;
if (buf->b_ml.ml_mfp == NULL) /* no memfile yet */
{
oldbuf = FALSE;
buf->b_nwindows = 0;
}
else /* existing memfile */
{
oldbuf = TRUE;
(void)buf_check_timestamp(buf, FALSE);
/* Check if autocommands made buffer invalid or changed the current
* buffer. */
if (!buf_valid(buf)
#ifdef FEAT_AUTOCMD
|| curbuf != old_curbuf
#endif
)
goto theend;
#ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
goto theend;
#endif
}
/* May jump to last used line number for a loaded buffer or when asked
* for explicitly */
if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST)
{
pos = buflist_findfpos(buf);
newlnum = pos->lnum;
solcol = pos->col;
}
/*
* Make the (new) buffer the one used by the current window.
* If the old buffer becomes unused, free it if ECMD_HIDE is FALSE.
* If the current buffer was empty and has no file name, curbuf
* is returned by buflist_new().
*/
if (buf != curbuf)
{
#ifdef FEAT_AUTOCMD
/*
* Be careful: The autocommands may delete any buffer and change
* the current buffer.
* - If the buffer we are going to edit is deleted, give up.
* - If the current buffer is deleted, prefer to load the new
* buffer when loading a buffer is required. This avoids
* loading another buffer which then must be closed again.
* - If we ended up in the new buffer already, need to skip a few
* things, set auto_buf.
*/
if (buf->b_fname != NULL)
new_name = vim_strsave(buf->b_fname);
au_new_curbuf = buf;
apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
if (!buf_valid(buf)) /* new buffer has been deleted */
{
delbuf_msg(new_name); /* frees new_name */
goto theend;
}
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
{
vim_free(new_name);
goto theend;
}
# endif
if (buf == curbuf) /* already in new buffer */
auto_buf = TRUE;
else
{
if (curbuf == old_curbuf)
#endif
buf_copy_options(buf, BCO_ENTER);
/* close the link to the current buffer */
u_sync(FALSE);
close_buffer(oldwin, curbuf,
(flags & ECMD_HIDE) ? 0 : DOBUF_UNLOAD, FALSE);
#ifdef FEAT_AUTOCMD
/* Autocommands may open a new window and leave oldwin open
* which leads to crashes since the above call sets
* oldwin->w_buffer to NULL. */
if (curwin != oldwin && oldwin != aucmd_win
&& win_valid(oldwin) && oldwin->w_buffer == NULL)
win_close(oldwin, FALSE);
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
{
vim_free(new_name);
goto theend;
}
# endif
/* Be careful again, like above. */
if (!buf_valid(buf)) /* new buffer has been deleted */
{
delbuf_msg(new_name); /* frees new_name */
goto theend;
}
if (buf == curbuf) /* already in new buffer */
auto_buf = TRUE;
else
#endif
{
#ifdef FEAT_SYN_HL
/*
* <VN> We could instead free the synblock
* and re-attach to buffer, perhaps.
*/
if (curwin->w_s == &(curwin->w_buffer->b_s))
curwin->w_s = &(buf->b_s);
#endif
curwin->w_buffer = buf;
curbuf = buf;
++curbuf->b_nwindows;
/* set 'fileformat' */
if (*p_ffs && !oldbuf)
set_fileformat(default_fileformat(), OPT_LOCAL);
}
/* May get the window options from the last time this buffer
* was in this window (or another window). If not used
* before, reset the local window options to the global
* values. Also restores old folding stuff. */
get_winopts(curbuf);
#ifdef FEAT_SPELL
did_get_winopts = TRUE;
#endif
#ifdef FEAT_AUTOCMD
}
vim_free(new_name);
au_new_curbuf = NULL;
#endif
}
else
++curbuf->b_nwindows;
curwin->w_pcmark.lnum = 1;
curwin->w_pcmark.col = 0;
}
else /* !other_file */
{
if (
#ifdef FEAT_LISTCMDS
(flags & ECMD_ADDBUF) ||
#endif
check_fname() == FAIL)
goto theend;
oldbuf = (flags & ECMD_OLDBUF);
}
if ((flags & ECMD_SET_HELP) || keep_help_flag)
{
char_u *p;
curbuf->b_help = TRUE;
#ifdef FEAT_QUICKFIX
set_string_option_direct((char_u *)"buftype", -1,
(char_u *)"help", OPT_FREE|OPT_LOCAL, 0);
#endif
/*
* Always set these options after jumping to a help tag, because the
* user may have an autocommand that gets in the way.
* Accept all ASCII chars for keywords, except ' ', '*', '"', '|', and
* latin1 word characters (for translated help files).
* Only set it when needed, buf_init_chartab() is some work.
*/
p =
#ifdef EBCDIC
(char_u *)"65-255,^*,^|,^\"";
#else
(char_u *)"!-~,^*,^|,^\",192-255";
#endif
if (STRCMP(curbuf->b_p_isk, p) != 0)
{
set_string_option_direct((char_u *)"isk", -1, p,
OPT_FREE|OPT_LOCAL, 0);
check_buf_options(curbuf);
(void)buf_init_chartab(curbuf, FALSE);
}
curbuf->b_p_ts = 8; /* 'tabstop' is 8 */
curwin->w_p_list = FALSE; /* no list mode */
curbuf->b_p_ma = FALSE; /* not modifiable */
curbuf->b_p_bin = FALSE; /* reset 'bin' before reading file */
curwin->w_p_nu = 0; /* no line numbers */
curwin->w_p_rnu = 0; /* no relative line numbers */
RESET_BINDING(curwin); /* no scroll or cursor binding */
#ifdef FEAT_ARABIC
curwin->w_p_arab = FALSE; /* no arabic mode */
#endif
#ifdef FEAT_RIGHTLEFT
curwin->w_p_rl = FALSE; /* help window is left-to-right */
#endif
#ifdef FEAT_FOLDING
curwin->w_p_fen = FALSE; /* No folding in the help window */
#endif
#ifdef FEAT_DIFF
curwin->w_p_diff = FALSE; /* No 'diff' */
#endif
#ifdef FEAT_SPELL
curwin->w_p_spell = FALSE; /* No spell checking */
#endif
#ifdef FEAT_AUTOCMD
buf = curbuf;
#endif
set_buflisted(FALSE);
}
else
{
#ifdef FEAT_AUTOCMD
buf = curbuf;
#endif
/* Don't make a buffer listed if it's a help buffer. Useful when
* using CTRL-O to go back to a help file. */
if (!curbuf->b_help)
set_buflisted(TRUE);
}
#ifdef FEAT_AUTOCMD
/* If autocommands change buffers under our fingers, forget about
* editing the file. */
if (buf != curbuf)
goto theend;
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
goto theend;
# endif
/* Since we are starting to edit a file, consider the filetype to be
* unset. Helps for when an autocommand changes files and expects syntax
* highlighting to work in the other file. */
did_filetype = FALSE;
#endif
/*
* other_file oldbuf
* FALSE FALSE re-edit same file, buffer is re-used
* FALSE TRUE re-edit same file, nothing changes
* TRUE FALSE start editing new file, new buffer
* TRUE TRUE start editing in existing buffer (nothing to do)
*/
if (!other_file && !oldbuf) /* re-use the buffer */
{
set_last_cursor(curwin); /* may set b_last_cursor */
if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL)
{
newlnum = curwin->w_cursor.lnum;
solcol = curwin->w_cursor.col;
}
#ifdef FEAT_AUTOCMD
buf = curbuf;
if (buf->b_fname != NULL)
new_name = vim_strsave(buf->b_fname);
else
new_name = NULL;
#endif
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);
if (u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE)
== FAIL)
goto theend;
u_unchanged(curbuf);
buf_freeall(curbuf, BFA_KEEP_UNDO);
/* tell readfile() not to clear or reload undo info */
readfile_flags = READ_KEEP_UNDO;
}
else
buf_freeall(curbuf, 0); /* free all things for buffer */
#ifdef FEAT_AUTOCMD
/* If autocommands deleted the buffer we were going to re-edit, give
* up and jump to the end. */
if (!buf_valid(buf))
{
delbuf_msg(new_name); /* frees new_name */
goto theend;
}
vim_free(new_name);
/* If autocommands change buffers under our fingers, forget about
* re-editing the file. Should do the buf_clear_file(), but perhaps
* the autocommands changed the buffer... */
if (buf != curbuf)
goto theend;
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
goto theend;
# endif
#endif
buf_clear_file(curbuf);
curbuf->b_op_start.lnum = 0; /* clear '[ and '] marks */
curbuf->b_op_end.lnum = 0;
}
/*
* If we get here we are sure to start editing
*/
/* don't redraw until the cursor is in the right line */
++RedrawingDisabled;
/* Assume success now */
retval = OK;
/*
* Reset cursor position, could be used by autocommands.
*/
check_cursor();
/*
* Check if we are editing the w_arg_idx file in the argument list.
*/
check_arg_idx(curwin);
#ifdef FEAT_AUTOCMD
if (!auto_buf)
#endif
{
/*
* Set cursor and init window before reading the file and executing
* autocommands. This allows for the autocommands to position the
* cursor.
*/
curwin_init();
#ifdef FEAT_FOLDING
/* It's possible that all lines in the buffer changed. Need to update
* automatic folding for all windows where it's used. */
# ifdef FEAT_WINDOWS
{
win_T *win;
tabpage_T *tp;
FOR_ALL_TAB_WINDOWS(tp, win)
if (win->w_buffer == curbuf)
foldUpdateAll(win);
}
# else
foldUpdateAll(curwin);
# endif
#endif
/* Change directories when the 'acd' option is set. */
DO_AUTOCHDIR
/*
* Careful: open_buffer() and apply_autocmds() may change the current
* buffer and window.
*/
lnum = curwin->w_cursor.lnum;
topline = curwin->w_topline;
if (!oldbuf) /* need to read the file */
{
#if defined(HAS_SWAP_EXISTS_ACTION)
swap_exists_action = SEA_DIALOG;
#endif
curbuf->b_flags |= BF_CHECK_RO; /* set/reset 'ro' flag */
/*
* Open the buffer and read the file.
*/
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (should_abort(open_buffer(FALSE, eap, readfile_flags)))
retval = FAIL;
#else
(void)open_buffer(FALSE, eap, readfile_flags);
#endif
#if defined(HAS_SWAP_EXISTS_ACTION)
if (swap_exists_action == SEA_QUIT)
retval = FAIL;
handle_swap_exists(old_curbuf);
#endif
}
#ifdef FEAT_AUTOCMD
else
{
/* Read the modelines, but only to set window-local options. Any
* buffer-local options have already been set and may have been
* changed by the user. */
do_modelines(OPT_WINONLY);
apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf,
&retval);
apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
&retval);
}
check_arg_idx(curwin);
#endif
/*
* If autocommands change the cursor position or topline, we should
* keep it.
*/
if (curwin->w_cursor.lnum != lnum)
{
newlnum = curwin->w_cursor.lnum;
newcol = curwin->w_cursor.col;
}
if (curwin->w_topline == topline)
topline = 0;
/* Even when cursor didn't move we need to recompute topline. */
changed_line_abv_curs();
#ifdef FEAT_TITLE
maketitle();
#endif
}
#ifdef FEAT_DIFF
/* Tell the diff stuff that this buffer is new and/or needs updating.
* Also needed when re-editing the same buffer, because unloading will
* have removed it as a diff buffer. */
if (curwin->w_p_diff)
{
diff_buf_add(curbuf);
diff_invalidate(curbuf);
}
#endif
#ifdef FEAT_SPELL
/* If the window options were changed may need to set the spell language.
* Can only do this after the buffer has been properly setup. */
if (did_get_winopts && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
(void)did_set_spelllang(curwin);
#endif
if (command == NULL)
{
if (newcol >= 0) /* position set by autocommands */
{
curwin->w_cursor.lnum = newlnum;
curwin->w_cursor.col = newcol;
check_cursor();
}
else if (newlnum > 0) /* line number from caller or old position */
{
curwin->w_cursor.lnum = newlnum;
check_cursor_lnum();
if (solcol >= 0 && !p_sol)
{
/* 'sol' is off: Use last known column. */
curwin->w_cursor.col = solcol;
check_cursor_col();
#ifdef FEAT_VIRTUALEDIT
curwin->w_cursor.coladd = 0;
#endif
curwin->w_set_curswant = TRUE;
}
else
beginline(BL_SOL | BL_FIX);
}
else /* no line number, go to last line in Ex mode */
{
if (exmode_active)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
beginline(BL_WHITE | BL_FIX);
}
}
#ifdef FEAT_WINDOWS
/* Check if cursors in other windows on the same buffer are still valid */
check_lnums(FALSE);
#endif
/*
* Did not read the file, need to show some info about the file.
* Do this after setting the cursor.
*/
if (oldbuf
#ifdef FEAT_AUTOCMD
&& !auto_buf
#endif
)
{
int msg_scroll_save = msg_scroll;
/* Obey the 'O' flag in 'cpoptions': overwrite any previous file
* message. */
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;
fileinfo(FALSE, TRUE, FALSE);
msg_scrolled_ign = FALSE;
}
if (command != NULL)
do_cmdline(command, NULL, NULL, DOCMD_VERBOSE);
#ifdef FEAT_KEYMAP
if (curbuf->b_kmap_state & KEYMAP_INIT)
(void)keymap_init();
#endif
--RedrawingDisabled;
if (!skip_redraw)
{
n = p_so;
if (topline == 0 && command == NULL)
p_so = 999; /* force cursor halfway the window */
update_topline();
#ifdef FEAT_SCROLLBIND
curwin->w_scbind_pos = curwin->w_topline;
#endif
p_so = n;
redraw_curbuf_later(NOT_VALID); /* redraw this buffer later */
}
if (p_im)
need_start_insertmode = TRUE;
/* Change directories when the 'acd' option is set. */
DO_AUTOCHDIR
#if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)
if (curbuf->b_ffname != NULL)
{
# ifdef FEAT_SUN_WORKSHOP
if (gui.in_use && usingSunWorkShop)
workshop_file_opened((char *)curbuf->b_ffname, curbuf->b_p_ro);
# endif
# ifdef FEAT_NETBEANS_INTG
if ((flags & ECMD_SET_HELP) != ECMD_SET_HELP)
netbeans_file_opened(curbuf);
# endif
}
#endif
theend:
#ifdef FEAT_AUTOCMD
if (did_set_swapcommand)
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
#endif
#ifdef FEAT_BROWSE
vim_free(browse_file);
#endif
vim_free(free_fname);
return retval;
}
#ifdef FEAT_AUTOCMD
static void
delbuf_msg(name)
char_u *name;
{
EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"),
name == NULL ? (char_u *)"" : name);
vim_free(name);
au_new_curbuf = NULL;
}
#endif
static int append_indent = 0; /* autoindent for first line */
/*
* ":insert" and ":append", also used by ":change"
*/
void
ex_append(eap)
exarg_T *eap;
{
char_u *theline;
int did_undo = FALSE;
linenr_T lnum = eap->line2;
int indent = 0;
char_u *p;
int vcol;
int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
/* the ! flag toggles autoindent */
if (eap->forceit)
curbuf->b_p_ai = !curbuf->b_p_ai;
/* First autoindent comes from the line we start on */
if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0)
append_indent = get_indent_lnum(lnum);
if (eap->cmdidx != CMD_append)
--lnum;
/* when the buffer is empty append to line 0 and delete the dummy line */
if (empty && lnum == 1)
lnum = 0;
State = INSERT; /* behave like in Insert mode */
if (curbuf->b_p_iminsert == B_IMODE_LMAP)
State |= LANGMAP;
for (;;)
{
msg_scroll = TRUE;
need_wait_return = FALSE;
if (curbuf->b_p_ai)
{
if (append_indent >= 0)
{
indent = append_indent;
append_indent = -1;
}
else if (lnum > 0)
indent = get_indent_lnum(lnum);
}
ex_keep_indent = FALSE;
if (eap->getline == NULL)
{
/* No getline() function, use the lines that follow. This ends
* when there is no more. */
if (eap->nextcmd == NULL || *eap->nextcmd == NUL)
break;
p = vim_strchr(eap->nextcmd, NL);
if (p == NULL)
p = eap->nextcmd + STRLEN(eap->nextcmd);
theline = vim_strnsave(eap->nextcmd, (int)(p - eap->nextcmd));
if (*p != NUL)
++p;
eap->nextcmd = p;
}
else
theline = eap->getline(
#ifdef FEAT_EVAL
eap->cstack->cs_looplevel > 0 ? -1 :
#endif
NUL, eap->cookie, indent);
lines_left = Rows - 1;
if (theline == NULL)
break;
/* Using ^ CTRL-D in getexmodeline() makes us repeat the indent. */
if (ex_keep_indent)
append_indent = indent;
/* Look for the "." after automatic indent. */
vcol = 0;
for (p = theline; indent > vcol; ++p)
{
if (*p == ' ')
++vcol;
else if (*p == TAB)
vcol += 8 - vcol % 8;
else
break;
}
if ((p[0] == '.' && p[1] == NUL)
|| (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
== FAIL))
{
vim_free(theline);
break;
}
/* don't use autoindent if nothing was typed. */
if (p[0] == NUL)
theline[0] = NUL;
did_undo = TRUE;
ml_append(lnum, theline, (colnr_T)0, FALSE);
appended_lines_mark(lnum, 1L);
vim_free(theline);
++lnum;
if (empty)
{
ml_delete(2L, FALSE);
empty = FALSE;
}
}
State = NORMAL;
if (eap->forceit)
curbuf->b_p_ai = !curbuf->b_p_ai;
/* "start" is set to eap->line2+1 unless that position is invalid (when
* eap->line2 pointed to the end of the buffer and nothing was appended)
* "end" is set to lnum when something has been appended, otherwise
* it is the same than "start" -- Acevedo */
curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
eap->line2 + 1 : curbuf->b_ml.ml_line_count;
if (eap->cmdidx != CMD_append)
--curbuf->b_op_start.lnum;
curbuf->b_op_end.lnum = (eap->line2 < lnum)
? lnum : curbuf->b_op_start.lnum;
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_SOL | BL_FIX);
need_wait_return = FALSE; /* don't use wait_return() now */
ex_no_reprint = TRUE;
}
/*
* ":change"
*/
void
ex_change(eap)
exarg_T *eap;
{
linenr_T lnum;
if (eap->line2 >= eap->line1
&& u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
return;
/* the ! flag toggles autoindent */
if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
append_indent = get_indent_lnum(eap->line1);
for (lnum = eap->line2; lnum >= eap->line1; --lnum)
{
if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
break;
ml_delete(eap->line1, FALSE);
}
/* make sure the cursor is not beyond the end of the file now */
check_cursor_lnum();
deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
/* ":append" on the line above the deleted lines. */
eap->line2 = eap->line1;
ex_append(eap);
}
void
ex_z(eap)
exarg_T *eap;
{
char_u *x;
int bigness;
char_u *kind;
int minus = 0;
linenr_T start, end, curs, i;
int j;
linenr_T lnum = eap->line2;
/* Vi compatible: ":z!" uses display height, without a count uses
* 'scroll' */
if (eap->forceit)
bigness = curwin->w_height;
else if (firstwin == lastwin)
bigness = curwin->w_p_scr * 2;
#ifdef FEAT_WINDOWS
else
bigness = curwin->w_height - 3;
#endif
if (bigness < 1)
bigness = 1;
x = eap->arg;
kind = x;
if (*kind == '-' || *kind == '+' || *kind == '='
|| *kind == '^' || *kind == '.')
++x;
while (*x == '-' || *x == '+')
++x;
if (*x != 0)
{
if (!VIM_ISDIGIT(*x))
{
EMSG(_("E144: non-numeric argument to :z"));
return;
}
else
{
bigness = atoi((char *)x);
p_window = bigness;
if (*kind == '=')
bigness += 2;
}
}
/* the number of '-' and '+' multiplies the distance */
if (*kind == '-' || *kind == '+')
for (x = kind + 1; *x == *kind; ++x)
;
switch (*kind)
{
case '-':
start = lnum - bigness * (linenr_T)(x - kind) + 1;
end = start + bigness - 1;
curs = end;
break;
case '=':
start = lnum - (bigness + 1) / 2 + 1;
end = lnum + (bigness + 1) / 2 - 1;
curs = lnum;
minus = 1;
break;
case '^':
start = lnum - bigness * 2;
end = lnum - bigness;
curs = lnum - bigness;
break;
case '.':
start = lnum - (bigness + 1) / 2 + 1;
end = lnum + (bigness + 1) / 2 - 1;
curs = end;
break;
default: /* '+' */
start = lnum;
if (*kind == '+')
start += bigness * (linenr_T)(x - kind - 1) + 1;
else if (eap->addr_count == 0)
++start;
end = start + bigness - 1;
curs = end;
break;
}
if (start < 1)
start = 1;
if (end > curbuf->b_ml.ml_line_count)
end = curbuf->b_ml.ml_line_count;
if (curs > curbuf->b_ml.ml_line_count)
curs = curbuf->b_ml.ml_line_count;
for (i = start; i <= end; i++)
{
if (minus && i == lnum)
{
msg_putchar('\n');
for (j = 1; j < Columns; j++)
msg_putchar('-');
}
print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
if (minus && i == lnum)
{
msg_putchar('\n');
for (j = 1; j < Columns; j++)
msg_putchar('-');
}
}
curwin->w_cursor.lnum = curs;
ex_no_reprint = TRUE;
}
/*
* Check if the restricted flag is set.
* If so, give an error message and return TRUE.
* Otherwise, return FALSE.
*/
int
check_restricted()
{
if (restricted)
{
EMSG(_("E145: Shell commands not allowed in rvim"));
return TRUE;
}
return FALSE;
}
/*
* Check if the secure flag is set (.exrc or .vimrc in current directory).
* If so, give an error message and return TRUE.
* Otherwise, return FALSE.
*/
int
check_secure()
{
if (secure)
{
secure = 2;
EMSG(_(e_curdir));
return TRUE;
}
#ifdef HAVE_SANDBOX
/*
* In the sandbox more things are not allowed, including the things
* disallowed in secure mode.
*/
if (sandbox != 0)
{
EMSG(_(e_sandbox));
return TRUE;
}
#endif
return FALSE;
}
static char_u *old_sub = NULL; /* previous substitute pattern */
static int global_need_beginline; /* call beginline() after ":g" */
/* do_sub()
*
* Perform a substitution from line eap->line1 to line eap->line2 using the
* command pointed to by eap->arg which should be of the form:
*
* /pattern/substitution/{flags}
*
* The usual escapes are supported as described in the regexp docs.
*/
void
do_sub(eap)
exarg_T *eap;
{
linenr_T lnum;
long i = 0;
regmmatch_T regmatch;
static int do_all = FALSE; /* do multiple substitutions per line */
static int do_ask = FALSE; /* ask for confirmation */
static int do_count = FALSE; /* count only */
static int do_error = TRUE; /* if false, ignore errors */
static int do_print = FALSE; /* print last line with subs. */
static int do_list = FALSE; /* list last line with subs. */
static int do_number = FALSE; /* list last line with line nr*/
static int do_ic = 0; /* ignore case flag */
char_u *pat = NULL, *sub = NULL; /* init for GCC */
int delimiter;
int sublen;
int got_quit = FALSE;
int got_match = FALSE;
int temp;
int which_pat;
char_u *cmd;
int save_State;
linenr_T first_line = 0; /* first changed line */
linenr_T last_line= 0; /* below last changed line AFTER the
* change */
linenr_T old_line_count = curbuf->b_ml.ml_line_count;
linenr_T line2;
long nmatch; /* number of lines in match */
char_u *sub_firstline; /* allocated copy of first sub line */
int endcolumn = FALSE; /* cursor in last column when done */
pos_T old_cursor = curwin->w_cursor;
int start_nsubs;
cmd = eap->arg;
if (!global_busy)
{
sub_nsubs = 0;
sub_nlines = 0;
}
start_nsubs = sub_nsubs;
if (eap->cmdidx == CMD_tilde)
which_pat = RE_LAST; /* use last used regexp */
else
which_pat = RE_SUBST; /* use last substitute regexp */
/* new pattern and substitution */
if (eap->cmd[0] == 's' && *cmd != NUL && !vim_iswhite(*cmd)
&& vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
{
/* don't accept alphanumeric for separator */
if (isalpha(*cmd))
{
EMSG(_("E146: Regular expressions can't be delimited by letters"));
return;
}
/*
* undocumented vi feature:
* "\/sub/" and "\?sub?" use last used search pattern (almost like
* //sub/r). "\&sub&" use last substitute pattern (like //sub/).
*/
if (*cmd == '\\')
{
++cmd;
if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
{
EMSG(_(e_backslash));
return;
}
if (*cmd != '&')
which_pat = RE_SEARCH; /* use last '/' pattern */
pat = (char_u *)""; /* empty search pattern */
delimiter = *cmd++; /* remember delimiter character */
}
else /* find the end of the regexp */
{
#ifdef FEAT_FKMAP /* reverse the flow of the Farsi characters */
if (p_altkeymap && curwin->w_p_rl)
lrF_sub(cmd);
#endif
which_pat = RE_LAST; /* use last used regexp */
delimiter = *cmd++; /* remember delimiter character */
pat = cmd; /* remember start of search pat */
cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg);
if (cmd[0] == delimiter) /* end delimiter found */
*cmd++ = NUL; /* replace it with a NUL */
}
/*
* Small incompatibility: vi sees '\n' as end of the command, but in
* Vim we want to use '\n' to find/substitute a NUL.
*/
sub = cmd; /* remember the start of the substitution */
while (cmd[0])
{
if (cmd[0] == delimiter) /* end delimiter found */
{
*cmd++ = NUL; /* replace it with a NUL */
break;
}
if (cmd[0] == '\\' && cmd[1] != 0) /* skip escaped characters */
++cmd;
mb_ptr_adv(cmd);
}
if (!eap->skip)
{
/* In POSIX vi ":s/pat/%/" uses the previous subst. string. */
if (STRCMP(sub, "%") == 0
&& vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
{
if (old_sub == NULL) /* there is no previous command */
{
EMSG(_(e_nopresub));
return;
}
sub = old_sub;
}
else
{
vim_free(old_sub);
old_sub = vim_strsave(sub);
}
}
}
else if (!eap->skip) /* use previous pattern and substitution */
{
if (old_sub == NULL) /* there is no previous command */
{
EMSG(_(e_nopresub));
return;
}
pat = NULL; /* search_regcomp() will use previous pattern */
sub = old_sub;
/* Vi compatibility quirk: repeating with ":s" keeps the cursor in the
* last column after using "$". */
endcolumn = (curwin->w_curswant == MAXCOL);
}
/*
* Find trailing options. When '&' is used, keep old options.
*/
if (*cmd == '&')
++cmd;
else
{
if (!p_ed)
{
if (p_gd) /* default is global on */
do_all = TRUE;
else
do_all = FALSE;
do_ask = FALSE;
}
do_error = TRUE;
do_print = FALSE;
do_count = FALSE;
do_number = FALSE;
do_ic = 0;
}
while (*cmd)
{
/*
* Note that 'g' and 'c' are always inverted, also when p_ed is off.
* 'r' is never inverted.
*/
if (*cmd == 'g')
do_all = !do_all;
else if (*cmd == 'c')
do_ask = !do_ask;
else if (*cmd == 'n')
do_count = TRUE;
else if (*cmd == 'e')
do_error = !do_error;
else if (*cmd == 'r') /* use last used regexp */
which_pat = RE_LAST;
else if (*cmd == 'p')
do_print = TRUE;
else if (*cmd == '#')
{
do_print = TRUE;
do_number = TRUE;
}
else if (*cmd == 'l')
{
do_print = TRUE;
do_list = TRUE;
}
else if (*cmd == 'i') /* ignore case */
do_ic = 'i';
else if (*cmd == 'I') /* don't ignore case */
do_ic = 'I';
else
break;
++cmd;
}
if (do_count)
do_ask = FALSE;
/*
* check for a trailing count
*/
cmd = skipwhite(cmd);
if (VIM_ISDIGIT(*cmd))
{
i = getdigits(&cmd);
if (i <= 0 && !eap->skip && do_error)
{
EMSG(_(e_zerocount));
return;
}
eap->line1 = eap->line2;
eap->line2 += i - 1;
if (eap->line2 > curbuf->b_ml.ml_line_count)
eap->line2 = curbuf->b_ml.ml_line_count;
}
/*
* check for trailing command or garbage
*/
cmd = skipwhite(cmd);
if (*cmd && *cmd != '"') /* if not end-of-line or comment */
{
eap->nextcmd = check_nextcmd(cmd);
if (eap->nextcmd == NULL)
{
EMSG(_(e_trailing));
return;
}
}
if (eap->skip) /* not executing commands, only parsing */
return;
if (!do_count && !curbuf->b_p_ma)
{
/* Substitution is not allowed in non-'modifiable' buffer */
EMSG(_(e_modifiable));
return;
}
if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)
{
if (do_error)
EMSG(_(e_invcmd));
return;
}
/* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
if (do_ic == 'i')
regmatch.rmm_ic = TRUE;
else if (do_ic == 'I')
regmatch.rmm_ic = FALSE;
sub_firstline = NULL;
/*
* ~ in the substitute pattern is replaced with the old pattern.
* We do it here once to avoid it to be replaced over and over again.
* But don't do it when it starts with "\=", then it's an expression.
*/
if (!(sub[0] == '\\' && sub[1] == '='))
sub = regtilde(sub, p_magic);
/*
* Check for a match on each line.
*/
line2 = eap->line2;
for (lnum = eap->line1; lnum <= line2 && !(got_quit
#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
|| aborting()
#endif
); ++lnum)
{
nmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,
(colnr_T)0, NULL);
if (nmatch)
{
colnr_T copycol;
colnr_T matchcol;
colnr_T prev_matchcol = MAXCOL;
char_u *new_end, *new_start = NULL;
unsigned new_start_len = 0;
char_u *p1;
int did_sub = FALSE;
int lastone;
int len, copy_len, needed_len;
long nmatch_tl = 0; /* nr of lines matched below lnum */
int do_again; /* do it again after joining lines */
int skip_match = FALSE;
linenr_T sub_firstlnum; /* nr of first sub line */
/*
* The new text is build up step by step, to avoid too much
* copying. There are these pieces:
* sub_firstline The old text, unmodified.
* copycol Column in the old text where we started
* looking for a match; from here old text still
* needs to be copied to the new text.
* matchcol Column number of the old text where to look
* for the next match. It's just after the
* previous match or one further.
* prev_matchcol Column just after the previous match (if any).
* Mostly equal to matchcol, except for the first
* match and after skipping an empty match.
* regmatch.*pos Where the pattern matched in the old text.
* new_start The new text, all that has been produced so
* far.
* new_end The new text, where to append new text.
*
* lnum The line number where we found the start of
* the match. Can be below the line we searched
* when there is a \n before a \zs in the
* pattern.
* sub_firstlnum The line number in the buffer where to look
* for a match. Can be different from "lnum"
* when the pattern or substitute string contains
* line breaks.
*
* Special situations:
* - When the substitute string contains a line break, the part up
* to the line break is inserted in the text, but the copy of
* the original line is kept. "sub_firstlnum" is adjusted for
* the inserted lines.
* - When the matched pattern contains a line break, the old line
* is taken from the line at the end of the pattern. The lines
* in the match are deleted later, "sub_firstlnum" is adjusted
* accordingly.
*
* The new text is built up in new_start[]. It has some extra
* room to avoid using alloc()/free() too often. new_start_len is
* the length of the allocated memory at new_start.
*
* Make a copy of the old line, so it won't be taken away when
* updating the screen or handling a multi-line match. The "old_"
* pointers point into this copy.
*/
sub_firstlnum = lnum;
copycol = 0;
matchcol = 0;
/* At first match, remember current cursor position. */
if (!got_match)
{
setpcmark();
got_match = TRUE;
}
/*
* Loop until nothing more to replace in this line.
* 1. Handle match with empty string.
* 2. If do_ask is set, ask for confirmation.
* 3. substitute the string.
* 4. if do_all is set, find next match
* 5. break if there isn't another match in this line
*/
for (;;)
{
/* Advance "lnum" to the line where the match starts. The
* match does not start in the first line when there is a line
* break before \zs. */
if (regmatch.startpos[0].lnum > 0)
{
lnum += regmatch.startpos[0].lnum;
sub_firstlnum += regmatch.startpos[0].lnum;
nmatch -= regmatch.startpos[0].lnum;
vim_free(sub_firstline);
sub_firstline = NULL;
}
if (sub_firstline == NULL)
{
sub_firstline = vim_strsave(ml_get(sub_firstlnum));
if (sub_firstline == NULL)
{
vim_free(new_start);
goto outofmem;
}
}
/* Save the line number of the last change for the final
* cursor position (just like Vi). */
curwin->w_cursor.lnum = lnum;
do_again = FALSE;
/*
* 1. Match empty string does not count, except for first
* match. This reproduces the strange vi behaviour.
* This also catches endless loops.
*/
if (matchcol == prev_matchcol
&& regmatch.endpos[0].lnum == 0
&& matchcol == regmatch.endpos[0].col)
{
if (sub_firstline[matchcol] == NUL)
/* We already were at the end of the line. Don't look
* for a match in this line again. */
skip_match = TRUE;
else
{
/* search for a match at next column */
#ifdef FEAT_MBYTE
if (has_mbyte)
matchcol += mb_ptr2len(sub_firstline + matchcol);
else
#endif
++matchcol;
}
goto skip;
}
/* Normally we continue searching for a match just after the
* previous match. */
matchcol = regmatch.endpos[0].col;
prev_matchcol = matchcol;
/*
* 2. If do_count is set only increase the counter.
* If do_ask is set, ask for confirmation.
*/
if (do_count)
{
/* For a multi-line match, put matchcol at the NUL at
* the end of the line and set nmatch to one, so that
* we continue looking for a match on the next line.
* Avoids that ":s/\nB\@=//gc" get stuck. */
if (nmatch > 1)
{
matchcol = (colnr_T)STRLEN(sub_firstline);
nmatch = 1;
skip_match = TRUE;
}
sub_nsubs++;
did_sub = TRUE;
goto skip;
}
if (do_ask)
{
int typed = 0;
/* change State to CONFIRM, so that the mouse works
* properly */
save_State = State;
State = CONFIRM;
#ifdef FEAT_MOUSE
setmouse(); /* disable mouse in xterm */
#endif
curwin->w_cursor.col = regmatch.startpos[0].col;
/* When 'cpoptions' contains "u" don't sync undo when
* asking for confirmation. */
if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
++no_u_sync;
/*
* Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
*/
while (do_ask)
{
if (exmode_active)
{
char_u *resp;
colnr_T sc, ec;
print_line_no_prefix(lnum, FALSE, FALSE);
getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
curwin->w_cursor.col = regmatch.endpos[0].col - 1;
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
msg_start();
for (i = 0; i < (long)sc; ++i)
msg_putchar(' ');
for ( ; i <= (long)ec; ++i)
msg_putchar('^');
resp = getexmodeline('?', NULL, 0);
if (resp != NULL)
{
typed = *resp;
vim_free(resp);
}
}
else
{
#ifdef FEAT_FOLDING
int save_p_fen = curwin->w_p_fen;
curwin->w_p_fen = FALSE;
#endif
/* Invert the matched string.
* Remove the inversion afterwards. */
temp = RedrawingDisabled;
RedrawingDisabled = 0;
search_match_lines = regmatch.endpos[0].lnum
- regmatch.startpos[0].lnum;
search_match_endcol = regmatch.endpos[0].col;
highlight_match = TRUE;
update_topline();
validate_cursor();
update_screen(SOME_VALID);
highlight_match = FALSE;
redraw_later(SOME_VALID);
#ifdef FEAT_FOLDING
curwin->w_p_fen = save_p_fen;
#endif
if (msg_row == Rows - 1)
msg_didout = FALSE; /* avoid a scroll-up */
msg_starthere();
i = msg_scroll;
msg_scroll = 0; /* truncate msg when
needed */
msg_no_more = TRUE;
/* write message same highlighting as for
* wait_return */
smsg_attr(hl_attr(HLF_R),
(char_u *)_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
msg_no_more = FALSE;
msg_scroll = i;
showruler(TRUE);
windgoto(msg_row, msg_col);
RedrawingDisabled = temp;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; /* allow scrolling here */
#endif
++no_mapping; /* don't map this key */
++allow_keys; /* allow special keys */
typed = plain_vgetc();
--allow_keys;
--no_mapping;
/* clear the question */
msg_didout = FALSE; /* don't scroll up */
msg_col = 0;
gotocmdline(TRUE);
}
need_wait_return = FALSE; /* no hit-return prompt */
if (typed == 'q' || typed == ESC || typed == Ctrl_C
#ifdef UNIX
|| typed == intr_char
#endif
)
{
got_quit = TRUE;
break;
}
if (typed == 'n')
break;
if (typed == 'y')
break;
if (typed == 'l')
{
/* last: replace and then stop */
do_all = FALSE;
line2 = lnum;
break;
}
if (typed == 'a')
{
do_ask = FALSE;
break;
}
#ifdef FEAT_INS_EXPAND
if (typed == Ctrl_E)
scrollup_clamp();
else if (typed == Ctrl_Y)
scrolldown_clamp();
#endif
}
State = save_State;
#ifdef FEAT_MOUSE
setmouse();
#endif
if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
--no_u_sync;
if (typed == 'n')
{
/* For a multi-line match, put matchcol at the NUL at
* the end of the line and set nmatch to one, so that
* we continue looking for a match on the next line.
* Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc"
* get stuck when pressing 'n'. */
if (nmatch > 1)
{
matchcol = (colnr_T)STRLEN(sub_firstline);
skip_match = TRUE;
}
goto skip;
}
if (got_quit)
break;
}
/* Move the cursor to the start of the match, so that we can
* use "\=col("."). */
curwin->w_cursor.col = regmatch.startpos[0].col;
/*
* 3. substitute the string.
*/
/* get length of substitution part */
sublen = vim_regsub_multi(®match,
sub_firstlnum - regmatch.startpos[0].lnum,
sub, sub_firstline, FALSE, p_magic, TRUE);
/* When the match included the "$" of the last line it may
* go beyond the last line of the buffer. */
if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
{
nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
skip_match = TRUE;
}
/* Need room for:
* - result so far in new_start (not for first sub in line)
* - original text up to match
* - length of substituted part
* - original text after match
*/
if (nmatch == 1)
p1 = sub_firstline;
else
{
p1 = ml_get(sub_firstlnum + nmatch - 1);
nmatch_tl += nmatch - 1;
}
copy_len = regmatch.startpos[0].col - copycol;
needed_len = copy_len + ((unsigned)STRLEN(p1)
- regmatch.endpos[0].col) + sublen + 1;
if (new_start == NULL)
{
/*
* Get some space for a temporary buffer to do the
* substitution into (and some extra space to avoid
* too many calls to alloc()/free()).
*/
new_start_len = needed_len + 50;
if ((new_start = alloc_check(new_start_len)) == NULL)
goto outofmem;
*new_start = NUL;
new_end = new_start;
}
else
{
/*
* Check if the temporary buffer is long enough to do the
* substitution into. If not, make it larger (with a bit
* extra to avoid too many calls to alloc()/free()).
*/
len = (unsigned)STRLEN(new_start);
needed_len += len;
if (needed_len > (int)new_start_len)
{
new_start_len = needed_len + 50;
if ((p1 = alloc_check(new_start_len)) == NULL)
{
vim_free(new_start);
goto outofmem;
}
mch_memmove(p1, new_start, (size_t)(len + 1));
vim_free(new_start);
new_start = p1;
}
new_end = new_start + len;
}
/*
* copy the text up to the part that matched
*/
mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);
new_end += copy_len;
(void)vim_regsub_multi(®match,
sub_firstlnum - regmatch.startpos[0].lnum,
sub, new_end, TRUE, p_magic, TRUE);
sub_nsubs++;
did_sub = TRUE;
/* Move the cursor to the start of the line, to avoid that it
* is beyond the end of the line after the substitution. */
curwin->w_cursor.col = 0;
/* For a multi-line match, make a copy of the last matched
* line and continue in that one. */
if (nmatch > 1)
{
sub_firstlnum += nmatch - 1;
vim_free(sub_firstline);
sub_firstline = vim_strsave(ml_get(sub_firstlnum));
/* When going beyond the last line, stop substituting. */
if (sub_firstlnum <= line2)
do_again = TRUE;
else
do_all = FALSE;
}
/* Remember next character to be copied. */
copycol = regmatch.endpos[0].col;
if (skip_match)
{
/* Already hit end of the buffer, sub_firstlnum is one
* less than what it ought to be. */
vim_free(sub_firstline);
sub_firstline = vim_strsave((char_u *)"");
copycol = 0;
}
/*
* Now the trick is to replace CTRL-M chars with a real line
* break. This would make it impossible to insert a CTRL-M in
* the text. The line break can be avoided by preceding the
* CTRL-M with a backslash. To be able to insert a backslash,
* they must be doubled in the string and are halved here.
* That is Vi compatible.
*/
for (p1 = new_end; *p1; ++p1)
{
if (p1[0] == '\\' && p1[1] != NUL) /* remove backslash */
STRMOVE(p1, p1 + 1);
else if (*p1 == CAR)
{
if (u_inssub(lnum) == OK) /* prepare for undo */
{
*p1 = NUL; /* truncate up to the CR */
ml_append(lnum - 1, new_start,
(colnr_T)(p1 - new_start + 1), FALSE);
mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
if (do_ask)
appended_lines(lnum - 1, 1L);
else
{
if (first_line == 0)
first_line = lnum;
last_line = lnum + 1;
}
/* All line numbers increase. */
++sub_firstlnum;
++lnum;
++line2;
/* move the cursor to the new line, like Vi */
++curwin->w_cursor.lnum;
/* copy the rest */
STRMOVE(new_start, p1 + 1);
p1 = new_start - 1;
}
}
#ifdef FEAT_MBYTE
else if (has_mbyte)
p1 += (*mb_ptr2len)(p1) - 1;
#endif
}
/*
* 4. If do_all is set, find next match.
* Prevent endless loop with patterns that match empty
* strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
* But ":s/\n/#/" is OK.
*/
skip:
/* We already know that we did the last subst when we are at
* the end of the line, except that a pattern like
* "bar\|\nfoo" may match at the NUL. "lnum" can be below
* "line2" when there is a \zs in the pattern after a line
* break. */
lastone = (skip_match
|| got_int
|| got_quit
|| lnum > line2
|| !(do_all || do_again)
|| (sub_firstline[matchcol] == NUL && nmatch <= 1
&& !re_multiline(regmatch.regprog)));
nmatch = -1;
/*
* Replace the line in the buffer when needed. This is
* skipped when there are more matches.
* The check for nmatch_tl is needed for when multi-line
* matching must replace the lines before trying to do another
* match, otherwise "\@<=" won't work.
* When asking the user we like to show the already replaced
* text, but don't do it when "\<@=" or "\<@!" is used, it
* changes what matches.
* When the match starts below where we start searching also
* need to replace the line first (using \zs after \n).
*/
if (lastone
|| (do_ask && !re_lookbehind(regmatch.regprog))
|| nmatch_tl > 0
|| (nmatch = vim_regexec_multi(®match, curwin,
curbuf, sub_firstlnum,
matchcol, NULL)) == 0
|| regmatch.startpos[0].lnum > 0)
{
if (new_start != NULL)
{
/*
* Copy the rest of the line, that didn't match.
* "matchcol" has to be adjusted, we use the end of
* the line as reference, because the substitute may
* have changed the number of characters. Same for
* "prev_matchcol".
*/
STRCAT(new_start, sub_firstline + copycol);
matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
prev_matchcol = (colnr_T)STRLEN(sub_firstline)
- prev_matchcol;
if (u_savesub(lnum) != OK)
break;
ml_replace(lnum, new_start, TRUE);
if (nmatch_tl > 0)
{
/*
* Matched lines have now been substituted and are
* useless, delete them. The part after the match
* has been appended to new_start, we don't need
* it in the buffer.
*/
++lnum;
if (u_savedel(lnum, nmatch_tl) != OK)
break;
for (i = 0; i < nmatch_tl; ++i)
ml_delete(lnum, (int)FALSE);
mark_adjust(lnum, lnum + nmatch_tl - 1,
(long)MAXLNUM, -nmatch_tl);
if (do_ask)
deleted_lines(lnum, nmatch_tl);
--lnum;
line2 -= nmatch_tl; /* nr of lines decreases */
nmatch_tl = 0;
}
/* When asking, undo is saved each time, must also set
* changed flag each time. */
if (do_ask)
changed_bytes(lnum, 0);
else
{
if (first_line == 0)
first_line = lnum;
last_line = lnum + 1;
}
sub_firstlnum = lnum;
vim_free(sub_firstline); /* free the temp buffer */
sub_firstline = new_start;
new_start = NULL;
matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
prev_matchcol = (colnr_T)STRLEN(sub_firstline)
- prev_matchcol;
copycol = 0;
}
if (nmatch == -1 && !lastone)
nmatch = vim_regexec_multi(®match, curwin, curbuf,
sub_firstlnum, matchcol, NULL);
/*
* 5. break if there isn't another match in this line
*/
if (nmatch <= 0)
{
/* If the match found didn't start where we were
* searching, do the next search in the line where we
* found the match. */
if (nmatch == -1)
lnum -= regmatch.startpos[0].lnum;
break;
}
}
line_breakcheck();
}
if (did_sub)
++sub_nlines;
vim_free(new_start); /* for when substitute was cancelled */
vim_free(sub_firstline); /* free the copy of the original line */
sub_firstline = NULL;
}
line_breakcheck();
}
if (first_line != 0)
{
/* Need to subtract the number of added lines from "last_line" to get
* the line number before the change (same as adding the number of
* deleted lines). */
i = curbuf->b_ml.ml_line_count - old_line_count;
changed_lines(first_line, 0, last_line - i, i);
}
outofmem:
vim_free(sub_firstline); /* may have to free allocated copy of the line */
/* ":s/pat//n" doesn't move the cursor */
if (do_count)
curwin->w_cursor = old_cursor;
if (sub_nsubs > start_nsubs)
{
/* Set the '[ and '] marks. */
curbuf->b_op_start.lnum = eap->line1;
curbuf->b_op_end.lnum = line2;
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
if (!global_busy)
{
if (!do_ask) /* when interactive leave cursor on the match */
{
if (endcolumn)
coladvance((colnr_T)MAXCOL);
else
beginline(BL_WHITE | BL_FIX);
}
if (!do_sub_msg(do_count) && do_ask)
MSG("");
}
else
global_need_beginline = TRUE;
if (do_print)
print_line(curwin->w_cursor.lnum, do_number, do_list);
}
else if (!global_busy)
{
if (got_int) /* interrupted */
EMSG(_(e_interr));
else if (got_match) /* did find something but nothing substituted */
MSG("");
else if (do_error) /* nothing found */
EMSG2(_(e_patnotf2), get_search_pat());
}
vim_free(regmatch.regprog);
}
/*
* Give message for number of substitutions.
* Can also be used after a ":global" command.
* Return TRUE if a message was given.
*/
int
do_sub_msg(count_only)
int count_only; /* used 'n' flag for ":s" */
{
/*
* Only report substitutions when:
* - more than 'report' substitutions
* - command was typed by user, or number of changed lines > 'report'
* - giving messages is not disabled by 'lazyredraw'
*/
if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
|| count_only)
&& messaging())
{
if (got_int)
STRCPY(msg_buf, _("(Interrupted) "));
else
*msg_buf = NUL;
if (sub_nsubs == 1)
vim_snprintf_add((char *)msg_buf, sizeof(msg_buf),
"%s", count_only ? _("1 match") : _("1 substitution"));
else
vim_snprintf_add((char *)msg_buf, sizeof(msg_buf),
count_only ? _("%ld matches") : _("%ld substitutions"),
sub_nsubs);
if (sub_nlines == 1)
vim_snprintf_add((char *)msg_buf, sizeof(msg_buf),
"%s", _(" on 1 line"));
else
vim_snprintf_add((char *)msg_buf, sizeof(msg_buf),
_(" on %ld lines"), (long)sub_nlines);
if (msg(msg_buf))
/* save message to display it after redraw */
set_keep_msg(msg_buf, 0);
return TRUE;
}
if (got_int)
{
EMSG(_(e_interr));
return TRUE;
}
return FALSE;
}
/*
* Execute a global command of the form:
*
* g/pattern/X : execute X on all lines where pattern matches
* v/pattern/X : execute X on all lines where pattern does not match
*
* where 'X' is an EX command
*
* The command character (as well as the trailing slash) is optional, and
* is assumed to be 'p' if missing.
*
* This is implemented in two passes: first we scan the file for the pattern and
* set a mark for each line that (not) matches. secondly we execute the command
* for each line that has a mark. This is required because after deleting
* lines we do not know where to search for the next match.
*/
void
ex_global(eap)
exarg_T *eap;
{
linenr_T lnum; /* line number according to old situation */
int ndone = 0;
int type; /* first char of cmd: 'v' or 'g' */
char_u *cmd; /* command argument */
char_u delim; /* delimiter, normally '/' */
char_u *pat;
regmmatch_T regmatch;
int match;
int which_pat;
if (global_busy)
{
EMSG(_("E147: Cannot do :global recursive")); /* will increment global_busy */
return;
}
if (eap->forceit) /* ":global!" is like ":vglobal" */
type = 'v';
else
type = *eap->cmd;
cmd = eap->arg;
which_pat = RE_LAST; /* default: use last used regexp */
/*
* undocumented vi feature:
* "\/" and "\?": use previous search pattern.
* "\&": use previous substitute pattern.
*/
if (*cmd == '\\')
{
++cmd;
if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
{
EMSG(_(e_backslash));
return;
}
if (*cmd == '&')
which_pat = RE_SUBST; /* use previous substitute pattern */
else
which_pat = RE_SEARCH; /* use previous search pattern */
++cmd;
pat = (char_u *)"";
}
else if (*cmd == NUL)
{
EMSG(_("E148: Regular expression missing from global"));
return;
}
else
{
delim = *cmd; /* get the delimiter */
if (delim)
++cmd; /* skip delimiter if there is one */
pat = cmd; /* remember start of pattern */
cmd = skip_regexp(cmd, delim, p_magic, &eap->arg);
if (cmd[0] == delim) /* end delimiter found */
*cmd++ = NUL; /* replace it with a NUL */
}
#ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
if (p_altkeymap && curwin->w_p_rl)
lrFswap(pat,0);
#endif
if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, ®match) == FAIL)
{
EMSG(_(e_invcmd));
return;
}
/*
* pass 1: set marks for each (not) matching line
*/
for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
{
/* a match on this line? */
match = vim_regexec_multi(®match, curwin, curbuf, lnum,
(colnr_T)0, NULL);
if ((type == 'g' && match) || (type == 'v' && !match))
{
ml_setmarked(lnum);
ndone++;
}
line_breakcheck();
}
/*
* pass 2: execute the command for each line that has been marked
*/
if (got_int)
MSG(_(e_interr));
else if (ndone == 0)
{
if (type == 'v')
smsg((char_u *)_("Pattern found in every line: %s"), pat);
else
smsg((char_u *)_(e_patnotf2), pat);
}
else
global_exe(cmd);
ml_clearmarked(); /* clear rest of the marks */
vim_free(regmatch.regprog);
}
/*
* Execute "cmd" on lines marked with ml_setmarked().
*/
void
global_exe(cmd)
char_u *cmd;
{
linenr_T old_lcount; /* b_ml.ml_line_count before the command */
buf_T *old_buf = curbuf; /* remember what buffer we started in */
linenr_T lnum; /* line number according to old situation */
/*
* Set current position only once for a global command.
* If global_busy is set, setpcmark() will not do anything.
* If there is an error, global_busy will be incremented.
*/
setpcmark();
/* When the command writes a message, don't overwrite the command. */
msg_didout = TRUE;
sub_nsubs = 0;
sub_nlines = 0;
global_need_beginline = FALSE;
global_busy = 1;
old_lcount = curbuf->b_ml.ml_line_count;
while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
{
curwin->w_cursor.lnum = lnum;
curwin->w_cursor.col = 0;
if (*cmd == NUL || *cmd == '\n')
do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
else
do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
ui_breakcheck();
}
global_busy = 0;
if (global_need_beginline)
beginline(BL_WHITE | BL_FIX);
else
check_cursor(); /* cursor may be beyond the end of the line */
/* the cursor may not have moved in the text but a change in a previous
* line may move it on the screen */
changed_line_abv_curs();
/* If it looks like no message was written, allow overwriting the
* command with the report for number of changes. */
if (msg_col == 0 && msg_scrolled == 0)
msg_didout = FALSE;
/* If substitutes done, report number of substitutes, otherwise report
* number of extra or deleted lines.
* Don't report extra or deleted lines in the edge case where the buffer
* we are in after execution is different from the buffer we started in. */
if (!do_sub_msg(FALSE) && curbuf == old_buf)
msgmore(curbuf->b_ml.ml_line_count - old_lcount);
}
#ifdef FEAT_VIMINFO
int
read_viminfo_sub_string(virp, force)
vir_T *virp;
int force;
{
if (force)
vim_free(old_sub);
if (force || old_sub == NULL)
old_sub = viminfo_readstring(virp, 1, TRUE);
return viminfo_readline(virp);
}
void
write_viminfo_sub_string(fp)
FILE *fp;
{
if (get_viminfo_parameter('/') != 0 && old_sub != NULL)
{
fputs(_("\n# Last Substitute String:\n$"), fp);
viminfo_writestring(fp, old_sub);
}
}
#endif /* FEAT_VIMINFO */
#if defined(EXITFREE) || defined(PROTO)
void
free_old_sub()
{
vim_free(old_sub);
}
#endif
#if (defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)) || defined(PROTO)
/*
* Set up for a tagpreview.
* Return TRUE when it was created.
*/
int
prepare_tagpreview(undo_sync)
int undo_sync; /* sync undo when leaving the window */
{
win_T *wp;
# ifdef FEAT_GUI
need_mouse_correct = TRUE;
# endif
/*
* If there is already a preview window open, use that one.
*/
if (!curwin->w_p_pvw)
{
for (wp = firstwin; wp != NULL; wp = wp->w_next)
if (wp->w_p_pvw)
break;
if (wp != NULL)
win_enter(wp, undo_sync);
else
{
/*
* There is no preview window open yet. Create one.
*/
if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
== FAIL)
return FALSE;
curwin->w_p_pvw = TRUE;
curwin->w_p_wfh = TRUE;
RESET_BINDING(curwin); /* don't take over 'scrollbind'
and 'cursorbind' */
# ifdef FEAT_DIFF
curwin->w_p_diff = FALSE; /* no 'diff' */
# endif
# ifdef FEAT_FOLDING
curwin->w_p_fdc = 0; /* no 'foldcolumn' */
# endif
return TRUE;
}
}
return FALSE;
}
#endif
/*
* ":help": open a read-only window on a help file
*/
void
ex_help(eap)
exarg_T *eap;
{
char_u *arg;
char_u *tag;
FILE *helpfd; /* file descriptor of help file */
int n;
int i;
#ifdef FEAT_WINDOWS
win_T *wp;
#endif
int num_matches;
char_u **matches;
char_u *p;
int empty_fnum = 0;
int alt_fnum = 0;
buf_T *buf;
#ifdef FEAT_MULTI_LANG
int len;
char_u *lang;
#endif
#ifdef FEAT_FOLDING
int old_KeyTyped = KeyTyped;
#endif
if (eap != NULL)
{
/*
* A ":help" command ends at the first LF, or at a '|' that is
* followed by some text. Set nextcmd to the following command.
*/
for (arg = eap->arg; *arg; ++arg)
{
if (*arg == '\n' || *arg == '\r'
|| (*arg == '|' && arg[1] != NUL && arg[1] != '|'))
{
*arg++ = NUL;
eap->nextcmd = arg;
break;
}
}
arg = eap->arg;
if (eap->forceit && *arg == NUL && !curbuf->b_help)
{
EMSG(_("E478: Don't panic!"));
return;
}
if (eap->skip) /* not executing commands */
return;
}
else
arg = (char_u *)"";
/* remove trailing blanks */
p = arg + STRLEN(arg) - 1;
while (p > arg && vim_iswhite(*p) && p[-1] != '\\')
*p-- = NUL;
#ifdef FEAT_MULTI_LANG
/* Check for a specified language */
lang = check_help_lang(arg);
#endif
/* When no argument given go to the index. */
if (*arg == NUL)
arg = (char_u *)"help.txt";
/*
* Check if there is a match for the argument.
*/
n = find_help_tags(arg, &num_matches, &matches,
eap != NULL && eap->forceit);
i = 0;
#ifdef FEAT_MULTI_LANG
if (n != FAIL && lang != NULL)
/* Find first item with the requested language. */
for (i = 0; i < num_matches; ++i)
{
len = (int)STRLEN(matches[i]);
if (len > 3 && matches[i][len - 3] == '@'
&& STRICMP(matches[i] + len - 2, lang) == 0)
break;
}
#endif
if (i >= num_matches || n == FAIL)
{
#ifdef FEAT_MULTI_LANG
if (lang != NULL)
EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg);
else
#endif
EMSG2(_("E149: Sorry, no help for %s"), arg);
if (n != FAIL)
FreeWild(num_matches, matches);
return;
}
/* The first match (in the requested language) is the best match. */
tag = vim_strsave(matches[i]);
FreeWild(num_matches, matches);
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
/*
* Re-use an existing help window or open a new one.
* Always open a new one for ":tab help".
*/
if (!curwin->w_buffer->b_help
#ifdef FEAT_WINDOWS
|| cmdmod.tab != 0
#endif
)
{
#ifdef FEAT_WINDOWS
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
#endif
{
/*
* There is no help window yet.
* Try to open the file specified by the "helpfile" option.
*/
if ((helpfd = mch_fopen((char *)p_hf, READBIN)) == NULL)
{
smsg((char_u *)_("Sorry, help file \"%s\" not found"), p_hf);
goto erret;
}
fclose(helpfd);
#ifdef FEAT_WINDOWS
/* Split off help window; put it at far top if no position
* specified, the current window is vertically split and
* narrow. */
n = WSP_HELP;
# ifdef FEAT_VERTSPLIT
if (cmdmod.split == 0 && curwin->w_width != Columns
&& curwin->w_width < 80)
n |= WSP_TOP;
# endif
if (win_split(0, n) == FAIL)
goto erret;
#else
/* use current window */
if (!can_abandon(curbuf, FALSE))
goto erret;
#endif
#ifdef FEAT_WINDOWS
if (curwin->w_height < p_hh)
win_setheight((int)p_hh);
#endif
/*
* Open help file (do_ecmd() will set b_help flag, readfile() will
* set b_p_ro flag).
* Set the alternate file to the previously edited file.
*/
alt_fnum = curbuf->b_fnum;
(void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL,
ECMD_HIDE + ECMD_SET_HELP,
#ifdef FEAT_WINDOWS
NULL /* buffer is still open, don't store info */
#else
curwin
#endif
);
if (!cmdmod.keepalt)
curwin->w_alt_fnum = alt_fnum;
empty_fnum = curbuf->b_fnum;
}
}
if (!p_im)
restart_edit = 0; /* don't want insert mode in help file */
#ifdef FEAT_FOLDING
/* Restore KeyTyped, setting 'filetype=help' may reset it.
* It is needed for do_tag top open folds under the cursor. */
KeyTyped = old_KeyTyped;
#endif
if (tag != NULL)
do_tag(tag, DT_HELP, 1, FALSE, TRUE);
/* Delete the empty buffer if we're not using it. Careful: autocommands
* may have jumped to another window, check that the buffer is not in a
* window. */
if (empty_fnum != 0 && curbuf->b_fnum != empty_fnum)
{
buf = buflist_findnr(empty_fnum);
if (buf != NULL && buf->b_nwindows == 0)
wipe_buffer(buf, TRUE);
}
/* keep the previous alternate file */
if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt)
curwin->w_alt_fnum = alt_fnum;
erret:
vim_free(tag);
}
#if defined(FEAT_MULTI_LANG) || defined(PROTO)
/*
* In an argument search for a language specifiers in the form "@xx".
* Changes the "@" to NUL if found, and returns a pointer to "xx".
* Returns NULL if not found.
*/
char_u *
check_help_lang(arg)
char_u *arg;
{
int len = (int)STRLEN(arg);
if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2])
&& ASCII_ISALPHA(arg[len - 1]))
{
arg[len - 3] = NUL; /* remove the '@' */
return arg + len - 2;
}
return NULL;
}
#endif
/*
* Return a heuristic indicating how well the given string matches. The
* smaller the number, the better the match. This is the order of priorities,
* from best match to worst match:
* - Match with least alpha-numeric characters is better.
* - Match with least total characters is better.
* - Match towards the start is better.
* - Match starting with "+" is worse (feature instead of command)
* Assumption is made that the matched_string passed has already been found to
* match some string for which help is requested. webb.
*/
int
help_heuristic(matched_string, offset, wrong_case)
char_u *matched_string;
int offset; /* offset for match */
int wrong_case; /* no matching case */
{
int num_letters;
char_u *p;
num_letters = 0;
for (p = matched_string; *p; p++)
if (ASCII_ISALNUM(*p))
num_letters++;
/*
* Multiply the number of letters by 100 to give it a much bigger
* weighting than the number of characters.
* If there only is a match while ignoring case, add 5000.
* If the match starts in the middle of a word, add 10000 to put it
* somewhere in the last half.
* If the match is more than 2 chars from the start, multiply by 200 to
* put it after matches at the start.
*/
if (ASCII_ISALNUM(matched_string[offset]) && offset > 0
&& ASCII_ISALNUM(matched_string[offset - 1]))
offset += 10000;
else if (offset > 2)
offset *= 200;
if (wrong_case)
offset += 5000;
/* Features are less interesting than the subjects themselves, but "+"
* alone is not a feature. */
if (matched_string[0] == '+' && matched_string[1] != NUL)
offset += 100;
return (int)(100 * num_letters + STRLEN(matched_string) + offset);
}
/*
* Compare functions for qsort() below, that checks the help heuristics number
* that has been put after the tagname by find_tags().
*/
static int
#ifdef __BORLANDC__
_RTLENTRYF
#endif
help_compare(s1, s2)
const void *s1;
const void *s2;
{
char *p1;
char *p2;
p1 = *(char **)s1 + strlen(*(char **)s1) + 1;
p2 = *(char **)s2 + strlen(*(char **)s2) + 1;
return strcmp(p1, p2);
}
/*
* Find all help tags matching "arg", sort them and return in matches[], with
* the number of matches in num_matches.
* The matches will be sorted with a "best" match algorithm.
* When "keep_lang" is TRUE try keeping the language of the current buffer.
*/
int
find_help_tags(arg, num_matches, matches, keep_lang)
char_u *arg;
int *num_matches;
char_u ***matches;
int keep_lang;
{
char_u *s, *d;
int i;
static char *(mtable[]) = {"*", "g*", "[*", "]*", ":*",
"/*", "/\\*", "\"*", "**",
"/\\(\\)",
"?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
"/\\?", "/\\z(\\)", "\\=", ":s\\=",
"[count]", "[quotex]", "[range]",
"[pattern]", "\\|", "\\%$"};
static char *(rtable[]) = {"star", "gstar", "[star", "]star", ":star",
"/star", "/\\\\star", "quotestar", "starstar",
"/\\\\(\\\\)",
"?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
"/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
"\\[count]", "\\[quotex]", "\\[range]",
"\\[pattern]", "\\\\bar", "/\\\\%\\$"};
int flags;
d = IObuff; /* assume IObuff is long enough! */
/*
* Recognize a few exceptions to the rule. Some strings that contain '*'
* with "star". Otherwise '*' is recognized as a wildcard.
*/
for (i = (int)(sizeof(mtable) / sizeof(char *)); --i >= 0; )
if (STRCMP(arg, mtable[i]) == 0)
{
STRCPY(d, rtable[i]);
break;
}
if (i < 0) /* no match in table */
{
/* Replace "\S" with "/\\S", etc. Otherwise every tag is matched.
* Also replace "\%^" and "\%(", they match every tag too.
* Also "\zs", "\z1", etc.
* Also "\@<", "\@=", "\@<=", etc.
* And also "\_$" and "\_^". */
if (arg[0] == '\\'
&& ((arg[1] != NUL && arg[2] == NUL)
|| (vim_strchr((char_u *)"%_z@", arg[1]) != NULL
&& arg[2] != NUL)))
{
STRCPY(d, "/\\\\");
STRCPY(d + 3, arg + 1);
/* Check for "/\\_$", should be "/\\_\$" */
if (d[3] == '_' && d[4] == '$')
STRCPY(d + 4, "\\$");
}
else
{
/* replace "[:...:]" with "\[:...:]"; "[+...]" with "\[++...]" */
if (arg[0] == '[' && (arg[1] == ':'
|| (arg[1] == '+' && arg[2] == '+')))
*d++ = '\\';
for (s = arg; *s; ++s)
{
/*
* Replace "|" with "bar" and '"' with "quote" to match the name of
* the tags for these commands.
* Replace "*" with ".*" and "?" with "." to match command line
* completion.
* Insert a backslash before '~', '$' and '.' to avoid their
* special meaning.
*/
if (d - IObuff > IOSIZE - 10) /* getting too long!? */
break;
switch (*s)
{
case '|': STRCPY(d, "bar");
d += 3;
continue;
case '"': STRCPY(d, "quote");
d += 5;
continue;
case '*': *d++ = '.';
break;
case '?': *d++ = '.';
continue;
case '$':
case '.':
case '~': *d++ = '\\';
break;
}
/*
* Replace "^x" by "CTRL-X". Don't do this for "^_" to make
* ":help i_^_CTRL-D" work.
* Insert '-' before and after "CTRL-X" when applicable.
*/
if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1])
|| vim_strchr((char_u *)"?@[\\]^", s[1]) != NULL)))
{
if (d > IObuff && d[-1] != '_')
*d++ = '_'; /* prepend a '_' */
STRCPY(d, "CTRL-");
d += 5;
if (*s < ' ')
{
#ifdef EBCDIC
*d++ = CtrlChar(*s);
#else
*d++ = *s + '@';
#endif
if (d[-1] == '\\')
*d++ = '\\'; /* double a backslash */
}
else
*d++ = *++s;
if (s[1] != NUL && s[1] != '_')
*d++ = '_'; /* append a '_' */
continue;
}
else if (*s == '^') /* "^" or "CTRL-^" or "^_" */
*d++ = '\\';
/*
* Insert a backslash before a backslash after a slash, for search
* pattern tags: "/\|" --> "/\\|".
*/
else if (s[0] == '\\' && s[1] != '\\'
&& *arg == '/' && s == arg + 1)
*d++ = '\\';
/* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in
* "CTRL-\_CTRL-N" */
if (STRNICMP(s, "CTRL-\\_", 7) == 0)
{
STRCPY(d, "CTRL-\\\\");
d += 7;
s += 6;
}
*d++ = *s;
/*
* If tag starts with ', toss everything after a second '. Fixes
* CTRL-] on 'option'. (would include the trailing '.').
*/
if (*s == '\'' && s > arg && *arg == '\'')
break;
}
*d = NUL;
if (*IObuff == '`')
{
if (d > IObuff + 2 && d[-1] == '`')
{
/* remove the backticks from `command` */
mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));
d[-2] = NUL;
}
else if (d > IObuff + 3 && d[-2] == '`' && d[-1] == ',')
{
/* remove the backticks and comma from `command`, */
mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));
d[-3] = NUL;
}
else if (d > IObuff + 4 && d[-3] == '`'
&& d[-2] == '\\' && d[-1] == '.')
{
/* remove the backticks and dot from `command`\. */
mch_memmove(IObuff, IObuff + 1, STRLEN(IObuff));
d[-4] = NUL;
}
}
}
}
*matches = (char_u **)"";
*num_matches = 0;
flags = TAG_HELP | TAG_REGEXP | TAG_NAMES | TAG_VERBOSE;
if (keep_lang)
flags |= TAG_KEEP_LANG;
if (find_tags(IObuff, num_matches, matches, flags, (int)MAXCOL, NULL) == OK
&& *num_matches > 0)
{
/* Sort the matches found on the heuristic number that is after the
* tag name. */
qsort((void *)*matches, (size_t)*num_matches,
sizeof(char_u *), help_compare);
/* Delete more than TAG_MANY to reduce the size of the listing. */
while (*num_matches > TAG_MANY)
vim_free((*matches)[--*num_matches]);
}
return OK;
}
/*
* After reading a help file: May cleanup a help buffer when syntax
* highlighting is not used.
*/
void
fix_help_buffer()
{
linenr_T lnum;
char_u *line;
int in_example = FALSE;
int len;
char_u *fname;
char_u *p;
char_u *rt;
int mustfree;
/* set filetype to "help". */
set_option_value((char_u *)"ft", 0L, (char_u *)"help", OPT_LOCAL);
#ifdef FEAT_SYN_HL
if (!syntax_present(curwin))
#endif
{
for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
{
line = ml_get_buf(curbuf, lnum, FALSE);
len = (int)STRLEN(line);
if (in_example && len > 0 && !vim_iswhite(line[0]))
{
/* End of example: non-white or '<' in first column. */
if (line[0] == '<')
{
/* blank-out a '<' in the first column */
line = ml_get_buf(curbuf, lnum, TRUE);
line[0] = ' ';
}
in_example = FALSE;
}
if (!in_example && len > 0)
{
if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' '))
{
/* blank-out a '>' in the last column (start of example) */
line = ml_get_buf(curbuf, lnum, TRUE);
line[len - 1] = ' ';
in_example = TRUE;
}
else if (line[len - 1] == '~')
{
/* blank-out a '~' at the end of line (header marker) */
line = ml_get_buf(curbuf, lnum, TRUE);
line[len - 1] = ' ';
}
}
}
}
/*
* In the "help.txt" and "help.abx" file, add the locally added help
* files. This uses the very first line in the help file.
*/
fname = gettail(curbuf->b_fname);
if (fnamecmp(fname, "help.txt") == 0
#ifdef FEAT_MULTI_LANG
|| (fnamencmp(fname, "help.", 5) == 0
&& ASCII_ISALPHA(fname[5])
&& ASCII_ISALPHA(fname[6])
&& TOLOWER_ASC(fname[7]) == 'x'
&& fname[8] == NUL)
#endif
)
{
for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; ++lnum)
{
line = ml_get_buf(curbuf, lnum, FALSE);
if (strstr((char *)line, "*local-additions*") == NULL)
continue;
/* Go through all directories in 'runtimepath', skipping
* $VIMRUNTIME. */
p = p_rtp;
while (*p != NUL)
{
copy_option_part(&p, NameBuff, MAXPATHL, ",");
mustfree = FALSE;
rt = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
if (fullpathcmp(rt, NameBuff, FALSE) != FPC_SAME)
{
int fcount;
char_u **fnames;
FILE *fd;
char_u *s;
int fi;
#ifdef FEAT_MBYTE
vimconv_T vc;
char_u *cp;
#endif
/* Find all "doc/ *.txt" files in this directory. */
add_pathsep(NameBuff);
#ifdef FEAT_MULTI_LANG
STRCAT(NameBuff, "doc/*.??[tx]");
#else
STRCAT(NameBuff, "doc/*.txt");
#endif
if (gen_expand_wildcards(1, &NameBuff, &fcount,
&fnames, EW_FILE|EW_SILENT) == OK
&& fcount > 0)
{
#ifdef FEAT_MULTI_LANG
int i1;
int i2;
char_u *f1;
char_u *f2;
char_u *t1;
char_u *e1;
char_u *e2;
/* If foo.abx is found use it instead of foo.txt in
* the same directory. */
for (i1 = 0; i1 < fcount; ++i1)
{
for (i2 = 0; i2 < fcount; ++i2)
{
if (i1 == i2)
continue;
if (fnames[i1] == NULL || fnames[i2] == NULL)
continue;
f1 = fnames[i1];
f2 = fnames[i2];
t1 = gettail(f1);
if (fnamencmp(f1, f2, t1 - f1) != 0)
continue;
e1 = vim_strrchr(t1, '.');
e2 = vim_strrchr(gettail(f2), '.');
if (e1 == NUL || e2 == NUL)
continue;
if (fnamecmp(e1, ".txt") != 0
&& fnamecmp(e1, fname + 4) != 0)
{
/* Not .txt and not .abx, remove it. */
vim_free(fnames[i1]);
fnames[i1] = NULL;
continue;
}
if (fnamencmp(f1, f2, e1 - f1) != 0)
continue;
if (fnamecmp(e1, ".txt") == 0
&& fnamecmp(e2, fname + 4) == 0)
{
/* use .abx instead of .txt */
vim_free(fnames[i1]);
fnames[i1] = NULL;
}
}
}
#endif
for (fi = 0; fi < fcount; ++fi)
{
if (fnames[fi] == NULL)
continue;
fd = mch_fopen((char *)fnames[fi], "r");
if (fd != NULL)
{
vim_fgets(IObuff, IOSIZE, fd);
if (IObuff[0] == '*'
&& (s = vim_strchr(IObuff + 1, '*'))
!= NULL)
{
#ifdef FEAT_MBYTE
int this_utf = MAYBE;
#endif
/* Change tag definition to a
* reference and remove <CR>/<NL>. */
IObuff[0] = '|';
*s = '|';
while (*s != NUL)
{
if (*s == '\r' || *s == '\n')
*s = NUL;
#ifdef FEAT_MBYTE
/* The text is utf-8 when a byte
* above 127 is found and no
* illegal byte sequence is found.
*/
if (*s >= 0x80 && this_utf != FALSE)
{
int l;
this_utf = TRUE;
l = utf_ptr2len(s);
if (l == 1)
this_utf = FALSE;
s += l - 1;
}
#endif
++s;
}
#ifdef FEAT_MBYTE
/* The help file is latin1 or utf-8;
* conversion to the current
* 'encoding' may be required. */
vc.vc_type = CONV_NONE;
convert_setup(&vc, (char_u *)(
this_utf == TRUE ? "utf-8"
: "latin1"), p_enc);
if (vc.vc_type == CONV_NONE)
/* No conversion needed. */
cp = IObuff;
else
{
/* Do the conversion. If it fails
* use the unconverted text. */
cp = string_convert(&vc, IObuff,
NULL);
if (cp == NULL)
cp = IObuff;
}
convert_setup(&vc, NULL, NULL);
ml_append(lnum, cp, (colnr_T)0, FALSE);
if (cp != IObuff)
vim_free(cp);
#else
ml_append(lnum, IObuff, (colnr_T)0,
FALSE);
#endif
++lnum;
}
fclose(fd);
}
}
FreeWild(fcount, fnames);
}
}
if (mustfree)
vim_free(rt);
}
break;
}
}
}
/*
* ":exusage"
*/
void
ex_exusage(eap)
exarg_T *eap UNUSED;
{
do_cmdline_cmd((char_u *)"help ex-cmd-index");
}
/*
* ":viusage"
*/
void
ex_viusage(eap)
exarg_T *eap UNUSED;
{
do_cmdline_cmd((char_u *)"help normal-index");
}
#if defined(FEAT_EX_EXTRA) || defined(PROTO)
static void helptags_one __ARGS((char_u *dir, char_u *ext, char_u *lang, int add_help_tags));
/*
* ":helptags"
*/
void
ex_helptags(eap)
exarg_T *eap;
{
garray_T ga;
int i, j;
int len;
#ifdef FEAT_MULTI_LANG
char_u lang[2];
#endif
expand_T xpc;
char_u *dirname;
char_u ext[5];
char_u fname[8];
int filecount;
char_u **files;
int add_help_tags = FALSE;
/* Check for ":helptags ++t {dir}". */
if (STRNCMP(eap->arg, "++t", 3) == 0 && vim_iswhite(eap->arg[3]))
{
add_help_tags = TRUE;
eap->arg = skipwhite(eap->arg + 3);
}
ExpandInit(&xpc);
xpc.xp_context = EXPAND_DIRECTORIES;
dirname = ExpandOne(&xpc, eap->arg, NULL,
WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE);
if (dirname == NULL || !mch_isdir(dirname))
{
EMSG2(_("E150: Not a directory: %s"), eap->arg);
return;
}
#ifdef FEAT_MULTI_LANG
/* Get a list of all files in the directory. */
STRCPY(NameBuff, dirname);
add_pathsep(NameBuff);
STRCAT(NameBuff, "*");
if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
EW_FILE|EW_SILENT) == FAIL
|| filecount == 0)
{
EMSG2("E151: No match: %s", NameBuff);
vim_free(dirname);
return;
}
/* Go over all files in the directory to find out what languages are
* present. */
ga_init2(&ga, 1, 10);
for (i = 0; i < filecount; ++i)
{
len = (int)STRLEN(files[i]);
if (len > 4)
{
if (STRICMP(files[i] + len - 4, ".txt") == 0)
{
/* ".txt" -> language "en" */
lang[0] = 'e';
lang[1] = 'n';
}
else if (files[i][len - 4] == '.'
&& ASCII_ISALPHA(files[i][len - 3])
&& ASCII_ISALPHA(files[i][len - 2])
&& TOLOWER_ASC(files[i][len - 1]) == 'x')
{
/* ".abx" -> language "ab" */
lang[0] = TOLOWER_ASC(files[i][len - 3]);
lang[1] = TOLOWER_ASC(files[i][len - 2]);
}
else
continue;
/* Did we find this language already? */
for (j = 0; j < ga.ga_len; j += 2)
if (STRNCMP(lang, ((char_u *)ga.ga_data) + j, 2) == 0)
break;
if (j == ga.ga_len)
{
/* New language, add it. */
if (ga_grow(&ga, 2) == FAIL)
break;
((char_u *)ga.ga_data)[ga.ga_len++] = lang[0];
((char_u *)ga.ga_data)[ga.ga_len++] = lang[1];
}
}
}
/*
* Loop over the found languages to generate a tags file for each one.
*/
for (j = 0; j < ga.ga_len; j += 2)
{
STRCPY(fname, "tags-xx");
fname[5] = ((char_u *)ga.ga_data)[j];
fname[6] = ((char_u *)ga.ga_data)[j + 1];
if (fname[5] == 'e' && fname[6] == 'n')
{
/* English is an exception: use ".txt" and "tags". */
fname[4] = NUL;
STRCPY(ext, ".txt");
}
else
{
/* Language "ab" uses ".abx" and "tags-ab". */
STRCPY(ext, ".xxx");
ext[1] = fname[5];
ext[2] = fname[6];
}
helptags_one(dirname, ext, fname, add_help_tags);
}
ga_clear(&ga);
FreeWild(filecount, files);
#else
/* No language support, just use "*.txt" and "tags". */
helptags_one(dirname, (char_u *)".txt", (char_u *)"tags", add_help_tags);
#endif
vim_free(dirname);
}
static void
helptags_one(dir, ext, tagfname, add_help_tags)
char_u *dir; /* doc directory */
char_u *ext; /* suffix, ".txt", ".itx", ".frx", etc. */
char_u *tagfname; /* "tags" for English, "tags-fr" for French. */
int add_help_tags; /* add "help-tags" tag */
{
FILE *fd_tags;
FILE *fd;
garray_T ga;
int filecount;
char_u **files;
char_u *p1, *p2;
int fi;
char_u *s;
int i;
char_u *fname;
# ifdef FEAT_MBYTE
int utf8 = MAYBE;
int this_utf8;
int firstline;
int mix = FALSE; /* detected mixed encodings */
# endif
/*
* Find all *.txt files.
*/
STRCPY(NameBuff, dir);
add_pathsep(NameBuff);
STRCAT(NameBuff, "*");
STRCAT(NameBuff, ext);
if (gen_expand_wildcards(1, &NameBuff, &filecount, &files,
EW_FILE|EW_SILENT) == FAIL
|| filecount == 0)
{
if (!got_int)
EMSG2("E151: No match: %s", NameBuff);
return;
}
/*
* Open the tags file for writing.
* Do this before scanning through all the files.
*/
STRCPY(NameBuff, dir);
add_pathsep(NameBuff);
STRCAT(NameBuff, tagfname);
fd_tags = mch_fopen((char *)NameBuff, "w");
if (fd_tags == NULL)
{
EMSG2(_("E152: Cannot open %s for writing"), NameBuff);
FreeWild(filecount, files);
return;
}
/*
* If using the "++t" argument or generating tags for "$VIMRUNTIME/doc"
* add the "help-tags" tag.
*/
ga_init2(&ga, (int)sizeof(char_u *), 100);
if (add_help_tags || fullpathcmp((char_u *)"$VIMRUNTIME/doc",
dir, FALSE) == FPC_SAME)
{
if (ga_grow(&ga, 1) == FAIL)
got_int = TRUE;
else
{
s = alloc(18 + (unsigned)STRLEN(tagfname));
if (s == NULL)
got_int = TRUE;
else
{
sprintf((char *)s, "help-tags\t%s\t1\n", tagfname);
((char_u **)ga.ga_data)[ga.ga_len] = s;
++ga.ga_len;
}
}
}
/*
* Go over all the files and extract the tags.
*/
for (fi = 0; fi < filecount && !got_int; ++fi)
{
fd = mch_fopen((char *)files[fi], "r");
if (fd == NULL)
{
EMSG2(_("E153: Unable to open %s for reading"), files[fi]);
continue;
}
fname = gettail(files[fi]);
# ifdef FEAT_MBYTE
firstline = TRUE;
# endif
while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int)
{
# ifdef FEAT_MBYTE
if (firstline)
{
/* Detect utf-8 file by a non-ASCII char in the first line. */
this_utf8 = MAYBE;
for (s = IObuff; *s != NUL; ++s)
if (*s >= 0x80)
{
int l;
this_utf8 = TRUE;
l = utf_ptr2len(s);
if (l == 1)
{
/* Illegal UTF-8 byte sequence. */
this_utf8 = FALSE;
break;
}
s += l - 1;
}
if (this_utf8 == MAYBE) /* only ASCII characters found */
this_utf8 = FALSE;
if (utf8 == MAYBE) /* first file */
utf8 = this_utf8;
else if (utf8 != this_utf8)
{
EMSG2(_("E670: Mix of help file encodings within a language: %s"), files[fi]);
mix = !got_int;
got_int = TRUE;
}
firstline = FALSE;
}
# endif
p1 = vim_strchr(IObuff, '*'); /* find first '*' */
while (p1 != NULL)
{
/* Use vim_strbyte() instead of vim_strchr() so that when
* 'encoding' is dbcs it still works, don't find '*' in the
* second byte. */
p2 = vim_strbyte(p1 + 1, '*'); /* find second '*' */
if (p2 != NULL && p2 > p1 + 1) /* skip "*" and "**" */
{
for (s = p1 + 1; s < p2; ++s)
if (*s == ' ' || *s == '\t' || *s == '|')
break;
/*
* Only accept a *tag* when it consists of valid
* characters, there is white space before it and is
* followed by a white character or end-of-line.
*/
if (s == p2
&& (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
&& (vim_strchr((char_u *)" \t\n\r", s[1]) != NULL
|| s[1] == '\0'))
{
*p2 = '\0';
++p1;
if (ga_grow(&ga, 1) == FAIL)
{
got_int = TRUE;
break;
}
s = alloc((unsigned)(p2 - p1 + STRLEN(fname) + 2));
if (s == NULL)
{
got_int = TRUE;
break;
}
((char_u **)ga.ga_data)[ga.ga_len] = s;
++ga.ga_len;
sprintf((char *)s, "%s\t%s", p1, fname);
/* find next '*' */
p2 = vim_strchr(p2 + 1, '*');
}
}
p1 = p2;
}
line_breakcheck();
}
fclose(fd);
}
FreeWild(filecount, files);
if (!got_int)
{
/*
* Sort the tags.
*/
sort_strings((char_u **)ga.ga_data, ga.ga_len);
/*
* Check for duplicates.
*/
for (i = 1; i < ga.ga_len; ++i)
{
p1 = ((char_u **)ga.ga_data)[i - 1];
p2 = ((char_u **)ga.ga_data)[i];
while (*p1 == *p2)
{
if (*p2 == '\t')
{
*p2 = NUL;
vim_snprintf((char *)NameBuff, MAXPATHL,
_("E154: Duplicate tag \"%s\" in file %s/%s"),
((char_u **)ga.ga_data)[i], dir, p2 + 1);
EMSG(NameBuff);
*p2 = '\t';
break;
}
++p1;
++p2;
}
}
# ifdef FEAT_MBYTE
if (utf8 == TRUE)
fprintf(fd_tags, "!_TAG_FILE_ENCODING\tutf-8\t//\n");
# endif
/*
* Write the tags into the file.
*/
for (i = 0; i < ga.ga_len; ++i)
{
s = ((char_u **)ga.ga_data)[i];
if (STRNCMP(s, "help-tags\t", 10) == 0)
/* help-tags entry was added in formatted form */
fputs((char *)s, fd_tags);
else
{
fprintf(fd_tags, "%s\t/*", s);
for (p1 = s; *p1 != '\t'; ++p1)
{
/* insert backslash before '\\' and '/' */
if (*p1 == '\\' || *p1 == '/')
putc('\\', fd_tags);
putc(*p1, fd_tags);
}
fprintf(fd_tags, "*\n");
}
}
}
#ifdef FEAT_MBYTE
if (mix)
got_int = FALSE; /* continue with other languages */
#endif
for (i = 0; i < ga.ga_len; ++i)
vim_free(((char_u **)ga.ga_data)[i]);
ga_clear(&ga);
fclose(fd_tags); /* there is no check for an error... */
}
#endif
#if defined(FEAT_SIGNS) || defined(PROTO)
/*
* Struct to hold the sign properties.
*/
typedef struct sign sign_T;
struct sign
{
sign_T *sn_next; /* next sign in list */
int sn_typenr; /* type number of sign */
char_u *sn_name; /* name of sign */
char_u *sn_icon; /* name of pixmap */
#ifdef FEAT_SIGN_ICONS
void *sn_image; /* icon image */
#endif
char_u *sn_text; /* text used instead of pixmap */
int sn_line_hl; /* highlight ID for line */
int sn_text_hl; /* highlight ID for text */
};
static sign_T *first_sign = NULL;
static int next_sign_typenr = 1;
static int sign_cmd_idx __ARGS((char_u *begin_cmd, char_u *end_cmd));
static void sign_list_defined __ARGS((sign_T *sp));
static void sign_undefine __ARGS((sign_T *sp, sign_T *sp_prev));
static char *cmds[] = {
"define",
#define SIGNCMD_DEFINE 0
"undefine",
#define SIGNCMD_UNDEFINE 1
"list",
#define SIGNCMD_LIST 2
"place",
#define SIGNCMD_PLACE 3
"unplace",
#define SIGNCMD_UNPLACE 4
"jump",
#define SIGNCMD_JUMP 5
NULL
#define SIGNCMD_LAST 6
};
/*
* Find index of a ":sign" subcmd from its name.
* "*end_cmd" must be writable.
*/
static int
sign_cmd_idx(begin_cmd, end_cmd)
char_u *begin_cmd; /* begin of sign subcmd */
char_u *end_cmd; /* just after sign subcmd */
{
int idx;
char save = *end_cmd;
*end_cmd = NUL;
for (idx = 0; ; ++idx)
if (cmds[idx] == NULL || STRCMP(begin_cmd, cmds[idx]) == 0)
break;
*end_cmd = save;
return idx;
}
/*
* ":sign" command
*/
void
ex_sign(eap)
exarg_T *eap;
{
char_u *arg = eap->arg;
char_u *p;
int idx;
sign_T *sp;
sign_T *sp_prev;
buf_T *buf;
/* Parse the subcommand. */
p = skiptowhite(arg);
idx = sign_cmd_idx(arg, p);
if (idx == SIGNCMD_LAST)
{
EMSG2(_("E160: Unknown sign command: %s"), arg);
return;
}
arg = skipwhite(p);
if (idx <= SIGNCMD_LIST)
{
/*
* Define, undefine or list signs.
*/
if (idx == SIGNCMD_LIST && *arg == NUL)
{
/* ":sign list": list all defined signs */
for (sp = first_sign; sp != NULL && !got_int; sp = sp->sn_next)
sign_list_defined(sp);
}
else if (*arg == NUL)
EMSG(_("E156: Missing sign name"));
else
{
/* Isolate the sign name. If it's a number skip leading zeroes,
* so that "099" and "99" are the same sign. But keep "0". */
p = skiptowhite(arg);
if (*p != NUL)
*p++ = NUL;
while (arg[0] == '0' && arg[1] != NUL)
++arg;
sp_prev = NULL;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
{
if (STRCMP(sp->sn_name, arg) == 0)
break;
sp_prev = sp;
}
if (idx == SIGNCMD_DEFINE)
{
/* ":sign define {name} ...": define a sign */
if (sp == NULL)
{
sign_T *lp;
int start = next_sign_typenr;
/* Allocate a new sign. */
sp = (sign_T *)alloc_clear((unsigned)sizeof(sign_T));
if (sp == NULL)
return;
/* Check that next_sign_typenr is not already being used.
* This only happens after wrapping around. Hopefully
* another one got deleted and we can use its number. */
for (lp = first_sign; lp != NULL; )
{
if (lp->sn_typenr == next_sign_typenr)
{
++next_sign_typenr;
if (next_sign_typenr == MAX_TYPENR)
next_sign_typenr = 1;
if (next_sign_typenr == start)
{
vim_free(sp);
EMSG(_("E612: Too many signs defined"));
return;
}
lp = first_sign; /* start all over */
continue;
}
lp = lp->sn_next;
}
sp->sn_typenr = next_sign_typenr;
if (++next_sign_typenr == MAX_TYPENR)
next_sign_typenr = 1; /* wrap around */
sp->sn_name = vim_strsave(arg);
if (sp->sn_name == NULL) /* out of memory */
{
vim_free(sp);
return;
}
/* add the new sign to the list of signs */
if (sp_prev == NULL)
first_sign = sp;
else
sp_prev->sn_next = sp;
}
/* set values for a defined sign. */
for (;;)
{
arg = skipwhite(p);
if (*arg == NUL)
break;
p = skiptowhite_esc(arg);
if (STRNCMP(arg, "icon=", 5) == 0)
{
arg += 5;
vim_free(sp->sn_icon);
sp->sn_icon = vim_strnsave(arg, (int)(p - arg));
backslash_halve(sp->sn_icon);
#ifdef FEAT_SIGN_ICONS
if (gui.in_use)
{
out_flush();
if (sp->sn_image != NULL)
gui_mch_destroy_sign(sp->sn_image);
sp->sn_image = gui_mch_register_sign(sp->sn_icon);
}
#endif
}
else if (STRNCMP(arg, "text=", 5) == 0)
{
char_u *s;
int cells;
int len;
arg += 5;
#ifdef FEAT_MBYTE
/* Count cells and check for non-printable chars */
if (has_mbyte)
{
cells = 0;
for (s = arg; s < p; s += (*mb_ptr2len)(s))
{
if (!vim_isprintc((*mb_ptr2char)(s)))
break;
cells += (*mb_ptr2cells)(s);
}
}
else
#endif
{
for (s = arg; s < p; ++s)
if (!vim_isprintc(*s))
break;
cells = (int)(s - arg);
}
/* Currently must be one or two display cells */
if (s != p || cells < 1 || cells > 2)
{
*p = NUL;
EMSG2(_("E239: Invalid sign text: %s"), arg);
return;
}
vim_free(sp->sn_text);
/* Allocate one byte more if we need to pad up
* with a space. */
len = (int)(p - arg + ((cells == 1) ? 1 : 0));
sp->sn_text = vim_strnsave(arg, len);
if (sp->sn_text != NULL && cells == 1)
STRCPY(sp->sn_text + len - 1, " ");
}
else if (STRNCMP(arg, "linehl=", 7) == 0)
{
arg += 7;
sp->sn_line_hl = syn_check_group(arg, (int)(p - arg));
}
else if (STRNCMP(arg, "texthl=", 7) == 0)
{
arg += 7;
sp->sn_text_hl = syn_check_group(arg, (int)(p - arg));
}
else
{
EMSG2(_(e_invarg2), arg);
return;
}
}
}
else if (sp == NULL)
EMSG2(_("E155: Unknown sign: %s"), arg);
else if (idx == SIGNCMD_LIST)
/* ":sign list {name}" */
sign_list_defined(sp);
else
/* ":sign undefine {name}" */
sign_undefine(sp, sp_prev);
}
}
else
{
int id = -1;
linenr_T lnum = -1;
char_u *sign_name = NULL;
char_u *arg1;
if (*arg == NUL)
{
if (idx == SIGNCMD_PLACE)
{
/* ":sign place": list placed signs in all buffers */
sign_list_placed(NULL);
}
else if (idx == SIGNCMD_UNPLACE)
{
/* ":sign unplace": remove placed sign at cursor */
id = buf_findsign_id(curwin->w_buffer, curwin->w_cursor.lnum);
if (id > 0)
{
buf_delsign(curwin->w_buffer, id);
update_debug_sign(curwin->w_buffer, curwin->w_cursor.lnum);
}
else
EMSG(_("E159: Missing sign number"));
}
else
EMSG(_(e_argreq));
return;
}
if (idx == SIGNCMD_UNPLACE && arg[0] == '*' && arg[1] == NUL)
{
/* ":sign unplace *": remove all placed signs */
buf_delete_all_signs();
return;
}
/* first arg could be placed sign id */
arg1 = arg;
if (VIM_ISDIGIT(*arg))
{
id = getdigits(&arg);
if (!vim_iswhite(*arg) && *arg != NUL)
{
id = -1;
arg = arg1;
}
else
{
arg = skipwhite(arg);
if (idx == SIGNCMD_UNPLACE && *arg == NUL)
{
/* ":sign unplace {id}": remove placed sign by number */
for (buf = firstbuf; buf != NULL; buf = buf->b_next)
if ((lnum = buf_delsign(buf, id)) != 0)
update_debug_sign(buf, lnum);
return;
}
}
}
/*
* Check for line={lnum} name={name} and file={fname} or buffer={nr}.
* Leave "arg" pointing to {fname}.
*/
for (;;)
{
if (STRNCMP(arg, "line=", 5) == 0)
{
arg += 5;
lnum = atoi((char *)arg);
arg = skiptowhite(arg);
}
else if (STRNCMP(arg, "name=", 5) == 0)
{
arg += 5;
sign_name = arg;
arg = skiptowhite(arg);
if (*arg != NUL)
*arg++ = NUL;
while (sign_name[0] == '0' && sign_name[1] != NUL)
++sign_name;
}
else if (STRNCMP(arg, "file=", 5) == 0)
{
arg += 5;
buf = buflist_findname(arg);
break;
}
else if (STRNCMP(arg, "buffer=", 7) == 0)
{
arg += 7;
buf = buflist_findnr((int)getdigits(&arg));
if (*skipwhite(arg) != NUL)
EMSG(_(e_trailing));
break;
}
else
{
EMSG(_(e_invarg));
return;
}
arg = skipwhite(arg);
}
if (buf == NULL)
{
EMSG2(_("E158: Invalid buffer name: %s"), arg);
}
else if (id <= 0)
{
if (lnum >= 0 || sign_name != NULL)
EMSG(_(e_invarg));
else
/* ":sign place file={fname}": list placed signs in one file */
sign_list_placed(buf);
}
else if (idx == SIGNCMD_JUMP)
{
/* ":sign jump {id} file={fname}" */
if (lnum >= 0 || sign_name != NULL)
EMSG(_(e_invarg));
else if ((lnum = buf_findsign(buf, id)) > 0)
{ /* goto a sign ... */
if (buf_jump_open_win(buf) != NULL)
{ /* ... in a current window */
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_WHITE);
}
else
{ /* ... not currently in a window */
char_u *cmd;
cmd = alloc((unsigned)STRLEN(buf->b_fname) + 25);
if (cmd == NULL)
return;
sprintf((char *)cmd, "e +%ld %s", (long)lnum, buf->b_fname);
do_cmdline_cmd(cmd);
vim_free(cmd);
}
#ifdef FEAT_FOLDING
foldOpenCursor();
#endif
}
else
EMSGN(_("E157: Invalid sign ID: %ld"), id);
}
else if (idx == SIGNCMD_UNPLACE)
{
/* ":sign unplace {id} file={fname}" */
if (lnum >= 0 || sign_name != NULL)
EMSG(_(e_invarg));
else
{
lnum = buf_delsign(buf, id);
update_debug_sign(buf, lnum);
}
}
/* idx == SIGNCMD_PLACE */
else if (sign_name != NULL)
{
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (STRCMP(sp->sn_name, sign_name) == 0)
break;
if (sp == NULL)
{
EMSG2(_("E155: Unknown sign: %s"), sign_name);
return;
}
if (lnum > 0)
/* ":sign place {id} line={lnum} name={name} file={fname}":
* place a sign */
buf_addsign(buf, id, lnum, sp->sn_typenr);
else
/* ":sign place {id} file={fname}": change sign type */
lnum = buf_change_sign_type(buf, id, sp->sn_typenr);
update_debug_sign(buf, lnum);
}
else
EMSG(_(e_invarg));
}
}
#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
/*
* Allocate the icons. Called when the GUI has started. Allows defining
* signs before it starts.
*/
void
sign_gui_started()
{
sign_T *sp;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (sp->sn_icon != NULL)
sp->sn_image = gui_mch_register_sign(sp->sn_icon);
}
#endif
/*
* List one sign.
*/
static void
sign_list_defined(sp)
sign_T *sp;
{
char_u *p;
smsg((char_u *)"sign %s", sp->sn_name);
if (sp->sn_icon != NULL)
{
MSG_PUTS(" icon=");
msg_outtrans(sp->sn_icon);
#ifdef FEAT_SIGN_ICONS
if (sp->sn_image == NULL)
MSG_PUTS(_(" (NOT FOUND)"));
#else
MSG_PUTS(_(" (not supported)"));
#endif
}
if (sp->sn_text != NULL)
{
MSG_PUTS(" text=");
msg_outtrans(sp->sn_text);
}
if (sp->sn_line_hl > 0)
{
MSG_PUTS(" linehl=");
p = get_highlight_name(NULL, sp->sn_line_hl - 1);
if (p == NULL)
MSG_PUTS("NONE");
else
msg_puts(p);
}
if (sp->sn_text_hl > 0)
{
MSG_PUTS(" texthl=");
p = get_highlight_name(NULL, sp->sn_text_hl - 1);
if (p == NULL)
MSG_PUTS("NONE");
else
msg_puts(p);
}
}
/*
* Undefine a sign and free its memory.
*/
static void
sign_undefine(sp, sp_prev)
sign_T *sp;
sign_T *sp_prev;
{
vim_free(sp->sn_name);
vim_free(sp->sn_icon);
#ifdef FEAT_SIGN_ICONS
if (sp->sn_image != NULL)
{
out_flush();
gui_mch_destroy_sign(sp->sn_image);
}
#endif
vim_free(sp->sn_text);
if (sp_prev == NULL)
first_sign = sp->sn_next;
else
sp_prev->sn_next = sp->sn_next;
vim_free(sp);
}
/*
* Get highlighting attribute for sign "typenr".
* If "line" is TRUE: line highl, if FALSE: text highl.
*/
int
sign_get_attr(typenr, line)
int typenr;
int line;
{
sign_T *sp;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (sp->sn_typenr == typenr)
{
if (line)
{
if (sp->sn_line_hl > 0)
return syn_id2attr(sp->sn_line_hl);
}
else
{
if (sp->sn_text_hl > 0)
return syn_id2attr(sp->sn_text_hl);
}
break;
}
return 0;
}
/*
* Get text mark for sign "typenr".
* Returns NULL if there isn't one.
*/
char_u *
sign_get_text(typenr)
int typenr;
{
sign_T *sp;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (sp->sn_typenr == typenr)
return sp->sn_text;
return NULL;
}
#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
void *
sign_get_image(typenr)
int typenr; /* the attribute which may have a sign */
{
sign_T *sp;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (sp->sn_typenr == typenr)
return sp->sn_image;
return NULL;
}
#endif
/*
* Get the name of a sign by its typenr.
*/
char_u *
sign_typenr2name(typenr)
int typenr;
{
sign_T *sp;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (sp->sn_typenr == typenr)
return sp->sn_name;
return (char_u *)_("[Deleted]");
}
#if defined(EXITFREE) || defined(PROTO)
/*
* Undefine/free all signs.
*/
void
free_signs()
{
while (first_sign != NULL)
sign_undefine(first_sign, NULL);
}
#endif
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
static enum
{
EXP_SUBCMD, /* expand :sign sub-commands */
EXP_DEFINE, /* expand :sign define {name} args */
EXP_PLACE, /* expand :sign place {id} args */
EXP_UNPLACE, /* expand :sign unplace" */
EXP_SIGN_NAMES /* expand with name of placed signs */
} expand_what;
/*
* Function given to ExpandGeneric() to obtain the sign command
* expansion.
*/
char_u *
get_sign_name(xp, idx)
expand_T *xp UNUSED;
int idx;
{
sign_T *sp;
int current_idx;
switch (expand_what)
{
case EXP_SUBCMD:
return (char_u *)cmds[idx];
case EXP_DEFINE:
{
char *define_arg[] =
{
"icon=", "linehl=", "text=", "texthl=", NULL
};
return (char_u *)define_arg[idx];
}
case EXP_PLACE:
{
char *place_arg[] =
{
"line=", "name=", "file=", "buffer=", NULL
};
return (char_u *)place_arg[idx];
}
case EXP_UNPLACE:
{
char *unplace_arg[] = { "file=", "buffer=", NULL };
return (char_u *)unplace_arg[idx];
}
case EXP_SIGN_NAMES:
/* Complete with name of signs already defined */
current_idx = 0;
for (sp = first_sign; sp != NULL; sp = sp->sn_next)
if (current_idx++ == idx)
return sp->sn_name;
return NULL;
default:
return NULL;
}
}
/*
* Handle command line completion for :sign command.
*/
void
set_context_in_sign_cmd(xp, arg)
expand_T *xp;
char_u *arg;
{
char_u *p;
char_u *end_subcmd;
char_u *last;
int cmd_idx;
char_u *begin_subcmd_args;
/* Default: expand subcommands. */
xp->xp_context = EXPAND_SIGN;
expand_what = EXP_SUBCMD;
xp->xp_pattern = arg;
end_subcmd = skiptowhite(arg);
if (*end_subcmd == NUL)
/* expand subcmd name
* :sign {subcmd}<CTRL-D>*/
return;
cmd_idx = sign_cmd_idx(arg, end_subcmd);
/* :sign {subcmd} {subcmd_args}
* |
* begin_subcmd_args */
begin_subcmd_args = skipwhite(end_subcmd);
p = skiptowhite(begin_subcmd_args);
if (*p == NUL)
{
/*
* Expand first argument of subcmd when possible.
* For ":jump {id}" and ":unplace {id}", we could
* possibly expand the ids of all signs already placed.
*/
xp->xp_pattern = begin_subcmd_args;
switch (cmd_idx)
{
case SIGNCMD_LIST:
case SIGNCMD_UNDEFINE:
/* :sign list <CTRL-D>
* :sign undefine <CTRL-D> */
expand_what = EXP_SIGN_NAMES;
break;
default:
xp->xp_context = EXPAND_NOTHING;
}
return;
}
/* expand last argument of subcmd */
/* :sign define {name} {args}...
* |
* p */
/* Loop until reaching last argument. */
do
{
p = skipwhite(p);
last = p;
p = skiptowhite(p);
} while (*p != NUL);
p = vim_strchr(last, '=');
/* :sign define {name} {args}... {last}=
* | |
* last p */
if (p == NUL)
{
/* Expand last argument name (before equal sign). */
xp->xp_pattern = last;
switch (cmd_idx)
{
case SIGNCMD_DEFINE:
expand_what = EXP_DEFINE;
break;
case SIGNCMD_PLACE:
expand_what = EXP_PLACE;
break;
case SIGNCMD_JUMP:
case SIGNCMD_UNPLACE:
expand_what = EXP_UNPLACE;
break;
default:
xp->xp_context = EXPAND_NOTHING;
}
}
else
{
/* Expand last argument value (after equal sign). */
xp->xp_pattern = p + 1;
switch (cmd_idx)
{
case SIGNCMD_DEFINE:
if (STRNCMP(last, "texthl", p - last) == 0 ||
STRNCMP(last, "linehl", p - last) == 0)
xp->xp_context = EXPAND_HIGHLIGHT;
else if (STRNCMP(last, "icon", p - last) == 0)
xp->xp_context = EXPAND_FILES;
else
xp->xp_context = EXPAND_NOTHING;
break;
case SIGNCMD_PLACE:
if (STRNCMP(last, "name", p - last) == 0)
expand_what = EXP_SIGN_NAMES;
else
xp->xp_context = EXPAND_NOTHING;
break;
default:
xp->xp_context = EXPAND_NOTHING;
}
}
}
#endif
#endif
#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
/*
* ":drop"
* Opens the first argument in a window. When there are two or more arguments
* the argument list is redefined.
*/
void
ex_drop(eap)
exarg_T *eap;
{
int split = FALSE;
win_T *wp;
buf_T *buf;
# ifdef FEAT_WINDOWS
tabpage_T *tp;
# endif
/*
* Check if the first argument is already being edited in a window. If
* so, jump to that window.
* We would actually need to check all arguments, but that's complicated
* and mostly only one file is dropped.
* This also ignores wildcards, since it is very unlikely the user is
* editing a file name with a wildcard character.
*/
set_arglist(eap->arg);
/*
* Expanding wildcards may result in an empty argument list. E.g. when
* editing "foo.pyc" and ".pyc" is in 'wildignore'. Assume that we
* already did an error message for this.
*/
if (ARGCOUNT == 0)
return;
# ifdef FEAT_WINDOWS
if (cmdmod.tab)
{
/* ":tab drop file ...": open a tab for each argument that isn't
* edited in a window yet. It's like ":tab all" but without closing
* windows or tabs. */
ex_all(eap);
}
else
# endif
{
/* ":drop file ...": Edit the first argument. Jump to an existing
* window if possible, edit in current window if the current buffer
* can be abandoned, otherwise open a new window. */
buf = buflist_findnr(ARGLIST[0].ae_fnum);
FOR_ALL_TAB_WINDOWS(tp, wp)
{
if (wp->w_buffer == buf)
{
# ifdef FEAT_WINDOWS
goto_tabpage_win(tp, wp);
# endif
curwin->w_arg_idx = 0;
return;
}
}
/*
* Check whether the current buffer is changed. If so, we will need
* to split the current window or data could be lost.
* Skip the check if the 'hidden' option is set, as in this case the
* buffer won't be lost.
*/
if (!P_HID(curbuf))
{
# ifdef FEAT_WINDOWS
++emsg_off;
# endif
split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
# ifdef FEAT_WINDOWS
--emsg_off;
# else
if (split)
return;
# endif
}
/* Fake a ":sfirst" or ":first" command edit the first argument. */
if (split)
{
eap->cmdidx = CMD_sfirst;
eap->cmd[0] = 's';
}
else
eap->cmdidx = CMD_first;
ex_rewind(eap);
}
}
#endif
| zyz2011-vim | src/ex_cmds.c | C | gpl2 | 185,622 |
/* 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_macosx.m -- Mac specific things for Mac OS/X.
*/
#ifndef MACOS_X_UNIX
Error: MACOS 9 is no longer supported in Vim 7
#endif
/* Avoid a conflict for the definition of Boolean between Mac header files and
* X11 header files. */
#define NO_X11_INCLUDES
#define BalloonEval int /* used in header files */
#include "vim.h"
#import <Cocoa/Cocoa.h>
/*
* Clipboard support for the console.
* Don't include this when building the GUI version, the functions in
* gui_mac.c are used then. TODO: remove those instead?
* But for MacVim we do need these ones.
*/
#if defined(FEAT_CLIPBOARD) && (!defined(FEAT_GUI_ENABLED) || defined(FEAT_GUI_MACVIM))
/* Used to identify clipboard data copied from Vim. */
NSString *VimPboardType = @"VimPboardType";
void
clip_mch_lose_selection(VimClipboard *cbd)
{
}
int
clip_mch_own_selection(VimClipboard *cbd)
{
/* This is called whenever there is a new selection and 'guioptions'
* contains the "a" flag (automatically copy selection). Return TRUE, else
* the "a" flag does nothing. Note that there is no concept of "ownership"
* of the clipboard in Mac OS X.
*/
return TRUE;
}
void
clip_mch_request_selection(VimClipboard *cbd)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSArray *supportedTypes = [NSArray arrayWithObjects:VimPboardType,
NSStringPboardType, nil];
NSString *bestType = [pb availableTypeFromArray:supportedTypes];
if (!bestType) goto releasepool;
int motion_type = MAUTO;
NSString *string = nil;
if ([bestType isEqual:VimPboardType])
{
/* This type should consist of an array with two objects:
* 1. motion type (NSNumber)
* 2. text (NSString)
* If this is not the case we fall back on using NSStringPboardType.
*/
id plist = [pb propertyListForType:VimPboardType];
if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2)
{
id obj = [plist objectAtIndex:1];
if ([obj isKindOfClass:[NSString class]])
{
motion_type = [[plist objectAtIndex:0] intValue];
string = obj;
}
}
}
if (!string)
{
/* Use NSStringPboardType. The motion type is detected automatically.
*/
NSMutableString *mstring =
[[pb stringForType:NSStringPboardType] mutableCopy];
if (!mstring) goto releasepool;
/* Replace unrecognized end-of-line sequences with \x0a (line feed). */
NSRange range = { 0, [mstring length] };
unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
withString:@"\x0a" options:0
range:range];
if (0 == n)
{
n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
options:0 range:range];
}
string = mstring;
}
/* Default to MAUTO, uses MCHAR or MLINE depending on trailing NL. */
if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
|| MAUTO == motion_type))
motion_type = MAUTO;
char_u *str = (char_u*)[string UTF8String];
int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
#ifdef FEAT_MBYTE
if (input_conv.vc_type != CONV_NONE)
str = string_convert(&input_conv, str, &len);
#endif
if (str)
clip_yank_selection(motion_type, str, len, cbd);
#ifdef FEAT_MBYTE
if (input_conv.vc_type != CONV_NONE)
vim_free(str);
#endif
releasepool:
[pool release];
}
/*
* Send the current selection to the clipboard.
*/
void
clip_mch_set_selection(VimClipboard *cbd)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* 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 put on the pasteboard. */
long_u llen = 0; char_u *str = 0;
int motion_type = clip_convert_selection(&str, &llen, cbd);
if (motion_type < 0)
goto releasepool;
/* TODO: Avoid overflow. */
int len = (int)llen;
#ifdef FEAT_MBYTE
if (output_conv.vc_type != CONV_NONE)
{
char_u *conv_str = string_convert(&output_conv, str, &len);
if (conv_str)
{
vim_free(str);
str = conv_str;
}
}
#endif
if (len > 0)
{
NSString *string = [[NSString alloc]
initWithBytes:str length:len encoding:NSUTF8StringEncoding];
/* See clip_mch_request_selection() for info on pasteboard types. */
NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSArray *supportedTypes = [NSArray arrayWithObjects:VimPboardType,
NSStringPboardType, nil];
[pb declareTypes:supportedTypes owner:nil];
NSNumber *motion = [NSNumber numberWithInt:motion_type];
NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
[pb setPropertyList:plist forType:VimPboardType];
[pb setString:string forType:NSStringPboardType];
[string release];
}
vim_free(str);
releasepool:
[pool release];
}
#endif /* FEAT_CLIPBOARD */
| zyz2011-vim | src/os_macosx.m | Objective-C | gpl2 | 5,173 |
#
# Borland C++ 5.0[12] makefile for vim, 16-bit windows gui version
# By Vince Negri
# *************************************************************
# * WARNING!
# * This was originally produced by the IDE, but has since been
# * modifed to make it work properly. Adjust with care!
# * In particular, leave LinkerLocalOptsAtW16_gvim16dexe alone
# * unless you are a guru.
# *************************************************************
#
# Look for BOR below and either pass a different value or
# adjust the path as required. For example
# make -fMake_w16.mak -DBOR=C:\PF\Borland\BC5.01 -B BccW16.cfg
# make -fMake_w16.mak
# Note: $(BOR) is effectively ignored unless BccW16.cfg is rebuilt.
#
# Does not compile with Borland C++ 4.51 Walter Briscoe 2003-02-24
# "out of memory" from compiler if gvim16 wildly wrong. WFB 2003-03-04
#
# vim16.def must be a DOS-formatted file. (\r\n line endings.)
# It is a UNIX-formatted file (\n line endings) in vim-*-extra.tar.gz
.AUTODEPEND
#
# Borland C++ tools
#
IMPLIB = Implib
BCC = Bcc +BccW16.cfg
TLINK = TLink
TLIB = TLib
BRC = Brc
TASM = Tasm
#
# IDE macros
#
#
# Options
#
!ifndef BOR
BOR = D:\BC5
!endif
# !ifndef INTDIR is lethal considering CLEAN below. WFB 2003-03-13
INTDIR=w16
# /Twe Make the target a Windows .EXE with explicit functions exportable +
# /x Map file off
# /l Include source line numbers in object map files`
# /c case sensitive link
# /C Case-sensitive exports and imports (16-bit only)
# /k Produce "No Stack" warning.
# /Oa Minimise segment alignment
# /Oc Minimise Chain fixes
# /Oi Minimise Iterated data
# /Or Minimise resource alignment
# /P -P=x Code pack size
# /V Windows version for application
# /L Folder to search for library files
LinkerLocalOptsAtW16_gvim16dexe =/Twe/x/l/c/C/k/Or/Oc/Oa/Oi/P=65535/V3.10
CompInheritOptsAt_gvim16dexe = \
-I$(BOR)\INCLUDE;PROTO;. \
-DFEAT_GUI;FEAT_GUI_MSWIN;FEAT_GUI_W16;MSWIN;WIN16;MSWIN16_FASTTEXT \
-DFEAT_TOOLBAR;WIN16_3DLOOK
#
# Dependency List
#
Dep_Gvim16 = \
gvim16.exe
ObjFiles = \
$(INTDIR)\buffer.obj\
$(INTDIR)\charset.obj\
$(INTDIR)\diff.obj\
$(INTDIR)\digraph.obj\
$(INTDIR)\edit.obj\
$(INTDIR)\eval.obj\
$(INTDIR)\ex_cmds.obj\
$(INTDIR)\ex_cmds2.obj\
$(INTDIR)\ex_docmd.obj\
$(INTDIR)\ex_eval.obj\
$(INTDIR)\ex_getln.obj\
$(INTDIR)\fileio.obj\
$(INTDIR)\fold.obj\
$(INTDIR)\getchar.obj\
$(INTDIR)\hardcopy.obj\
$(INTDIR)\hashtab.obj\
$(INTDIR)\gui.obj\
$(INTDIR)\gui_w16.obj\
$(INTDIR)\main.obj\
$(INTDIR)\mark.obj\
$(INTDIR)\mbyte.obj\
$(INTDIR)\memfile.obj\
$(INTDIR)\memline.obj\
$(INTDIR)\menu.obj\
$(INTDIR)\message.obj\
$(INTDIR)\misc1.obj\
$(INTDIR)\misc2.obj\
$(INTDIR)\move.obj\
$(INTDIR)\normal.obj\
$(INTDIR)\ops.obj\
$(INTDIR)\option.obj\
$(INTDIR)\os_win16.obj\
$(INTDIR)\os_msdos.obj\
$(INTDIR)\os_mswin.obj\
$(INTDIR)\popupmnu.obj\
$(INTDIR)\quickfix.obj\
$(INTDIR)\regexp.obj\
$(INTDIR)\screen.obj\
$(INTDIR)\search.obj\
$(INTDIR)\spell.obj\
$(INTDIR)\syntax.obj\
$(INTDIR)\tag.obj\
$(INTDIR)\term.obj\
$(INTDIR)\ui.obj\
$(INTDIR)\undo.obj\
$(INTDIR)\version.obj\
$(INTDIR)\window.obj
Dep_gvim16dexe = \
vimtbar.lib\
vim16.def\
$(INTDIR)\vim16.res\
$(ObjFiles)
# Without the following, the implicit rule in BUILTINS.MAK is picked up
# for a rule for .c.obj rather than the local implicit rule
.SUFFIXES
.SUFFIXES .c .obj
.path.c = .
# -P- Force C++ compilation off
# -c Compilation only
# -n Place .OBJ files
{.}.c{$(INTDIR)}.obj:
$(BCC) -P- -c -n$(INTDIR)\ {$< }
Gvim16 : BccW16.cfg $(Dep_Gvim16)
echo MakeNode
gvim16.exe : $(Dep_gvim16dexe)
$(TLINK) $(LinkerLocalOptsAtW16_gvim16dexe) @&&|
c0wl.obj $(ObjFiles)
|,$*,,vimtbar ctl3dv2 import cwl, vim16.def,$(INTDIR)\vim16.res
# Force objects to be built if $(BOR) changes
$(ObjFiles) : Make_w16.mak BccW16.cfg
$(INTDIR)\vim16.res : vim16.rc
$(BRC) -R @&&|
$(CompInheritOptsAt_gvim16dexe) -fo$*.res $?
|
# Compiler configuration file
# There is no rule for $(INTDIR) as make always says it does not exist
BccW16.cfg :
-@if not exist $(INTDIR)\$(NULL) mkdir $(INTDIR)
Copy &&|
-3 ; Generate 80386 protected-mode compatible instructions
-a ; Byte alignment
-dc ; Move string literals from data segment to code segment
-ff ; Fast floating point
-H ; Generate and use precompiled headers
-H=$(INTDIR)\gvim16.csm ; gvim16.csm is the precompiled header filename
-k- ; No standard stack frame
-ml ; Large memory model
-OW ; Suppress the inc bp/dec bp on windows far functions
-O1 ; Generate smallest possible code
-O2 ; Generate fastest possible code (overrides prior -O1 control)
-pr ; Fastcall calling convention passing parameters in registers
-R- ; Exclude browser information in generated .OBJ files
-v- ; Turn off source debugging
-vi ; Turn inline function expansion on
-WE ; Only __far _export functions are exported
-w ; Display warnings
-w-par ; Suppress: Parameter 'parameter' is never used
-w-pch ; Cannot create pre-compiled header: initialized data in header
-w-sig ; identifier' declared but never used
-w-ucp ; Mixing pointers to different 'char' types
-wuse ; 'identifier' declared but never used
$(CompInheritOptsAt_gvim16dexe)
| $@
!IF "$(OS)" == "Windows_NT"
NULL=
DEL_TREE = rmdir /s /q
!ELSE
NULL=nul
DEL_TREE = deltree /y
!ENDIF
CLEAN:
-@if exist $(INTDIR)\$(NULL) $(DEL_TREE) $(INTDIR)
-@if exist BccW16.cfg erase BccW16.cfg
-@if exist gvim16.exe erase gvim16.exe
| zyz2011-vim | src/Make_w16.mak | Makefile | gpl2 | 5,560 |
/* 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.
*/
/*
* NextStep has a problem with configure, undefine a few things:
*/
#ifdef NeXT
# ifdef HAVE_UTIME
# undef HAVE_UTIME
# endif
# ifdef HAVE_SYS_UTSNAME_H
# undef HAVE_SYS_UTSNAME_H
# endif
#endif
#include <stdio.h>
#include <ctype.h>
#ifdef VAXC
# include <types.h>
# include <stat.h>
#else
# include <sys/types.h>
# include <sys/stat.h>
#endif
#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#endif
#ifdef __EMX__
# define HAVE_TOTAL_MEM
#endif
#if defined(__CYGWIN__) || defined(__CYGWIN32__)
# define WIN32UNIX /* Compiling for Win32 using Unix files. */
# define BINARY_FILE_IO
# define CASE_INSENSITIVE_FILENAME
# define USE_FNAME_CASE /* Fix filename case differences. */
#endif
/* On AIX 4.2 there is a conflicting prototype for ioctl() in stropts.h and
* unistd.h. This hack should fix that (suggested by Jeff George).
* But on AIX 4.3 it's alright (suggested by Jake Hamby). */
#if defined(FEAT_GUI) && defined(_AIX) && !defined(_AIX43) && !defined(_NO_PROTO)
# define _NO_PROTO
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_LIBC_H
# include <libc.h> /* for NeXT */
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h> /* defines BSD, if it's a BSD system */
#endif
/*
* Sun defines FILE on SunOS 4.x.x, Solaris has a typedef for FILE
*/
#if defined(sun) && !defined(FILE)
# define SOLARIS
#endif
/*
* Using getcwd() is preferred, because it checks for a buffer overflow.
* Don't use getcwd() on systems do use system("sh -c pwd"). There is an
* autoconf check for this.
* Use getcwd() anyway if getwd() isn't present.
*/
#if defined(HAVE_GETCWD) && !(defined(BAD_GETCWD) && defined(HAVE_GETWD))
# define USE_GETCWD
#endif
#ifndef __ARGS
/* The AIX VisualAge cc compiler defines __EXTENDED__ instead of __STDC__
* because it includes pre-ansi features. */
# if defined(__STDC__) || defined(__GNUC__) || defined(__EXTENDED__)
# define __ARGS(x) x
# else
# define __ARGS(x) ()
# endif
#endif
/* always use unlink() to remove files */
#ifndef PROTO
# ifdef VMS
# define mch_remove(x) delete((char *)(x))
# define vim_mkdir(x, y) mkdir((char *)(x), y)
# ifdef VAX
# else
# define mch_rmdir(x) rmdir((char *)(x))
# endif
# else
# define vim_mkdir(x, y) mkdir((char *)(x), y)
# define mch_rmdir(x) rmdir((char *)(x))
# define mch_remove(x) unlink((char *)(x))
# endif
#endif
/* The number of arguments to a signal handler is configured here. */
/* It used to be a long list of almost all systems. Any system that doesn't
* have an argument??? */
#define SIGHASARG
/* List 3 arg systems here. I guess __sgi, please test and correct me. jw. */
#if defined(__sgi) && defined(HAVE_SIGCONTEXT)
# define SIGHAS3ARGS
#endif
#ifdef SIGHASARG
# ifdef SIGHAS3ARGS
# define SIGPROTOARG (int, int, struct sigcontext *)
# define SIGDEFARG(s) (s, sig2, scont) int s, sig2; struct sigcontext *scont;
# define SIGDUMMYARG 0, 0, (struct sigcontext *)0
# else
# define SIGPROTOARG (int)
# define SIGDEFARG(s) (s) int s UNUSED;
# define SIGDUMMYARG 0
# endif
#else
# define SIGPROTOARG (void)
# define SIGDEFARG(s) ()
# define SIGDUMMYARG
#endif
#ifdef HAVE_DIRENT_H
# include <dirent.h>
# ifndef NAMLEN
# define NAMLEN(dirent) strlen((dirent)->d_name)
# endif
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# if HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# if HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# if HAVE_NDIR_H
# include <ndir.h>
# endif
#endif
#if !defined(HAVE_SYS_TIME_H) || defined(TIME_WITH_SYS_TIME)
# include <time.h> /* on some systems time.h should not be
included together with sys/time.h */
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <signal.h>
#if defined(DIRSIZ) && !defined(MAXNAMLEN)
# define MAXNAMLEN DIRSIZ
#endif
#if defined(UFS_MAXNAMLEN) && !defined(MAXNAMLEN)
# define MAXNAMLEN UFS_MAXNAMLEN /* for dynix/ptx */
#endif
#if defined(NAME_MAX) && !defined(MAXNAMLEN)
# define MAXNAMLEN NAME_MAX /* for Linux before .99p3 */
#endif
/*
* Note: if MAXNAMLEN has the wrong value, you will get error messages
* for not being able to open the swap file.
*/
#if !defined(MAXNAMLEN)
# define MAXNAMLEN 512 /* for all other Unix */
#endif
#define BASENAMELEN (MAXNAMLEN - 5)
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#ifdef __COHERENT__
# undef __ARGS
#endif
#if (defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)) \
|| (defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)) \
|| defined(HAVE_SYSCTL) || defined(HAVE_SYSCONF)
# define HAVE_TOTAL_MEM
#endif
#ifdef VMS
# include <unixio.h>
# include <unixlib.h>
# include <signal.h>
# include <file.h>
# include <ssdef.h>
# include <descrip.h>
# include <libclidef.h>
# include <lnmdef.h>
# include <psldef.h>
# include <prvdef.h>
# include <dvidef.h>
# include <dcdef.h>
# include <stsdef.h>
# include <iodef.h>
# include <ttdef.h>
# include <tt2def.h>
# include <jpidef.h>
# include <rms.h>
# include <trmdef.h>
# include <string.h>
# include <starlet.h>
# include <socket.h>
# include <lib$routines.h>
# ifdef FEAT_GUI_GTK
# include "gui_gtk_vms.h"
# endif
typedef struct dsc$descriptor DESC;
#endif
/*
* Unix system-dependent file names
*/
#ifndef SYS_VIMRC_FILE
# define SYS_VIMRC_FILE "$VIM/vimrc"
#endif
#ifndef SYS_GVIMRC_FILE
# define SYS_GVIMRC_FILE "$VIM/gvimrc"
#endif
#ifndef DFLT_HELPFILE
# define DFLT_HELPFILE "$VIMRUNTIME/doc/help.txt"
#endif
#ifndef FILETYPE_FILE
# define FILETYPE_FILE "filetype.vim"
#endif
#ifndef FTPLUGIN_FILE
# define FTPLUGIN_FILE "ftplugin.vim"
#endif
#ifndef INDENT_FILE
# define INDENT_FILE "indent.vim"
#endif
#ifndef FTOFF_FILE
# define FTOFF_FILE "ftoff.vim"
#endif
#ifndef FTPLUGOF_FILE
# define FTPLUGOF_FILE "ftplugof.vim"
#endif
#ifndef INDOFF_FILE
# define INDOFF_FILE "indoff.vim"
#endif
#ifndef SYS_MENU_FILE
# define SYS_MENU_FILE "$VIMRUNTIME/menu.vim"
#endif
#ifndef USR_EXRC_FILE
# ifdef VMS
# define USR_EXRC_FILE "sys$login:.exrc"
# else
# define USR_EXRC_FILE "$HOME/.exrc"
# endif
#endif
#if !defined(USR_EXRC_FILE2) && defined(OS2)
# define USR_EXRC_FILE2 "$VIM/.exrc"
#endif
#if !defined(USR_EXRC_FILE2) && defined(VMS)
# define USR_EXRC_FILE2 "sys$login:_exrc"
#endif
#ifndef USR_VIMRC_FILE
# ifdef VMS
# define USR_VIMRC_FILE "sys$login:.vimrc"
# else
# define USR_VIMRC_FILE "$HOME/.vimrc"
# endif
#endif
#if !defined(USR_VIMRC_FILE2) && defined(OS2)
# define USR_VIMRC_FILE2 "$VIM/.vimrc"
#endif
#if !defined(USR_VIMRC_FILE2) && defined(VMS)
# define USR_VIMRC_FILE2 "sys$login:_vimrc"
#endif
#ifndef USR_GVIMRC_FILE
# ifdef VMS
# define USR_GVIMRC_FILE "sys$login:.gvimrc"
# else
# define USR_GVIMRC_FILE "$HOME/.gvimrc"
# endif
#endif
#ifdef VMS
# ifndef USR_GVIMRC_FILE2
# define USR_GVIMRC_FILE2 "sys$login:_gvimrc"
# endif
#endif
#ifndef EVIM_FILE
# define EVIM_FILE "$VIMRUNTIME/evim.vim"
#endif
#ifdef FEAT_VIMINFO
# ifndef VIMINFO_FILE
# ifdef VMS
# define VIMINFO_FILE "sys$login:.viminfo"
# else
# define VIMINFO_FILE "$HOME/.viminfo"
# endif
# endif
# if !defined(VIMINFO_FILE2) && defined(OS2)
# define VIMINFO_FILE2 "$VIM/.viminfo"
# endif
# if !defined(VIMINFO_FILE2) && defined(VMS)
# define VIMINFO_FILE2 "sys$login:_viminfo"
# endif
#endif
#ifndef EXRC_FILE
# define EXRC_FILE ".exrc"
#endif
#ifndef VIMRC_FILE
# define VIMRC_FILE ".vimrc"
#endif
#ifdef FEAT_GUI
# ifndef GVIMRC_FILE
# define GVIMRC_FILE ".gvimrc"
# endif
#endif
#ifndef SYNTAX_FNAME
# define SYNTAX_FNAME "$VIMRUNTIME/syntax/%s.vim"
#endif
#ifndef DFLT_BDIR
# ifdef OS2
# define DFLT_BDIR ".,c:/tmp,~/tmp,~/"
# else
# ifdef VMS
# define DFLT_BDIR "./,sys$login:,tmp:"
# else
# define DFLT_BDIR ".,~/tmp,~/" /* default for 'backupdir' */
# endif
# endif
#endif
#ifndef DFLT_DIR
# ifdef OS2
# define DFLT_DIR ".,~/tmp,c:/tmp,/tmp"
# else
# ifdef VMS
# define DFLT_DIR "./,sys$login:,tmp:"
# else
# define DFLT_DIR ".,~/tmp,/var/tmp,/tmp" /* default for 'directory' */
# endif
# endif
#endif
#ifndef DFLT_VDIR
# ifdef OS2
# define DFLT_VDIR "$VIM/vimfiles/view"
# else
# ifdef VMS
# define DFLT_VDIR "sys$login:vimfiles/view"
# else
# define DFLT_VDIR "$HOME/.vim/view" /* default for 'viewdir' */
# endif
# endif
#endif
#define DFLT_ERRORFILE "errors.err"
#ifdef OS2
# define DFLT_RUNTIMEPATH "$HOME/vimfiles,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,$HOME/vimfiles/after"
#else
# ifdef VMS
# define DFLT_RUNTIMEPATH "sys$login:vimfiles,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,sys$login:vimfiles/after"
# else
# ifdef RUNTIME_GLOBAL
# define DFLT_RUNTIMEPATH "~/.vim," RUNTIME_GLOBAL ",$VIMRUNTIME," RUNTIME_GLOBAL "/after,~/.vim/after"
# else
# define DFLT_RUNTIMEPATH "~/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,~/.vim/after"
# endif
# endif
#endif
#ifdef OS2
/*
* Try several directories to put the temp files.
*/
# define TEMPDIRNAMES "$TMP", "$TEMP", "c:\\TMP", "c:\\TEMP", ""
# define TEMPNAMELEN 128
#else
# ifdef VMS
# ifndef VAX
# define VMS_TEMPNAM /* to fix default .LIS extension */
# endif
# define TEMPNAME "TMP:v?XXXXXX.txt"
# define TEMPNAMELEN 28
# else
# define TEMPDIRNAMES "$TMPDIR", "/tmp", ".", "$HOME"
# define TEMPNAMELEN 256
# endif
#endif
/* Special wildcards that need to be handled by the shell */
#define SPECIAL_WILDCHAR "`'{"
#ifndef HAVE_OPENDIR
# define NO_EXPANDPATH
#endif
/*
* Unix has plenty of memory, use large buffers
*/
#define CMDBUFFSIZE 1024 /* size of the command processing buffer */
/* Use the system path length if it makes sense. */
#if defined(PATH_MAX) && (PATH_MAX > 1000)
# define MAXPATHL PATH_MAX
#else
# define MAXPATHL 1024
#endif
#define CHECK_INODE /* used when checking if a swap file already
exists for a file */
#ifdef VMS /* Use less memory because of older systems */
# ifndef DFLT_MAXMEM
# define DFLT_MAXMEM (2*1024)
# endif
# ifndef DFLT_MAXMEMTOT
# define DFLT_MAXMEMTOT (5*1024)
# endif
#else
# ifndef DFLT_MAXMEM
# define DFLT_MAXMEM (5*1024) /* use up to 5 Mbyte for a buffer */
# endif
# ifndef DFLT_MAXMEMTOT
# define DFLT_MAXMEMTOT (10*1024) /* use up to 10 Mbyte for Vim */
# endif
#endif
/* memmove is not present on all systems, use memmove, bcopy, memcpy or our
* own version */
/* Some systems have (void *) arguments, some (char *). If we use (char *) it
* works for all */
#ifdef USEMEMMOVE
# define mch_memmove(to, from, len) memmove((char *)(to), (char *)(from), len)
#else
# ifdef USEBCOPY
# define mch_memmove(to, from, len) bcopy((char *)(from), (char *)(to), len)
# else
# ifdef USEMEMCPY
# define mch_memmove(to, from, len) memcpy((char *)(to), (char *)(from), len)
# else
# define VIM_MEMMOVE /* found in misc2.c */
# endif
# endif
#endif
#ifndef PROTO
# ifdef HAVE_RENAME
# define mch_rename(src, dst) rename(src, dst)
# else
int mch_rename __ARGS((const char *src, const char *dest));
# endif
# ifndef VMS
# ifdef __MVS__
/* on OS390 Unix getenv() doesn't return a pointer to persistent
* storage -> use __getenv() */
# define mch_getenv(x) (char_u *)__getenv((char *)(x))
# else
# define mch_getenv(x) (char_u *)getenv((char *)(x))
# endif
# define mch_setenv(name, val, x) setenv(name, val, x)
# endif
#endif
#if !defined(S_ISDIR) && defined(S_IFDIR)
# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
#if !defined(S_ISREG) && defined(S_IFREG)
# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif
#if !defined(S_ISBLK) && defined(S_IFBLK)
# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
#endif
#if !defined(S_ISSOCK) && defined(S_IFSOCK)
# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
#endif
#if !defined(S_ISFIFO) && defined(S_IFIFO)
# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#endif
#if !defined(S_ISCHR) && defined(S_IFCHR)
# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#endif
/* Note: Some systems need both string.h and strings.h (Savage). However,
* some systems can't handle both, only use string.h in that case. */
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#if defined(HAVE_STRINGS_H) && !defined(NO_STRINGS_WITH_STRING_H)
# include <strings.h>
#endif
#if defined(HAVE_SETJMP_H)
# include <setjmp.h>
# ifdef HAVE_SIGSETJMP
# define JMP_BUF sigjmp_buf
# define SETJMP(x) sigsetjmp((x), 1)
# define LONGJMP siglongjmp
# else
# define JMP_BUF jmp_buf
# define SETJMP(x) setjmp(x)
# define LONGJMP longjmp
# endif
#endif
#define HAVE_DUP /* have dup() */
#define HAVE_ST_MODE /* have stat.st_mode */
/* We have three kinds of ACL support. */
#define HAVE_ACL (HAVE_POSIX_ACL || HAVE_SOLARIS_ACL || HAVE_AIX_ACL)
| zyz2011-vim | src/os_unix.h | C | gpl2 | 12,800 |