• Stars
    star
    188
  • Rank 205,563 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

<neovim-editor> WebComponent to embed Neovim to your app with great ease

<neovim-editor> Web Component

Build Status

This component provides <neovim-editor>, an HTML custom element built on Polymer v2 and flux. It provides a frontend for the Neovim editor using Neovim's MessagePack API. It allows you to easily embed a Neovim-backed editor into your application.

This component assumes to be used in Node.js environment. (i.e. Electron)

You can use this component for modern desktop application frameworks such as Electron or NW.js. You can even use it in Electron-based editors such as Atom or VS Code.

This component is designed around the Flux architecture. You can access the UI event notifications and can call Neovim APIs directly via <neovim-editor>'s APIs.

You can install this component as an npm package.

$ npm install neovim-component

Current supported nvim version is v0.1.6 or later.

Examples

Each example only takes 100~300 lines.

Minimal Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="/path/to/webcomponents-lite.js"></script>
    <link rel="import" href="/path/to/polymer.html" />
    <link rel="import" href="/path/to/neovim-editor.html" />
  </head>
  <body>
    <neovim-editor></neovim-editor>
  </body>
</html>

Minimal Electron app can be found in the example directory. This is a good start point to use this package and it shows how the component works.

main screenshot

How to run minimal example is:

$ git clone https://github.com/rhysd/neovim-component.git
$ cd neovim-component
$ npm start

Markdown Editor Example

For a more complicated and realistic example, see the markdown editor example. The markdown previewer is integrated with the Neovim GUI using the <neovim-editor> component.

markdown example screenshot

Image Popup Example

This is an image popup widget example here. The gi mapping is defined to show an image under the cursor in a tooltip.

image popup example screenshot

Mini Browser Example

This example shows how to include a mini web-browser using the <webview> tag from Electron.

mini browser example screenshot

Why Did You Create This?

Vim has very powerful editing features, but Vim is an editor (see :help design-not) and unfortunately lacks support for many graphical tools that writers and programmers like. NyaoVim adds support for graphical features without losing Vim's powerful text editing abilities. Neovim's msgpack APIs provide a perfect way to add a GUI layer using HTML and CSS. NyaoVim is a GUI frontend as a proof of concept.

Architecture

data flow

<neovim-editor> has an editor property to access the internal APIs of the component.

  • editor.screen is a view of the component (using canvas). It receives user input and dispatches input actions to the data store.
  • editor.process is a process handler to interact with the backing Neovim process via msgpack-rpc APIs. You can call Neovim's APIs via the Neovim client (editor.getClient() helper).
  • editor.store is the state of this component. You can access the current state of the editor through this object.

<neovim-editor> Properties

You can customize <neovim-editor> with the following properties:

Name Description Default
width Width of the editor in pixels. null
height Height of the editor in pixels. null
font Name of the editor's monospace font. "monospace"
font-size Font-size in pixels. 12
line-height Line height rate relative to font size. 1.3
nvim-cmd Command used to start Neovim. "nvim"
argv Arguments passed with the Neovim command. []
on-quit Callback function to run when Neovim quits. null
on-error Callback function for Neovim errors. null
disable-alt-key Do not send alt key input to Neovim. false
disable-meta-key Do not send meta key input to Neovim. false
cursor-draw-delay Delay in millisec before drawing cursor. 10
no-blink-cursor Blink cursor or not. false
window-title Specify first window title. "Neovim"

<neovim-editor> APIs

Receive internal various events

You can receive various events (including UI redraw notifications) from the store. The store is a part of flux architecture. It's a global instance of EventEmitter.

You can also access the state of editor via the store. Note that all values are read only. Do not change the values of the store directly, it will break the internal state of the component.

const neovim_element = document.getElementById('neovim');
const Store = neovim_element.editor.store;

// Handle cursor movements
Store.on('cursor', () => console.log('Cursor is moved to ', Store.cursor));

// Handle mode changes
Store.on('mode', () => console.log('Mode is changed to ', Store.mode));

// Handle text redraws
Store.on('put', () => console.log('UI was redrawn'));

// Accessing the state of the editor.
const bounds = [ Store.size.lines, Store.size.cols ];
const cursor_pos = [ Store.cursor.line, Store.cursor.col ];

Call Neovim APIs

You can call Neovim APIs via the client. When you call APIs via the client, it sends the call to the underlying Neovim process via MessagePack RPC and will return a Promise which resolves to the returned value.

<neovim-component> uses promised-neovim-client package. You can see the all API definitions here. If you know further about Neovim APIs, python client implementation may be helpful.

const neovim_element = document.getElementById('neovim');
const client = neovim_element.editor.getClient();

