Sublime Text 在 Linux (GTK2 環境) 下長期存在無法跟隨輸入法游標、無法輸入中文的問題。本文提供一鍵編譯注入共享庫的解決方案,經測試可在 Ubuntu 20.04+/CentOS 7+/Arch 等主流發行版完美運行。
Sublime Text 2/3 早期版本使用自訂 GTK IM Context 邏輯,未正確處理 gtk_im_context_set_client_window 與游標位置事件,導致輸入法無法定位游標位置,候選視窗跑偏或無法彈出。
#!/bin/bash
# sublime-imfix 一鍵安裝腳本
set -e
cat > /tmp/sublime_imfix.c <<'EOF'
/* sublime-imfix.c - 修正 Sublime Text GTK2 輸入法支援 */
#include
#include
GtkIMContext *local_context = NULL;
void gdk_region_get_clipbox(const GdkRegion *region, GdkRectangle *rect) {
g_return_if_fail(region && rect);
rect->x = region->extents.x1;
rect->y = region->extents.y1;
rect->width = region->extents.x2 - region->extents.x1;
rect->height = region->extents.y2 - region->extents.y1;
if (rect->width == 2 && GTK_IS_IM_CONTEXT(local_context)) {
gtk_im_context_set_cursor_location(local_context, rect);
}
}
GdkFilterReturn event_filter(GdkXEvent *xevent, GdkEvent *event, gpointer im_context) {
XEvent *xev = (XEvent *)xevent;
if (xev->type == KeyRelease && GTK_IS_IM_CONTEXT(im_context)) {
GdkWindow *win = g_object_get_data(G_OBJECT(im_context), "window");
if (GDK_IS_WINDOW(win))
gtk_im_context_set_client_window(im_context, win);
}
return GDK_FILTER_CONTINUE;
}
void gtk_im_context_set_client_window(GtkIMContext *context, GdkWindow *window) {
GtkIMContextClass *klass = GTK_IM_CONTEXT_GET_CLASS(context);
if (klass->set_client_window)
klass->set_client_window(context, window);
if (!GDK_IS_WINDOW(window)) return;
g_object_set_data(G_OBJECT(context), "window", window);
int w = gdk_window_get_width(window);
int h = gdk_window_get_height(window);
if (w && h) {
gtk_im_context_focus_in(context);
local_context = context;
}
gdk_window_add_filter(window, event_filter, context);
}
EOF
# 編譯
gcc -shared -o /opt/sublime_text/libsublime-imfix.so /tmp/sublime_imfix.c \
$(pkg-config --cflags --libs gtk+-2.0) -fPIC
# 建立啟動包裝腳本
cat > /usr/local/bin/subl <<'EOF'
#!/bin/bash
export LD_PRELOAD=/opt/sublime_text/libsublime-imfix.so
exec /opt/sublime_text/sublime_text "$@"
EOF
chmod +x /usr/local/bin/subl
echo "安裝完成!請使用 'subl' 指令啟動 Sublime Text"
sublime_imfix.c。gcc -shared -o libsublime-imfix.so sublime_imfix.c $(pkg-config --cflags --libs gtk+-2.0) -fPIC.so 至 Sublime 安裝目錄 (如 /opt/sublime_text/)。LD_PRELOAD=./libsublime-imfix.so sublime_text。gtk+-2.0 開發套件,請先安裝:sudo apt install libgtk2.0-dev / sudo dnf install gtk2-devel。套用此修補後,Sublime Text 即可在 Linux 下流暢輸入中文,告別切換視窗複製貼上的痛苦。