├── screenshot.png ├── nvim_pygtk3 ├── runtime │ ├── autoload │ │ ├── provider │ │ │ └── clipboard.vim │ │ └── nvim_pygtk3.vim │ └── ginit.vim ├── __init__.py ├── application.py └── window.py ├── share ├── applications │ ├── nvim-pygtk3-term.desktop │ └── nvim-pygtk3.desktop └── icons │ └── hicolor │ └── scalable │ └── apps │ └── neovim.svg ├── LICENSE ├── setup.py ├── .gitignore └── README.md /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rliang/nvim-pygtk3/HEAD/screenshot.png -------------------------------------------------------------------------------- /nvim_pygtk3/runtime/autoload/provider/clipboard.vim: -------------------------------------------------------------------------------- 1 | fu! provider#clipboard#Call(method, args) 2 | retu rpcrequest(g:gui_channel, 'Gui', 'Clipboard', a:method, a:args) 3 | endf 4 | -------------------------------------------------------------------------------- /share/applications/nvim-pygtk3-term.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=Neovim Terminal (PyGTK3) 4 | Icon=neovim 5 | Exec=nvim-pygtk3 +term 6 | Comment=PyGTK3 front-end for the Neovim text editor (Terminal) 7 | Categories=GTK;TerminalEmulator; 8 | -------------------------------------------------------------------------------- /nvim_pygtk3/__init__.py: -------------------------------------------------------------------------------- 1 | from .window import NeovimWindow 2 | from .application import NeovimApplication 3 | 4 | __all__ = ('NeovimWindow', 'NeovimApplication') 5 | 6 | 7 | def main(): 8 | import sys 9 | NeovimApplication(__package__, __path__).run(sys.argv[1:]) 10 | -------------------------------------------------------------------------------- /share/applications/nvim-pygtk3.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=Neovim (PyGTK3) 4 | Icon=neovim 5 | Exec=nvim-pygtk3 -- %F 6 | Comment=PyGTK3 front-end for the Neovim text editor 7 | Categories=GTK;Utility;TextEditor; 8 | MimeType=text/english;text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++; 9 | Terminal=false 10 | -------------------------------------------------------------------------------- /nvim_pygtk3/runtime/ginit.vim: -------------------------------------------------------------------------------- 1 | if exists('g:GuiLoaded') | fini | en 2 | let g:GuiLoaded = 1 3 | 4 | augroup nvim_pygtk3 5 | au! 6 | 7 | au DirChanged,BufEnter,BufLeave * cal nvim_pygtk3#notify_bufs(0) 8 | au TermOpen * cal nvim_pygtk3#notify_bufs(0) 9 | au TextChanged,TextChangedI,BufWritePost * cal nvim_pygtk3#notify_bufs(0) 10 | cal nvim_pygtk3#notify_bufs(0) 11 | 12 | au DirChanged,BufEnter,BufLeave * cal nvim_pygtk3#notify_tabs(0) 13 | au TabEnter,TabLeave,TabNew,TabClosed * cal nvim_pygtk3#notify_tabs(0) 14 | cal nvim_pygtk3#notify_tabs(0) 15 | 16 | au ColorScheme * cal nvim_pygtk3#notify_colors(0) 17 | cal nvim_pygtk3#notify_colors(0) 18 | 19 | au CursorMoved,CursorMovedI * cal nvim_pygtk3#notify_scroll(0) 20 | au FocusGained,FocusLost * cal nvim_pygtk3#notify_scroll(1) 21 | au VimResized * cal nvim_pygtk3#notify_scroll(1) 22 | augroup END 23 | 24 | com! -nargs=? -bang GuiFont cal nvim_pygtk3#notify_font('') 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import gi 3 | gi.require_version('Gtk', '3.0') 4 | 5 | setup(name='nvim-pygtk3', 6 | version='0.3.4', 7 | description='PyGTK3 frontend to Neovim with some visual GUI elements.', 8 | long_description=open('README.md').read(), 9 | author='R. Liang', 10 | author_email='ricardoliang@gmail.com', 11 | url='https://github.com/rliang/nvim-pygtk3', 12 | license='MIT', 13 | keywords='neovim pygtk3 gtk3', 14 | install_requires=['neovim>=0.1.10'], 15 | packages=['nvim_pygtk3'], 16 | package_data={'nvim_pygtk3': ['runtime/*.vim', 17 | 'runtime/**/*.vim', 18 | 'runtime/**/**/*.vim']}, 19 | entry_points={'gui_scripts': ['nvim-pygtk3=nvim_pygtk3:main']}, 20 | data_files=[('share/applications', 21 | ['share/applications/nvim-pygtk3.desktop', 22 | 'share/applications/nvim-pygtk3-term.desktop']), 23 | ('share/icons/hicolor/scalable/apps', 24 | ['share/icons/hicolor/scalable/apps/neovim.svg'])]) 25 | -------------------------------------------------------------------------------- /nvim_pygtk3/application.py: -------------------------------------------------------------------------------- 1 | from gi.repository import GLib, Gio, Gtk 2 | import os 3 | from glob import glob 4 | from uuid import uuid4 5 | from .window import NeovimWindow 6 | 7 | 8 | class NeovimApplication(Gtk.Application): 9 | 10 | def __init__(self, name, path, *args, **kwargs): 11 | super().__init__(*args, 12 | application_id=f'org.{name}', 13 | flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE, 14 | **kwargs) 15 | self.runtime = ','.join(os.path.join(p, 'runtime') for p in path) 16 | self.scripts = os.path.join(GLib.get_user_config_dir(), name, '*.py') 17 | self.scripts = [compile(open(script).read(), script, 'exec') 18 | for script in glob(self.scripts)] 19 | 20 | def do_command_line(self, command_line): 21 | window = NeovimWindow(application=self) 22 | self._configure(window) 23 | window.show_all() 24 | window.present() 25 | GLib.idle_add(window.terminal.spawn, 26 | os.path.join(GLib.get_tmp_dir(), f'nvim-{uuid4()}'), 27 | command_line.get_arguments(), 28 | self.runtime) 29 | 30 | def _configure(self, window): 31 | def connect(obj, sig): 32 | return lambda fun: obj.connect(sig, lambda obj, *args: fun(*args)) 33 | for script in self.scripts: 34 | exec(script, {'window': window, 'connect': connect}) 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Ignore built files 92 | *.out 93 | -------------------------------------------------------------------------------- /nvim_pygtk3/runtime/autoload/nvim_pygtk3.vim: -------------------------------------------------------------------------------- 1 | fu! s:buf_label(nr) 2 | retu fnamemodify(pathshorten(bufname(a:nr)), ":~:.") 3 | endf 4 | 5 | let s:bufs_state=[] 6 | fu! nvim_pygtk3#notify_bufs(force) 7 | let bufs=range(1, bufnr('$')) 8 | let bufs=filter(bufs, {k,v -> bufloaded(v) && buflisted(v)}) 9 | let bufs=map(bufs, {k,v -> [v, s:buf_label(v), getbufvar(v, "&mod")]}) 10 | let state=[bufs, bufnr('%')] 11 | if state != s:bufs_state || a:force 12 | let s:bufs_state = state 13 | cal rpcnotify(g:gui_channel, 'Gui', 'Bufs', state[0], state[1]) 14 | en 15 | endf 16 | 17 | let s:tabs_state=[] 18 | fu! nvim_pygtk3#notify_tabs(force) 19 | let tabs=range(1, tabpagenr('$')) 20 | let tabs=map(tabs, {k,v -> s:buf_label(get(tabpagebuflist(v), 0, 0))}) 21 | let state=[tabs, tabpagenr()] 22 | if state != s:tabs_state || a:force 23 | let s:tabs_state = state 24 | cal rpcnotify(g:gui_channel, 'Gui', 'Tabs', state[0], state[1]) 25 | en 26 | endf 27 | 28 | let s:color_state=[] 29 | fu! nvim_pygtk3#notify_colors(force) 30 | let state=[synIDattr(hlID('Normal'), 'bg'), &bg == 'dark'] 31 | if state != s:color_state || a:force 32 | let s:color_state = state 33 | cal rpcnotify(g:gui_channel, 'Gui', 'Color', state[0], state[1]) 34 | en 35 | endf 36 | 37 | let s:scroll_state=[] 38 | fu! nvim_pygtk3#notify_scroll(force) 39 | let state=[line('w0') - 1, line('w$'), line('$')] 40 | if state != s:scroll_state || a:force 41 | let s:scroll_state = state 42 | cal rpcnotify(g:gui_channel, 'Gui', 'Scroll', state[0], state[1], state[2]) 43 | en 44 | endf 45 | 46 | fu! nvim_pygtk3#notify_font(font) 47 | cal rpcnotify(g:gui_channel, 'Gui', 'Font', a:font) 48 | endf 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nvim-pygtk3 2 | 3 | PyGTK3 frontend to Neovim with some visual GUI elements. 4 | 5 | * Provides GTK's clipboard (no need for xclip/xsel) 6 | * Buffers on header bar 7 | * GUI Tabs 8 | * Overlay scrollbars 9 | * Applies GTK's light/dark themes according to `&bg` 10 | * Applies font from `:GuiFont`, or from GSettings' 11 | `org.gnome.desktop.interface:monospace-font-name` 12 | * Customizable with Python scripts 13 | 14 | ## Preview 15 | 16 | ![](screenshot.png) 17 | 18 | ## Installation 19 | 20 | Requirements: 21 | 22 | * `python 3.6+` 23 | * `python-setuptools` (make) 24 | * `python-neovim` 25 | * `python-gobject` 26 | * `vte3` 27 | 28 | Per-user: 29 | 30 | ```sh 31 | $ python setup.py install --user --root=/ 32 | ``` 33 | 34 | System-wide: 35 | 36 | ```sh 37 | $ sudo python setup.py install --root=/ 38 | ``` 39 | 40 | ## Python scripts 41 | 42 | Scripts in `$XDG_CONFIG_HOME/nvim_pygtk3/*.py` are `exec`'d at startup, 43 | exposing the following globals: 44 | 45 | * `connect`: Utility wrapper to connect GObject signals. 46 | * `window`: The GTK top-level window. 47 | [Docs](https://developer.gnome.org/gtk3/unstable/GtkApplicationWindow.html) 48 | * `window.terminal`: The VTE terminal that hosts neovim. 49 | [Docs](https://developer.gnome.org/vte/unstable/VteTerminal.html) 50 | * `window.switcher`: The GtkStackSwitcher that displays buffers. 51 | [Docs](https://developer.gnome.org/gtk3/unstable/GtkStackSwitcher.html) 52 | * `window.notebook`: The GtkNotebook that displays tabs. 53 | [Docs](https://developer.gnome.org/gtk3/unstable/GtkNotebook.html) 54 | * `window.viewport`: The GtkViewport that holds the terminal. 55 | [Docs](https://developer.gnome.org/gtk3/unstable/GtkViewport.html) 56 | 57 | The `window` object has the following additional signals: 58 | 59 | * `nvim-setup`: Emitted when neovim has started. 60 | * `nvim-notify`: Emitted when neovim has notified the GUI. 61 | * `nvim-request`: Emitted when neovim has requested the GUI. 62 | 63 | Example script `~/.config/nvim_pygtk3/a.py`: 64 | 65 | ```python 66 | @connect(window, 'nvim-setup') 67 | def a(nvim): 68 | nvim.command(f'call rpcnotify({nvim.channel_id}, "hello", "world")') 69 | 70 | @connect(window, 'nvim-notify') 71 | def b(nvim, event, args): 72 | if event == 'hello': 73 | print('hello', args) 74 | 75 | @connect(window.terminal, 'cursor-moved') 76 | def c(): 77 | print('cursor moved!') 78 | ``` 79 | -------------------------------------------------------------------------------- /share/icons/hicolor/scalable/apps/neovim.svg: -------------------------------------------------------------------------------- 1 | 2 | 18 | 20 | 21 | 23 | image/svg+xml 24 | 26 | neovim-mark@2x 27 | 28 | 29 | 30 | 54 | neovim-mark@2x 56 | Created with Sketch (http://www.bohemiancoding.com/sketch) 57 | 59 | 67 | 72 | 77 | 78 | 86 | 90 | 94 | 95 | 103 | 108 | 113 | 114 | 115 | 120 | 124 | 130 | 137 | 143 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /nvim_pygtk3/window.py: -------------------------------------------------------------------------------- 1 | from gi.repository import GObject, GLib, Gio, Gdk, Gtk, Vte, Pango 2 | import neovim 3 | from threading import Thread 4 | from functools import partial 5 | 6 | 7 | class NeovimBufferBar(Gtk.StackSwitcher): 8 | """Widget that displays open buffers as GtkToggleButtons. 9 | 10 | The buttons also indicate modified buffers through a `document-edit` icon. 11 | 12 | To increase performance, buttons are kept in a cache that is increased as 13 | needed. 14 | 15 | """ 16 | 17 | updating = GObject.Property(type=bool, default=False) 18 | 19 | def __init__(self, *args, **kwargs): 20 | super().__init__(*args, **kwargs) 21 | self.btns = [] 22 | self.bids = [] 23 | 24 | @GObject.Signal() 25 | def nvim_switch_buffer(self, id: int): 26 | """Signal emitted when the current buffer should be switched. 27 | 28 | :id: the buffer number to switch to. 29 | 30 | """ 31 | pass 32 | 33 | def _do_button_toggled(self, btn: Gtk.ToggleButton): 34 | """Handler for when a button is toggled. 35 | 36 | Emits `nvim-switch-buffer` if the button was toggled ON, and the widget 37 | isn't in the middle of an update. 38 | 39 | Also avoids toggling off buttons, since the user can't "unswitch" to a 40 | buffer. 41 | 42 | :btn: the toggled button. 43 | 44 | """ 45 | if not self.props.updating: 46 | if btn.get_active(): 47 | id = self.bids[self.btns.index(btn)] 48 | self.emit('nvim-switch-buffer', id) 49 | else: 50 | btn.set_active(True) 51 | 52 | def update(self, buflist: list, bufcurr: int): 53 | """Updates the widget's buttons. 54 | 55 | Increases the internal button cache if needed, then displays the 56 | appropriate amount of buttons, updating their state. 57 | 58 | :buflist: list of tuples (buffer-number, buffer-name, buffer-modified). 59 | :bufcurr: the active buffer's number. 60 | 61 | """ 62 | self.props.updating = True 63 | self.bids = [id for id, *_ in buflist] 64 | for _ in range(len(buflist) - len(self.btns)): 65 | ico = Gtk.Image(icon_name='document-edit-symbolic') 66 | btn = Gtk.ToggleButton(None, can_focus=False, image=ico) 67 | btn.connect('toggled', self._do_button_toggled) 68 | self.btns.append(btn) 69 | for btn in self.get_children(): 70 | self.remove(btn) 71 | for btn, (id, name, modified) in zip(self.btns, buflist): 72 | btn.set_label(name) 73 | btn.set_active(id == bufcurr) 74 | btn.set_always_show_image(modified) 75 | self.add(btn) 76 | self.show_all() 77 | self.props.updating = False 78 | 79 | 80 | class NeovimTabBar(Gtk.Notebook): 81 | """Widget that displays tabs. 82 | 83 | Pages added to this widget are dummies, since the actual content is drawn 84 | elsewhere. 85 | 86 | """ 87 | 88 | updating = GObject.Property(type=bool, default=False) 89 | 90 | def __init__(self, *args, **kwargs): 91 | super().__init__(*args, show_border=False, **kwargs) 92 | self.connect('switch-page', self._do_switch_page) 93 | 94 | @GObject.Signal() 95 | def nvim_switch_tab(self, id: int): 96 | """Signal emitted when the current tab should be switched. 97 | 98 | :id: the tab number to switch to. 99 | 100 | """ 101 | pass 102 | 103 | def _do_switch_page(self, _, page: Gtk.Widget, num: int): 104 | """Handler for when a tab page is selected. 105 | 106 | Emits `nvim-switch-tab` if the widget is not in the middle of an 107 | update. 108 | 109 | :page: the selected tab page. 110 | :num: the selected tab page number. 111 | 112 | """ 113 | if not self.props.updating: 114 | self.emit('nvim-switch-tab', num + 1) 115 | 116 | def update(self, tablist: list, tabcurr: int): 117 | """Updates the widget's tabs. 118 | 119 | :tablist: list of tab names. 120 | :tabcurr: the active buffer's number. 121 | 122 | """ 123 | self.props.updating = True 124 | for _ in range(self.get_n_pages()): 125 | self.remove_page(-1) 126 | for name in tablist: 127 | page = Gtk.Box() 128 | self.append_page(page, Gtk.Label(name)) 129 | self.child_set_property(page, 'tab-expand', True) 130 | self.show_all() 131 | self.set_current_page(tabcurr - 1) 132 | self.set_show_tabs(self.get_n_pages() > 1) 133 | self.props.updating = False 134 | 135 | 136 | class NeovimViewport(Gtk.Viewport): 137 | """Widget that manages scrollbars. 138 | 139 | Typically this should be added to a GtkScrolledWindow, and the widget that 140 | draws neovim's content should be added to this. 141 | 142 | The internal GtkAdjustment's range is forced between [0, 1] to prevent the 143 | child widget from looking overscrolled. 144 | """ 145 | 146 | lines = GObject.Property(type=int, default=1) 147 | updating = GObject.Property(type=bool, default=False) 148 | 149 | def __init__(self, *args, **kwargs): 150 | super().__init__(*args, **kwargs) 151 | vadj = self.get_vadjustment() 152 | vadj.connect('value-changed', self._do_vadjustment_value_changed) 153 | 154 | @GObject.Signal() 155 | def nvim_vscrolled(self, val: int): 156 | """Signal emitted when the current window should be scrolled. 157 | 158 | :val: the line number to scroll to. 159 | 160 | """ 161 | pass 162 | 163 | def _do_vadjustment_value_changed(self, vadj: Gtk.Adjustment): 164 | """Handler for when the GtkAdjustment's value is changed. 165 | 166 | Emits `nvim-vscrolled` if the widget is not in the middle of an 167 | update and the bounds are still valid, i.e. not changed automatically 168 | by GTK. 169 | 170 | :vadj: the adjustment. 171 | 172 | """ 173 | if not self.props.updating and vadj.get_upper() == 1.0: 174 | v = vadj.get_value() 175 | v = v if v == 0.0 else v + vadj.get_page_size() 176 | self.emit('nvim-vscrolled', int(v * self.props.lines)) 177 | 178 | def update(self, a: int, b: int, lines: int): 179 | """Updates the viewport. 180 | 181 | :a: the first visible line of the current window's buffer. 182 | :b: the last visible line of the current window's buffer. 183 | :lines: the current window's buffer's line count. 184 | 185 | """ 186 | self.props.updating = True 187 | a, b, self.props.lines = map(float, (a, b, lines)) 188 | p = (b - a) / self.props.lines 189 | v = (a if a == 0.0 else a + 1.0) / self.props.lines 190 | vadj = self.get_vadjustment() 191 | vadj.configure(v, 0.0, 1.0, 1.0 / self.props.lines, p, p) 192 | self.props.updating = False 193 | 194 | 195 | class NeovimTerminal(Vte.Terminal): 196 | """Widget that manages the child neovim process and displays its content. 197 | 198 | TODO: use a GtkDrawingArea and `Nvim.ui_attach` instead. 199 | 200 | """ 201 | 202 | def __init__(self, *args, **kwargs): 203 | super().__init__(*args, 204 | is_focus=True, 205 | has_focus=True, 206 | pointer_autohide=True, 207 | scrollback_lines=0, 208 | **kwargs) 209 | self.reset_font() 210 | self.reset_color() 211 | 212 | @GObject.Signal() 213 | def nvim_attached(self, nvim: object): 214 | """Signal emitted when successfully attached to neovim's remote API. 215 | 216 | :nvim: the attached `neovim.Nvim` instance. 217 | 218 | """ 219 | pass 220 | 221 | def spawn(self, addr: str, argv: list, rtp: str): 222 | """Spawns the neovim process. 223 | 224 | Upon success, attaches to it and emits `nvim-attached`. 225 | 226 | :addr: the socket path for neovim to listen on. 227 | :argv: additional arguments passed to neovim. 228 | :rtp: additional comma-separated vim runtime paths. 229 | 230 | """ 231 | 232 | def callback(self): 233 | self.disconnect(once) 234 | self.emit('nvim-attached', neovim.attach('socket', path=addr)) 235 | once = self.connect('cursor-moved', callback) 236 | self.spawn_sync(Vte.PtyFlags.DEFAULT, 237 | None, 238 | ['nvim', f'+set rtp^={rtp}', *argv], 239 | [f'NVIM_LISTEN_ADDRESS={addr}'], 240 | GLib.SpawnFlags.SEARCH_PATH, 241 | None, 242 | None, 243 | None) 244 | 245 | def update_font(self, value: str): 246 | """Updates the widget's font. 247 | 248 | :value: see vim's `:h guifont`. 249 | 250 | """ 251 | family, *attrs = value.split(':') 252 | font = Pango.FontDescription(string=family.replace('_', ' ')) 253 | for a in attrs: 254 | if a[0] == 'h': 255 | font.set_size(float(a[1:]) * Pango.SCALE) 256 | if a[0] == 'b': 257 | font.set_weight(Pango.Weight.BOLD) 258 | if a[0] == 'i': 259 | font.set_style(Pango.Style.ITALIC) 260 | self.set_font(font) 261 | 262 | def update_color(self, bg_color: str, is_dark: bool): 263 | """Updates the widget's background color and theme. 264 | 265 | :bg_color: string representing the color, or 'None'. 266 | :is_dark: whether the background is dark, see `:h background`. 267 | 268 | """ 269 | self.get_settings().props.gtk_application_prefer_dark_theme = is_dark 270 | if bg_color != 'None': 271 | rgba = Gdk.RGBA() 272 | rgba.parse(bg_color) 273 | self.set_color_background(rgba) 274 | else: 275 | GLib.idle_add(self.reset_color) 276 | 277 | def reset_font(self): 278 | """Sets the widget's font from GSettings, if any. """ 279 | giosss = Gio.SettingsSchemaSource.get_default() 280 | schema = giosss.lookup('org.gnome.desktop.interface', True) 281 | if not schema: 282 | self.set_font(Pango.FontDescription(string='Monospace')) 283 | return 284 | settings = Gio.Settings(settings_schema=schema) 285 | value = settings.get_string('monospace-font-name') 286 | self.set_font(Pango.FontDescription(string=value)) 287 | 288 | def reset_color(self): 289 | """Sets the widget's backgound color from the GTK theme. """ 290 | sctx = self.get_style_context() 291 | rgba = sctx.get_background_color(sctx.get_state()) 292 | self.set_color_background(rgba) 293 | 294 | 295 | class NeovimWindow(Gtk.ApplicationWindow): 296 | """The main window, which wires neovim and the widgets together. """ 297 | 298 | def __init__(self, *args, **kwargs): 299 | super().__init__(*args, 300 | default_width=640, 301 | default_height=480, 302 | **kwargs) 303 | self.switcher = NeovimBufferBar() 304 | self.set_titlebar(Gtk.HeaderBar(show_close_button=True, 305 | custom_title=self.switcher)) 306 | vbox = Gtk.Box(parent=self, orientation=Gtk.Orientation.VERTICAL) 307 | self.notebook = NeovimTabBar(parent=vbox) 308 | self.viewport = NeovimViewport(parent=Gtk.ScrolledWindow(parent=vbox)) 309 | self.terminal = NeovimTerminal(parent=self.viewport, expand=True) 310 | self.terminal.connect('child-exited', lambda *_: 311 | self.close()) 312 | self.terminal.connect('nvim-attached', lambda _, nvim: 313 | self.emit('nvim-setup', nvim)) 314 | 315 | @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) 316 | def nvim_setup(self, nvim: object): 317 | """Signal emitted before neovim's main loop. 318 | 319 | After the emission, widgets which can control neovim are connected to 320 | the API instance. Then, the main loop's thread is started. 321 | 322 | :nvim: the `neovim.Nvim` instance. 323 | 324 | """ 325 | nvim.vars['gui_channel'] = nvim.channel_id 326 | nvim.subscribe('Gui') 327 | nvim.options['showtabline'] = 0 328 | nvim.options['ruler'] = False 329 | nvim.async_call(partial(nvim.command, 'ru! ginit.vim')) 330 | self.terminal.connect('focus-in-event', lambda *_: 331 | nvim.async_call(partial(nvim.command, 332 | f'do FocusGained'))) 333 | self.terminal.connect('focus-out-event', lambda *_: 334 | nvim.async_call(partial(nvim.command, 335 | f'do FocusLost'))) 336 | self.switcher.connect('nvim-switch-buffer', lambda _, num: 337 | nvim.async_call(partial(nvim.command, 338 | f'b {num}'))) 339 | self.notebook.connect('nvim-switch-tab', lambda _, num: 340 | nvim.async_call(partial(nvim.command, 341 | f'{num}tabn'))) 342 | self.viewport.connect('nvim-vscrolled', lambda _, val: 343 | nvim.async_call(partial(nvim.command, 344 | f'norm! {val}gg'))) 345 | Thread(daemon=True, target=nvim.run_loop, 346 | args=(partial(self.emit, 'nvim-request', nvim), 347 | partial(self.emit, 'nvim-notify', nvim))).start() 348 | 349 | @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) 350 | def nvim_notify(self, nvim: object, sub: str, args: object): 351 | """Signal emitted on a notification from neovim. 352 | 353 | This is called on neovim's event loop, so modifications to GTK widgets 354 | should be done through `GLib.idle_add()`. 355 | 356 | :nvim: the `neovim.Nvim` instance. 357 | :sub: the event name. 358 | :args: the event arguments. 359 | 360 | """ 361 | if sub == 'Gui' and args[0] == 'Bufs': 362 | return GLib.idle_add(self.switcher.update, *args[1:]) 363 | if sub == 'Gui' and args[0] == 'Tabs': 364 | return GLib.idle_add(self.notebook.update, *args[1:]) 365 | if sub == 'Gui' and args[0] == 'Font': 366 | return GLib.idle_add(self.terminal.update_font, *args[1:]) 367 | if sub == 'Gui' and args[0] == 'Color': 368 | return GLib.idle_add(self.terminal.update_color, *args[1:]) 369 | if sub == 'Gui' and args[0] == 'Scroll': 370 | return GLib.idle_add(self.viewport.update, *args[1:]) 371 | 372 | @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) 373 | def nvim_request(self, nvim: object, sub: str, args: object) -> object: 374 | """Signal emitted on a request from neovim. 375 | 376 | This is called on neovim's event loop, so modifications to GTK widgets 377 | should be done through `GLib.idle_add()`. 378 | 379 | After emission, should return an appropriate value expected by the 380 | request. 381 | 382 | :nvim: the `neovim.Nvim` instance. 383 | :sub: the request name. 384 | :args: the request arguments. 385 | 386 | """ 387 | if sub == 'Gui' and args[0] == 'Clipboard': 388 | return self.update_clipboard(*args[1:]) 389 | 390 | def update_clipboard(self, method: str, data: list): 391 | """Handles a clipboard request. 392 | 393 | This is called on neovim's event loop, so modifications to GTK widgets 394 | should be done through `GLib.idle_add()`. 395 | 396 | :method: `get` to obtain the clipboard's contents or `set` to update 397 | them. 398 | :data: when the method is `set`, contains the lines to add to the 399 | clipboard, else None. 400 | :returns: the clipboard's contents when the method is `get`, else None. 401 | 402 | """ 403 | cb = Gtk.Clipboard.get_default(Gdk.Display.get_default()) 404 | if method == 'set': 405 | text = '\n'.join(data[0]) 406 | return cb.set_text(text, len(text)) 407 | if method == 'get': 408 | text = cb.wait_for_text() 409 | return text.split('\n') if text else [] 410 | 411 | --------------------------------------------------------------------------------