// Send a command
client.command('vsplit');

// Send input
client.input('<C-w><C-l>');

// Evaluate a Vim script expression
client.eval('"aaa" . "bbb"').then(result => console.log(result));

// Get the 'b:foo' variable
client.getCurrentBuffer()
    .then(buf => buf.getVar('foo'))
    .then(v => console.log(v));

// Query something (windows, buffers, etc.)
// Move to the neighbor window and show its information.
client.getWindows()
    .then(windows => client.secCurrentWindow(windows[1]))
    .then(() => client.getCurrentWindow())
    .then(win => console.log(win));

// Receive an RPC request from Neovim
client.on('request', (n, args, res) => console.log(`Name: ${n}, Args: ${JSON.stringify(args)}, Response: ${res}`));

Editor lifecycle

You can receive notifications related to lifecycle of the editor.

const neovim_element = document.getElementById('neovim');

// Called when the Neovim background process attaches
neovim_element.editor.on('process-attached', () => console.log('Neovim process is ready'));

// Called when the Neovim process is disconnected (usually by :quit)
neovim_element.editor.on('quit', () => console.log('Neovim process died'));

// Called when the <neovim-component> detaches
neovim_element.editor.on('detach', () => console.log('Element does not exist in DOM.'));

// Called upon experiencing an error in the internal process 
neovim_element.editor.on('error', err => alert(err.message));

View APIs

  • Resize screen
const editor = document.getElementById('neovim').editor;
editor.screen.resize(80, 100); // Resize screen to 80 lines and 100 columns
editor.screen.resizeWithPixels(1920, 1080); // Resize screen to 1920px x 1080px
  • Change font size
const editor = document.getElementById('neovim').editor;
editor.screen.changeFontSize(18); // Change font size to 18px
  • Convert pixels to lines/cols.
const editor = document.getElementById('neovim').editor;

const loc = editor.screen.convertPositionToLocation(80, 24);
console.log(loc.x, loc.y);  // Coordinates in pixels of (line, col) = (80, 24)

const pos = editor.screen.convertLocationToPosition(400, 300);
const.log(pos.col, pos.line);  // line/col of location (400px, 300px)
  • Notify of screen-size changes:

When some process has changed the screen-size you must notify the screen. The internal <canvas> element has a fixed size and must update itself if there are size changes. Call screen.checkShouldResize() if the screen size may have changed. Note that you don't need to care about resize event of <body> element. <neovim-editor> component automatically detects this particular resize event and updates automatically. screen.checkShouldResize() will simply be ignored if nothing has actually changed.

const editor = document.getElementById('neovim').editor;

function showUpSomeElementInNeovim() {
    const e = document.getElementById('some-elem');

    // New element shows up!  The screen may be resized by the change.
    // 'none' -> 'block'
    e.style.display = 'block';

    // This call tells to editor to adjust itself in the case that it has been resized
    editor.screen.checkShouldResize();
}

Other APIs

  • Setting arguments afterwards:

If your app doesn't use Polymer you can set arguments afterwards using JavaScript Note that it is better to use argv property of <neovim-element> if possible.

const editor = document.getElementById('neovim').editor;
editor.setArgv(['README.md']);
  • Focusing the editor

<neovim-editor> is just a web-component, so it can be focused just like other elements.
If it loses focus the editor won't receive any input events. The editor instance has a method to re-focus the editor in JavaScript. The store instance contains the current focus state.

const editor = document.getElementById('neovim').editor;
console.log(editor.store.focused);
editor.store.on('focus-changed', () => {
    console.log('Focus was changed: ' + editor.store.focused);
});

// Refocus the editor to ensure it receives user input.
editor.focus();

Log Levels

<neovim-component> prints logs in the browser console. The log level is controlled by the NODE_ENV environment variable:

  • NODE_ENV=debug will log everything.
  • NODE_ENV=production ignores all logs except for warnings and errors.
  • Setting NODE_ENV to empty string or some other value enables logging for info, warnings, and errors.

TODOs

More Repositories

1

vim.wasm

Vim editor ported to WebAssembly
Vim Script
5,305
star
2

actionlint

:octocat: Static checker for GitHub Actions workflow files
Go
2,605
star
3

NyaoVim

Web-enhanced Extensible Neovim Frontend
TypeScript
2,207
star
4

git-messenger.vim

Vim and Neovim plugin to reveal the commit messages under the cursor
Vim Script
1,263
star
5

vim-grammarous

A powerful grammar checker for Vim using LanguageTool.
Vim Script
1,058
star
6

vim-clang-format

Vim plugin for clang-format, a formatter for C, C++, Obj-C, Java, JavaScript, and so on.
Vim Script
1,036
star
7

