diff options
| author | bptato <nincsnevem662@gmail.com> | 2022-07-22 19:52:31 +0200 |
|---|---|---|
| committer | bptato <nincsnevem662@gmail.com> | 2022-07-22 19:52:31 +0200 |
| commit | 6f7bcc54ab03bc31be309352c73fd8d8153f9c91 (patch) | |
| tree | dc4fd8a80ccc8a5a8f7c5a567fcbf80c3e66eccb /src | |
| parent | c69a8ab7576e2053afc5dfcee5c7152a07c31230 (diff) | |
| download | chawan-6f7bcc54ab03bc31be309352c73fd8d8153f9c91.tar.gz | |
Add search function
Uses libregexp from QuickJS. Incremental search is quite hacky for now,
but overall it seems to work OK.
Diffstat (limited to 'src')
| -rw-r--r-- | src/bindings/libregexp.h | 92 | ||||
| -rw-r--r-- | src/bindings/libregexp.nim | 19 | ||||
| -rw-r--r-- | src/bindings/libunicode.h | 124 | ||||
| -rw-r--r-- | src/bindings/quickjs.nim | 3 | ||||
| -rw-r--r-- | src/client.nim | 118 | ||||
| -rw-r--r-- | src/config/config.nim | 2 | ||||
| -rw-r--r-- | src/io/buffer.nim | 230 | ||||
| -rw-r--r-- | src/io/lineedit.nim | 59 | ||||
| -rw-r--r-- | src/js/javascript.nim | 14 | ||||
| -rw-r--r-- | src/js/regex.nim | 105 |
10 files changed, 676 insertions, 90 deletions
diff --git a/src/bindings/libregexp.h b/src/bindings/libregexp.h new file mode 100644 index 00000000..9aedb7e9 --- /dev/null +++ b/src/bindings/libregexp.h @@ -0,0 +1,92 @@ +/* + * Regular Expression Engine + * + * Copyright (c) 2017-2018 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef LIBREGEXP_H +#define LIBREGEXP_H + +#include <stddef.h> + +#include "libunicode.h" + +#define LRE_BOOL int /* for documentation purposes */ + +#define LRE_FLAG_GLOBAL (1 << 0) +#define LRE_FLAG_IGNORECASE (1 << 1) +#define LRE_FLAG_MULTILINE (1 << 2) +#define LRE_FLAG_DOTALL (1 << 3) +#define LRE_FLAG_UTF16 (1 << 4) +#define LRE_FLAG_STICKY (1 << 5) + +#define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */ + +uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size, + const char *buf, size_t buf_len, int re_flags, + void *opaque); +int lre_get_capture_count(const uint8_t *bc_buf); +int lre_get_flags(const uint8_t *bc_buf); +const char *lre_get_groupnames(const uint8_t *bc_buf); +int lre_exec(uint8_t **capture, + const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen, + int cbuf_type, void *opaque); + +int lre_parse_escape(const uint8_t **pp, int allow_utf16); +LRE_BOOL lre_is_space(int c); + +/* must be provided by the user */ +LRE_BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size); +void *lre_realloc(void *opaque, void *ptr, size_t size); + +/* JS identifier test */ +extern uint32_t const lre_id_start_table_ascii[4]; +extern uint32_t const lre_id_continue_table_ascii[4]; + +static inline int lre_js_is_ident_first(int c) +{ + if ((uint32_t)c < 128) { + return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1; + } else { +#ifdef CONFIG_ALL_UNICODE + return lre_is_id_start(c); +#else + return !lre_is_space(c); +#endif + } +} + +static inline int lre_js_is_ident_next(int c) +{ + if ((uint32_t)c < 128) { + return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1; + } else { + /* ZWNJ and ZWJ are accepted in identifiers */ +#ifdef CONFIG_ALL_UNICODE + return lre_is_id_continue(c) || c == 0x200C || c == 0x200D; +#else + return !lre_is_space(c) || c == 0x200C || c == 0x200D; +#endif + } +} + +#undef LRE_BOOL + +#endif /* LIBREGEXP_H */ diff --git a/src/bindings/libregexp.nim b/src/bindings/libregexp.nim new file mode 100644 index 00000000..1b84400e --- /dev/null +++ b/src/bindings/libregexp.nim @@ -0,0 +1,19 @@ +const lreheader = "bindings/libregexp.h" + +const + LRE_FLAG_GLOBAL* = 1 shl 0 + LRE_FLAG_IGNORECASE* = 1 shl 1 + LRE_FLAG_MULTILINE* = 1 shl 2 + LRE_FLAG_DOTALL* = 1 shl 3 + LRE_FLAG_UTF16* = 1 shl 4 + LRE_FLAG_STICKY* = 1 shl 5 + +proc lre_compile*(plen: ptr cint, error_msg: cstring, error_msg_size: cint, + buf: cstring, buf_len: csize_t, re_flags: cint, + opaque: pointer): ptr uint8 {.importc: "lre_compile", header: lreheader.} + +proc lre_exec*(capture: ptr ptr uint8, bc_buf: ptr uint8, cbuf: ptr uint8, + cindex: cint, clen: cint, cbuf_type: cint, + opaque: pointer): cint {.importc: "lre_exec", header: lreheader.} + +proc lre_get_capture_count*(bc_buf: ptr uint8): cint {.importc: "lre_get_capture_count", header: lreheader.} diff --git a/src/bindings/libunicode.h b/src/bindings/libunicode.h new file mode 100644 index 00000000..cfa600a5 --- /dev/null +++ b/src/bindings/libunicode.h @@ -0,0 +1,124 @@ +/* + * Unicode utilities + * + * Copyright (c) 2017-2018 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef LIBUNICODE_H +#define LIBUNICODE_H + +#include <inttypes.h> + +#define LRE_BOOL int /* for documentation purposes */ + +/* define it to include all the unicode tables (40KB larger) */ +#define CONFIG_ALL_UNICODE + +#define LRE_CC_RES_LEN_MAX 3 + +typedef enum { + UNICODE_NFC, + UNICODE_NFD, + UNICODE_NFKC, + UNICODE_NFKD, +} UnicodeNormalizationEnum; + +int lre_case_conv(uint32_t *res, uint32_t c, int conv_type); +LRE_BOOL lre_is_cased(uint32_t c); +LRE_BOOL lre_is_case_ignorable(uint32_t c); + +/* char ranges */ + +typedef struct { + int len; /* in points, always even */ + int size; + uint32_t *points; /* points sorted by increasing value */ + void *mem_opaque; + void *(*realloc_func)(void *opaque, void *ptr, size_t size); +} CharRange; + +typedef enum { + CR_OP_UNION, + CR_OP_INTER, + CR_OP_XOR, +} CharRangeOpEnum; + +void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); +void cr_free(CharRange *cr); +int cr_realloc(CharRange *cr, int size); +int cr_copy(CharRange *cr, const CharRange *cr1); + +static inline int cr_add_point(CharRange *cr, uint32_t v) +{ + if (cr->len >= cr->size) { + if (cr_realloc(cr, cr->len + 1)) + return -1; + } + cr->points[cr->len++] = v; + return 0; +} + +static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2) +{ + if ((cr->len + 2) > cr->size) { + if (cr_realloc(cr, cr->len + 2)) + return -1; + } + cr->points[cr->len++] = c1; + cr->points[cr->len++] = c2; + return 0; +} + +int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len); + +static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2) +{ + uint32_t b_pt[2]; + b_pt[0] = c1; + b_pt[1] = c2 + 1; + return cr_union1(cr, b_pt, 2); +} + +int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, + const uint32_t *b_pt, int b_len, int op); + +int cr_invert(CharRange *cr); + +#ifdef CONFIG_ALL_UNICODE + +LRE_BOOL lre_is_id_start(uint32_t c); +LRE_BOOL lre_is_id_continue(uint32_t c); + +int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, + UnicodeNormalizationEnum n_type, + void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); + +/* Unicode character range functions */ + +int unicode_script(CharRange *cr, + const char *script_name, LRE_BOOL is_ext); +int unicode_general_category(CharRange *cr, const char *gc_name); +int unicode_prop(CharRange *cr, const char *prop_name); + +#endif /* CONFIG_ALL_UNICODE */ + +#undef LRE_BOOL + +#endif /* LIBUNICODE_H */ diff --git a/src/bindings/quickjs.nim b/src/bindings/quickjs.nim index 76cd74cd..73cba0d2 100644 --- a/src/bindings/quickjs.nim +++ b/src/bindings/quickjs.nim @@ -96,6 +96,7 @@ proc JS_NewRuntime*(): JSRuntime {.importc: "JS_NewRuntime", header: qjsheader.} proc JS_FreeRuntime*(rt: JSRuntime) {.importc: "JS_FreeRuntime", header: qjsheader.} proc JS_NewContext*(rt: JSRuntime): JSContext {.importc: "JS_NewContext", header: qjsheader.} +proc JS_NewContextRaw*(rt: JSRuntime): JSContext {.importc: "JS_NewContextRaw", header: qjsheader.} proc JS_FreeContext*(ctx: JSContext) {.importc: "JS_FreeContext", header: qjsheader.} proc JS_GetGlobalObject*(ctx: JSContext): JSValue {.importc: "JS_GetGlobalObject", header: qjsheader.} @@ -127,3 +128,5 @@ proc JS_GetException*(ctx: JSContext): JSValue {.importc: "JS_GetException", hea proc JS_SetContextOpaque*(ctx: JSContext, opaque: pointer) {.importc: "JS_SetContextOpaque", header: qjsheader.} proc JS_GetContextOpaque*(ctx: JSContext): pointer {.importc: "JS_GetContextOpaque", header: qjsheader.} + +proc js_free_rt*(rt: JSRuntime, p: pointer) {.importc: "js_free_rt".} diff --git a/src/client.nim b/src/client.nim index 8eb63b33..d8f6e2e7 100644 --- a/src/client.nim +++ b/src/client.nim @@ -2,6 +2,7 @@ import options import os import streams import terminal +import unicode import css/sheet import config/config @@ -9,6 +10,7 @@ import io/buffer import io/lineedit import io/loader import js/javascript +import js/regex import types/url import utils/twtstr @@ -24,11 +26,17 @@ type loader: FileLoader jsrt: JSRuntime jsctx: JSContext + regex: Option[Regex] + revsearch: bool ActionError = object of IOError LoadError = object of ActionError InterruptError = object of LoadError +proc statusMode(client: Client) = + print(HVP(client.buffer.height + 1, 1)) + print(EL()) + proc js_console_log(ctx: JSContext, this: JSValue, argc: int, argv: ptr JSValue): JSValue {.cdecl.} = let opaque = ctx.getOpaque() for i in 0..<argc: @@ -42,12 +50,8 @@ proc js_console_log(ctx: JSContext, this: JSValue, argc: int, argv: ptr JSValue) opaque.err &= '\n' return JS_UNDEFINED -# Probably never called, but just in case... proc `=destroy`(client: var ClientObj) = if client.jsctx != nil: - let opaque = client.jsctx.getOpaque() - if opaque != nil: - dealloc(opaque) free(client.jsctx) if client.jsrt != nil: free(client.jsrt) @@ -59,7 +63,7 @@ proc newClient*(): Client = let ctx = rt.newJSContext() result.jsrt = rt result.jsctx = ctx - let global = ctx.getGlobalObject() + var global = ctx.getGlobalObject() let console = newJSObject(result.jsctx) console.setFunctionProperty("log", js_console_log) global.setProperty("console", console) @@ -127,6 +131,8 @@ proc readPipe(client: Client, ctype: string) = client.buffer.contenttype = if ctype != "": ctype else: "text/plain" client.buffer.ispipe = true client.buffer.istream = newFileStream(stdin) + const url = parseUrl("file://-").get + client.buffer.location = url client.buffer.load() #TODO is this portable at all? if reopen(stdin, "/dev/tty", fmReadWrite): @@ -196,8 +202,7 @@ proc reloadPage(client: Client) = proc changeLocation(client: Client) = let buffer = client.buffer var url = buffer.location.serialize(true) - print(HVP(buffer.height + 1, 1)) - print(EL()) + client.statusMode() let status = readLine("URL: ", url, buffer.width) if status: client.loadUrl(url) @@ -229,8 +234,7 @@ proc toggleSource*(client: Client) = proc command(client: Client) = var iput: string - print(HVP(client.buffer.height + 1, 1)) - print(EL()) + client.statusMode() let status = readLine("COMMAND: ", iput, client.buffer.width) if status and iput.len > 0: let ret = client.jsctx.eval(iput, "<stdin>", JS_EVAL_TYPE_GLOBAL) @@ -240,7 +244,7 @@ proc command(client: Client) = let str = ex.toString() if str.issome: opaque.err &= str.get & '\n' - let stack = ex.getProperty("stack") + var stack = ex.getProperty("stack") if not stack.isUndefined(): let str = stack.toString() if str.issome: @@ -262,6 +266,94 @@ proc command(client: Client) = client.buffer.contenttype = "text/plain" client.setupBuffer() +proc searchNext(client: Client) = + if client.regex.issome: + if not client.revsearch: + discard client.buffer.cursorNextMatch(client.regex.get) + else: + discard client.buffer.cursorPrevMatch(client.regex.get) + +proc searchPrev(client: Client) = + if client.regex.issome: + if not client.revsearch: + discard client.buffer.cursorPrevMatch(client.regex.get) + else: + discard client.buffer.cursorNextMatch(client.regex.get) + +proc search(client: Client) = + client.statusMode() + var iput: string + let status = readLine("/", iput, client.buffer.width) + if status: + if iput.len != 0: + client.regex = compileSearchRegex(iput) + client.revsearch = false + client.searchNext() + +proc searchBack(client: Client) = + client.statusMode() + var iput: string + let status = readLine("?", iput, client.buffer.width) + if status: + if iput.len != 0: + client.regex = compileSearchRegex(iput) + client.revsearch = true + client.searchNext() + +proc isearch(client: Client) = + client.statusMode() + var iput: string + let cpos = client.buffer.cpos + let status = readLine("/", iput, client.buffer.width, {}, (proc(state: var LineState): bool = + client.buffer.marks.setLen(0) + let regex = compileSearchRegex($state.news) + client.buffer.cpos = cpos + if regex.issome: + let match = client.buffer.cursorNextMatch(regex.get) + if match.success: + client.buffer.addMark(match.x, match.y, match.str) + let nos = client.buffer.nostatus + client.buffer.redraw = true + client.buffer.refreshBuffer(true) + print(HVP(client.buffer.height + 1, 2)) + else: + client.buffer.marks.setLen(0) + return true + false + )) + client.buffer.marks.setLen(0) + client.buffer.redraw = true + if status: + client.regex = compileSearchRegex(iput) + else: + client.buffer.cpos = cpos + +proc isearchBack(client: Client) = + client.statusMode() + var iput: string + let cpos = client.buffer.cpos + let status = readLine("?", iput, client.buffer.width, {}, (proc(state: var LineState): bool = + client.buffer.marks.setLen(0) + let regex = compileSearchRegex($state.news) + client.buffer.cpos = cpos + if regex.issome: + let match = client.buffer.cursorPrevMatch(regex.get) + if match.success: + client.buffer.addMark(match.x, match.y, match.str) + let nos = client.buffer.nostatus + client.buffer.redraw = true + client.buffer.refreshBuffer(true) + print(HVP(client.buffer.height + 1, 2)) + return true + false + )) + client.buffer.marks.setLen(0) + client.buffer.redraw = true + if status: + client.regex = compileSearchRegex(iput) + else: + client.buffer.cpos = cpos + proc quit(client: Client) = eraseScreen() print(HVP(0, 0)) @@ -319,6 +411,12 @@ proc input(client: Client) = of ACTION_NEXT_BUFFER: client.nextBuffer() of ACTION_DISCARD_BUFFER: client.discardBuffer() of ACTION_COMMAND: client.command() + of ACTION_SEARCH: client.search() + of ACTION_SEARCH_BACK: client.searchBack() + of ACTION_ISEARCH: client.isearch() + of ACTION_ISEARCH_BACK: client.isearchBack() + of ACTION_SEARCH_NEXT: client.searchNext() + of ACTION_SEARCH_PREV: client.searchPrev() else: discard proc inputLoop(client: Client) = diff --git a/src/config/config.nim b/src/config/config.nim index 5d04f5e5..5c1d3a16 100644 --- a/src/config/config.nim +++ b/src/config/config.nim @@ -28,6 +28,8 @@ type ACTION_CURSOR_RIGHT_EDGE, ACTION_CURSOR_VERT_MIDDLE, ACTION_CURSOR_LEFT_EDGE, ACTION_CENTER_LINE, ACTION_LINE_INFO, ACTION_COMMAND, + ACTION_SEARCH, ACTION_SEARCH_BACK, ACTION_ISEARCH, ACTION_ISEARCH_BACK, + ACTION_SEARCH_NEXT, ACTION_SEARCH_PREV, ACTION_LINED_SUBMIT, ACTION_LINED_CANCEL, ACTION_LINED_BACKSPACE, ACTION_LINED_DELETE, ACTION_LINED_CLEAR, ACTION_LINED_KILL, ACTION_LINED_KILL_WORD, diff --git a/src/io/buffer.nim b/src/io/buffer.nim index e7a5d881..065a85a8 100644 --- a/src/io/buffer.nim +++ b/src/io/buffer.nim @@ -16,13 +16,34 @@ import io/cell import io/lineedit import io/loader import io/term +import js/regex import layout/box import render/renderdocument import render/rendertext +import types/color import types/url import utils/twtstr type + CursorPosition* = object + cursorx*: int + cursory*: int + xend*: int + fromx*: int + fromy*: int + + BufferMatch* = object + success*: bool + x*: int + y*: int + str*: string + + Mark* = object + x: int + y: int + format: Format + grid: FixedGrid + Buffer* = ref object contenttype*: string title*: string @@ -33,11 +54,7 @@ type hovertext*: string width*: int height*: int - cursorx*: int - cursory*: int - xend*: int - fromx*: int - fromy*: int + cpos*: CursorPosition attrs*: TermAttributes document*: Document viewport*: Viewport @@ -53,9 +70,10 @@ type prevnode*: Node sourcepair*: Buffer prev*: Buffer - next* {.cursor.}: Buffer + next*: Buffer userstyle*: CSSStylesheet loader*: FileLoader + marks*: seq[Mark] proc newBuffer*(): Buffer = new(result) @@ -67,6 +85,12 @@ proc newBuffer*(): Buffer = result.prevdisplay = newFixedGrid(result.width, result.height) result.statusmsg = newFixedGrid(result.width) +func cursorx*(buffer: Buffer): int {.inline.} = buffer.cpos.cursorx +func cursory*(buffer: Buffer): int {.inline.} = buffer.cpos.cursory +func fromx*(buffer: Buffer): int {.inline.} = buffer.cpos.fromx +func fromy*(buffer: Buffer): int {.inline.} = buffer.cpos.fromy +func xend*(buffer: Buffer): int {.inline.} = buffer.cpos.xend + func generateFullOutput(buffer: Buffer): string = var x = 0 var w = 0 @@ -171,6 +195,14 @@ func generateStatusMessage*(buffer: Buffer): string = if w < buffer.width: result &= EL() +func generateMark*(buffer: Buffer, mark: Mark): string = + var format = newFormat() + var w = 0 + for cell in mark.grid: + result &= format.processFormat(cell.format) + result &= $cell.runes + w += cell.width() + func numLines(buffer: Buffer): int = buffer.lines.len func lastVisibleLine(buffer: Buffer): int = min(buffer.fromy + buffer.height, buffer.numLines) @@ -228,17 +260,20 @@ func getCursorClickable(buffer: Buffer): Element = func currentLine(buffer: Buffer): string = return buffer.lines[buffer.cursory].str -func currentCursorBytes(buffer: Buffer): int = - let line = buffer.currentLine +func cursorBytes(buffer: Buffer, y: int, cc = buffer.fromx + buffer.cursorx): int = + assert y < buffer.lines.len + let line = buffer.lines[y].str var w = 0 var i = 0 - let cc = buffer.fromx + buffer.cursorx while i < line.len and w < cc: var r: Rune fastRuneAt(line, i, r) w += r.width() return i +func currentCursorBytes(buffer: Buffer, cc = buffer.fromx + buffer.cursorx): int = + return buffer.cursorBytes(buffer.cursory, cc) + func currentWidth(buffer: Buffer): int = let line = buffer.currentLine if line.len == 0: return 0 @@ -333,20 +368,20 @@ proc refreshDisplay(buffer: Buffer) = proc setCursorX(buffer: Buffer, x: int, refresh = true, save = true) = if (not refresh) or (buffer.fromx <= x and x < buffer.fromx + buffer.width): - buffer.cursorx = x + buffer.cpos.cursorx = x else: if refresh and buffer.fromx > buffer.cursorx: - buffer.fromx = max(buffer.currentLineWidth() - 1, 0) - buffer.cursorx = buffer.fromx + buffer.cpos.fromx = max(buffer.currentLineWidth() - 1, 0) + buffer.cpos.cursorx = buffer.fromx elif x > buffer.cursorx: - buffer.fromx = max(x - buffer.width + 1, 0) - buffer.cursorx = x + buffer.cpos.fromx = max(x - buffer.width + 1, 0) + buffer.cpos.cursorx = x elif x < buffer.cursorx: - buffer.fromx = x - buffer.cursorx = x + buffer.cpos.fromx = x + buffer.cpos.cursorx = x buffer.redraw = true if save: - buffer.xend = buffer.cursorx + buffer.cpos.xend = buffer.cursorx proc restoreCursorX(buffer: Buffer) = buffer.setCursorX(max(min(buffer.currentLineWidth() - 1, buffer.xend), 0), false, false) @@ -355,23 +390,32 @@ proc setCursorY(buffer: Buffer, y: int) = if buffer.cursory == y: return if y - buffer.fromy >= 0 and y - buffer.height < buffer.fromy: - buffer.cursory = y + buffer.cpos.cursory = y else: if y > buffer.cursory: - buffer.fromy = max(y - buffer.height + 1, 0) + buffer.cpos.fromy = max(y - buffer.height + 1, 0) else: - buffer.fromy = min(y, buffer.maxfromy) - buffer.cursory = y + buffer.cpos.fromy = min(y, buffer.maxfromy) + buffer.cpos.cursory = y buffer.redraw = true buffer.restoreCursorX() +proc centerLine*(buffer: Buffer) = + let ny = max(min(buffer.cursory - buffer.height div 2, buffer.numLines - buffer.height), 0) + if ny != buffer.fromy: + buffer.cpos.fromy = ny + buffer.redraw = true + proc setCursorXY*(buffer: Buffer, x, y: int) = + let fy = buffer.fromy buffer.setCursorY(max(min(y, buffer.numLines - 1), 0)) buffer.setCursorX(max(min(buffer.currentLineWidth(), x), 0)) + if fy != buffer.fromy: + buffer.centerLine() proc setFromXY*(buffer: Buffer, x, y: int) = - buffer.fromy = max(min(y, buffer.maxfromy), 0) - buffer.fromx = max(min(x, buffer.maxfromx), 0) + buffer.cpos.fromy = max(min(y, buffer.maxfromy), 0) + buffer.cpos.fromx = max(min(x, buffer.maxfromx), 0) proc cursorDown*(buffer: Buffer) = if buffer.cursory < buffer.numLines - 1: @@ -563,61 +607,55 @@ proc cursorVertMiddle*(buffer: Buffer) = proc cursorRightEdge*(buffer: Buffer) = buffer.setCursorX(min(buffer.fromx + buffer.width - 1, buffer.currentLineWidth)) -proc centerLine*(buffer: Buffer) = - let ny = max(min(buffer.cursory - buffer.height div 2, buffer.numLines - buffer.height), 0) - if ny != buffer.fromy: - buffer.fromy = ny - buffer.redraw = true - proc halfPageUp*(buffer: Buffer) = - buffer.cursory = max(buffer.cursory - buffer.height div 2 + 1, 0) + buffer.cpos.cursory = max(buffer.cursory - buffer.height div 2 + 1, 0) let nfy = max(0, buffer.fromy - buffer.height div 2 + 1) if nfy != buffer.fromy: - buffer.fromy = nfy + buffer.cpos.fromy = nfy buffer.redraw = true buffer.restoreCursorX() proc halfPageDown*(buffer: Buffer) = - buffer.cursory = min(buffer.cursory + buffer.height div 2 - 1, buffer.numLines - 1) + buffer.cpos.cursory = min(buffer.cursory + buffer.height div 2 - 1, buffer.numLines - 1) let nfy = min(max(buffer.numLines - buffer.height, 0), buffer.fromy + buffer.height div 2 - 1) if nfy != buffer.fromy: - buffer.fromy = nfy + buffer.cpos.fromy = nfy buffer.redraw = true buffer.restoreCursorX() proc pageUp*(buffer: Buffer) = - buffer.cursory = max(buffer.cursory - buffer.height, 0) + buffer.cpos.cursory = max(buffer.cursory - buffer.height, 0) let nfy = max(0, buffer.fromy - buffer.height) if nfy != buffer.fromy: - buffer.fromy = nfy + buffer.cpos.fromy = nfy buffer.redraw = true buffer.restoreCursorX() proc pageDown*(buffer: Buffer) = - buffer.cursory = min(buffer.cursory + buffer.height, buffer.numLines - 1) + buffer.cpos.cursory = min(buffer.cursory + buffer.height, buffer.numLines - 1) let nfy = min(buffer.fromy + buffer.height, max(buffer.numLines - buffer.height, 0)) if nfy != buffer.fromy: - buffer.fromy = nfy + buffer.cpos.fromy = nfy buffer.redraw = true buffer.restoreCursorX() proc pageLeft*(buffer: Buffer) = - buffer.cursorx = max(buffer.cursorx - buffer.width, 0) + buffer.cpos.cursorx = max(buffer.cursorx - buffer.width, 0) let nfx = max(0, buffer.fromx - buffer.width) if nfx != buffer.fromx: - buffer.fromx = nfx + buffer.cpos.fromx = nfx buffer.redraw = true proc pageRight*(buffer: Buffer) = - buffer.cursorx = min(buffer.fromx, buffer.currentLineWidth()) + buffer.cpos.cursorx = min(buffer.fromx, buffer.currentLineWidth()) let nfx = min(max(buffer.maxScreenWidth() - buffer.width, 0), buffer.fromx + buffer.width) if nfx != buffer.fromx: - buffer.fromx = nfx + buffer.cpos.fromx = nfx buffer.redraw = true proc scrollDown*(buffer: Buffer) = if buffer.fromy + buffer.height < buffer.numLines: - inc buffer.fromy + inc buffer.cpos.fromy if buffer.fromy > buffer.cursory: buffer.cursorDown() buffer.redraw = true @@ -626,7 +664,7 @@ proc scrollDown*(buffer: Buffer) = proc scrollUp*(buffer: Buffer) = if buffer.fromy > 0: - dec buffer.fromy + dec buffer.cpos.fromy if buffer.fromy + buffer.height <= buffer.cursory: buffer.cursorUp() buffer.redraw = true @@ -635,12 +673,12 @@ proc scrollUp*(buffer: Buffer) = proc scrollRight*(buffer: Buffer) = if buffer.fromx + buffer.width < buffer.maxScreenWidth(): - inc buffer.fromx + inc buffer.cpos.fromx buffer.redraw = true proc scrollLeft*(buffer: Buffer) = if buffer.fromx > 0: - dec buffer.fromx + dec buffer.cpos.fromx if buffer.cursorx < buffer.fromx: buffer.setCursorX(max(buffer.currentLineWidth() - 1, 0)) buffer.redraw = true @@ -660,8 +698,78 @@ proc gotoAnchor*(buffer: Buffer) = return inc i -proc gotoLocation*(buffer: Buffer, s: string) = - discard parseUrl(s, buffer.location.some, buffer.location, true) +proc addMark*(buffer: Buffer, x, y: int, str: string) = + assert y < buffer.lines.len + var format = newFormat() + format.reverse = true + #TODO get rid of the string part; marks should only consist of a position and + # a length. + var grid = newFixedGrid(str.width()) + var i = 0 + for r in str.runes: + grid[i].runes.add(r) + grid[i].format = format + i += r.width() + buffer.marks.add(Mark(x: x, y: y, format: format, grid: grid)) + +proc cursorNextMatch(buffer: Buffer, regex: Regex, sy, ey: int, wrap = false): BufferMatch = + for y in sy..ey: + let s = if y == buffer.cursory and not wrap: + buffer.currentCursorBytes(buffer.fromx + buffer.cursorx + 1) + else: + 0 + let res = regex.exec(buffer.lines[y].str, s) + if res.success and res.captures.len > 0: + let cap = res.captures[0] + buffer.setCursorXY(cap.s, y) + result.success = true + result.y = y + result.x = buffer.cursorBytes(y, cap.s) + result.str = buffer.lines[y].str.substr(cap.s, cap.e - 1) + return + +proc cursorNextMatch*(buffer: Buffer, regex: Regex, wrap = true): BufferMatch = + let s = buffer.currentCursorBytes(buffer.fromx + buffer.cursorx + 1) + var low = buffer.cursory + if s == buffer.lines.len: + low += 1 + if low > buffer.lines.high: + low = 0 + let ret = buffer.cursorNextMatch(regex, low, buffer.lines.high) + if ret.success: + return ret + if wrap: + return buffer.cursorNextMatch(regex, 0, low, true) + +proc cursorPrevMatch*(buffer: Buffer, regex: Regex, sy, ey: int, wrap = false): BufferMatch = + for y in countdown(sy, ey): + let e = if y == buffer.cursory and not wrap: + buffer.currentCursorBytes() + else: + buffer.lines[y].str.len + 1 + let res = regex.exec(buffer.lines[y].str) + if res.success: + for i in countdown(res.captures.high, 0): + let cap = res.captures[i] + if cap.s < e: + buffer.setCursorXY(cap.s, y) + result.success = true + result.y = y + result.x = buffer.cursorBytes(y, cap.s) + result.str = buffer.lines[y].str.substr(cap.s, cap.e - 1) + return + +proc cursorPrevMatch*(buffer: Buffer, regex: Regex, wrap = true): BufferMatch = + var high = buffer.cursory + if buffer.fromx + buffer.cursorx - 1 < 0: + high -= 1 + if high < 0: + high = buffer.lines.high + let ret = buffer.cursorPrevMatch(regex, high, 0) + if ret.success: + return ret + if wrap: + return buffer.cursorPrevMatch(regex, buffer.lines.high, high) proc refreshTermAttrs*(buffer: Buffer): bool = let newAttrs = getTermAttributes() @@ -674,11 +782,11 @@ proc refreshTermAttrs*(buffer: Buffer): bool = proc updateCursor(buffer: Buffer) = if buffer.fromy > buffer.lastVisibleLine - 1: - buffer.fromy = 0 - buffer.cursory = buffer.lastVisibleLine - 1 + buffer.cpos.fromy = 0 + buffer.cpos.cursory = buffer.lastVisibleLine - 1 if buffer.lines.len == 0: - buffer.cursory = 0 + buffer.cpos.cursory = 0 proc updateHover(buffer: Buffer) = let thisnode = buffer.currentDisplayCell().node @@ -1086,7 +1194,7 @@ proc drawBuffer*(buffer: Buffer) = print(format.processFormat(newFormat())) print('\n') -proc refreshBuffer*(buffer: Buffer) = +proc refreshBuffer*(buffer: Buffer, peek = false) = buffer.title = buffer.getTitle() stdout.hideCursor() @@ -1106,10 +1214,18 @@ proc refreshBuffer*(buffer: Buffer) = buffer.refreshDisplay() buffer.displayBufferSwapOutput() - if not buffer.nostatus: - buffer.statusMsgForBuffer() - else: - buffer.nostatus = false - buffer.displayStatusMessage() - buffer.cursorBufferPos() + for mark in buffer.marks: + if mark.y in buffer.fromy..(buffer.fromy + buffer.height) and mark.x in buffer.fromx..(buffer.fromx + buffer.width): + print(HVP(mark.y - buffer.fromy + 1, mark.x - buffer.fromx + 1)) + print(SGR()) + print(buffer.generateMark(mark)) + print(SGR()) + + if not peek: + if not buffer.nostatus: + buffer.statusMsgForBuffer() + else: + buffer.nostatus = false + buffer.displayStatusMessage() + buffer.cursorBufferPos() stdout.showCursor() diff --git a/src/io/lineedit.nim b/src/io/lineedit.nim index ce719d47..64a1358c 100644 --- a/src/io/lineedit.nim +++ b/src/io/lineedit.nim @@ -7,8 +7,10 @@ import sugar import utils/twtstr import config/config -type LineState = object - news: seq[Rune] +type LineState* = object + news*: seq[Rune] + prompt*: string + current: string s: string feedNext: bool escNext: bool @@ -17,7 +19,8 @@ type LineState = object minlen: int maxlen: int displen: int - spaces: seq[string] + disallowed: set[char] + callback: proc(state: var LineState): bool {.closure.} func lwidth(r: Rune): int = if r.isControlChar(): @@ -69,7 +72,7 @@ proc begin(state: LineState) = state.forward(state.minlen) proc space(state: LineState, i: int) = - print(state.spaces[i]) + print(' '.repeat(i)) proc redraw(state: var LineState) = var dispw = state.news.lwidth(state.shift, state.shift + state.displen) @@ -120,17 +123,10 @@ proc insertCharseq(state: var LineState, cs: var seq[Rune], disallowed: set[char state.cursor += cs.len state.fullRedraw() -proc readLine*(current: var string, minlen, maxlen: int, disallowed: set[char] = {}): bool = - var state: LineState - state.news = current.toRunes() - state.cursor = state.news.len - state.minlen = minlen - state.maxlen = maxlen - state.displen = state.maxlen - 1 - #cache strings - for i in 0..(maxlen - minlen): - state.spaces.add(' '.repeat(i)) - printesc(current) +proc readLine(state: var LineState): bool = + printesc(state.prompt) + printesc(state.current) + while true: if not state.feedNext: state.s = "" @@ -147,7 +143,6 @@ proc readLine*(current: var string, minlen, maxlen: int, disallowed: set[char] = of ACTION_LINED_CANCEL: return false of ACTION_LINED_SUBMIT: - current = $state.news return true of ACTION_LINED_BACKSPACE: if state.cursor > 0: @@ -248,7 +243,7 @@ proc readLine*(current: var string, minlen, maxlen: int, disallowed: set[char] = state.cursor = 0 of ACTION_LINED_END: if state.cursor < state.news.len: - if state.news.lwidth(state.shift, state.news.len) < maxlen: + if state.news.lwidth(state.shift, state.news.len) < state.maxlen: state.forward(state.news.lwidth(state.cursor, state.news.len)) else: state.fullRedraw() @@ -257,10 +252,32 @@ proc readLine*(current: var string, minlen, maxlen: int, disallowed: set[char] = state.feedNext = true elif validateUtf8(state.s) == -1: var cs = state.s.toRunes() - state.insertCharseq(cs, disallowed) + state.insertCharseq(cs, state.disallowed) + if state.callback(state): + state.fullRedraw() else: state.feedNext = true -proc readLine*(prompt: string, current: var string, termwidth: int, disallowed: set[char] = {}): bool = - printesc(prompt) - readLine(current, prompt.lwidth(), termwidth - prompt.len, disallowed) +proc readLine*(prompt: string, current: var string, termwidth: int, + disallowed: set[char], + callback: proc(state: var LineState): bool {.closure.}): bool = + var state: LineState + + state.prompt = prompt + state.current = current + state.news = current.toRunes() + state.cursor = state.news.len + state.minlen = prompt.lwidth() + state.maxlen = termwidth - prompt.len + state.displen = state.maxlen - 1 + state.disallowed = disallowed + state.callback = callback + + if state.readLine(): + current = $state.news + return true + return false + +proc readLine*(prompt: string, current: var string, termwidth: int, + disallowed: set[char] = {}): bool = + readLine(prompt, current, termwidth, disallowed, (proc(state: var LineState): bool = false)) diff --git a/src/js/javascript.nim b/src/js/javascript.nim index 2518f252..95e37110 100644 --- a/src/js/javascript.nim +++ b/src/js/javascript.nim @@ -35,6 +35,9 @@ proc newJSContext*(rt: JSRuntime): JSContext = opaque.err = "" JS_SetContextOpaque(result, opaque) +proc newJSContextRaw*(rt: JSRuntime): JSContext = + result = JS_NewContextRaw(rt) + func getJSObject*(ctx: JSContext, v: JSValue): JSObject = result.ctx = ctx result.val = v @@ -94,14 +97,21 @@ proc setFunctionProperty*(obj: JSObject, name: string, fun: JSCFunction) = # return fun(JSObject(ctx: ctx, qjs: obj), invoc) #), cstring(name), 1)) -proc free*(ctx: JSContext) = +proc free*(ctx: var JSContext) = + eprint "free" + let opaque = ctx.getOpaque() + if opaque != nil: + dealloc(opaque) JS_FreeContext(ctx) + ctx = nil -proc free*(rt: JSRuntime) = +proc free*(rt: var JSRuntime) = JS_FreeRuntime(rt) + rt = nil proc free*(obj: JSObject) = JS_FreeValue(obj.ctx, obj.val) + #TODO maybe? obj.val = JS_NULL proc eval*(ctx: JSContext, s: string, file: string, eval_flags: int): JSObject = result.ctx = ctx diff --git a/src/js/regex.nim b/src/js/regex.nim new file mode 100644 index 00000000..a1bd7d35 --- /dev/null +++ b/src/js/regex.nim @@ -0,0 +1,105 @@ +# Interface for QuickJS libregexp. + +import options + +import bindings/libregexp +import bindings/quickjs +import js/javascript + +export + LRE_FLAG_GLOBAL, + LRE_FLAG_IGNORECASE, + LRE_FLAG_MULTILINE, + LRE_FLAG_DOTALL, + LRE_FLAG_UTF16, + LRE_FLAG_STICKY + +type + Regex* = object + bytecode*: ptr uint8 + + RegexResult* = object + success*: bool + captures*: seq[tuple[s, e: int]] # start, end + +var dummyRuntime = newJSRuntime() +var dummyContext = dummyRuntime.newJSContextRaw() + +proc `=destroy`(regex: var Regex) = + if regex.bytecode != nil: + dummyRuntime.js_free_rt(regex.bytecode) + regex.bytecode = nil + +proc compileRegex*(buf: string, flags: int): Option[Regex] = + var regex: Regex + var len: cint + var error_msg_size = 64 + var error_msg = cast[cstring](alloc0(error_msg_size)) + let bytecode = lre_compile(addr len, error_msg, cint(error_msg_size), cstring(buf), csize_t(buf.len), cint(flags), dummyContext) + if error_msg != nil: + #TODO error handling? + dealloc(error_msg) + error_msg = nil + if bytecode == nil: + return none(Regex) # Failed to compile. + regex.bytecode = bytecode + return some(regex) + +proc compileSearchRegex*(str: string): Option[Regex] = + # Parse any applicable flags in regex/<flags>. The last forward slash is + # dropped when <flags> is empty, and interpreted as a character when the + # flags are is invalid. + + var i = str.high + var flagsi = -1 + while i >= 0: + case str[i] + of '/': + if i > 0 and str[i - 1] == '\\': break # escaped + flagsi = i + break + of 'i', 'm', 's': discard + else: break # invalid flag + dec i + + var flags = LRE_FLAG_GLOBAL # for easy backwards matching + + if flagsi == -1: + return compileRegex(str, flags) + + for i in flagsi..str.high: + case str[i] + of '/': discard + of 'i': flags = flags or LRE_FLAG_IGNORECASE + of 'm': flags = flags or LRE_FLAG_MULTILINE + of 's': flags = flags or LRE_FLAG_DOTALL + else: assert false + return compileRegex(str.substr(0, flagsi - 1), flags) + +proc exec*(regex: Regex, str: string, start = 0): RegexResult = + assert 0 <= start and start <= str.len + let cstr = cstring(str) + let captureCount = lre_get_capture_count(cast[ptr uint8](regex.bytecode)) + var capture: ptr ptr uint8 = nil + if captureCount > 0: + capture = cast[ptr ptr uint8](alloc0(sizeof(ptr uint8) * captureCount * 2)) + let ret = lre_exec(capture, regex.bytecode, + cast[ptr uint8](cstr), cint(start), + cint(str.len), cint(0), dummyContext) + result.success = ret == 1 #TODO error handling? (-1) + if result.success: + var i = 0 + let cstrAddress = cast[int](cstr) + while i < captureCount * sizeof(ptr uint8): + let startPointerAddress = cast[int](capture) + i + i += sizeof(ptr uint8) + let endPointerAddress = cast[int](capture) + i + i += sizeof(ptr uint8) + let startPointer = cast[ptr ptr uint8](startPointerAddress) + let endPointer = cast[ptr ptr uint8](endPointerAddress) + let startAddress = cast[int](startPointer[]) + let endAddress = cast[int](endPointer[]) + let s = startAddress - cstrAddress + let e = endAddress - cstrAddress + result.captures.add((s, e)) + dealloc(capture) |