├── .gitignore ├── pyrightconfig.json ├── caret.gif ├── pyproject.toml ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── rplugin └── python3 │ └── magma │ ├── options.py │ ├── utils.py │ ├── outputbuffer.py │ ├── io.py │ ├── runtime.py │ ├── outputchunks.py │ ├── magmabuffer.py │ ├── images.py │ └── __init__.py ├── autoload └── health │ └── magma.vim ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | -------------------------------------------------------------------------------- /pyrightconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extraPaths": ["rplugin/python3"] 3 | } 4 | -------------------------------------------------------------------------------- /caret.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dccsillag/magma-nvim/HEAD/caret.gif -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 79 3 | 4 | [tool.mypy] 5 | ignore_missing_imports = true 6 | strict = true 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[Feature Request] " 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[Bug] " 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /rplugin/python3/magma/options.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from pynvim import Nvim 4 | 5 | 6 | class MagmaOptions: 7 | automatically_open_output: bool 8 | wrap_output: bool 9 | output_window_borders: bool 10 | show_mimetype_debug: bool 11 | cell_highlight_group: str 12 | save_path: str 13 | image_provider: str 14 | copy_output: bool 15 | 16 | def __init__(self, nvim: Nvim): 17 | self.automatically_open_output = nvim.vars.get( 18 | "magma_automatically_open_output", True 19 | ) 20 | self.wrap_output = nvim.vars.get("magma_wrap_output", False) 21 | self.output_window_borders = nvim.vars.get( 22 | "magma_output_window_borders", True 23 | ) 24 | self.show_mimetype_debug = nvim.vars.get( 25 | "magma_show_mimetype_debug", False 26 | ) 27 | self.cell_highlight_group = nvim.vars.get( 28 | "magma_cell_highlight_group", "CursorLine" 29 | ) 30 | self.save_path = nvim.vars.get( 31 | "magma_save_cell", 32 | os.path.join(nvim.funcs.stdpath("data"), "magma"), 33 | ) 34 | self.image_provider = nvim.vars.get("magma_image_provider", "none") 35 | self.copy_output = nvim.vars.get( 36 | "magma_copy_output", False 37 | ) 38 | -------------------------------------------------------------------------------- /autoload/health/magma.vim: -------------------------------------------------------------------------------- 1 | function! s:python_has_module(module) abort 2 | python3 import importlib 3 | return py3eval("importlib.util.find_spec(vim.eval('a:module')) is not None") 4 | endfunction 5 | 6 | function! s:python_module_check(module, pip_package) abort 7 | if s:python_has_module(a:module) 8 | call health#report_ok('Python package ' .. a:pip_package .. ' found') 9 | else 10 | call health#report_error('Python package ' .. a:pip_package .. ' not found', 11 | \ ['pip install ' .. a:pip_package]) 12 | endif 13 | endfunction 14 | 15 | function! health#magma#check() abort 16 | call health#report_start('requirements') 17 | 18 | if has("nvim-0.5") 19 | call health#report_ok('NeoVim >=0.5') 20 | else 21 | call health#report_error('magma-nvim requires NeoVim >=0.5') 22 | endif 23 | 24 | if !has("python3") 25 | call health#report_error('magma-nvim requires a Python provider to be configured!') 26 | return 27 | endif 28 | 29 | python3 import sys 30 | if py3eval("sys.version_info.major == 3 and sys.version_info.minor >= 8") 31 | call health#report_ok('Python >=3.8') 32 | else 33 | call health#report_error('magma-nvim requires Python >=3.8') 34 | endif 35 | 36 | call s:python_module_check("pynvim", "pynvim") 37 | call s:python_module_check("jupyter_client", "jupyter-client") 38 | call s:python_module_check("ueberzug", "ueberzug") 39 | call s:python_module_check("PIL", "Pillow") 40 | call s:python_module_check("cairosvg", "cairosvg") 41 | call s:python_module_check("pnglatex", "pnglatex") 42 | call s:python_module_check("plotly", "plotly") 43 | call s:python_module_check("kaleido", "kaleido") 44 | endfunction 45 | -------------------------------------------------------------------------------- /rplugin/python3/magma/utils.py: -------------------------------------------------------------------------------- 1 | from typing import Union, List 2 | 3 | from pynvim import Nvim 4 | 5 | 6 | class MagmaException(Exception): 7 | pass 8 | 9 | 10 | def nvimui(func): # type: ignore 11 | def inner(self, *args, **kwargs): # type: ignore 12 | try: 13 | func(self, *args, **kwargs) 14 | except MagmaException as err: 15 | self.nvim.err_write("[Magma] " + str(err) + "\n") 16 | 17 | return inner 18 | 19 | 20 | class Position: 21 | bufno: int 22 | lineno: int 23 | colno: int 24 | 25 | def __init__(self, bufno: int, lineno: int, colno: int): 26 | self.bufno = bufno 27 | self.lineno = lineno 28 | self.colno = colno 29 | 30 | def __lt__(self, other: "Position") -> bool: 31 | return (self.lineno, self.colno) < (other.lineno, other.colno) 32 | 33 | def __le__(self, other: "Position") -> bool: 34 | return (self.lineno, self.colno) <= (other.lineno, other.colno) 35 | 36 | 37 | class DynamicPosition(Position): 38 | nvim: Nvim 39 | extmark_namespace: int 40 | bufno: int 41 | 42 | extmark_id: int 43 | 44 | def __init__( 45 | self, 46 | nvim: Nvim, 47 | extmark_namespace: int, 48 | bufno: int, 49 | lineno: int, 50 | colno: int, 51 | ): 52 | self.nvim = nvim 53 | self.extmark_namespace = extmark_namespace 54 | 55 | self.bufno = bufno 56 | self.extmark_id = self.nvim.funcs.nvim_buf_set_extmark( 57 | self.bufno, extmark_namespace, lineno, colno, {} 58 | ) 59 | 60 | def __del__(self) -> None: 61 | self.nvim.funcs.nvim_buf_del_extmark( 62 | self.bufno, self.extmark_namespace, self.extmark_id 63 | ) 64 | 65 | def _get_pos(self) -> List[int]: 66 | out = self.nvim.funcs.nvim_buf_get_extmark_by_id( 67 | self.bufno, self.extmark_namespace, self.extmark_id, {} 68 | ) 69 | assert isinstance(out, list) and all(isinstance(x, int) for x in out) 70 | return out 71 | 72 | @property 73 | def lineno(self) -> int: # type: ignore 74 | return self._get_pos()[0] 75 | 76 | @property 77 | def colno(self) -> int: # type: ignore 78 | return self._get_pos()[1] 79 | 80 | 81 | class Span: 82 | begin: Union[Position, DynamicPosition] 83 | end: Union[Position, DynamicPosition] 84 | 85 | def __init__( 86 | self, 87 | begin: Union[Position, DynamicPosition], 88 | end: Union[Position, DynamicPosition], 89 | ): 90 | self.begin = begin 91 | self.end = end 92 | 93 | def __contains__(self, pos: Union[Position, DynamicPosition]) -> bool: 94 | return self.begin <= pos and pos < self.end 95 | 96 | def get_text(self, nvim: Nvim) -> str: 97 | assert self.begin.bufno == self.end.bufno 98 | bufno = self.begin.bufno 99 | 100 | lines: List[str] = nvim.funcs.nvim_buf_get_lines( 101 | bufno, self.begin.lineno, self.end.lineno + 1, True 102 | ) 103 | 104 | if len(lines) == 1: 105 | return lines[0][self.begin.colno : self.end.colno] 106 | else: 107 | return "\n".join( 108 | [lines[0][self.begin.colno :]] 109 | + lines[1:-1] 110 | + [lines[-1][: self.end.colno]] 111 | ) 112 | -------------------------------------------------------------------------------- /rplugin/python3/magma/outputbuffer.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from pynvim import Nvim 4 | from pynvim.api import Buffer 5 | 6 | from magma.images import Canvas 7 | from magma.outputchunks import Output, OutputStatus 8 | from magma.options import MagmaOptions 9 | from magma.utils import Position 10 | 11 | 12 | class OutputBuffer: 13 | nvim: Nvim 14 | canvas: Canvas 15 | 16 | output: Output 17 | 18 | display_buffer: Buffer 19 | display_window: Optional[int] 20 | 21 | options: MagmaOptions 22 | 23 | def __init__(self, nvim: Nvim, canvas: Canvas, options: MagmaOptions): 24 | self.nvim = nvim 25 | self.canvas = canvas 26 | 27 | self.output = Output(None) 28 | 29 | self.display_buffer = self.nvim.buffers[ 30 | self.nvim.funcs.nvim_create_buf(False, True) 31 | ] 32 | self.display_window = None 33 | 34 | self.options = options 35 | 36 | def _buffer_to_window_lineno(self, lineno: int) -> int: 37 | win_top = self.nvim.funcs.line("w0") 38 | assert isinstance(win_top, int) 39 | return lineno - win_top + 1 40 | 41 | def _get_header_text(self, output: Output) -> str: 42 | if output.execution_count is None: 43 | execution_count = "..." 44 | else: 45 | execution_count = str(output.execution_count) 46 | 47 | if output.status == OutputStatus.HOLD: 48 | status = "* On Hold" 49 | elif output.status == OutputStatus.DONE: 50 | if output.success: 51 | status = "✓ Done" 52 | else: 53 | status = "✗ Failed" 54 | elif output.status == OutputStatus.RUNNING: 55 | status = "... Running" 56 | else: 57 | raise ValueError("bad output.status: %s" % output.status) 58 | 59 | if output.old: 60 | old = "[OLD] " 61 | else: 62 | old = "" 63 | 64 | return f"{old}Out[{execution_count}]: {status}" 65 | 66 | def enter(self) -> None: 67 | if self.display_window is not None: # TODO open window if is None? 68 | self.nvim.funcs.nvim_set_current_win(self.display_window) 69 | 70 | def clear_interface(self) -> None: 71 | if self.display_window is not None: 72 | self.nvim.funcs.nvim_win_close(self.display_window, True) 73 | self.display_window = None 74 | 75 | def show(self, anchor: Position) -> None: # XXX .show_outputs(_, anchor) 76 | # FIXME use `anchor.buffer`, Not `self.nvim.current.window` 77 | 78 | # Get width&height, etc 79 | win_col = self.nvim.current.window.col 80 | win_row = self._buffer_to_window_lineno(anchor.lineno + 1) 81 | win_width = self.nvim.current.window.width 82 | win_height = self.nvim.current.window.height 83 | if self.options.output_window_borders: 84 | win_height -= 2 85 | 86 | # Clear buffer: 87 | self.nvim.funcs.deletebufline(self.display_buffer.number, 1, "$") 88 | # Add output chunks to buffer 89 | lines_str = "" 90 | lineno = 0 91 | shape = (win_col, win_row, win_width, win_height) 92 | if len(self.output.chunks) > 0: 93 | for chunk in self.output.chunks: 94 | chunktext = chunk.place( 95 | self.options, lineno, shape, self.canvas 96 | ) 97 | lines_str += chunktext 98 | lineno += chunktext.count("\n") 99 | lines = lines_str.rstrip().split("\n") 100 | actualLines = [] 101 | for line in lines: 102 | parts = line.split('\r') 103 | last = parts[-1] 104 | if last != "": 105 | actualLines.append(last) 106 | lines = actualLines 107 | lineno = len(lines) 108 | else: 109 | lines = [lines_str] 110 | self.display_buffer[0] = self._get_header_text(self.output) # TODO 111 | self.display_buffer.append(lines) 112 | 113 | # Open output window 114 | assert self.display_window is None 115 | if win_row < win_height: 116 | self.display_window = self.nvim.funcs.nvim_open_win( 117 | self.display_buffer.number, 118 | False, 119 | { 120 | "relative": "win", 121 | "col": 0, 122 | "row": win_row, 123 | "width": win_width, 124 | "height": min(win_height - win_row, lineno + 1), 125 | "anchor": "NW", 126 | "style": None 127 | if self.options.output_window_borders 128 | else "minimal", 129 | "border": "rounded" 130 | if self.options.output_window_borders 131 | else "none", 132 | "focusable": False, 133 | }, 134 | ) 135 | # self.nvim.funcs.nvim_win_set_option( 136 | # self.display_window, "wrap", True 137 | # ) 138 | -------------------------------------------------------------------------------- /rplugin/python3/magma/io.py: -------------------------------------------------------------------------------- 1 | from typing import Type, Optional, Dict, Any 2 | import os 3 | 4 | from pynvim.api import Buffer 5 | 6 | from magma.utils import MagmaException, Span, DynamicPosition 7 | from magma.options import MagmaOptions 8 | from magma.outputchunks import OutputStatus, Output, to_outputchunk 9 | from magma.outputbuffer import OutputBuffer 10 | from magma.magmabuffer import MagmaBuffer 11 | 12 | 13 | class MagmaIOError(Exception): 14 | @classmethod 15 | def assert_has_key( 16 | cls, data: Dict[str, Any], key: str, type_: Optional[Type[Any]] = None 17 | ) -> Any: 18 | if key not in data: 19 | raise cls(f"Missing key: {key}") 20 | value = data[key] 21 | if type_ is not None and not isinstance(value, type_): 22 | raise cls( 23 | f"Incorrect type for key '{key}': expected {type_.__name__}, \ 24 | got {type(value).__name__}" 25 | ) 26 | return value 27 | 28 | 29 | def get_default_save_file(options: MagmaOptions, buffer: Buffer) -> str: 30 | # XXX: this is string containment checking. Beware. 31 | if "nofile" in buffer.options["buftype"]: 32 | raise MagmaException("Buffer does not correspond to a file") 33 | 34 | mangled_name = buffer.name.replace("%", "%%").replace("/", "%") 35 | 36 | return os.path.join(options.save_path, mangled_name + ".json") 37 | 38 | 39 | def load(magmabuffer: MagmaBuffer, data: Dict[str, Any]) -> None: 40 | MagmaIOError.assert_has_key(data, "content_checksum", str) 41 | 42 | if magmabuffer._get_content_checksum() != data["content_checksum"]: 43 | raise MagmaIOError("Buffer contents' checksum does not match!") 44 | 45 | MagmaIOError.assert_has_key(data, "cells", list) 46 | for cell in data["cells"]: 47 | MagmaIOError.assert_has_key(cell, "span", dict) 48 | MagmaIOError.assert_has_key(cell["span"], "begin", dict) 49 | MagmaIOError.assert_has_key(cell["span"]["begin"], "lineno", int) 50 | MagmaIOError.assert_has_key(cell["span"]["begin"], "colno", int) 51 | MagmaIOError.assert_has_key(cell["span"], "end", dict) 52 | MagmaIOError.assert_has_key(cell["span"]["end"], "lineno", int) 53 | MagmaIOError.assert_has_key(cell["span"]["end"], "colno", int) 54 | begin_position = DynamicPosition( 55 | magmabuffer.nvim, 56 | magmabuffer.extmark_namespace, 57 | magmabuffer.buffer.number, 58 | cell["span"]["begin"]["lineno"], 59 | cell["span"]["begin"]["colno"], 60 | ) 61 | end_position = DynamicPosition( 62 | magmabuffer.nvim, 63 | magmabuffer.extmark_namespace, 64 | magmabuffer.buffer.number, 65 | cell["span"]["end"]["lineno"], 66 | cell["span"]["end"]["colno"], 67 | ) 68 | span = Span(begin_position, end_position) 69 | 70 | # XXX: do we really want to have the execution count here? 71 | # what happens when the counts start to overlap? 72 | MagmaIOError.assert_has_key(cell, "execution_count", int) 73 | output = Output(cell["execution_count"]) 74 | 75 | MagmaIOError.assert_has_key(cell, "status", int) 76 | output.status = OutputStatus(cell["status"]) 77 | 78 | MagmaIOError.assert_has_key(cell, "success", bool) 79 | output.success = cell["success"] 80 | 81 | MagmaIOError.assert_has_key(cell, "chunks", list) 82 | for chunk in cell["chunks"]: 83 | MagmaIOError.assert_has_key(chunk, "data", dict) 84 | MagmaIOError.assert_has_key(chunk, "metadata", dict) 85 | output.chunks.append( 86 | to_outputchunk( 87 | magmabuffer.runtime._alloc_file, 88 | chunk["data"], 89 | chunk["metadata"], 90 | ) 91 | ) 92 | 93 | output.old = True 94 | 95 | magmabuffer.outputs[span] = OutputBuffer( 96 | magmabuffer.nvim, magmabuffer.canvas, magmabuffer.options 97 | ) 98 | 99 | 100 | def save(magmabuffer: MagmaBuffer) -> Dict[str, Any]: 101 | return { 102 | "version": 1, 103 | "kernel": magmabuffer.runtime.kernel_name, 104 | "content_checksum": magmabuffer._get_content_checksum(), 105 | "cells": [ 106 | { 107 | "span": { 108 | "begin": { 109 | "lineno": span.begin.lineno, 110 | "colno": span.begin.colno, 111 | }, 112 | "end": { 113 | "lineno": span.end.lineno, 114 | "colno": span.end.colno, 115 | }, 116 | }, 117 | "execution_count": output.output.execution_count, 118 | "status": output.output.status.value, 119 | "success": output.output.success, 120 | "chunks": [ 121 | { 122 | "data": chunk.jupyter_data, 123 | "metadata": chunk.jupyter_metadata, 124 | } 125 | for chunk in output.output.chunks 126 | if chunk.jupyter_data is not None 127 | and chunk.jupyter_metadata is not None 128 | ], 129 | } 130 | for span, output in magmabuffer.outputs.items() 131 | ], 132 | } 133 | -------------------------------------------------------------------------------- /rplugin/python3/magma/runtime.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Tuple, List, Dict, Generator, IO, Any 2 | from enum import Enum 3 | from contextlib import contextmanager 4 | from queue import Empty as EmptyQueueException 5 | import os 6 | import tempfile 7 | import json 8 | 9 | import jupyter_client 10 | 11 | from magma.options import MagmaOptions 12 | from magma.outputchunks import ( 13 | Output, 14 | MimetypesOutputChunk, 15 | ErrorOutputChunk, 16 | TextOutputChunk, 17 | OutputStatus, 18 | to_outputchunk, 19 | clean_up_text 20 | ) 21 | 22 | 23 | class RuntimeState(Enum): 24 | STARTING = 0 25 | IDLE = 1 26 | RUNNING = 2 27 | 28 | 29 | class JupyterRuntime: 30 | state: RuntimeState 31 | kernel_name: str 32 | 33 | kernel_manager: jupyter_client.KernelManager 34 | kernel_client: jupyter_client.KernelClient 35 | 36 | allocated_files: List[str] 37 | 38 | options: MagmaOptions 39 | 40 | def __init__(self, kernel_name: str, options: MagmaOptions): 41 | self.state = RuntimeState.STARTING 42 | self.kernel_name = kernel_name 43 | 44 | if ".json" not in self.kernel_name: 45 | 46 | self.external_kernel = True 47 | self.kernel_manager = jupyter_client.manager.KernelManager( 48 | kernel_name=kernel_name 49 | ) 50 | self.kernel_manager.start_kernel() 51 | self.kernel_client = self.kernel_manager.client() 52 | assert isinstance( 53 | self.kernel_client, 54 | jupyter_client.blocking.client.BlockingKernelClient, 55 | ) 56 | self.kernel_client.start_channels() 57 | 58 | self.allocated_files = [] 59 | 60 | self.options = options 61 | 62 | else: 63 | kernel_file = kernel_name 64 | self.external_kernel = True 65 | # Opening JSON file 66 | kernel_json = json.load(open(kernel_file)) 67 | # we have a kernel json 68 | self.kernel_manager = jupyter_client.manager.KernelManager( 69 | kernel_name=kernel_json["kernel_name"] 70 | ) 71 | self.kernel_client = self.kernel_manager.client() 72 | 73 | self.kernel_client.load_connection_file(connection_file=kernel_file) 74 | 75 | self.allocated_files = [] 76 | 77 | self.options = options 78 | 79 | def is_ready(self) -> bool: 80 | return self.state.value > RuntimeState.STARTING.value 81 | 82 | def deinit(self) -> None: 83 | for path in self.allocated_files: 84 | if os.path.exists(path): 85 | os.remove(path) 86 | 87 | if self.external_kernel is False: 88 | self.kernel_client.shutdown() 89 | 90 | def interrupt(self) -> None: 91 | self.kernel_manager.interrupt_kernel() 92 | 93 | def restart(self) -> None: 94 | self.state = RuntimeState.STARTING 95 | self.kernel_manager.restart_kernel() 96 | 97 | def run_code(self, code: str) -> None: 98 | self.kernel_client.execute(code) 99 | 100 | @contextmanager 101 | def _alloc_file( 102 | self, extension: str, mode: str 103 | ) -> Generator[Tuple[str, IO[bytes]], None, None]: 104 | with tempfile.NamedTemporaryFile( 105 | suffix="." + extension, mode=mode, delete=False 106 | ) as file: 107 | path = file.name 108 | yield path, file 109 | self.allocated_files.append(path) 110 | 111 | def _append_chunk( 112 | self, output: Output, data: Dict[str, Any], metadata: Dict[str, Any] 113 | ) -> None: 114 | if self.options.show_mimetype_debug: 115 | output.chunks.append(MimetypesOutputChunk(list(data.keys()))) 116 | 117 | output.chunks.append(to_outputchunk(self._alloc_file, data, metadata)) 118 | 119 | def _tick_one( 120 | self, output: Output, message_type: str, content: Dict[str, Any] 121 | ) -> bool: 122 | 123 | def copy_on_demand(content_ctor): 124 | if self.options.copy_output: 125 | import pyperclip 126 | if type(content_ctor) is str: 127 | pyperclip.copy(content_ctor) 128 | else: 129 | pyperclip.copy(content_ctor()) 130 | 131 | if output._should_clear: 132 | output.chunks.clear() 133 | output._should_clear = False 134 | 135 | if message_type == "execute_input": 136 | output.execution_count = content["execution_count"] 137 | if self.external_kernel is False: 138 | assert output.status != OutputStatus.DONE 139 | if output.status == OutputStatus.HOLD: 140 | output.status = OutputStatus.RUNNING 141 | elif output.status == OutputStatus.RUNNING: 142 | output.status = OutputStatus.DONE 143 | else: 144 | raise ValueError( 145 | "bad value for output.status: %r" % output.status 146 | ) 147 | return True 148 | elif message_type == "status": 149 | execution_state = content["execution_state"] 150 | assert execution_state != "starting" 151 | if execution_state == "idle": 152 | self.state = RuntimeState.IDLE 153 | output.status = OutputStatus.DONE 154 | return True 155 | elif execution_state == "busy": 156 | self.state = RuntimeState.RUNNING 157 | return True 158 | else: 159 | return False 160 | elif message_type == "execute_reply": 161 | # This doesn't really give us any relevant information. 162 | return False 163 | elif message_type == "execute_result": 164 | self._append_chunk(output, content["data"], content["metadata"]) 165 | if 'text/plain' in content['data']: 166 | copy_on_demand(content["data"]['text/plain']) 167 | return True 168 | elif message_type == "error": 169 | output.chunks.append( 170 | ErrorOutputChunk( 171 | content["ename"], content["evalue"], content["traceback"] 172 | ) 173 | ) 174 | copy_on_demand(lambda: "\n\n".join(map(clean_up_text, content["traceback"]))) 175 | output.success = False 176 | return True 177 | elif message_type == "stream": 178 | copy_on_demand(content["text"]) 179 | output.chunks.append(TextOutputChunk(content["text"])) 180 | return True 181 | elif message_type == "display_data": 182 | # XXX: consider content['transient'], if we end up saving execution 183 | # outputs. 184 | self._append_chunk(output, content["data"], content["metadata"]) 185 | return True 186 | elif message_type == "update_display_data": 187 | # We don't really want to bother with this type of message. 188 | return False 189 | elif message_type == "clear_output": 190 | if content["wait"]: 191 | output._should_clear = True 192 | else: 193 | output.chunks.clear() 194 | return True 195 | # TODO: message_type == 'debug'? 196 | else: 197 | return False 198 | 199 | def tick(self, output: Optional[Output]) -> bool: 200 | did_stuff = False 201 | 202 | assert isinstance( 203 | self.kernel_client, 204 | jupyter_client.blocking.client.BlockingKernelClient, 205 | ) 206 | 207 | if not self.is_ready(): 208 | try: 209 | self.kernel_client.wait_for_ready(timeout=0) 210 | self.state = RuntimeState.IDLE 211 | did_stuff = True 212 | except RuntimeError: 213 | return False 214 | 215 | if output is None: 216 | return did_stuff 217 | 218 | while True: 219 | try: 220 | message = self.kernel_client.get_iopub_msg(timeout=0) 221 | 222 | if "content" not in message or "msg_type" not in message: 223 | continue 224 | 225 | did_stuff_now = self._tick_one( 226 | output, message["msg_type"], message["content"] 227 | ) 228 | did_stuff = did_stuff or did_stuff_now 229 | 230 | if output.status == OutputStatus.DONE: 231 | break 232 | except EmptyQueueException: 233 | break 234 | 235 | return did_stuff 236 | 237 | 238 | def get_available_kernels() -> List[str]: 239 | return list(jupyter_client.kernelspec.find_kernel_specs().keys()) 240 | -------------------------------------------------------------------------------- /rplugin/python3/magma/outputchunks.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Optional, 3 | Tuple, 4 | List, 5 | Dict, 6 | Any, 7 | Callable, 8 | IO, 9 | ) 10 | from contextlib import AbstractContextManager 11 | from enum import Enum 12 | from abc import ABC, abstractmethod 13 | from math import floor 14 | import re 15 | import textwrap 16 | import os 17 | 18 | from magma.images import Canvas 19 | from magma.options import MagmaOptions 20 | 21 | 22 | class OutputChunk(ABC): 23 | jupyter_data: Optional[Dict[str, Any]] = None 24 | jupyter_metadata: Optional[Dict[str, Any]] = None 25 | 26 | @abstractmethod 27 | def place( 28 | self, 29 | options: MagmaOptions, 30 | lineno: int, 31 | shape: Tuple[int, int, int, int], 32 | canvas: Canvas, 33 | ) -> str: 34 | pass 35 | 36 | # Adapted from [https://stackoverflow.com/a/14693789/4803382]: 37 | ANSI_CODE_REGEX = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") 38 | def clean_up_text(text: str) -> str: 39 | text = ANSI_CODE_REGEX.sub("", text) 40 | text = text.replace("\r\n", "\n") 41 | return text 42 | 43 | class TextOutputChunk(OutputChunk): 44 | text: str 45 | 46 | def __init__(self, text: str): 47 | self.text = text 48 | 49 | def _cleanup_text(self, text: str) -> str: 50 | return clean_up_text(text) 51 | 52 | def place( 53 | self, 54 | options: MagmaOptions, 55 | _: int, 56 | shape: Tuple[int, int, int, int], 57 | __: Canvas, 58 | ) -> str: 59 | text = self._cleanup_text(self.text) 60 | if options.wrap_output: 61 | win_width = shape[2] 62 | text = "\n".join( 63 | "\n".join(textwrap.wrap(line, width=win_width)) 64 | for line in text.split("\n") 65 | ) 66 | return text 67 | 68 | 69 | class TextLnOutputChunk(TextOutputChunk): 70 | def __init__(self, text: str): 71 | super().__init__(text + "\n") 72 | 73 | 74 | class BadOutputChunk(TextLnOutputChunk): 75 | def __init__(self, mimetypes: List[str]): 76 | super().__init__( 77 | "" % mimetypes 78 | ) 79 | 80 | 81 | class MimetypesOutputChunk(TextLnOutputChunk): 82 | def __init__(self, mimetypes: List[str]): 83 | super().__init__("[DEBUG] Received mimetypes: %r" % mimetypes) 84 | 85 | 86 | class ErrorOutputChunk(TextLnOutputChunk): 87 | def __init__(self, name: str, message: str, traceback: List[str]): 88 | super().__init__( 89 | "\n".join( 90 | [ 91 | f"[Error] {name}: {message}", 92 | "Traceback:", 93 | ] 94 | + traceback 95 | ) 96 | ) 97 | 98 | 99 | class AbortedOutputChunk(TextLnOutputChunk): 100 | def __init__(self) -> None: 101 | super().__init__("") 102 | 103 | 104 | class ImageOutputChunk(OutputChunk): 105 | def __init__( 106 | self, img_path: str, img_checksum: str, img_shape: Tuple[int, int] 107 | ): 108 | self.img_path = img_path 109 | self.img_checksum = img_checksum 110 | self.img_width, self.img_height = img_shape 111 | 112 | def _get_char_pixelsize(self) -> Optional[Tuple[int, int]]: 113 | import termios 114 | import fcntl 115 | import struct 116 | 117 | # FIXME: This is not really in Ueberzug's public API. 118 | # We should move this function into this codebase. 119 | try: 120 | from ueberzug.process import get_pty_slave 121 | except ImportError: 122 | return None 123 | 124 | pty = get_pty_slave(os.getppid()) 125 | assert pty is not None 126 | 127 | with open(pty) as fd_pty: 128 | farg = struct.pack("HHHH", 0, 0, 0, 0) 129 | fretint = fcntl.ioctl(fd_pty, termios.TIOCGWINSZ, farg) 130 | rows, cols, xpixels, ypixels = struct.unpack("HHHH", fretint) 131 | 132 | if xpixels == 0 and ypixels == 0: 133 | return None 134 | 135 | return max(1, xpixels // cols), max(1, ypixels // rows) 136 | 137 | def _determine_n_lines( 138 | self, lineno: int, shape: Tuple[int, int, int, int] 139 | ) -> int: 140 | _, y, w, h = shape 141 | 142 | max_nlines = max(0, (h - y) - lineno - 1) 143 | 144 | maybe_pixelsizes = self._get_char_pixelsize() 145 | if maybe_pixelsizes is not None: 146 | xpixels, ypixels = maybe_pixelsizes 147 | 148 | if ( 149 | (self.img_width / xpixels) / (self.img_height / ypixels) 150 | ) * max_nlines <= w: 151 | nlines = max_nlines 152 | else: 153 | nlines = floor( 154 | ((self.img_height / ypixels) / (self.img_width / xpixels)) 155 | * w 156 | ) 157 | nlines = min(nlines, self.img_height // ypixels) 158 | else: 159 | nlines = max_nlines // 3 160 | 161 | return nlines 162 | 163 | def place( 164 | self, 165 | _: MagmaOptions, 166 | lineno: int, 167 | shape: Tuple[int, int, int, int], 168 | canvas: Canvas, 169 | ) -> str: 170 | x, y, w, h = shape 171 | nlines = self._determine_n_lines(lineno, shape) 172 | 173 | canvas.add_image( 174 | self.img_path, 175 | self.img_checksum, 176 | x=x, 177 | y=y + lineno + 1, # TODO: consider scroll in the display window 178 | width=w, 179 | height=nlines, 180 | ) 181 | return "\n" * nlines 182 | 183 | 184 | class OutputStatus(Enum): 185 | HOLD = 0 186 | RUNNING = 1 187 | DONE = 2 188 | 189 | 190 | class Output: 191 | execution_count: Optional[int] 192 | chunks: List[OutputChunk] 193 | status: OutputStatus 194 | success: bool 195 | old: bool 196 | 197 | _should_clear: bool 198 | 199 | def __init__(self, execution_count: Optional[int]): 200 | self.execution_count = execution_count 201 | self.status = OutputStatus.HOLD 202 | self.chunks = [] 203 | self.success = True 204 | self.old = False 205 | 206 | self._should_clear = False 207 | 208 | 209 | def to_outputchunk( 210 | alloc_file: Callable[ 211 | [str, str], 212 | "AbstractContextManager[Tuple[str, IO[bytes]]]", 213 | ], 214 | data: Dict[str, Any], 215 | metadata: Dict[str, Any], 216 | ) -> OutputChunk: 217 | def _to_image_chunk(path: str) -> OutputChunk: 218 | import hashlib 219 | from PIL import Image 220 | 221 | pil_image = Image.open(path) 222 | return ImageOutputChunk( 223 | path, 224 | hashlib.md5(pil_image.tobytes()).hexdigest(), 225 | pil_image.size, 226 | ) 227 | 228 | # Output chunk functions: 229 | def _from_image_png(imgdata: bytes) -> OutputChunk: 230 | import base64 231 | 232 | with alloc_file("png", "wb") as (path, file): 233 | file.write(base64.b64decode(str(imgdata))) 234 | return _to_image_chunk(path) 235 | 236 | def _from_image_svgxml(svg: str) -> OutputChunk: 237 | import cairosvg 238 | 239 | with alloc_file("png", "wb") as (path, file): 240 | cairosvg.svg2png(svg, write_to=file) 241 | return _to_image_chunk(path) 242 | 243 | def _from_application_plotly(figure_json: Any) -> OutputChunk: 244 | from plotly.io import from_json 245 | import json 246 | 247 | figure = from_json(json.dumps(figure_json)) 248 | 249 | with alloc_file("png", "wb") as (path, file): 250 | figure.write_image(file, engine="kaleido") 251 | return _to_image_chunk(path) 252 | 253 | def _from_latex(tex: str) -> OutputChunk: 254 | from pnglatex import pnglatex 255 | 256 | with alloc_file("png", "w") as (path, _): 257 | pass 258 | pnglatex(tex, path) 259 | return _to_image_chunk(path) 260 | 261 | def _from_plaintext(text: str) -> OutputChunk: 262 | return TextLnOutputChunk(text) 263 | 264 | OUTPUT_CHUNKS = { 265 | "image/png": _from_image_png, 266 | "image/svg+xml": _from_image_svgxml, 267 | "application/vnd.plotly.v1+json": _from_application_plotly, 268 | "text/latex": _from_latex, 269 | "text/plain": _from_plaintext, 270 | } 271 | 272 | chunk = None 273 | for mimetype, process_func in OUTPUT_CHUNKS.items(): 274 | try: 275 | maybe_data = data.get(mimetype) 276 | if maybe_data is not None: 277 | chunk = process_func(maybe_data) # type: ignore 278 | break 279 | except ImportError: 280 | continue 281 | 282 | if chunk is None: 283 | chunk = BadOutputChunk(list(data.keys())) 284 | 285 | chunk.jupyter_data = data 286 | chunk.jupyter_metadata = metadata 287 | 288 | return chunk 289 | -------------------------------------------------------------------------------- /rplugin/python3/magma/magmabuffer.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Dict 2 | from queue import Queue 3 | import hashlib 4 | 5 | import pynvim 6 | from pynvim import Nvim 7 | from pynvim.api import Buffer 8 | 9 | from magma.options import MagmaOptions 10 | from magma.images import Canvas 11 | from magma.utils import MagmaException, Position, Span 12 | from magma.outputbuffer import OutputBuffer 13 | from magma.outputchunks import OutputStatus 14 | from magma.runtime import JupyterRuntime 15 | 16 | 17 | class MagmaBuffer: 18 | nvim: Nvim 19 | canvas: Canvas 20 | highlight_namespace: int 21 | extmark_namespace: int 22 | buffer: Buffer 23 | 24 | runtime: JupyterRuntime 25 | 26 | outputs: Dict[Span, OutputBuffer] 27 | current_output: Optional[Span] 28 | queued_outputs: "Queue[Span]" 29 | 30 | selected_cell: Optional[Span] 31 | should_open_display_window: bool 32 | updating_interface: bool 33 | 34 | options: MagmaOptions 35 | 36 | def __init__( 37 | self, 38 | nvim: Nvim, 39 | canvas: Canvas, 40 | highlight_namespace: int, 41 | extmark_namespace: int, 42 | buffer: Buffer, 43 | options: MagmaOptions, 44 | kernel_name: str, 45 | ): 46 | self.nvim = nvim 47 | self.canvas = canvas 48 | self.highlight_namespace = highlight_namespace 49 | self.extmark_namespace = extmark_namespace 50 | self.buffer = buffer 51 | 52 | self._doautocmd("MagmaInitPre") 53 | 54 | self.runtime = JupyterRuntime(kernel_name, options) 55 | 56 | self.outputs = {} 57 | self.current_output = None 58 | self.queued_outputs = Queue() 59 | 60 | self.selected_cell = None 61 | self.should_open_display_window = False 62 | self.updating_interface = False 63 | 64 | self.options = options 65 | 66 | self._doautocmd("MagmaInitPost") 67 | 68 | def _doautocmd(self, autocmd: str) -> None: 69 | assert " " not in autocmd 70 | self.nvim.command(f"doautocmd User {autocmd}") 71 | 72 | def deinit(self) -> None: 73 | self._doautocmd("MagmaDeinitPre") 74 | self.runtime.deinit() 75 | self._doautocmd("MagmaDeinitPost") 76 | 77 | def interrupt(self) -> None: 78 | self.runtime.interrupt() 79 | 80 | def restart(self, delete_outputs: bool = False) -> None: 81 | if delete_outputs: 82 | self.outputs = {} 83 | self.clear_interface() 84 | 85 | self.runtime.restart() 86 | 87 | def run_code(self, code: str, span: Span) -> None: 88 | self._delete_all_cells_in_span(span) 89 | self.runtime.run_code(code) 90 | 91 | if span in self.outputs: 92 | self.outputs[span].clear_interface() 93 | del self.outputs[span] 94 | 95 | self.outputs[span] = OutputBuffer(self.nvim, self.canvas, self.options) 96 | self.queued_outputs.put(span) 97 | 98 | self.selected_cell = span 99 | self.should_open_display_window = True 100 | self.update_interface() 101 | 102 | self._check_if_done_running() 103 | 104 | def reevaluate_cell(self) -> None: 105 | self.selected_cell = self._get_selected_span() 106 | if self.selected_cell is None: 107 | raise MagmaException("Not in a cell") 108 | 109 | code = self.selected_cell.get_text(self.nvim) 110 | 111 | self.run_code(code, self.selected_cell) 112 | 113 | def _check_if_done_running(self) -> None: 114 | # TODO: refactor 115 | is_idle = ( self.current_output is None 116 | or not self.current_output in self.outputs 117 | ) or ( self.current_output is not None 118 | and self.outputs[self.current_output].output.status 119 | == OutputStatus.DONE 120 | ) 121 | if is_idle and not self.queued_outputs.empty(): 122 | key = self.queued_outputs.get_nowait() 123 | self.current_output = key 124 | 125 | def tick(self) -> None: 126 | self._check_if_done_running() 127 | 128 | was_ready = self.runtime.is_ready() 129 | if self.current_output is None or not self.current_output in self.outputs: 130 | did_stuff = self.runtime.tick(None) 131 | else: 132 | did_stuff = self.runtime.tick( 133 | self.outputs[self.current_output].output 134 | ) 135 | if did_stuff: 136 | self.update_interface() 137 | if not was_ready and self.runtime.is_ready(): 138 | self.nvim.api.notify( 139 | "Kernel '%s' is ready." % self.runtime.kernel_name, 140 | pynvim.logging.INFO, 141 | {"title": "Magma"}, 142 | ) 143 | 144 | def enter_output(self) -> None: 145 | if self.selected_cell is not None: 146 | self.outputs[self.selected_cell].enter() 147 | 148 | def _get_cursor_position(self) -> Position: 149 | _, lineno, colno, _, _ = self.nvim.funcs.getcurpos() 150 | return Position(self.nvim.current.buffer.number, lineno - 1, colno - 1) 151 | 152 | def clear_interface(self) -> None: 153 | if self.updating_interface: 154 | return 155 | 156 | self.nvim.funcs.nvim_buf_clear_namespace( 157 | self.buffer.number, 158 | self.highlight_namespace, 159 | 0, 160 | -1, 161 | ) 162 | # and self.nvim.funcs.winbufnr(self.display_window) != -1: 163 | if self.selected_cell is not None and self.selected_cell in self.outputs: 164 | self.outputs[self.selected_cell].clear_interface() 165 | self.canvas.clear() 166 | 167 | def _get_selected_span(self) -> Optional[Span]: 168 | current_position = self._get_cursor_position() 169 | selected = None 170 | for span in reversed(self.outputs.keys()): 171 | if current_position in span: 172 | selected = span 173 | break 174 | 175 | return selected 176 | 177 | def _delete_all_cells_in_span(self, span: Span) -> None: 178 | for output_span in reversed(list(self.outputs.keys())): 179 | if ( 180 | output_span.begin in span 181 | or output_span.end in span 182 | or span.begin in output_span 183 | or span.end in output_span 184 | ): 185 | self.outputs[output_span].clear_interface() 186 | del self.outputs[output_span] 187 | 188 | def delete_cell(self) -> None: 189 | self.selected_cell = self._get_selected_span() 190 | if self.selected_cell is None: 191 | return 192 | 193 | self.outputs[self.selected_cell].clear_interface() 194 | del self.outputs[self.selected_cell] 195 | 196 | def update_interface(self) -> None: 197 | if self.buffer.number != self.nvim.current.buffer.number: 198 | return 199 | if self.buffer.number != self.nvim.current.window.buffer.number: 200 | return 201 | 202 | self.clear_interface() 203 | 204 | self.updating_interface = True 205 | 206 | selected_cell = self._get_selected_span() 207 | 208 | if self.options.automatically_open_output: 209 | self.should_open_display_window = True 210 | else: 211 | if self.selected_cell != selected_cell: 212 | self.should_open_display_window = False 213 | 214 | self.selected_cell = selected_cell 215 | 216 | if self.selected_cell is not None: 217 | self._show_selected(self.selected_cell) 218 | self.canvas.present() 219 | 220 | self.updating_interface = False 221 | 222 | def _show_selected(self, span: Span) -> None: 223 | if span.begin.lineno == span.end.lineno: 224 | self.nvim.funcs.nvim_buf_add_highlight( 225 | self.buffer.number, 226 | self.highlight_namespace, 227 | self.options.cell_highlight_group, 228 | span.begin.lineno, 229 | span.begin.colno, 230 | span.end.colno, 231 | ) 232 | else: 233 | self.nvim.funcs.nvim_buf_add_highlight( 234 | self.buffer.number, 235 | self.highlight_namespace, 236 | self.options.cell_highlight_group, 237 | span.begin.lineno, 238 | span.begin.colno, 239 | -1, 240 | ) 241 | for lineno in range(span.begin.lineno + 1, span.end.lineno): 242 | self.nvim.funcs.nvim_buf_add_highlight( 243 | self.buffer.number, 244 | self.highlight_namespace, 245 | self.options.cell_highlight_group, 246 | lineno, 247 | 0, 248 | -1, 249 | ) 250 | self.nvim.funcs.nvim_buf_add_highlight( 251 | self.buffer.number, 252 | self.highlight_namespace, 253 | self.options.cell_highlight_group, 254 | span.end.lineno, 255 | 0, 256 | span.end.colno, 257 | ) 258 | 259 | if self.should_open_display_window: 260 | self.outputs[span].show(span.end) 261 | 262 | def _get_content_checksum(self) -> str: 263 | return hashlib.md5( 264 | "\n".join( 265 | self.nvim.current.buffer.api.get_lines(0, -1, True) 266 | ).encode("utf-8") 267 | ).hexdigest() 268 | -------------------------------------------------------------------------------- /rplugin/python3/magma/images.py: -------------------------------------------------------------------------------- 1 | from typing import Set, Dict 2 | import os 3 | from abc import ABC, abstractmethod 4 | import time 5 | 6 | from pynvim import Nvim 7 | 8 | from magma.utils import MagmaException 9 | 10 | 11 | class Canvas(ABC): 12 | @abstractmethod 13 | def init(self) -> None: 14 | """ 15 | Initialize the canvas. 16 | 17 | This will be called before the canvas is ever used. 18 | """ 19 | 20 | @abstractmethod 21 | def deinit(self) -> None: 22 | """ 23 | Deinitialize the canvas. 24 | 25 | The canvas will not be used after this operation. 26 | """ 27 | 28 | @abstractmethod 29 | def present(self) -> None: 30 | """ 31 | Present the canvas. 32 | 33 | This is called only when a redraw is necessary -- so, if desired, it 34 | can be implemented so that `clear` and `add_image` only queue images as 35 | to be drawn, and `present` actually performs the operaetions, in order 36 | to reduce flickering. 37 | """ 38 | 39 | @abstractmethod 40 | def clear(self) -> None: 41 | """ 42 | Clear all images from the canvas. 43 | """ 44 | 45 | @abstractmethod 46 | def add_image( 47 | self, 48 | path: str, 49 | identifier: str, 50 | x: int, 51 | y: int, 52 | width: int, 53 | height: int, 54 | ) -> None: 55 | """ 56 | Add an image to the canvas. 57 | 58 | Parameters 59 | - path: str 60 | Path to the image we want to show 61 | - identifier: str 62 | A string which identifies this image (it is a checksum of of its 63 | data). It is given for convenience for methods which require 64 | identifiers, but can be safely ignored. 65 | - x: int 66 | Column number of where the image is supposed to be drawn at (top-left 67 | corner). 68 | - y: int 69 | Row number of where the image is supposed to be drawn at (top-right 70 | corner). 71 | - width: int 72 | The desired width for the image, in terminal columns. 73 | - height: int 74 | The desired height for the image, in terminal rows. 75 | """ 76 | 77 | 78 | class NoCanvas(Canvas): 79 | def __init__(self) -> None: 80 | pass 81 | 82 | def init(self) -> None: 83 | pass 84 | 85 | def deinit(self) -> None: 86 | pass 87 | 88 | def present(self) -> None: 89 | pass 90 | 91 | def clear(self) -> None: 92 | pass 93 | 94 | def add_image( 95 | self, 96 | path: str, 97 | identifier: str, 98 | x: int, 99 | y: int, 100 | width: int, 101 | height: int, 102 | ) -> None: 103 | pass 104 | 105 | 106 | class UeberzugCanvas(Canvas): 107 | ueberzug_canvas: "ueberzug.Canvas" # type: ignore 108 | 109 | identifiers: Dict[str, "ueberzug.Placement"] # type: ignore 110 | 111 | _visible: Set[str] 112 | _to_make_visible: Set[str] 113 | _to_make_invisible: Set[str] 114 | 115 | def __init__(self) -> None: 116 | import ueberzug.lib.v0 as ueberzug 117 | 118 | self.ueberzug_canvas = ueberzug.Canvas() 119 | self.identifiers = {} 120 | 121 | self._visible = set() 122 | self._to_make_visible = set() 123 | self._to_make_invisible = set() 124 | 125 | def init(self) -> None: 126 | self.ueberzug_canvas.__enter__() 127 | 128 | def deinit(self) -> None: 129 | if len(self.identifiers) > 0: 130 | self.ueberzug_canvas.__exit__() 131 | 132 | def present(self) -> None: 133 | import ueberzug.lib.v0 as ueberzug 134 | 135 | self._to_make_invisible.difference_update(self._to_make_visible) 136 | for identifier in self._to_make_invisible: 137 | self.identifiers[ 138 | identifier 139 | ].visibility = ueberzug.Visibility.INVISIBLE 140 | for identifier in self._to_make_visible: 141 | self.identifiers[ 142 | identifier 143 | ].visibility = ueberzug.Visibility.VISIBLE 144 | self._visible.add(identifier) 145 | self._to_make_invisible.clear() 146 | self._to_make_visible.clear() 147 | 148 | def clear(self) -> None: 149 | for identifier in self._visible: 150 | self._to_make_invisible.add(identifier) 151 | self._visible.clear() 152 | 153 | def add_image( 154 | self, 155 | path: str, 156 | identifier: str, 157 | x: int, 158 | y: int, 159 | width: int, 160 | height: int, 161 | ) -> None: 162 | import ueberzug.lib.v0 as ueberzug 163 | 164 | if width > 0 and height > 0: 165 | identifier += f"-{os.getpid()}-{x}-{y}-{width}-{height}" 166 | 167 | if identifier in self.identifiers: 168 | img = self.identifiers[identifier] 169 | else: 170 | img = self.ueberzug_canvas.create_placement( 171 | identifier, 172 | x=x, 173 | y=y, 174 | width=width, 175 | height=height, 176 | scaler=ueberzug.ScalerOption.FIT_CONTAIN.value, 177 | ) 178 | self.identifiers[identifier] = img 179 | img.path = path 180 | 181 | self._to_make_visible.add(identifier) 182 | 183 | 184 | class KittyImage: 185 | # Adapted from https://sw.kovidgoyal.net/kitty/graphics-protocol/ 186 | 187 | def __init__( 188 | self, 189 | id: int, 190 | path: str, 191 | row: int, 192 | col: int, 193 | width: int, 194 | height: int, 195 | nvim: Nvim, 196 | ): 197 | self.id = id 198 | self.path = path 199 | self.row = row 200 | self.col = col 201 | self.width = width 202 | self.height = height 203 | self.nvim = nvim 204 | 205 | def serialize_gr_command(self, **cmd): # type: ignore 206 | payload = cmd.pop("payload", None) 207 | cmd = ",".join("{}={}".format(k, v) for k, v in cmd.items()) # type: ignore 208 | ans = [] # type: ignore 209 | w = ans.append 210 | w(b"\033_G"), w(cmd.encode("ascii")) # type: ignore 211 | if payload: 212 | w(b";") 213 | w(payload) 214 | w(b"\033\\") 215 | ans = b"".join(ans) # type: ignore 216 | if "tmux" in os.environ["TERM"]: 217 | ans = b"\033Ptmux;" + ans.replace(b"\033", b"\033\033") + b"\033\\" # type: ignore 218 | return ans 219 | 220 | def write_chunked(self, **cmd): # type: ignore 221 | from base64 import standard_b64encode 222 | 223 | data = standard_b64encode(cmd.pop("data")) 224 | while data: 225 | chunk, data = data[:4096], data[4096:] 226 | m = 1 if data else 0 227 | self.nvim.lua.stdout.write( 228 | self.serialize_gr_command(payload=chunk, m=m, **cmd) # type: ignore 229 | ) 230 | cmd.clear() 231 | 232 | def show(self) -> None: 233 | with open(self.path, "rb") as f: 234 | self.write_chunked( # type: ignore 235 | a="T", # transmit directly to the terminal 236 | i=self.id, 237 | f=100, # for now, only png 238 | v=self.height, 239 | s=self.width, 240 | C=1, 241 | z=10, 242 | q=2, 243 | data=f.read(), 244 | ) 245 | 246 | def hide(self) -> None: 247 | self.nvim.lua.stdout.write( 248 | self.serialize_gr_command( # type: ignore 249 | i=self.id, 250 | a="d", # remove image 251 | q=2, 252 | ) 253 | ) 254 | 255 | 256 | class Kitty(Canvas): 257 | nvim: Nvim 258 | images: Dict[str, KittyImage] 259 | to_make_visible: Set[str] 260 | to_make_invisible: Set[str] 261 | visible: Set[str] 262 | next_id: int 263 | 264 | def __init__(self, nvim: Nvim): 265 | self.nvim = nvim 266 | self.images = {} 267 | self.visible = set() 268 | self.to_make_visible = set() 269 | self.to_make_invisible = set() 270 | self.next_id = 0 271 | nvim.exec_lua( 272 | """ 273 | local fd = vim.loop.new_pipe(false) 274 | fd:open(1) 275 | local function write(data) 276 | fd:write(data) 277 | end 278 | 279 | stdout = {write = write} 280 | """ 281 | ) 282 | 283 | def init(self) -> None: 284 | pass 285 | 286 | def deinit(self) -> None: 287 | pass 288 | 289 | def present(self) -> None: 290 | # images to both show and hide should be ignored 291 | to_work_on = self.to_make_visible.difference( 292 | self.to_make_visible.intersection(self.to_make_invisible) 293 | ) 294 | self.to_make_invisible.difference_update(self.to_make_visible) 295 | for identifier in self.to_make_invisible: 296 | 297 | def hide_fn(image: KittyImage) -> None: 298 | image.hide() 299 | # we need the sleep here, otherwise the escape codes might 300 | # `spill` over into the buffer when doing 301 | # several rapid operations consectively 302 | time.sleep(0.01) 303 | 304 | self.nvim.async_call(hide_fn, self.images[identifier]) 305 | for identifier in to_work_on: 306 | image = self.images[identifier] 307 | 308 | def fn(nvim: Nvim, image: KittyImage) -> None: 309 | eventignore_save = nvim.options["eventignore"] 310 | nvim.options["eventignore"] = "all" 311 | 312 | org_position = nvim.current.window.cursor 313 | # We need to move the cursor to the place where we want to 314 | # place the image. 315 | # We need to make sure we are still in the buffer. 316 | nvim.current.window.cursor = ( 317 | min(image.row + 1, len(nvim.current.buffer)), 318 | image.col, 319 | ) 320 | image.show() 321 | time.sleep(0.01) 322 | 323 | nvim.current.window.cursor = org_position 324 | nvim.options["eventignore"] = eventignore_save 325 | 326 | self.nvim.async_call(fn, self.nvim, image) 327 | self.visible.update(self.to_make_visible) 328 | self.to_make_invisible.clear() 329 | self.to_make_visible.clear() 330 | 331 | def clear(self) -> None: 332 | for identifier in self.visible: 333 | self.to_make_invisible.add(identifier) 334 | self.visible.clear() 335 | 336 | def add_image( 337 | self, 338 | path: str, 339 | identifier: str, 340 | x: int, 341 | y: int, 342 | width: int, 343 | height: int, 344 | ) -> None: 345 | if identifier not in self.images: 346 | self.images[identifier] = KittyImage( 347 | id=self.next_id, 348 | path=path, 349 | row=y, 350 | col=x, 351 | width=width, 352 | height=height, 353 | nvim=self.nvim, 354 | ) 355 | self.next_id += 1 356 | else: 357 | self.images[identifier].path = path 358 | self.to_make_visible.add(identifier) 359 | 360 | 361 | def get_canvas_given_provider(name: str, nvim: Nvim) -> Canvas: 362 | if name == "none": 363 | return NoCanvas() 364 | elif name == "ueberzug": 365 | return UeberzugCanvas() 366 | elif name == "kitty": 367 | return Kitty(nvim) 368 | else: 369 | raise MagmaException(f"Unknown image provider: '{name}'") 370 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Magma 2 | 3 | Magma is a NeoVim plugin for running code interactively with Jupyter. 4 | 5 | ![](https://user-images.githubusercontent.com/15617291/128964224-f157022c-25cd-4a60-a0da-7d1462564ae4.gif) 6 | 7 | ## Requirements 8 | 9 | - NeoVim 0.5+ 10 | - Python 3.8+ 11 | - Required Python packages: 12 | - [`pynvim`](https://github.com/neovim/pynvim) (for the Remote Plugin API) 13 | - [`jupyter_client`](https://github.com/jupyter/jupyter_client) (for interacting with Jupyter) 14 | - [`ueberzug`](https://github.com/seebye/ueberzug) (for displaying images. Not available on MacOS, but see [#15](https://github.com/dccsillag/magma-nvim/issues/15) for alternatives) 15 | - [`Pillow`](https://github.com/python-pillow/Pillow) (also for displaying images, should be installed with `ueberzug`) 16 | - [`cairosvg`](https://cairosvg.org/) (for displaying SVG images) 17 | - [`pnglatex`](https://pypi.org/project/pnglatex/) (for displaying TeX formulas) 18 | - `plotly` and `kaleido` (for displaying Plotly figures) 19 | - `pyperclip` if you want to use `magma_copy_output` 20 | - For .NET (C#, F#) 21 | - `dotnet tool install -g Microsoft.dotnet-interactive` 22 | - `dotnet interactive jupyter install` 23 | 24 | You can do a `:checkhealth` to see if you are ready to go. 25 | 26 | **Note:** Python packages which are used only for the display of some specific kind of output are only imported when that output actually appears. 27 | 28 | ## Installation 29 | 30 | Use your favourite package/plugin manager. 31 | 32 | If you use `packer.nvim`, 33 | 34 | ```lua 35 | use { 'dccsillag/magma-nvim', run = ':UpdateRemotePlugins' } 36 | ``` 37 | 38 | If you use `vim-plug`, 39 | 40 | ```vim 41 | Plug 'dccsillag/magma-nvim', { 'do': ':UpdateRemotePlugins' } 42 | ``` 43 | 44 | Note that you will still need to configure keymappings -- see [Keybindings](#keybindings). 45 | 46 | ## Suggested settings 47 | 48 | If you want a quickstart, these are the author's suggestions of mappings and options (beware of potential conflicts of these mappings with your own!): 49 | 50 | ```vim 51 | nnoremap r :MagmaEvaluateOperator 52 | nnoremap rr :MagmaEvaluateLine 53 | xnoremap r :MagmaEvaluateVisual 54 | nnoremap rc :MagmaReevaluateCell 55 | nnoremap rd :MagmaDelete 56 | nnoremap ro :MagmaShowOutput 57 | 58 | let g:magma_automatically_open_output = v:false 59 | let g:magma_image_provider = "ueberzug" 60 | ``` 61 | 62 | **Note:** Key mappings are not defined by default because of potential conflicts -- the user should decide which keys they want to use (if at all). 63 | 64 | **Note:** The options that are altered here don't have these as their default values in order to provide a simpler (albeit perhaps a bit more inconvenient) UI for someone who just added the plugin without properly reading the README. 65 | 66 | To make initialisation of kernels easier, you can add these commands: 67 | 68 | ```lua 69 | function MagmaInitPython() 70 | vim.cmd[[ 71 | :MagmaInit python3 72 | :MagmaEvaluateArgument a=5 73 | ]] 74 | end 75 | 76 | function MagmaInitCSharp() 77 | vim.cmd[[ 78 | :MagmaInit .net-csharp 79 | :MagmaEvaluateArgument Microsoft.DotNet.Interactive.Formatting.Formatter.SetPreferredMimeTypesFor(typeof(System.Object),"text/plain"); 80 | ]] 81 | end 82 | 83 | function MagmaInitFSharp() 84 | vim.cmd[[ 85 | :MagmaInit .net-fsharp 86 | :MagmaEvaluateArgument Microsoft.DotNet.Interactive.Formatting.Formatter.SetPreferredMimeTypesFor(typeof,"text/plain") 87 | ]] 88 | end 89 | 90 | vim.cmd[[ 91 | :command MagmaInitPython lua MagmaInitPython() 92 | :command MagmaInitCSharp lua MagmaInitCSharp() 93 | :command MagmaInitFSharp lua MagmaInitFSharp() 94 | ]] 95 | ``` 96 | 97 | ## Usage 98 | 99 | The plugin provides a bunch of commands to enable interaction. It is recommended to map most of them to keys, as explained in [Keybindings](#keybindings). However, this section will refer to the commands by their names (so as to not depend on some specific mappings). 100 | 101 | ### Interface 102 | 103 | When you execute some code, it will create a *cell*. You can recognize a cell because it will be highlighted when your cursor is in it. 104 | 105 | A cell is delimited using two extmarks (see `:help api-extended-marks`), so it will adjust to you editing the text within it. 106 | 107 | When your cursor is in a cell (i.e., you have an *active cell*), a floating window may be shown below the cell, reporting output. This is the *display window*, or *output window*. (To see more about whether a window is shown or not, see `:MagmaShowOutput` and `g:magma_automatically_open_output`). When you cursor is not in any cell, no cell is active. 108 | 109 | Also, the active cell is searched for from newest to oldest. That means that you can have a cell within another cell, and if the one within is newer, then that one will be selected. (Same goes for merely overlapping cells). 110 | 111 | The output window has a header, containing the execution count and execution state (i.e., whether the cell is waiting to be run, running, has finished successfully or has finished with an error). Below the header are shown the outputs. 112 | 113 | Jupyter provides a rich set of outputs. To see what we can currently handle, see [Output Chunks](#output-chunks). 114 | 115 | ### Commands 116 | 117 | #### MagmaInit 118 | 119 | This command initializes a runtime for the current buffer. 120 | 121 | It can take a single argument, the Jupyter kernel's name. For example, 122 | 123 | ```vim 124 | :MagmaInit python3 125 | ``` 126 | 127 | will initialize the current buffer with a `python3` kernel. 128 | 129 | It can also be called with no arguments, as such: 130 | 131 | ```vim 132 | :MagmaInit 133 | ``` 134 | 135 | This will prompt you for which kernel you want to launch (from the list of available kernels). 136 | 137 | #### MagmaDeinit 138 | 139 | This command deinitializes the current buffer's runtime and magma instance. 140 | 141 | ```vim 142 | :MagmaDeinit 143 | ``` 144 | 145 | **Note** You don't need to run this, as deinitialization will happen automatically upon closing Vim or the buffer being unloaded. This command exists in case you just want to make Magma stop running. 146 | 147 | #### MagmaEvaluateLine 148 | 149 | Evaluate the current line. 150 | 151 | Example usage: 152 | 153 | ```vim 154 | :MagmaEvaluateLine 155 | ``` 156 | 157 | #### MagmaEvaluateVisual 158 | 159 | Evaluate the selected text. 160 | 161 | Example usage (after having selected some text): 162 | 163 | ```vim 164 | :MagmaEvaluateVisual 165 | ``` 166 | 167 | #### MagmaEvaluateOperator 168 | 169 | Evaluate the text given by some operator. 170 | 171 | This won't do much outside of an `` mapping. Example usage: 172 | 173 | ```vim 174 | nnoremap r nvim_exec('MagmaEvaluateOperator', v:true) 175 | ``` 176 | 177 | Upon using this mapping, you will enter operator mode, with which you will be able to select text you want to execute. You can, of course, hit ESC to cancel, as usual with operator mode. 178 | 179 | #### MagmaEvaluateArgument 180 | 181 | Evaluate the text following this command. Could be used for some automation (e. g. run something on initialization of a kernel). 182 | 183 | ```vim 184 | :MagmaEvaluateArgument a=5; 185 | ``` 186 | 187 | #### MagmaReevaluateCell 188 | 189 | Reevaluate the currently selected cell. 190 | 191 | ```vim 192 | :MagmaReevaluateCell 193 | ``` 194 | 195 | #### MagmaDelete 196 | 197 | Delete the currently selected cell. (If there is no selected cell, do nothing.) 198 | 199 | Example usage: 200 | 201 | ```vim 202 | :MagmaDelete 203 | ``` 204 | 205 | #### MagmaShowOutput 206 | 207 | This only makes sense when you have `g:magma_automatically_open_output = v:false`. See [Customization](#customization). 208 | 209 | Running this command with some active cell will open the output window. 210 | 211 | Example usage: 212 | 213 | ```vim 214 | :MagmaShowOutput 215 | ``` 216 | 217 | #### MagmaInterrupt 218 | 219 | Send a keyboard interrupt to the kernel. Interrupts the currently running cell and does nothing if not 220 | cell is running. 221 | 222 | Example usage: 223 | 224 | ```vim 225 | :MagmaInterrupt 226 | ``` 227 | 228 | #### MagmaRestart 229 | 230 | Shuts down and restarts the current kernel. 231 | 232 | Optionally deletes all output if used with a bang. 233 | 234 | Example usage: 235 | 236 | ```vim 237 | :MagmaRestart 238 | ``` 239 | 240 | Example usage (also deleting outputs): 241 | 242 | ```vim 243 | :MagmaRestart! 244 | ``` 245 | 246 | #### MagmaSave 247 | 248 | Save the current cells and evaluated outputs into a JSON file, which can then be loaded back with [`:MagmaLoad`](#magmaload). 249 | 250 | It has two forms; first, receiving a parameter, specifying where to save to: 251 | 252 | ```vim 253 | :MagmaSave file_to_save.json 254 | ``` 255 | 256 | If that parameter is omitted, then one will be automatically generated using the `g:magma_save_path` option. 257 | 258 | ```vim 259 | :MagmaSave 260 | ``` 261 | 262 | #### MagmaLoad 263 | 264 | Load the cells and evaluated outputs stored in a given JSON file, which should have been generated with [`:MagmaSave`](#magmasave). 265 | 266 | Like `MagmaSave`, It has two forms; first, receiving a parameter, specifying where to save to: 267 | 268 | ```vim 269 | :MagmaLoad file_to_load.json 270 | ``` 271 | 272 | If that parameter is omitted, then one will be automatically generated using the `g:magma_save_path` option. 273 | 274 | #### MagmaEnterOutput 275 | 276 | Enter the output window, if it is currently open. You must call this as follows: 277 | 278 | ```vim 279 | :noautocmd MagmaEnterOutput 280 | ``` 281 | 282 | This is escpecially useful when you have a long output (or errors) and wish to inspect it. 283 | 284 | ## Keybindings 285 | 286 | It is recommended to map all the evaluate commands to the same mapping (in different modes). For example, if we wanted to bind evaluation to `r`: 287 | 288 | ```vim 289 | nnoremap r nvim_exec('MagmaEvaluateOperator', v:true) 290 | nnoremap rr :MagmaEvaluateLine 291 | xnoremap r :MagmaEvaluateVisual 292 | nnoremap rc :MagmaReevaluateCell 293 | ``` 294 | 295 | This way, `r` will behave just like standard keys such as `y` and `d`. 296 | 297 | You can, of course, also map other commands: 298 | 299 | ```vim 300 | nnoremap rd :MagmaDelete 301 | nnoremap ro :MagmaShowOutput 302 | nnoremap rq :noautocmd MagmaEnterOutput 303 | ``` 304 | 305 | ## Customization 306 | 307 | Customization is done via variables. 308 | 309 | ### `g:magma_image_provider` 310 | 311 | Defaults to `"none"`. 312 | 313 | This configures how to display images. The following options are available: 314 | 315 | - `"none"` -- don't show images. 316 | - `"ueberzug"` -- use [Ueberzug](https://github.com/seebye/ueberzug) to display images. 317 | - `"kitty"` -- use the Kitty protocol to display images. 318 | 319 | ### `g:magma_automatically_open_output` 320 | 321 | Defaults to `v:true`. 322 | 323 | If this is true, then whenever you have an active cell its output window will be automatically shown. 324 | 325 | If this is false, then the output window will only be automatically shown when you've just evaluated the code. So, if you take your cursor out of the cell, and then come back, the output window won't be opened (but the cell will be highlighted). This means that there will be nothing covering your code. You can then open the output window at will using [`:MagmaShowOutput`](#magma-show-output). 326 | 327 | ### `g:magma_wrap_output` 328 | 329 | Defaults to `v:true`. 330 | 331 | If this is true, then text output in the output window will be wrapped (akin to `set wrap`). 332 | 333 | ### `g:magma_output_window_borders` 334 | 335 | Defaults to `v:true`. 336 | 337 | If this is true, then the output window will have rounded borders. If it is false, it will have no borders. 338 | 339 | ### `g:magma_cell_highlight_group` 340 | 341 | Defaults to `"CursorLine"`. 342 | 343 | The highlight group to be used for highlighting cells. 344 | 345 | ### `g:magma_save_path` 346 | 347 | Defaults to `stdpath("data") .. "/magma"`. 348 | 349 | Where to save/load with [`:MagmaSave`](#magmasave) and [`:MagmaLoad`](#magmaload) (with no parameters). 350 | 351 | The generated file is placed in this directory, with the filename itself being the buffer's name, with `%` replaced by `%%` and `/` replaced by `%`, and postfixed with the extension `.json`. 352 | 353 | ### `g:magma_copy_output` 354 | 355 | Defaults to `v:false`. 356 | 357 | To copy the evaluation output to clipboard automatically. 358 | 359 | ### [DEBUG] `g:magma_show_mimetype_debug` 360 | 361 | Defaults to `v:false`. 362 | 363 | If this is true, then before any non-iostream output chunk, Magma shows the mimetypes it received for it. 364 | 365 | This is meant for debugging and adding new mimetypes. 366 | 367 | ## Autocommands 368 | 369 | We provide some `User` autocommands (see `:help User`) for further customization. They are: 370 | 371 | - `MagmaInitPre`: runs right before `MagmaInit` initialization happens for a buffer 372 | - `MagmaInitPost`: runs right after `MagmaInit` initialization happens for a buffer 373 | - `MagmaDeinitPre`: runs right before `MagmaDeinit` deinitialization happens for a buffer 374 | - `MagmaDeinitPost`: runs right after `MagmaDeinit` deinitialization happens for a buffer 375 | 376 | ## Extras 377 | 378 | ### Output Chunks 379 | 380 | In the Jupyter protocol, most output-related messages provide a dictionary of mimetypes which can be used to display the data. Theoretically, a `text/plain` field (i.e., plain text) is always present, so we (theoretically) always have that fallback. 381 | 382 | Here is a list of the currently handled mimetypes: 383 | 384 | - `text/plain`: Plain text. Shown as text in the output window's buffer. 385 | - `image/png`: A PNG image. Shown according to `g:magma_image_provider`. 386 | - `image/svg+xml`: A SVG image. Rendered into a PNG with [CairoSVG](https://cairosvg.org/) and shown with [Ueberzug](https://github.com/seebye/ueberzug). 387 | - `application/vnd.plotly.v1+json`: A Plotly figure. Rendered into a PNG with [Plotly](https://plotly.com/python/) + [Kaleido](https://github.com/plotly/Kaleido) and shown with [Ueberzug](https://github.com/seebye/ueberzug). 388 | - `text/latex`: A LaTeX formula. Rendered into a PNG with [pnglatex](https://pypi.org/project/pnglatex/) and shown with [Ueberzug](https://github.com/seebye/ueberzug). 389 | 390 | This already provides quite a bit of basic functionality. As development continues, more mimetypes will be added. 391 | 392 | ### Correct progress bars and alike stuff 393 | 394 | ![](./caret.gif) 395 | 396 | ### Notifications 397 | 398 | We use the `vim.notify` API. This means that you can use plugins such as [rcarriga/nvim-notify](https://github.com/rcarriga/nvim-notify) for pretty notifications. 399 | -------------------------------------------------------------------------------- /rplugin/python3/magma/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from typing import Any, Dict, List, Optional, Tuple 4 | 5 | import pynvim 6 | from magma.images import Canvas, get_canvas_given_provider 7 | from magma.io import MagmaIOError, get_default_save_file, load, save 8 | from magma.magmabuffer import MagmaBuffer 9 | from magma.options import MagmaOptions 10 | from magma.outputbuffer import OutputBuffer 11 | from magma.runtime import get_available_kernels 12 | from magma.utils import DynamicPosition, MagmaException, Span, nvimui 13 | from pynvim import Nvim 14 | 15 | 16 | @pynvim.plugin 17 | class Magma: 18 | nvim: Nvim 19 | canvas: Optional[Canvas] 20 | initialized: bool 21 | 22 | highlight_namespace: int 23 | extmark_namespace: int 24 | 25 | buffers: Dict[int, MagmaBuffer] 26 | 27 | timer: Optional[int] 28 | 29 | options: MagmaOptions 30 | 31 | def __init__(self, nvim: Nvim): 32 | self.nvim = nvim 33 | self.initialized = False 34 | 35 | self.canvas = None 36 | self.buffers = {} 37 | self.timer = None 38 | 39 | def _initialize(self) -> None: 40 | assert not self.initialized 41 | 42 | self.options = MagmaOptions(self.nvim) 43 | 44 | self.canvas = get_canvas_given_provider( 45 | self.options.image_provider, self.nvim 46 | ) 47 | self.canvas.init() 48 | 49 | self.highlight_namespace = self.nvim.funcs.nvim_create_namespace( 50 | "magma-highlights" 51 | ) 52 | self.extmark_namespace = self.nvim.funcs.nvim_create_namespace( 53 | "magma-extmarks" 54 | ) 55 | 56 | self.timer = self.nvim.eval( 57 | "timer_start(500, 'MagmaTick', {'repeat': -1})" 58 | ) 59 | 60 | self._set_autocommands() 61 | 62 | self.initialized = True 63 | 64 | def _set_autocommands(self) -> None: 65 | self.nvim.command("augroup magma") 66 | self.nvim.command( 67 | " autocmd CursorMoved * call MagmaUpdateInterface()" 68 | ) 69 | self.nvim.command( 70 | " autocmd CursorMovedI * call MagmaUpdateInterface()" 71 | ) 72 | self.nvim.command( 73 | " autocmd WinScrolled * call MagmaUpdateInterface()" 74 | ) 75 | self.nvim.command( 76 | " autocmd BufEnter * call MagmaUpdateInterface()" 77 | ) 78 | self.nvim.command( 79 | " autocmd BufLeave * call MagmaClearInterface()" 80 | ) 81 | self.nvim.command( 82 | " autocmd BufUnload * call MagmaOnBufferUnload()" 83 | ) 84 | self.nvim.command(" autocmd ExitPre * call MagmaOnExitPre()") 85 | self.nvim.command("augroup END") 86 | 87 | def _deinitialize(self) -> None: 88 | for magma in self.buffers.values(): 89 | magma.deinit() 90 | if self.canvas is not None: 91 | self.canvas.deinit() 92 | if self.timer is not None: 93 | self.nvim.funcs.timer_stop(self.timer) 94 | 95 | def _initialize_if_necessary(self) -> None: 96 | if not self.initialized: 97 | self._initialize() 98 | 99 | def _get_magma(self, requires_instance: bool) -> Optional[MagmaBuffer]: 100 | maybe_magma = self.buffers.get(self.nvim.current.buffer.number) 101 | if requires_instance and maybe_magma is None: 102 | raise MagmaException( 103 | "Magma is not initialized; run `:MagmaInit ` to \ 104 | initialize." 105 | ) 106 | return maybe_magma 107 | 108 | def _clear_interface(self) -> None: 109 | if not self.initialized: 110 | return 111 | 112 | for magma in self.buffers.values(): 113 | magma.clear_interface() 114 | assert self.canvas is not None 115 | self.canvas.present() 116 | 117 | def _update_interface(self) -> None: 118 | if not self.initialized: 119 | return 120 | 121 | magma = self._get_magma(False) 122 | if magma is None: 123 | return 124 | 125 | magma.update_interface() 126 | 127 | def _ask_for_choice( 128 | self, preface: str, options: List[str] 129 | ) -> Optional[str]: 130 | index: int = self.nvim.funcs.inputlist( 131 | [preface] 132 | + [f"{i+1}. {option}" for i, option in enumerate(options)] 133 | ) 134 | if index == 0: 135 | return None 136 | else: 137 | return options[index - 1] 138 | 139 | def _initialize_buffer(self, kernel_name: str) -> MagmaBuffer: 140 | assert self.canvas is not None 141 | magma = MagmaBuffer( 142 | self.nvim, 143 | self.canvas, 144 | self.highlight_namespace, 145 | self.extmark_namespace, 146 | self.nvim.current.buffer, 147 | self.options, 148 | kernel_name, 149 | ) 150 | 151 | self.buffers[self.nvim.current.buffer.number] = magma 152 | 153 | return magma 154 | 155 | @pynvim.command("MagmaInit", nargs="?", sync=True, complete='file') # type: ignore 156 | @nvimui # type: ignore 157 | def command_init(self, args: List[str]) -> None: 158 | self._initialize_if_necessary() 159 | 160 | if args: 161 | kernel_name = args[0] 162 | self._initialize_buffer(kernel_name) 163 | else: 164 | PROMPT = "Select the kernel to launch:" 165 | available_kernels = get_available_kernels() 166 | if self.nvim.exec_lua("return vim.ui.select ~= nil"): 167 | self.nvim.exec_lua( 168 | """ 169 | vim.ui.select( 170 | {%s}, 171 | {prompt = "%s"}, 172 | function(choice) 173 | if choice ~= nil then 174 | vim.cmd("MagmaInit " .. choice) 175 | end 176 | end 177 | ) 178 | """ 179 | % ( 180 | ", ".join(repr(x) for x in available_kernels), 181 | PROMPT, 182 | ) 183 | ) 184 | else: 185 | kernel_name = self._ask_for_choice( 186 | PROMPT, 187 | available_kernels, # type: ignore 188 | ) 189 | if kernel_name is not None: 190 | self.command_init([kernel_name]) 191 | 192 | def _deinit_buffer(self, magma: MagmaBuffer) -> None: 193 | magma.deinit() 194 | del self.buffers[magma.buffer.number] 195 | 196 | @pynvim.command("MagmaDeinit", nargs=0, sync=True) # type: ignore 197 | @nvimui # type: ignore 198 | def command_deinit(self) -> None: 199 | self._initialize_if_necessary() 200 | 201 | magma = self._get_magma(True) 202 | assert magma is not None 203 | 204 | self._clear_interface() 205 | 206 | self._deinit_buffer(magma) 207 | 208 | def _do_evaluate( 209 | self, pos: Tuple[Tuple[int, int], Tuple[int, int]] 210 | ) -> None: 211 | self._initialize_if_necessary() 212 | 213 | magma = self._get_magma(True) 214 | assert magma is not None 215 | 216 | bufno = self.nvim.current.buffer.number 217 | span = Span( 218 | DynamicPosition(self.nvim, self.extmark_namespace, bufno, *pos[0]), 219 | DynamicPosition(self.nvim, self.extmark_namespace, bufno, *pos[1]), 220 | ) 221 | 222 | code = span.get_text(self.nvim) 223 | 224 | magma.run_code(code, span) 225 | 226 | def _do_evaluate_expr(self, expr): 227 | self._initialize_if_necessary() 228 | 229 | magma = self._get_magma(True) 230 | assert magma is not None 231 | bufno = self.nvim.current.buffer.number 232 | span = Span( 233 | DynamicPosition(self.nvim, self.extmark_namespace, bufno, 0, 0), 234 | DynamicPosition(self.nvim, self.extmark_namespace, bufno, 0, 0), 235 | ) 236 | magma.run_code(expr, span) 237 | 238 | @pynvim.command("MagmaEnterOutput", sync=True) # type: ignore 239 | @nvimui # type: ignore 240 | def command_enter_output_window(self) -> None: 241 | magma = self._get_magma(True) 242 | assert magma is not None 243 | magma.enter_output() 244 | 245 | @pynvim.command("MagmaEvaluateArgument", nargs=1, sync=True) 246 | @nvimui 247 | def commnand_magma_evaluate_argument(self, expr) -> None: 248 | assert len(expr) == 1 249 | self._do_evaluate_expr(expr[0]) 250 | 251 | @pynvim.command("MagmaEvaluateVisual", sync=True) # type: ignore 252 | @nvimui # type: ignore 253 | def command_evaluate_visual(self) -> None: 254 | _, lineno_begin, colno_begin, _ = self.nvim.funcs.getpos("'<") 255 | _, lineno_end, colno_end, _ = self.nvim.funcs.getpos("'>") 256 | span = ( 257 | ( 258 | lineno_begin - 1, 259 | min(colno_begin, len(self.nvim.funcs.getline(lineno_begin))) 260 | - 1, 261 | ), 262 | ( 263 | lineno_end - 1, 264 | min(colno_end, len(self.nvim.funcs.getline(lineno_end))), 265 | ), 266 | ) 267 | 268 | self._do_evaluate(span) 269 | 270 | @pynvim.command("MagmaEvaluateOperator", sync=True) # type: ignore 271 | @nvimui # type: ignore 272 | def command_evaluate_operator(self) -> None: 273 | self._initialize_if_necessary() 274 | 275 | self.nvim.options["operatorfunc"] = "MagmaOperatorfunc" 276 | self.nvim.out_write("g@\n") 277 | 278 | @pynvim.command("MagmaEvaluateLine", nargs=0, sync=True) # type: ignore 279 | @nvimui # type: ignore 280 | def command_evaluate_line(self) -> None: 281 | _, lineno, _, _, _ = self.nvim.funcs.getcurpos() 282 | lineno -= 1 283 | 284 | span = ((lineno, 0), (lineno, -1)) 285 | 286 | self._do_evaluate(span) 287 | 288 | @pynvim.command("MagmaReevaluateCell", nargs=0, sync=True) # type: ignore 289 | @nvimui # type: ignore 290 | def command_evaluate_cell(self) -> None: 291 | self._initialize_if_necessary() 292 | 293 | magma = self._get_magma(True) 294 | assert magma is not None 295 | 296 | magma.reevaluate_cell() 297 | 298 | @pynvim.command("MagmaInterrupt", nargs=0, sync=True) # type: ignore 299 | @nvimui # type: ignore 300 | def command_interrupt(self) -> None: 301 | magma = self._get_magma(True) 302 | assert magma is not None 303 | 304 | magma.interrupt() 305 | 306 | @pynvim.command("MagmaRestart", nargs=0, sync=True, bang=True) # type: ignore # noqa 307 | @nvimui # type: ignore 308 | def command_restart(self, bang: bool) -> None: 309 | magma = self._get_magma(True) 310 | assert magma is not None 311 | 312 | magma.restart(delete_outputs=bang) 313 | 314 | @pynvim.command("MagmaDelete", nargs=0, sync=True) # type: ignore 315 | @nvimui # type: ignore 316 | def command_delete(self) -> None: 317 | self._initialize_if_necessary() 318 | 319 | magma = self._get_magma(True) 320 | assert magma is not None 321 | 322 | magma.delete_cell() 323 | 324 | @pynvim.command("MagmaShowOutput", nargs=0, sync=True) # type: ignore 325 | @nvimui # type: ignore 326 | def command_show_output(self) -> None: 327 | self._initialize_if_necessary() 328 | 329 | magma = self._get_magma(True) 330 | assert magma is not None 331 | 332 | magma.should_open_display_window = True 333 | self._update_interface() 334 | 335 | @pynvim.command("MagmaSave", nargs="?", sync=True) # type: ignore 336 | @nvimui # type: ignore 337 | def command_save(self, args: List[str]) -> None: 338 | self._initialize_if_necessary() 339 | 340 | if args: 341 | path = args[0] 342 | else: 343 | path = get_default_save_file( 344 | self.options, self.nvim.current.buffer 345 | ) 346 | 347 | dirname = os.path.dirname(path) 348 | if not os.path.exists(dirname): 349 | os.makedirs(dirname) 350 | 351 | magma = self._get_magma(True) 352 | assert magma is not None 353 | 354 | with open(path, "w") as file: 355 | json.dump(save(magma), file) 356 | 357 | @pynvim.command("MagmaLoad", nargs="?", sync=True) # type: ignore 358 | @nvimui # type: ignore 359 | def command_load(self, args: List[str]) -> None: 360 | self._initialize_if_necessary() 361 | 362 | if args: 363 | path = args[0] 364 | else: 365 | path = get_default_save_file( 366 | self.options, self.nvim.current.buffer 367 | ) 368 | 369 | if self.nvim.current.buffer.number in self.buffers: 370 | raise MagmaException( 371 | "Magma is already initialized; MagmaLoad initializes Magma." 372 | ) 373 | 374 | with open(path) as file: 375 | data = json.load(file) 376 | 377 | magma = None 378 | 379 | try: 380 | MagmaIOError.assert_has_key(data, "version", int) 381 | if (version := data["version"]) != 1: 382 | raise MagmaIOError(f"Bad version: {version}") 383 | 384 | MagmaIOError.assert_has_key(data, "kernel", str) 385 | kernel_name = data["kernel"] 386 | 387 | magma = self._initialize_buffer(kernel_name) 388 | 389 | load(magma, data) 390 | 391 | self._update_interface() 392 | except MagmaIOError as err: 393 | if magma is not None: 394 | self._deinit_buffer(magma) 395 | 396 | raise MagmaException("Error while doing Magma IO: " + str(err)) 397 | 398 | # Internal functions which are exposed to VimScript 399 | 400 | @pynvim.function("MagmaClearInterface", sync=True) # type: ignore 401 | @nvimui # type: ignore 402 | def function_clear_interface(self, _: Any) -> None: 403 | self._clear_interface() 404 | 405 | @pynvim.function("MagmaOnBufferUnload", sync=True) # type: ignore 406 | @nvimui # type: ignore 407 | def function_on_buffer_unload(self, _: Any) -> None: 408 | abuf_str = self.nvim.funcs.expand("") 409 | if not abuf_str: 410 | return 411 | 412 | magma = self.buffers.get(int(abuf_str)) 413 | if magma is None: 414 | return 415 | 416 | self._deinit_buffer(magma) 417 | 418 | @pynvim.function("MagmaOnExitPre", sync=True) # type: ignore 419 | @nvimui # type: ignore 420 | def function_on_exit_pre(self, _: Any) -> None: 421 | self._deinitialize() 422 | 423 | @pynvim.function("MagmaTick", sync=True) # type: ignore 424 | @nvimui # type: ignore 425 | def function_magma_tick(self, _: Any) -> None: 426 | self._initialize_if_necessary() 427 | 428 | magma = self._get_magma(False) 429 | if magma is None: 430 | return 431 | 432 | magma.tick() 433 | 434 | @pynvim.function("MagmaUpdateInterface", sync=True) # type: ignore 435 | @nvimui # type: ignore 436 | def function_update_interface(self, _: Any) -> None: 437 | self._update_interface() 438 | 439 | @pynvim.function("MagmaOperatorfunc", sync=True) # type: ignore 440 | @nvimui # type: ignore 441 | def function_magma_operatorfunc(self, args: List[str]) -> None: 442 | if not args: 443 | return 444 | 445 | kind = args[0] 446 | 447 | _, lineno_begin, colno_begin, _ = self.nvim.funcs.getpos("'[") 448 | _, lineno_end, colno_end, _ = self.nvim.funcs.getpos("']") 449 | 450 | if kind == "line": 451 | colno_begin = 1 452 | colno_end = -1 453 | elif kind == "char": 454 | pass 455 | else: 456 | raise MagmaException( 457 | f"this kind of selection is not supported: '{kind}'" 458 | ) 459 | 460 | span = ( 461 | ( 462 | lineno_begin - 1, 463 | min(colno_begin, len(self.nvim.funcs.getline(lineno_begin))) 464 | - 1, 465 | ), 466 | ( 467 | lineno_end - 1, 468 | min(colno_end, len(self.nvim.funcs.getline(lineno_end))), 469 | ), 470 | ) 471 | 472 | self._do_evaluate(span) 473 | 474 | @pynvim.function("MagmaDefineCell", sync=True) 475 | def function_magma_define_cell(self, args: List[int]) -> None: 476 | if not args: 477 | return 478 | 479 | self._initialize_if_necessary() 480 | magma = self._get_magma(True) 481 | assert magma is not None 482 | 483 | start = args[0] 484 | end = args[1] 485 | bufno = self.nvim.current.buffer.number 486 | span = Span( 487 | DynamicPosition( 488 | self.nvim, self.extmark_namespace, bufno, start - 1, 0 489 | ), 490 | DynamicPosition(self.nvim, self.extmark_namespace, bufno, end - 1, -1), 491 | ) 492 | magma.outputs[span] = OutputBuffer(self.nvim, self.canvas, self.options) 493 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------