clever-f.vim

Extended f, F, t and T key mappings for Vim.
Vim Script
968
star
8

Shiba

Rich markdown live preview app with linter
TypeScript
751
star
9

gocaml

🐫 Statically typed functional programming language implementation with Go and LLVM
Go
732
star
10

kiro-editor

A terminal UTF-8 text editor written in Rust 📝🦀
Rust
728
star
11

committia.vim

A Vim plugin for more pleasant editing on commit messages
Vim Script
687
star
12

go-github-selfupdate

Binary self-update mechanism for Go commands using GitHub
Go
527
star
13

conflict-marker.vim

Weapon to fight against conflicts in Vim.
Vim Script
442
star
14

wain

WebAssembly implementation from scratch in Safe Rust with zero dependencies
Rust
425
star
15

hgrep

Grep with human-friendly search results
Rust
419
star
16

electron-about-window

'About This App' mini-window for Electron apps
TypeScript
405
star
17

Mstdn

Tiny web-based mastodon client for your desktop
TypeScript
390
star
18

tui-textarea

Simple yet powerful multi-line text editor widget for ratatui and tui-rs
Rust
287
star
19

vim-color-spring-night

Low-contrast calm color scheme for Vim
Rust
276
star
20

cargo-husky

Setup Git hooks automatically for cargo projects with 🐶
Rust
260
star
21

dot-github

.github directory generator
Go
248
star
22

8cc.vim

C Compiler written in Vim script
Vim Script
227
star
23

vim-startuptime

A small Go program for better `vim --startuptime` alternative
Go
191
star
24

notes-cli

Small markdown note taking CLI app playing nicely with your favorite editor and other CLI tools
Go
191
star
25

dotfiles

dotfiles symbolic links management CLI
Go
191
star
26

reply.vim

REPLs play nicely with :terminal on Vim and Neovim
Vim Script
183
star
27

monolith-of-web

A chrome extension to make a single static HTML file of the web page using a WebAssembly port of monolith CLI
TypeScript
183
star
28

github-complete.vim

Vim input completion for GitHub
Vim Script
168
star
29

Trendy

Menubar app to keep you in the loop of GitHub trends :octocat:
TypeScript
166
star
30

git-brws

Command line tool to open repository, file, commit, diff, tag, pull request, blame, issue or project's website in browser for various repository hosting services.
Rust
166
star
31

devdocs.vim

Open devdocs.io from Vim
Vim Script
164
star
32

react-vimjs

Vim in Your Web App
JavaScript
158
star
33

vim-operator-surround

Vim operator mapping to enclose text objects with surrounds like paren, quote and so on.
Vim Script
137
star
34

react-vim-wasm

Vim editor embedded in your React web application
TypeScript
128
star
35

action-setup-vim

GitHub Action to setup Vim or Neovim on Linux, macOS and Windows for testing Vim plugins
TypeScript
126
star
36

accelerated-jk

A vim plugin to accelerate up-down moving!
Vim Script
125
star
37

dogfiles

dog + dotfiles = dogfiles
Vim Script
120
star
38

vim-gfm-syntax

GitHub Flavored Markdown syntax highlight extension for Vim
Vim Script
117
star
39

wandbox-vim

Wandbox plugin for vimmers. http://melpon.org/wandbox/
Vim Script
108
star
40

fixjson

JSON Fixer for Humans using (relaxed) JSON5
TypeScript
99
star
41

tinyjson

Simple JSON parser/generator for Rust
Rust
97
star
42

remark-emoji

Remark markdown transformer to replace :emoji: in text
JavaScript
93
star
43

YourFukurou

Hackable YoruFukurou alternative Twitter client
TypeScript
88
star
44

vim-lsp-ale

Bridge between vim-lsp and ALE
Vim Script
86
star
45

Dachs

Dachs; A Doggy 🐶 Programming Language
C++
81
star
46

vim-textobj-anyblock

A text object for any of '', "", (), {}, [] and <>.
Vim Script
79
star
47

vim-wasm

WebAssembly filetype support for Vim
Vim Script
77
star
48

world-map-gen

🗺️Random world map generator CLI and library for Rust and WebAssembly
Rust
74
star
49

vim-go-impl

A Vim plugin to use `impl` command
Vim Script
72
star
50

rust-doc.vim

Search Rust documents and open with browser from Vim.
Vim Script
71
star
51

ghci-color

colorize ghci output
PowerShell
71
star
52

electron-in-page-search

Module to introduce Electron's native in-page search avoiding pitfalls
TypeScript
66
star
53

translate-markdown

