Khắc phục lỗi không gõ được tiếng Việt trong Sublime Text 3 trên Ubuntu qua terminal

Di chuyển vào thư mục cài đặt Sublime Text và tạo tệp nguồn C để xử lý input method:

cd /opt/sublime_text/
sudo nano sublime-fcitx-fix.c

Dán đoạn mã sau vào tệp sublime-fcitx-fix.c — mã này giúp đồng bộ vị trí con trỏ với bộ gõ tiếng Việt (fcitx):

#include <gtk/gtk.h>
#include <gdk/gdkx.h>

typedef GdkSegment GdkRegionBox;

struct _GdkRegion {
    long size;
    long numRects;
    GdkRegionBox *rects;
    GdkRegionBox extents;
};

static GtkIMContext* active_im_context = NULL;

void gdk_region_get_clipbox(const GdkRegion* region, GdkRectangle* rect) {
    if (!region || !rect) return;

    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;

    // Nhận diện con trỏ văn bản (chiều rộng = 2 pixel)
    if (rect->width == 2 && GTK_IS_IM_CONTEXT(active_im_context)) {
        gtk_im_context_set_cursor_location(active_im_context, rect);
    }
}

static GdkFilterReturn x11_event_filter(GdkXEvent* xevent, GdkEvent* event, gpointer ctx) {
    XEvent* xev = (XEvent*)xevent;
    if (xev->type == KeyRelease && GTK_IS_IM_CONTEXT(ctx)) {
        GdkWindow* win = g_object_get_data(G_OBJECT(ctx), "target_window");
        if (GDK_IS_WINDOW(win)) {
            gtk_im_context_set_client_window(ctx, win);
        }
    }
    return GDK_FILTER_CONTINUE;
}

void gtk_im_context_set_client_window(GtkIMContext* ctx, GdkWindow* window) {
    GtkIMContextClass* klass = GTK_IM_CONTEXT_GET_CLASS(ctx);
    if (klass->set_client_window) {
        klass->set_client_window(ctx, window);
    }

    if (!GDK_IS_WINDOW(window)) return;

    g_object_set_data(G_OBJECT(ctx), "target_window", window);
    int w = gdk_window_get_width(window);
    int h = gdk_window_get_height(window);

    if (w && h) {
        gtk_im_context_focus_in(ctx);
        active_im_context = ctx;
    }

    gdk_window_add_filter(window, x11_event_filter, ctx);
}

Cài đặt các thư viện cần thiết để biên dịch:

sudo apt update
sudo apt install build-essential libgtk2.0-dev

Biên dịch mã nguồn thành thư viện chia sẻ:

cd /opt/sublime_text/
sudo gcc -shared -o libsublime-inputfix.so sublime-fcitx-fix.c `pkg-config --cflags --libs gtk+-2.0` -fPIC

Sau khi thành công, bạn sẽ thấy tệp libsublime-inputfix.so trong thư mục.

Khởi động thử Sublime Text với thư viện vừa tạo:

LD_PRELOAD=./libsublime-inputfix.so ./sublime_text

Nếu gõ tiếng Việt hoạt động, hãy tích hợp vĩnh viễn bằng cách sửa lệnh subl:

sudo nano /usr/bin/subl

Thêm dòng sau ngay đầu tệp:

export LD_PRELOAD=/opt/sublime_text/libsublime-inputfix.so

Thẻ: sublime-text Ubuntu fctix gcc gtk2

Đăng vào ngày 29 tháng 6 lúc 03:24