CLI tool to translate Markdown document with Google translate
JavaScript
66
star
54

tweet-app

Desktop Twitter client only for tweeting. Timeline never shows up.
TypeScript
65
star
55

dirname-filename-esm

__dirname and __filename for ES Modules environment
JavaScript
65
star
56

github-clone-all

Clone (~1000) repos matched to query on GitHub using Search API
Go
63
star
57

Tui

Twitter client based on mobile.twitter.com in menu bar
TypeScript
62
star
58

array_view

Wrapper for references to array in C++.
C++
58
star
59

vim-textobj-ruby

Make text objects with various ruby block structures.
Vim Script
56
star
60

fast-json-clone

Clone plain JSON value faster than the fastest
TypeScript
56
star
61

riscv32-cpu-chisel

Learning how to make RISC-V 32bit CPU with Chisel
Scala
55
star
62

changelog-from-release

Simple changelog generator via GitHub releases
Go
54
star
63

vim-llvm

Vim filetype support for LLVM (including official files)
Vim Script
49
star
64

Tilectron

Tiling window browser built on Electron.
JavaScript
45
star
65

nyaovim-markdown-preview

Live Markdown Preview on NyaoVim
HTML
45
star
66

Chromenu

Mobile Chrome in your menubar
TypeScript
43
star
67

Crisp

Lisp dialect implemented with Crystal
Crystal
43
star
68

path-slash

Tiny Rust library to convert a file path from/to slash path
Rust
41
star
69

open-pdf.vim

Convert pdf file to plain text, cache it and open it quickly in vim using pdftotext.
Vim Script
39
star
70

fixred

Fix outdated links in files with redirect URLs
Rust
35
star
71

ghpr-blame.vim

Vim plugin which is like `git-blame`, but for pull requests on GitHub
Vim Script
34
star
72

vim-healthcheck

Polyfill of Neovim's health-check for Vim
Vim Script
33
star
73

nyaovim-mini-browser

Embedded Mini Browser for NyaoVim
HTML
31
star
74

vim-color-splatoon

Vim Splatoon randomized color scheme. Let's play!
Vim Script
29
star
75

vim-fixjson

Vim plugin for fixjson; a JSON fixer for Humans
Vim Script
24
star
76

unite-redpen.vim

A unite.vim integration of redpen for automatic proof reading
Vim Script
24
star
77

vimwasm-try-plugin

Try Vim plugin on your browser without installing it using vim.wasm!
Go
24
star
78

react-component-octicons

Zero-dependency React component for Octicons
TypeScript
24
star
79

go-fakeio

Small Go library to fake stdout/stderr/stdin mainly for unit testing
Go
24
star
80

unite-codic.vim

A unite.vim source for codic-vim.
Vim Script
23
star
81

vim-goyacc

Vim filetype support for goyacc
Vim Script
22
star
82

gofmtrlx

(a bit) relaxed gofmt
Go
22
star
83

try-colorscheme.vim

Try colorscheme on your Vim without installation
Vim Script
21
star
84

node-github-trend

node.js library for scraping GitHub trending repositories.
TypeScript
20
star
85

node-github-emoji

Node.js library for GitHub Emoji :octocat: with TypeScript support
TypeScript
20
star
86

vim-syntax-christmas-tree

Vim filetype plugin for X'mas
Vim Script
20
star
87

toy-riscv-backend

Toy RISC-V LLVM backend
C++
18
star
88

FrozenString

C++ immutable string library in C++11 constexpr and type-level
C++
18
star
89

nyaovim-tree-view

Tree-view sidebar for NyaoVim
JavaScript
18
star
90

vim-github-actions

(Outdated) Vim syntax/indent support for GitHub Actions *.workflow files
Vim Script
18
star
91

zsh-bundle-exec

No longer need to type in 'bundle exec'.
Shell
17
star
92

locerr

❌ locerr (locational error): Library for nice-looking errors in source code
Go
16
star
93

rhysd

README.md for my profile page
Ruby
16
star
94

unite-ruby-require.vim

A unite.vim source for searching gems to require
Vim Script
15
star
95

vim-textobj-conflict

Vim text object plugin to select conflicts
Vim Script
15
star
96

electron-open-url

Open URL with Electron window from command line or Node.js program
JavaScript
15
star
97

vim-notes-cli

Vim plugin for notes-cli
Vim Script
15
star
98

marked-sanitizer-github

A sanitizer for marked.js which sanitizes HTML elements in markdown with the same manner as GitHub
TypeScript
14
star
99

api-dts

d.ts generator from JSON API response
Go
13
star
100

Irasutoyer

Desktop app for Irasutoya lovers
TypeScript
13
star