/// Interactive hex editor application, defines behavior for main program.
///
/// Also dubbed the View System. It attempts to visually represent types
/// on screen.
///
/// Copyright: dd86k
/// License: MIT
/// Authors: $(LINK2 https://github.com/dd86k, dd86k)
module view;
import core.stdc.stdlib : malloc, realloc, free, exit;
import std.algorithm.comparison : min, max;
import std.algorithm.searching : canFind;
import std.array : insertInPlace;
import std.conv : text, to;
import std.file : exists;
import std.process : environment;
import std.stdio : File;
import std.format : sformat;
import std.functional : toDelegate;
import os.terminal;
import ddhx.charset : Charset;
import ddhx.document.base : IDocument, DocCaps;
import ddhx.document.file : FileDocument, OFlags;
import ddhx.document.memory : MemoryDocument;
import ddhx.editor.base : IDocumentEditor, PieceInfo;
import ddhx.formatting;
import ddhx.inspector;
import ddhx.logger;
import ddhx.platform; // For assertion, MAXSIZE
import colors;
import configuration;
import messages;
import patterns;
import ranges;
import searches;
import status;
import utils;
private debug enum DEBUG = "+debug"; else enum DEBUG = "";
/// Copyright string
immutable string DDHX_COPYRIGHT = "Copyright (c) 2017-2026 dd86k ";
/// App version
///
/// For packaging, the DEB script expects this.
/// Also, Debian uses tilde (~) for pre-release markers.
immutable string DDHX_VERSION = "0.14.1"~DEBUG;
/// Build timestamp
immutable string DDHX_BUILDINFO = "Built: "~__TIMESTAMP__;
/// Chunk size to use when I/O is involved (reading, writing)
private enum CONFIG_CHUNKSIZE = KiB!128;
/// In-place save history-preservation stash cap. Beyond this volume of
/// overwritten source ranges, save in place but drop undo history rather
/// than buffering it all in memory.
private enum CONFIG_INPLACE_STASH_BUDGET = MiB!64;
/// Needle size limit for selection searches, at most a chunk for search.
private enum CONFIG_NEEDLE_LIMIT = KiB!128;
static assert(CONFIG_NEEDLE_LIMIT <= SEARCH_CHUNKSIZE, "search reads needles within a chunk");
/// Rows of context kept around a find result when the view scrolls to it.
private enum CONFIG_FIND_PADDING = 1;
/// Buffer size for diff navigation scans: a chunk, plus room for the one
/// element of overlap that carries the hunk state between chunks (the widest
/// supported element is 8 bytes).
private enum CONFIG_DIFFBUFSIZE = CONFIG_CHUNKSIZE + 8;
/// Amount of data before warning for a copy for clipboard.
private enum CONFIG_COPY_WORRY = MiB!16;
private enum // Internal editor status flags
{
/// Update the entire view panel (address/data/text)
UVIEW = 1 << 1,
/// Update the header bar
UHEADER = 1 << 2,
/// Update the status bar
USTATUS = 1 << 3,
/// Pending message
UMESSAGE = 1 << 16,
/// Editing (of an element) in progress
UEDITING = 1 << 17,
/// Update header, view, and status
UALL = UHEADER | UVIEW | USTATUS,
/// Selection is active and has a range going
SELECT_ACTIVE = 1,
/// Mark started, so don't clear it (a hack for "mark"/"unmark" commands)
SELECT_ONGOING = 1 << 1,
}
private enum PanelType
{
data,
text,
inspector, // Read-only view; visibility is RC.inspector. Reserved as a
// focus target for future actions (e.g. scroll within panel,
// jump cursor to a typed value).
}
private alias command_func = void function(Session*, Argument[]);
/// Argument completion: candidates for the argument after args, starting with
/// partial. A candidate ending with a space is a whole argument, others are
/// meant to be typed further (directory, key modifier).
private alias complete_func = string[] function(Argument[] args, string partial);
private
struct Keybind
{
/// Function implementing command
command_func impl;
/// Parameters to add
Argument[] parameters;
}
private
struct CurrentSelection
{
long anchor; /// original position when started
int status; /// current status
}
/// Editor session.
//
// Because Editor mostly exists for ddhx (editor) and RC can be manually
// handled elsewhere.
struct Session
{
/// Runtime configuration.
RC rc;
///
IDocumentEditor editor;
/// Original file
IDocument ogdoc;
/// Target file path.
string target;
// NOTE: Maximum number of handles
//
// The front-end uses FileDocument class to open files, which uses OSFile.
// OSFile uses the operating system native File API, and not the C runtime's,
// which is typically limited from 512 to 4096 handles per process (and 32-bit seeks).
//
// On Windows, that's typically about 64K (Win32) or 16M (Win64) file handles.
// 16K for network files.
//
// On Linux, querying prlimit.1 (6.17-generic amd64), or /proc/self/limits,
// for NOFILE ("Max open files"), yields 1024 as a soft limit, and 524288 as a
// hard limit.
//
// Don't even worry about closing handles for undo operations because a redo will
// require to re-open that file anyway.
/// Opened documents.
///
/// Since the front-end is the one opening files, make it the one to track
/// them as well. This leaves editors without the duty to manage them,
/// making testing easier.
IDocument[] documents;
/// Active selection
CurrentSelection selection;
/// Bookmarks, sorted by address (ascending). Inserted/removed by
/// the "bookmark-set" / "bookmark-unset" commands.
Bookmark[] bookmarks;
/// Logical position at the start of the view.
long position_view;
/// Logical position of the cursor in the editor.
long position_cursor;
/// Currently focused panel.
PanelType panel;
/// Cursor position when edit started
long editpos;
/// Input system
InputFormatter input;
/// Diff panel: file compared against the current view (null = panel hidden).
/// Opened by the "diff-file" command, shown at the bottom of the screen.
IDocument diffdoc;
/// Path of the diffed file, displayed inside the panel separator line.
string diffpath;
}
private __gshared // globals have the ugly "g_" prefix to be told apart
{
// Editor status, resetted every time update() is called
int g_status;
// Terminal dimensions, updated by update()
int g_rows; /// Terminal rows available
int g_cols; /// Terminal columns available
int g_viewrows; /// Effective height for view panel
// HACK: Global for screen resize events
// Eventually, a session manager could hold multiple sessions and return
// the 'current' session (return sessions[current]).
Session *g_session;
// Message buffer.
// Sadly, format() allocates a buffer and sformat() throws when it runs out
// of the buffer instead of resizing (that would suck to implement anyway).
char[] g_messagebuf;
// Message slice result.
string g_message;
/// Last search needle buffer (find commands use this).
Pattern g_needle;
/// Last replacement buffer (find-replace uses this).
Pattern g_replacement;
/// Digit position within current element (0-based, left to right) for digit mode
int g_digitpos;
/// Global clipboard buffer.
ubyte *g_clipboard_ptr;
size_t g_clipboard_len;
/// Registered commands
command_func[string] g_commands;
/// Argument completion of registered commands
complete_func[string] g_completers;
/// Registered shortcuts
Keybind[int] g_keys;
///
ColorMapper g_colors;
}
/// Represents a command with a name (required), a shortcut, and a function
/// that implements it (required).
struct Command
{
string name; /// Command short name
string description; /// Short description
int key; /// Default shortcut
command_func impl; /// Implementation
complete_func complete; /// Argument completion, or null
}
// Reserved (Ideal: Ctrl=Action, Alt=Alternative):
// - "hash": Hash selection with result in status
// Mostly checksums and digests under 256 bits.
// 256 bits -> 32 Bytes -> 64 hex characters
// Command names
//
// Because navigation keys are the most essential, they get short names.
// For example, mpv uses LEFT and RIGHT to bind to "seek -10" and "seek 10".
// Thus, we use "left" and "right" to bind to left-arrow and right-arrow.
//
// Additionally, both "bind ctrl+9 right" and "bind ctrl+9 goto +1" are valid assignation.
//
// For the rest, prefer "thing-do" (e.g., bookmark-set).
// Command designs
// - Names: If commonly used (ie, navigation), command is one word
// - Selection: command parameters are prioritized over selections
/// List of default commands and shortcuts
immutable Command[] default_commands = [
// Navigation
{ "left", "Move cursor left one element",
Key.LeftArrow, &move_left },
{ "right", "Move cursor right one element",
Key.RightArrow, &move_right },
{ "up", "Move cursor upward a line",
Key.UpArrow, &move_up },
{ "down", "Move cursor downward a line",
Key.DownArrow, &move_down },
{ "home", "Move cursor to start of line",
Key.Home, &move_ln_start },
{ "end", "Move cursor to end of line",
Key.End, &move_ln_end },
{ "top", "Move cursor to start of document",
Mod.ctrl|Key.Home, &move_abs_start },
{ "bottom", "Move cursor to end of document",
Mod.ctrl|Key.End, &move_abs_end },
{ "page-up", "Move cursor up a screen",
Key.PageUp, &move_pg_up },
{ "page-down", "Move cursor down a screen",
Key.PageDown, &move_pg_down },
{ "view-up", "Move view up a row",
Mod.ctrl|Key.UpArrow, &view_up },
{ "view-down", "Move view down a row",
Mod.ctrl|Key.DownArrow, &view_down },
{ "skip-back", "Skip same elements backward",
Mod.ctrl|Key.LeftArrow, &move_skip_backward },
{ "skip-front", "Skip same elements forward",
Mod.ctrl|Key.RightArrow, &move_skip_forward },
// Deletions
{ "delete", "Delete data at cursor position",
Key.Delete, &delete_front },
{ "delete-back", "Delete data before cursor position",
Key.Backspace, &delete_back },
// Selections
{ "select-left", "Extend selection one element backward",
Mod.shift|Key.LeftArrow, &select_left },
{ "select-right", "Extend selection one element forward",
Mod.shift|Key.RightArrow, &select_right },
{ "select-up", "Extend selection one line up",
Mod.shift|Key.UpArrow, &select_up },
{ "select-down", "Extend selection one line down",
Mod.shift|Key.DownArrow, &select_down },
{ "select-home", "Extend selection to start of line",
Mod.shift|Key.Home, &select_home },
{ "select-end", "Extend selection to end of line",
Mod.shift|Key.End, &select_end },
{ "select-top", "Extend selection to start of document",
Mod.ctrl|Mod.shift|Key.Home,&select_top },
{ "select-bottom", "Extend selection to end of document",
Mod.ctrl|Mod.shift|Key.End, &select_bottom },
{ "select-all", "Select entire document",
Mod.ctrl|Key.A, &select_all },
{ "select", "Select elements using a range expression",
0, &select },
{ "mark" , "Start a selection",
0, &mark },
{ "unmark", "End selection",
0, &unmark },
// Bookmarks
{ "bookmark-set", "Add a bookmark over a range, selection, or cursor",
0, &bookmark_set },
{ "bookmark-unset", "Remove bookmarks overlapping a range, selection, or cursor",
0, &bookmark_unset },
{ "bookmark-toggle", "Set a bookmark, or unset any that overlap the target range",
Key.M, &bookmark_toggle },
{ "bookmark-next", "Jump to the next bookmark",
']', &bookmark_next },
{ "bookmark-prev", "Jump to the previous bookmark",
'[', &bookmark_prev },
{ "bookmark-clear", "Clear list of bookmarks",
0, &bookmark_clear },
{ "bookmark-save", "Save bookmarks to a file",
0, &bookmark_save, &complete_path },
{ "bookmark-load", "Load bookmarks from a file",
0, &bookmark_load, &complete_path },
// Mode, panel...
{ "change-panel", "Switch data panel",
Key.Tab, &change_panel },
{ "toggle-inspector", "Show or hide the data inspector panel",
Mod.alt|Key.I, &toggle_inspector },
{ "toggle-endian", "Toggle endian (little/big)",
Mod.alt|Key.E, &toggle_endian },
// Acting as a toggle (file opened + no args=close) is fine
{ "diff-file", "Diff a file against the current view (no path closes it)",
0, &diff_file, &complete_path },
{ "diff-next", "Jump to the next difference against the diffed file",
Key.RightBrace, &diff_next },
{ "diff-prev", "Jump to the previous difference against the diffed file",
Key.LeftBrace, &diff_prev },
{ "change-mode", "Change writing mode (between overwrite and insert)",
Key.Insert, &change_writemode },
// Find
{ "find", "Find data in document using patterns",
Mod.ctrl|Key.F, &find },
{ "find-back", "Find data in document, backward direction",
Mod.ctrl|Key.B, &find_back },
{ "find-next", "Repeat search forward",
Mod.ctrl|Key.N, &find_next },
{ "find-prev", "Repeat search backward",
Mod.shift|Key.N, &find_prev },
{ "find-bookmark", "Bookmark every match of a pattern in the document",
0, &find_bookmark },
// Data manipulation
{ "replace", "Replace data using a pattern",
0, &replace_ }, // avoid Phobos conflict
{ "insert", "Insert data using a pattern",
0, &insert_ }, // avoid Phobos conflict
{ "replace-range", "Replace data using a range and pattern",
0, &replace_range },
{ "insert-range", "Insert data using a range and pattern",
0, &insert_range },
{ "replace-file", "Replace data using a file",
0, &replace_file, &complete_path },
{ "insert-file", "Insert data using a file",
0, &insert_file, &complete_path },
// Find and Data manipulation
{ "find-replace", "Find next occurrence and replace it",
Mod.ctrl|Key.R, &find_replace },
{ "find-replace-all", "Find and replace all occurrences",
0, &find_replace_all },
// Copy-Paste
{ "copy", "Copy data into buffer",
Mod.alt|Key.C, &clip_copy },
{ "cut", "Copy data into buffer and delete selection",
Mod.alt|Key.X, &clip_cut },
{ "paste", "Paste clipboard data into document", // modal!
Mod.alt|Key.V, &clip_paste },
{ "clear-clip", "Clear clipboard data",
0, &clip_clear },
{ "save", "Save document",
Mod.ctrl|Key.S, &save },
// NOTE: "save-as" exists solely because it's a dedicated operation.
// Despite that "save" could have just gotten an optional parameter.
// Analogous to GNU nano having ^O.
{ "save-as", "Save document as a different file",
Mod.ctrl|Key.O, &save_as, &complete_path },
{ "open", "Open a file, replacing the current document",
0, &open_, &complete_path },
{ "close", "Close the document, leaving an empty buffer",
0, &close_ },
// Undo-Redo
{ "undo", "Undo last edit",
Mod.ctrl|Key.U, &undo },
{ "redo", "Redo previous change",
Mod.ctrl|Key.Y, &redo },
// Position
{ "goto", "Navigate or jump to a specific position",
Mod.ctrl|Key.G, &goto_ },
// Reports
{ "report", "Report position, document size, and % in bytes",
Mod.ctrl|Key.P, &report },
// TODO: Deprecate report-name (pollutes command list), replaced by show
{ "report-name", "Report document name on screen",
0, &report_name },
// TODO: Deprecate report-version (pollutes command list), replaced by show
{ "report-version", "Report ddhx version on screen",
0, &report_version },
// Show information command
{ "show", "Show information",
0, &show, &complete_show },
// Exports
{ "export-range", "Export selected range to file",
0, &export_range, &complete_path },
// Misc actions
{ "refresh", "Refresh entire screen",
Mod.ctrl|Key.L, &refresh },
{ "autosize", "Automatically set column size depending of screen",
Mod.alt|Key.R, &autosize },
{ "set", "Set a configuration value for this session",
0, &set, &complete_set },
{ "bind", "Bind a new command shortcut for this session",
0, &bind, &complete_bind },
{ "unbind", "Remove or reset a bind shortcut",
0, &unbind, &complete_key },
{ "color", "Change scheme color for this session",
0, &color, &complete_color },
{ "reset-keys", "Reset all binded keys to default for this session",
0, &reset_keys },
{ "menu", "Invoke command prompt",
Key.Enter, &prompt_command },
{ "quit", "Quit program",
Mod.ctrl|Key.Q, &quit },
];
// There used to be a test that checked for dupes but it caused issues elsewhere.
/// Initiate default keys and commands.
void initdefaults()
{
// Setup default commands and shortcuts
foreach (command; default_commands)
{
g_commands[command.name] = command.impl;
if (command.complete)
g_completers[command.name] = command.complete;
if (command.key)
g_keys[command.key] = Keybind( command.impl, null );
}
// Add a "debug" command for, you guessed it, debugging for debug builds
debug g_commands["debug"] = (Session* session, Argument[] args)
{
if (args.length == 0)
throw new Exception(MSG_MISSING_ACTION);
// Don't need a throw command, this throws plenty
switch (args[0].text) {
case "msg":
// Very long message by default
string msg = args.length > 1 ?
args[1].text :
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"~
"aaaaaa"; // Otherwise, 86x 'a'
message(msg);
break;
case "dump":
string target = args.length > 1 ? args[1].text : "ddhx_dump.txt";
import std.datetime : Clock;
import ddhx.platform : TARGET_ENV, TARGET_OS, TARGET_PLATFORM;
File file; // Old LDC opAssign bug might resurface, idk
file.open(target, "w");
file.writeln("ddhx debug dump");
file.writeln("Time\t: ", Clock.currTime());
file.writeln("Version\t: ", DDHX_VERSION);
file.writeln("System\t: ", TARGET_OS);
file.writeln("Environment\t: ", TARGET_ENV);
file.writeln("Platform\t: ", TARGET_PLATFORM);
file.writeln();
file.writeln("Terminal");
TerminalSize termsize = terminalSize();
file.writeln("\t", termsize.columns, " columns");
file.writeln("\t", termsize.rows, " rows");
import core.memory : GC;
file.writeln("GC");
GC.Stats stats = GC.stats();
file.writeln("\t", stats.freeSize, " B Free");
file.writeln("\t", stats.usedSize, " B Used");
static if (__VERSION__ >= 2087)
file.writeln("\t", stats.allocatedInCurrentThread, " B Allocated (thread)");
/*GC.ProfileStats profiler = GC.profileStats(); // Useless if not enabled?
file.writeln("\t", profiler.numCollections, " Cycles");
file.writeln("\t", profiler.totalCollectionTime, " Total Collection Time");
file.writeln("\t", profiler.totalPauseTime, " Total Pause Time");
file.writeln("\t", profiler.maxPauseTime, " Max Pause Time");
file.writeln("\t", profiler.maxCollectionTime, " Max Collection Time");*/
file.writeln("Globals");
file.writeln("\tg_messagebuf.length\t: ", g_messagebuf.length);
file.writeln("\tg_message.length\t: ", g_message.length);
file.writeln("\tg_needle.length\t: ", g_needle.data.length);
file.writeln("\tg_clipboard_ptr\t: ", g_clipboard_ptr);
file.writeln("\tg_clipboard_len\t: ", g_clipboard_len);
file.writeln("\tg_commands.length\t: ", g_commands.length);
file.writeln("\tg_keys.length\t: ", g_keys.length);
file.writeln("\tg_rows\t: ", g_rows);
file.writeln("\tg_cols\t: ", g_cols);
file.writeln("\tg_viewrows\t: ", g_viewrows);
file.writeln("Session");
file.writeln("\tg_session.position_cursor\t: ", g_session.position_cursor);
file.writeln("\tg_session.position_view\t: ", g_session.position_view);
file.writeln("\tg_session.target\t: ", g_session.target);
file.writeln("\tg_session.selection.anchor\t: ", g_session.selection.anchor);
file.writeln("\tg_session.selection.status\t: ", g_session.selection.status);
file.writeln("\tg_session.editpos\t: ", g_session.editpos);
file.writeln("\tg_session.input.index\t: ", g_session.input.index);
file.writeln("Selection");
Selection sel = selection(g_session);
file.writeln("\tselection.start\t: ", sel.start);
file.writeln("\tselection.end\t: ", sel.end);
file.writeln("\tselection.length\t: ", sel.length);
file.writeln("RC");
file.writeln("\tg_session.rc.address_spacing\t: ", g_session.rc.address_spacing);
file.writeln("\tg_session.rc.address_type\t: ", g_session.rc.address_type);
file.writeln("\tg_session.rc.charset\t: ", g_session.rc.charset);
file.writeln("\tg_session.rc.columns\t: ", g_session.rc.columns);
file.writeln("\tg_session.rc.data_type\t: ", g_session.rc.data_type);
file.writeln("\tg_session.rc.header\t: ", g_session.rc.header);
file.writeln("\tg_session.rc.status\t: ", g_session.rc.status);
file.writeln("\tg_session.rc.mirror_cursor\t: ", g_session.rc.mirror_cursor);
file.writeln("\tg_session.rc.writemode\t: ", g_session.rc.writemode);
file.writeln("Editor");
file.writeln("\tClass\t: ", session.editor); // prints type!
file.writeln("\tSize\t: ", session.editor.size());
file.writeln("\tEdited\t: ", session.editor.edited());
// TODO: Dump document and editor information
file.flush();
file.close();
break;
default:
throw new Exception("Exception");
}
};
}
// Bind a key to a command with default set of parameters
void bindkey(int key, string command, Argument[] parameters)
{
log(`key=%d command="%s" params="%s"`, key, command, parameters);
void function(Session*, Argument[]) *impl = command in g_commands;
if (impl == null)
throw new Exception(text(MSG_UNKNOWN_COMMAND, command));
g_keys[key] = Keybind( *impl, parameters );
}
// Unbind/reset key
void unbindkey(int key)
{
Keybind *k = key in g_keys;
if (k == null) // nothing to unbind
return;
// Check commands for a default keybind
foreach (command; default_commands)
{
// Reset keybind to its default
if (command.key == key)
{
k.impl = command.impl;
k.parameters = null;
return;
}
}
// If key is not part of default keybinds, remove from active set
g_keys.remove(key);
}
pragma(inline)
const(Keybind)* binded(int key)
{
return key in g_keys;
}
void setcolor(ColorScheme scheme, ColorMap map)
{
g_colors.set(scheme, map);
}
Session* create_session(IDocumentEditor editor, ref RC rc, string path)
{
Session *session = new Session(rc);
session.target = path; // assign target path, a NULL value is valid
session.editor = editor; // assign editor instance
return session;
}
void start_session(Session *session, string initmsg,
string bookmarks_file = null,
string diff_file = null)
{
terminalInit(TermFeat.altScreen | TermFeat.inputSys);
terminalClear(); // alt buffers usually clears, except on framebuffers (e.g., fbcon)
terminalResizeHandler(&onresize);
terminalHideCursor();
g_session = session;
g_status = UALL;
g_messagebuf.length = 4096;
session.input = new InputFormatter; // hack due to buffer escapes
sync_settings();
if (session.rc.columns_auto)
autosize(session, null);
message(initmsg);
demote_writemode(session); // may replace initmsg, warning is more important
if (bookmarks_file)
{
log(`bookmarks_file="%s"`, diff_file);
try bookmark_load(session, [ Argument(bookmarks_file) ]);
catch (Exception ex)
{
log("%s", ex);
message("bookmarks: %s", ex.msg);
}
}
if (diff_file)
{
log(`diff_file="%s"`, diff_file);
try .diff_file(session, [ Argument(diff_file) ]);
catch (Exception ex)
{
log("%s", ex);
message("diff: %s", ex.msg);
}
}
loop(g_session);
terminalRestore();
}
/// Open the file or disk at path, replacing the current document, and return
/// the status message. A missing file becomes a new file at that path.
/// Throws on other errors, leaving the current document untouched.
string open_document(Session *session, string path)
{
import os.path : displayName;
import os.error : OSException;
IDocument doc;
try doc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
catch (OSException ex)
{
// Other errors (permission denied, unsupported type, etc.) are
// reported, only a missing file is treated as new
version (Windows)
{
import core.sys.windows.windef : ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND;
bool notfound = ex.oscode == ERROR_FILE_NOT_FOUND
|| ex.oscode == ERROR_PATH_NOT_FOUND;
}
else
{
import core.stdc.errno : ENOENT;
bool notfound = ex.oscode == ENOENT;
}
if (notfound == false)
throw ex;
log("%s", ex.msg);
}
close_document(session);
session.target = path;
string msg = MSG_NEW_FILE;
if (doc)
{
session.editor.open(doc);
session.ogdoc = doc;
msg = displayName(path);
}
if (session.rc.writemode == WritingMode.readonly)
msg ~= " [readonly]";
return msg;
}
private:
/// Close the document and files inserted into it, resetting the session to
/// an empty buffer. Unsaved edits are lost.
void close_document(Session *session)
{
session.editor.close();
if (session.ogdoc)
session.ogdoc.close();
session.ogdoc = null;
foreach (IDocument doc; session.documents)
doc.close();
session.documents = null;
session.target = null;
session.selection = CurrentSelection.init;
session.bookmarks = null;
session.position_view = 0;
session.position_cursor = 0;
session.editpos = 0;
if (session.input) // NOTE: null before start_session
session.input.reset();
g_digitpos = 0;
g_status |= UALL;
}
/// Ask to save unsaved edits, false if the user canceled.
bool confirm_discard(Session *session)
{
if (session.editor.edited() == false)
return true;
switch (promptkey("Save? (Yes/No/Cancel) ")) {
case 'n', 'N':
return true;
case 'y', 'Y':
save(session, null);
return true;
default:
// Canceling isn't an error
message(MSG_CANCELED);
return false;
}
}
// Sync RC options to various front-end components, notably when a setting changes
void sync_settings()
{
// Editor options
g_session.editor.coalescing = g_session.rc.coalescing;
// Input system
g_session.input.change(g_session.rc.data_type);
}
// Insert mode is unavailable on fixed-size documents (e.g., disks), but the
// configuration is applied before knowing which document gets opened.
// Rather than refusing to start (or refusing every setting change), the mode
// is demoted to overwrite, and the user is told about it.
void demote_writemode(Session *session)
{
if (session.rc.writemode != WritingMode.insert || fixedsize(session) == false)
return;
session.rc.writemode = WritingMode.overwrite;
message(MSG_INSERT_MODE_UNAVAILABLE);
}
void onresize() // I/O is allowed here
{
// If autoresize configuration is enabled, automatically set column count
if (g_session.rc.columns_auto)
autosize(g_session, null);
realign(g_session);
// Yes, on resize, conhost will show the console's cursor again
version (Windows) terminalHideCursor();
g_status |= UALL; // draw everything
update(g_session);
}
//
void loop(Session *session)
{
bool ctrlc;
Lupdate:
update(session); // Clears status!
Lread:
TermInput input = terminalRead();
switch (input.type) {
case InputType.signal:
switch (input.signal) {
case TerminalSignal.interrupted:
// Quit without saving
if (ctrlc)
{
terminalRestore();
exit(0);
}
session.selection.status = 0; // force all select off
ctrlc = true;
message("Again to quit");
goto Lupdate;
default:
}
break;
case InputType.keyDown:
ctrlc = false;
// Key mapped to command
const(Keybind) *k = binded( input.key );
if (k)
{
log("key=%s (%d)", input.key, input.key);
try k.impl(session, cast(Argument[])k.parameters);
catch (Exception ex)
{
log("%s", ex);
// "error: " is not prepended, because a message is already
// an indicator that something happened.
// For example, "Not implemented" is self-descriptive enough
// to say "oh yeah, that's an error".
// Plus, likely a waste of space.
message(ex.msg);
}
// If we have additional input pending, read them immediately
if (input.pending) goto Lread;
goto Lupdate;
}
// Check if the writing mode is valid
switch (session.rc.writemode) {
case WritingMode.readonly:
message("Can't edit in read-only mode");
goto Lupdate;
default:
}
if (session.rc.writemode == WritingMode.digit)
{
char typed = input.kbuffer[0];
// Digit mode: edit a single digit/nibble within the current element
DataSpec spec = selectDataSpec(session.rc.data_type);
// Validate the typed character for the data type
if (g_session.input.validate(typed) == false)
goto Lread; // invalid character for this data type
// Read the current element from the editor
Element elem;
ubyte[] raw = session.editor.view(session.position_cursor, elem.raw.ptr, spec.size_of);
if (raw.length < spec.size_of)
goto Lread; // not enough data
// Format current element value into thus buffer as text and replace digit
ElementText elbuf = void;
g_session.input.formatRaw(elbuf, raw.ptr, raw.length);
elbuf[g_digitpos] = typed;
// Parse the modified string back to bytes
if (elem.parse(session.rc.data_type, elbuf[0..spec.spacing]) == false)
goto Lread; // parse failed (e.g., overflow)
// Write it back
session.editor.replace(session.position_cursor, elem.raw.ptr, spec.size_of);
// Force any selection off
session.selection.status = 0;
// Advance digit position
try move_right(g_session, null);
catch (Exception ex)
{
log("%s", ex);
message(ex.msg);
}
g_status |= UVIEW;
goto Lupdate;
}
// start new edit
if (g_session.input.index == 0)
g_session.editpos = session.position_cursor;
// Prefer kbuffer to key because key gets translated (e.g., 'f' -> 'F')
if (g_session.input.add(input.kbuffer[0]) == false)
goto Lread; // don't even bother updating the screen
// We have a valid key and mode, so disrupt selection
session.selection.status = 0;
// if full, move cursor
if (g_session.input.full())
{
// Forcing to move cursor forces the edit to be applied,
// since cursor position when starting an edit is saved.
// The other of this is in moveabs. It detects when cursor
// has moved and will proceed with saving, but might throw
// too.
try move_right(g_session, null);
catch (Exception ex)
{
log("%s", ex);
message(ex.msg);
}
goto Lupdate;
}
g_status |= UEDITING; // active edit
break;
default:
goto Lread;
}
goto Lupdate;
}
bool iscancelling(ref TermInput input)
{
return
(input.type == InputType.keyDown && input.key == Key.Escape) ||
(input.type == InputType.signal && input.signal == TerminalSignal.interrupted);
}
// Invoke command prompt
string promptline(string prompt, scope Completer complete = null)
{
assert(prompt, "Prompt text missing");
assert(prompt.length, "Prompt text required"); // disallow empty
// Repaint header at minimum, but with view... Just in case
g_status |= USTATUS;
// Clear upper space
TerminalSize tsize = terminalSize();
// Print prompt, cursor will be after prompt
terminalCursor(0, tsize.rows - 1);
terminalWrite(prompt);
// Show and hide cursor for this scope. scope(exit) is OK with exceptions
terminalShowCursor();
scope(exit) terminalHideCursor();
// Passing x,y to fix issues where obtaining cursor position is not possible
return readline(cast(int)prompt.length, tsize.rows - 1, RL_HISTORY, complete);
}
int promptkey(string text)
{
assert(text, "Prompt text missing");
assert(text.length, "Prompt text required"); // disallow empty
g_status |= USTATUS; // Needs to be repainted anyway
// Clear upper space
TerminalSize tsize = terminalSize();
int tcols = tsize.columns - 1;
if (tcols < 10)
throw new Exception(MSG_NOT_ENOUGH_SPACE_FOR_PROMPT);
terminalCursor(0, tsize.rows - 1);
terminalWriteChar(' ', tcols);
// Print prompt, cursor will be after prompt
terminalCursor(0, tsize.rows - 1);
terminalWrite(text);
terminalShowCursor();
scope(exit) terminalHideCursor();
// Read character
Lread:
TermInput input = terminalRead();
if (input.type != InputType.keyDown)
goto Lread;
if (iscancelling(input))
throw new Exception(MSG_CANCELED);
return input.key;
}
/// Argument idx of args, or prompted for with prefix, completing with complete.
string askstring(Argument[] args, size_t idx, string prefix, complete_func complete = null)
{
// The answer is the argument as typed, so candidates go in unquoted
string[] raw(const(char)[] line, size_t caret, out size_t start)
{
string[] words;
try words = complete(args[0..min(idx, args.length)], line[0..caret].idup);
catch (Exception) {}
foreach (ref string word; words)
{
if (word.length && word[$-1] == ' ')
word = word[0..$-1];
}
return words;
}
return askline(args, idx, prefix, complete ? &raw : null);
}
/// Argument idx of args, or prompted for with prefix, completing with complete.
string askline(Argument[] args, size_t idx, string prefix, scope Completer complete)
{
string s = args is null || args.length <= idx ? promptline(prefix, complete) : args[idx].text;
// Empty string? Cancel! Can't do anything with that.
// Bonus: Besides, throwing an exception is easier to manage than
// manually checking the output at every invokation.
if (s is null || s.length == 0)
throw new Exception(MSG_CANCELED);
return s;
}
// Ask for range expression
Range askrange(Argument[] args, size_t idx, string prefix)
{
string str = askstring(args, idx, prefix);
Range r = range(str);
switch (r.start) {
case RangeSentinel.eof: // why would you?
throw new Exception(MSG_RANGE_START_CANNOT_BE_EOF);
case RangeSentinel.cursor:
r.start = g_session.position_cursor;
break;
default:
}
long docsize = g_session.editor.size();
switch (r.end) {
case RangeSentinel.eof:
r.end = docsize == 0 ? 0 : docsize - 1;
break;
case RangeSentinel.cursor:
r.end = g_session.position_cursor;
break;
default:
if (r.flags & RANGE_RELATIVE)
r.end = r.start + r.end;
}
if (r.start < 0)
throw new Exception(MSG_RANGE_START_OUT_OF_RANGE);
if (r.end < 0)
throw new Exception(MSG_RANGE_END_OUT_OF_RANGE);
if (r.start > r.end)
throw new Exception(MSG_RANGE_START_AFTER_END);
return r;
}
//
// ANCHOR Completion
//
/// Words starting with partial, sorted, as whole arguments.
string[] matching(const(string)[] words, string partial)
{
import std.algorithm.searching : startsWith;
import std.algorithm.sorting : sort;
string[] results;
foreach (string word; words)
{
if (word.startsWith(partial))
results ~= word ~ " ";
}
sort(results);
return results;
}
/// Candidates for a command line typed up to caret, quoted as needed, with
/// start set to where they go.
string[] complete_line(const(char)[] line, size_t caret, out size_t start)
{
import std.ascii : isWhite;
string[] words;
try
{
Argument[] argv = partialArguments(line[0..caret], start);
string partial = argv[$-1].text;
if (argv.length == 1)
words = matching(g_commands.keys, partial);
else if (const(complete_func) *complete = cast(string)argv[0].data in g_completers)
words = (*complete)(argv[1..$-1], partial);
}
catch (Exception) // half-typed escape, or bytes that are not text
return null;
// No space added when there is one after the caret already
bool spaced = caret < line.length && isWhite(line[caret]);
foreach (ref string word; words)
{
bool whole = word.length && word[$-1] == ' ';
string arg = quoteArgument(whole ? word[0..$-1] : word);
word = whole && spaced == false ? arg ~ " " : arg;
}
return words;
}
/// File paths starting with partial, directories ending with a separator.
string[] complete_path(Argument[] args, string partial)
{
import std.algorithm.searching : startsWith;
import std.algorithm.sorting : sort;
import std.file : dirEntries, DirEntry, SpanMode;
import std.path : baseName, dirSeparator, filenameCharCmp, isDirSeparator;
if (args.length)
return null;
// "dir/na": list "dir/", match "na"
size_t cut = partial.length;
while (cut > 0 && isDirSeparator(partial[cut - 1]) == false)
--cut;
string dir = partial[0..cut];
string name = partial[cut..$];
string[] results;
try foreach (DirEntry entry; dirEntries(dir.length ? dir : ".", SpanMode.shallow, false))
{
string base = baseName(entry.name);
// Hidden files only when asked for
if (name.length == 0 && base[0] == '.')
continue;
// Case-insensitive on Windows. Names that are not UTF-8 are skipped
bool match;
try match = startsWith!((dchar a, dchar b) => filenameCharCmp(a, b) == 0)(base, name);
catch (Exception) {}
if (match == false)
continue;
bool isdir; // false on a dangling link
try isdir = entry.isDir;
catch (Exception) {}
results ~= dir ~ base ~ (isdir ? dirSeparator : " ");
}
catch (Exception) {} // unreadable directory: what was listed so far
sort(results);
return results;
}
/// Subjects of the show command.
string[] complete_show(Argument[] args, string partial)
{
return args.length ? null : matching([ "name", "path", "size", "version" ], partial);
}
/// Setting names, then values of that setting.
string[] complete_set(Argument[] args, string partial)
{
switch (args.length) {
case 0:
string[] names;
foreach (ref immutable(Config) config; configurations)
names ~= config.name;
return matching(names, partial);
case 1:
return matching(setting_values(args[0].text), partial);
default:
return null;
}
}
/// Values a setting takes, as quoted in its availvalues ("h[exadecimal]"
/// reads as "hexadecimal"), or null for free-form settings.
string[] setting_values(string name)
{
import std.array : replace;
import std.string : indexOf;
import ddhx.charset : charsets;
string[] values;
// Listed here so a new charset can't be forgotten in availvalues
if (name == "charset")
{
foreach (immutable(Charset)* set; charsets)
values ~= set.id;
return values;
}
foreach (ref immutable(Config) config; configurations)
{
if (config.name != name)
continue;
if (config.availvalues == "Boolean")
return [ "on", "off" ];
string s = config.availvalues;
for (;;)
{
ptrdiff_t open = indexOf(s, '"');
if (open < 0)
break;
ptrdiff_t close = indexOf(s[open + 1..$], '"');
if (close < 0)
break;
values ~= s[open + 1..open + 1 + close].replace("[", "").replace("]", "");
s = s[open + close + 2..$];
}
break;
}
return values;
}
unittest
{
assert(setting_values("address") == [ "hexadecimal", "octal", "decimal" ]);
assert(setting_values("endian") == [ "little", "big", "le", "be" ]);
assert(setting_values("header") == [ "on", "off" ]);
assert(setting_values("columns") == [ "auto" ]);
assert(setting_values("status-format") == null);
assert(setting_values("charset").canFind("ascii"));
assert(setting_values("nope") == null);
}
/// Key names for a bind, keeping modifiers typed so far.
string[] complete_key(Argument[] args, string partial)
{
import std.algorithm.searching : startsWith;
import std.string : lastIndexOf;
if (args.length)
return null;
// "ctrl+pa": keep "ctrl+", match "pa"
string mods = partial[0..lastIndexOf(partial, '+') + 1];
string name = partial[mods.length..$];
string[] results;
foreach (string mod; [ "ctrl+", "alt+", "shift+" ])
{
if (canFind(mods, mod) == false && mod.startsWith(name))
results ~= mods ~ mod;
}
foreach (ref immutable(KeyName) key; keyNames)
{
if (key.name.startsWith(name))
results ~= mods ~ key.name ~ " ";
}
return results;
}
unittest
{
assert(complete_key(null, "ctrl+a") == [ "ctrl+alt+" ]);
assert(complete_key(null, "ctrl+alt+page") == [ "ctrl+alt+page-up ", "ctrl+alt+page-down " ]);
assert(complete_key(null, "f1") == [ "f1 ", "f10 ", "f11 ", "f12 " ]);
}
/// Key, then command name, then that command's own arguments.
string[] complete_bind(Argument[] args, string partial)
{
switch (args.length) {
case 0:
return complete_key(args, partial);
case 1:
return matching(g_commands.keys, partial);
default:
const(complete_func) *complete = cast(string)args[1].data in g_completers;
return complete ? (*complete)(args[2..$], partial) : null;
}
}
/// Color scheme, then a color map ("fg", "fg:bg", "invert", "reset").
string[] complete_color(Argument[] args, string partial)
{
import std.array : replace;
import std.string : indexOf;
string[] colors = [ "default" ];
foreach (string member; __traits(allMembers, TermColor))
colors ~= member;
switch (args.length) {
case 0:
string[] schemes = [ "reset" ];
foreach (string member; __traits(allMembers, ColorScheme))
schemes ~= member.replace("_", "-");
return matching(schemes, partial);
case 1:
// "red:bl": keep "red:", match background "bl"
ptrdiff_t colon = indexOf(partial, ':');
if (colon < 0)
return matching(colors ~ [ "invert", "reset" ], partial);
string[] results = matching(colors, partial[colon + 1..$]);
foreach (ref string color; results)
color = partial[0..colon + 1] ~ color;
return results;
default:
return null;
}
}
unittest
{
assert(complete_color(null, "diff") == [ "diff-changed ", "diff-missing " ]);
Argument[] scheme = [ Argument("cursor") ];
assert(complete_color(scheme, "re") == [ "red ", "reset " ]);
assert(complete_color(scheme, "red:bri") == [ "red:brightaqua ", "red:brightblue ",
"red:brightgreen ", "red:brightpurple ", "red:brightred ", "red:brightyellow " ]);
}
// Get length from range result
long rangelen(ref Range r)
{
return r.end - r.start + 1;
}
string tempName(string basename)
{
import std.random : uniform;
import std.format : format;
return format("%s.tmp-ddhx-%u", basename, uniform(10_000, 100_000)); // 10,000..99,999 incl.
}
// Save changes to file target
public void save_to_file(IDocumentEditor editor, string target) // public so benchmark can use this
{
log("target='%s'", target);
// Caller is responsible to populate target path.
// Use assertion (as soft assert) to avoid stopping program.
assertion(target != null, "target is NULL");
assertion(target.length > 0, "target is EMPTY");
import std.path : baseName, dirName, buildPath;
import std.file : rename, getAttributes, setAttributes, remove;
import os.file : availableDiskSpace;
long docsize = editor.size();
// We need enough disk space for the temporary file
ulong avail = availableDiskSpace(target);
log("avail=%u docsize=%d", avail, docsize);
if (avail < docsize)
throw new Exception(text(MSG_INSUFFICIENT_SPACE_NEED, docsize - avail, " bytes"));
// 1. Create a temp file into same directory (with tmp suffix)
string basedir = dirName(target);
string basenam = baseName(target);
string tmpname = tempName(basenam);
string tmppath = buildPath(basedir, tmpname);
log(`basedir="%s" basenam="%s" tmpname="%s" tmppath="%s"`,
basedir, basenam, tmpname, tmppath);
// On failure, remove temporary file
scope(failure) remove(tmppath);
// 2. Allocate buffer, read from editor, and write to temp file
{
ubyte[] buffer = (cast(ubyte*)malloc(CONFIG_CHUNKSIZE))[0..CONFIG_CHUNKSIZE];
if (buffer is null)
throw new Exception(MSG_OUT_OF_MEMORY);
scope(exit) free(buffer.ptr);
File fileout = File(tmppath, "w");
long position;
do
{
fileout.rawWrite( editor.view(position, buffer) );
position += CONFIG_CHUNKSIZE;
}
while (position < docsize);
fileout.flush(); // On the safer side
fileout.sync();
fileout.close();
}
// 3. Copy attributes of target
// Times
// POSIX only has concepts of access and modify times.
// Both are irrelevant for saving. And sadly, since there are no
// concepts of birth date handling (assumed read-only), then I
// won't rip my hair trying to get and set it to target.
// Windows... There are no std.file.setTimesWin. Don't know why.
bool target_exists = exists(target);
uint attr = void;
if (target_exists)
attr = getAttributes(target);
// 4. Replace target
// std.file.rename
// Windows: Uses MoveFileExW with MOVEFILE_REPLACE_EXISTING.
// Remember, TxF (transactional stuff) is deprecated!
// POSIX: Confirmed a to be an atomic operation, using rename(3).
rename(tmppath, target);
// 5. Apply attributes to target
// Windows: Hidden, system, etc.
// POSIX: Permissions
if (target_exists)
{
// GVFS might refuse to set attributes, a minor defect.
// A good test is using chmod.1, it will spit out an error.
try setAttributes(target, attr);
catch (Exception ex)
{
// Log message only, don't need stack
log("[WARNING] setAttributes failed: %s", ex.msg);
}
}
editor.markSaved();
// Generic house cleaning
import core.memory : GC;
GC.collect();
GC.minimize();
}
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
import std.file : remove, readText;
static immutable path = "tmp_save_test";
// In case residue exists from a failing test
if (exists(path))
remove(path);
// Save file as new (target does not exist)
static immutable string data0 = "test data";
scope IDocumentEditor e0 = new DummyDocumentEditor(cast(immutable(ubyte)[])data0);
save_to_file(e0, path);
if (readText(path) != data0)
{
remove(path); // Let's not leave residue
assert(false, "Save content differs for data0");
}
// Save different data to existing path (target exists)
static immutable string data1 = "test data again!";
scope IDocumentEditor e1 = new DummyDocumentEditor(cast(immutable(ubyte)[])data1);
save_to_file(e1, path);
if (readText(path) != data1)
{
remove(path); // Let's not leave residue
assert(false, "Save content differs for data1");
}
remove(path);
}
// Whether in-place saving is worthwhile for this write volume (total size
// of dirty/displaced pieces). In-place writes only that volume; a full save
// rewrites the whole document and replaces it atomically. Once the write
// volume approaches the document size the I/O advantage vanishes, so prefer
// the full save (and its atomicity) past a margin. The memory stash needed
// to preserve undo history is sized and decided later, in save_inplace.
// This function is for file documents, it is useless for disk/process doc types.
bool prefer_inplace(long writevol, long docsize)
{
// 75% margin guard. Over that, saving in-place is a little pointless.
// Subtract rather than (docsize * 3 / 4): the multiply overflows near
// ~2.6 EiB (long.max/3), the subtraction never does.
long margin = docsize - (docsize / 4);
return writevol < margin;
}
unittest
{
assert(prefer_inplace(0, 100)); // no edits, nothing to write
assert(prefer_inplace(10, 100)); // small edit
assert(prefer_inplace(100, 100) == false); // whole document dirty
assert(prefer_inplace(150, 100) == false); // grew and entirely dirty
assert(prefer_inplace(0, 0) == false); // empty: nothing gained
// Large edit on a much larger file: worthwhile
assert(prefer_inplace(MiB!64 + 1, MiB!512));
assert(prefer_inplace(MiB!128, MiB!512));
assert(prefer_inplace(MiB!256, MiB!512));
}
// Try saving "in-place" (directly) to the file at path.
// Opens its own read-write handle, writes dirty regions, and closes it.
// The editor first stashes (to keep undo history valid) source references that the save would
// invalidate (prepareInplaceSave), which keeps its state and undo history
// valid afterwards and makes write order irrelevant. Editors without that
// support only qualify when no source piece is displaced, and their
// history is dropped by reopening the document.
// Can't save with MemoryDocument, caller responsibility.
public void save_inplace(IDocumentEditor editor, string path) // public so benchmark can use this
{
enum OFLAGS = OFlags.exists | OFlags.readWrite | OFlags.share;
scope FileDocument wdoc = new FileDocument(path, OFLAGS);
scope(exit) wdoc.close();
long docsize = editor.size();
long filesize = wdoc.size();
// Pieces this save writes. Read before preservation: retargeting turns
// displaced source pieces into buffer pieces (clearing displacement),
// but leaves logicalPos/size intact, so this list stays valid for the
// write loop either way.
PieceInfo[] pieces = editor.dirtyPieceInfos(true);
long writevol;
bool displaced;
foreach (ref piece; pieces)
{
writevol += piece.size;
if (piece.sourceOffset >= 0)
displaced = true;
}
// Preserving undo history stashes the overwritten source ranges in
// memory (~writevol). Past the budget, save in place but drop history
// instead of rewriting the whole file: the write is still writevol
// bytes, and reopening rebases the editor onto the new contents.
// In simpler terms, if the stash is too large to fit in memory,
// continue saving in-place, but don't bother keeping stash (undo history).
bool preserve = writevol <= CONFIG_INPLACE_STASH_BUDGET;
bool preserved = preserve && editor.prepareInplaceSave();
log("path='%s' pieces=%u writevol=%d preserve=%d preserved=%d displaced=%d (editor=%d, file=%d)",
path, pieces.length, writevol, preserve, preserved, displaced, docsize, filesize);
// Without preservation, displaced pieces read regions this save
// overwrites, and no write order is safe without buffering.
// Throwing here (before any write) lets the caller fall back to a
// full save, which handles displacement fine.
if (displaced && preserved == false)
throw new Exception(MSG_CANNOT_SAVE_INPLACE_DISPLACED);
if (docsize > filesize)
wdoc.resize(docsize); // extend first so we can write to the end
// Write all dirty/displaced pieces; order does not matter (see above)
ubyte[] buf; buf.length = CONFIG_CHUNKSIZE;
foreach (ref piece; pieces)
{
long sz = piece.size;
long lp = piece.logicalPos;
for (long off = 0; off < sz; off += CONFIG_CHUNKSIZE)
{
size_t len = cast(size_t) min(sz - off, CONFIG_CHUNKSIZE);
wdoc.writeAt(lp + off, editor.view(lp + off, buf[0 .. len]));
}
}
if (docsize < filesize)
wdoc.resize(docsize); // shrink after writing
wdoc.flush();
if (preserved)
{
// Editor state, including undo history, is still valid against
// the new file contents thanks to the preservation step.
editor.markSaved();
}
else
{
// The file was rewritten under the editor's own document handle,
// so source pieces reference pre-save offsets. Reopening rebases
// the editor onto the new file contents at the cost of history.
IDocument basedoc = editor.document();
if (basedoc)
editor.open(basedoc); // TODO: Signal history lost
else
editor.markSaved();
}
}
// Test with zero edits
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, world!");
}
// Test with one edit of the same size
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string newdata = "plane";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.replace(7, newdata.ptr, newdata.length);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, plane!");
}
// Test that undo/redo history survives an in-place save, and that saving
// again after undo/redo writes the reverted/reapplied contents to disk.
// This mirrors the Ctrl+S / Ctrl+U / Ctrl+Y flow end to end.
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit ('h' -> 'H')
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable char newbyte = 'H';
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.replace(0, &newbyte, 1);
// save in place; edit is now on disk and editor is clean
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "Hello, world!");
// undo must still be available after the save (history preserved)
assert(editor.undo() >= 0);
assert(editor.edited()); // now differs from the saved file
ubyte[13] buf = void;
assert(editor.view(0, buf[]) == "hello, world!"); // reverted in memory
// saving again writes the reverted contents back to disk
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, world!");
// redo must also survive the save and reapply the edit
assert(editor.redo() >= 0);
assert(editor.edited());
assert(editor.view(0, buf[]) == "Hello, world!");
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "Hello, world!");
editor.close();
fdoc.close();
}
// Test with one edit that makes document larger
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string newdata = " and plane";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.insert(12, newdata.ptr, newdata.length);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, world and plane!");
}
// Test with one edit that makes document smaller
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string newdata = "dd!";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(7, 6);
editor.insert(7, newdata.ptr, newdata.length);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, dd!");
}
// Test with regular file with data to zero-size
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(0, 13);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == []);
}
// Test with regular empty file with no data to file with data
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create empty document
static immutable string path = "temp";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string data = "hello, world!";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.insert(0, data.ptr, data.length);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, world!");
}
// Test with sparse edits (ie, start and end)
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world! I am text.";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string data0 = "apple";
static immutable string data1 = "ipad";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.replace( 7, data0.ptr, data0.length);
editor.replace(19, data1.ptr, data1.length);
// save, close
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello, apple! I am ipad.");
}
// Test with multiple sparse save sessions (edit + save multiple times)
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
// create document with init data
static immutable string path = "temp";
static immutable string data = "hello, world! I am text.";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
// open read-only, create editor and edit
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string data0 = "apple";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.replace(7, data0.ptr, data0.length);
// first edit and save
assert(editor.edited() == true);
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, apple! I am text.");
// second edit and save
static immutable string data1 = "ipad";
editor.replace(19, data1.ptr, data1.length);
assert(editor.edited() == true);
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, apple! I am ipad.");
editor.close();
fdoc.close();
}
// Test: insert at position 0, all original data shifts right
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
static immutable string prefix = ">> ";
editor.insert(0, prefix.ptr, prefix.length);
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == ">> hello, world!");
}
// Test: mixed delete + insert (doc grew), piece shifts left while doc grew
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEFGH";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(0, 3); // delete "ABC" -> "DEFGH"
static immutable string ins = "XYZXYZ";
editor.insert(5, ins.ptr, ins.length); // insert at end -> "DEFGHXYZXYZ"
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "DEFGHXYZXYZ");
}
// Test: mixed delete + insert (doc shrank), piece shifts right while doc shrank
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEFGH";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(6, 2); // delete "GH" -> "ABCDEF"
static immutable string ins = "X";
editor.insert(2, ins.ptr, ins.length); // insert "X" at 2 -> "ABXCDEF"
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "ABXCDEF");
}
// Test: append at end and insert beyond original content
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "hello";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[])data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
static immutable string suffix = "!";
editor.insert(5, suffix.ptr, suffix.length);
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "hello!");
}
// Test: multiple inserts creating a chain of displaced source pieces.
// Insert in the middle splits the source, then insert at 0 pushes both
// halves right. The topological sort must write the later source piece
// first so the earlier one's read range isn't corrupted.
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEF";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
// Split the source piece by inserting in the middle
static immutable string ins1 = "XX";
editor.insert(3, ins1.ptr, ins1.length); // "ABCXXDEF"
// Displace both source halves by inserting at position 0
static immutable string ins2 = "YY";
editor.insert(0, ins2.ptr, ins2.length); // "YYABCXXDEF"
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "YYABCXXDEF");
}
// Test: same document size, but displaced source piece.
// Deleting and inserting the same amount keeps the file size, yet the
// source piece no longer lines up with its file offset and must be
// rewritten (the size check alone would pick the dirty-only strategy).
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEFGH";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(0, 3); // "DEFGH"
static immutable string ins = "XYZ";
editor.insert(5, ins.ptr, ins.length); // "DEFGHXYZ", same size as file
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(read(path) == "DEFGHXYZ");
}
// Fill a buffer with deterministic aperiodic bytes for the large tests.
version (unittest)
private void fillTestPattern(ubyte[] buffer)
{
ulong state = 0x9E3779B97F4A7C15;
foreach (ref b; buffer)
{
state = state * 6364136223846793005 + 1442695040888963407;
b = cast(ubyte)(state >> 56);
}
}
// Test: source piece larger than one I/O chunk shifted toward higher
// offsets. The piece overlaps its own read range, so ascending chunk
// writes would clobber source bytes before later chunks read them.
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
enum SIZE = CONFIG_CHUNKSIZE * 2 + 512; // spans multiple chunks
ubyte[] data; data.length = SIZE;
fillTestPattern(data);
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
static immutable string ins = "!";
editor.insert(0, ins.ptr, ins.length); // shift everything right by one
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
ubyte[] written = cast(ubyte[]) read(path);
assert(written.length == SIZE + 1);
assert(written[0] == '!');
assert(written[1 .. $] == data);
}
// Test: source piece larger than one I/O chunk shifted toward lower
// offsets (delete at start), the ascending order counterpart.
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
enum SIZE = CONFIG_CHUNKSIZE * 2 + 512; // spans multiple chunks
ubyte[] data; data.length = SIZE;
fillTestPattern(data);
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(0, 1); // shift everything left by one
save_inplace(editor, path);
assert(editor.edited() == false);
editor.close();
fdoc.close();
assert(cast(ubyte[]) read(path) == data[1 .. $]);
}
// Test: editor stays consistent after an in-place save that displaced
// source pieces. The file is rewritten under the editor, so its view must
// be rebased, and a following edit + save session must produce the right
// file (previously, pieces kept reading pre-save offsets).
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEF";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
static immutable string ins = "YY";
editor.insert(0, ins.ptr, ins.length); // "YYABCDEF"
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "YYABCDEF");
// View must reflect the saved document, not stale source offsets
ubyte[16] viewbuf;
assert(editor.view(0, viewbuf[0 .. 8]) == "YYABCDEF");
assert(editor.size() == 8);
// Second edit + save session on the rebased editor
static immutable string ins2 = "!";
editor.insert(8, ins2.ptr, ins2.length); // "YYABCDEF!"
save_inplace(editor, path);
assert(editor.edited() == false);
assert(editor.view(0, viewbuf[0 .. 9]) == "YYABCDEF!");
editor.close();
fdoc.close();
assert(read(path) == "YYABCDEF!");
}
// Test: undo history survives an in-place save. The overwritten source
// bytes are stashed in memory before the file is rewritten, so undoing
// past the save point restores them, and redo still works.
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
static immutable string newdata = "plane";
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.replace(7, newdata.ptr, newdata.length);
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, plane!");
// Undo must restore the overwritten bytes from the stash
ubyte[32] buffer;
assert(editor.undo() >= 0);
assert(editor.edited());
assert(editor.view(0, buffer[0 .. 13]) == "hello, world!");
// And saving the undone state must write them back
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, world!");
// Redo still works after two in-place saves
assert(editor.redo() >= 0);
assert(editor.view(0, buffer[0 .. 13]) == "hello, plane!");
editor.close();
fdoc.close();
}
// Test: undo survives an in-place save that displaced pieces and grew
// the document (insert, save, undo, save shrinks it back)
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "ABCDEF";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
static immutable string ins = "YY";
editor.insert(0, ins.ptr, ins.length); // "YYABCDEF"
save_inplace(editor, path);
assert(read(path) == "YYABCDEF");
ubyte[16] buffer;
assert(editor.undo() >= 0);
assert(editor.size() == 6);
assert(editor.view(0, buffer[0 .. 6]) == "ABCDEF");
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "ABCDEF");
editor.close();
fdoc.close();
}
// Test: undo survives a truncating in-place save (data past the new end
// is stashed before the file shrinks)
unittest
{
import ddhx.editor : spawnEditor;
import std.file : remove, read;
static immutable string path = "temp";
static immutable string data = "hello, world!";
{
scope FileDocument setup = new FileDocument(path, OFlags.readWrite);
setup.writeAt(0, cast(ubyte[]) data);
setup.flush();
setup.close();
}
scope(exit) remove(path);
scope FileDocument fdoc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
scope IDocumentEditor editor = spawnEditor();
editor.open(fdoc);
editor.remove(5, 8); // "hello"
save_inplace(editor, path);
assert(read(path) == "hello");
ubyte[16] buffer;
assert(editor.undo() >= 0);
assert(editor.view(0, buffer[0 .. 13]) == "hello, world!");
save_inplace(editor, path);
assert(editor.edited() == false);
assert(read(path) == "hello, world!");
editor.close();
fdoc.close();
}
// True if the opened document cannot change size (e.g., disk, process memory)
bool fixedsize(Session *session)
{
IDocument doc = session.editor.document();
return doc ? (doc.caps() & DocCaps.resize) == 0 : false;
}
// Move the cursor relative to its position within the file
void moverel(Session *session, long pos)
{
// An unaligned cursor is on the EOF slot, which is drawn one element past
// the trailing partial element.
moveabs(session, align64up(session.position_cursor, size_of(session.rc.data_type)) + pos);
}
// Move the cursor to an absolute file position
void moveabs(Session *session, long pos)
{
// If the cursor position changed while editing... Just save the edit.
if (session.input.index() && session.editpos != pos)
{
ubyte[] data = session.input.data;
if (session.rc.writemode == WritingMode.overwrite)
session.editor.replace(session.editpos, data.ptr, data.length);
else
session.editor.insert(session.editpos, data.ptr, data.length);
session.input.reset(); // needed so new input isn't confused
g_status |= UVIEW; // new data
}
long docsize = session.editor.size();
// Cursor obviously cannot be of negative value
if (pos < 0)
pos = 0;
// Fix when cursor is attempting to select non-existant data
else if (session.selection.status && pos >= docsize)
// Ternary fixes zero-length + selection overflow
pos = (docsize > 0) ? docsize - 1 : 0;
// Fixed-size documents cannot append, so there is no EOF position
else if (pos >= docsize && fixedsize(session))
pos = (docsize > 0) ? docsize - 1 : 0;
// Fix when cursor is past playable area (doc size + EOF)
else if (pos > docsize)
pos = docsize;
int data_size = size_of(session.rc.data_type);
// Adjust cursor position to base depending on data size, except the EOF
// slot: aligning it would land on a trailing partial element, where
// appending is impossible.
// Can throw SIGFPE if data_size is wrong (zero?)
if (pos != docsize)
pos -= pos % data_size;
// No need to update if it's at the same place
if (pos == session.position_cursor)
return;
session.position_cursor = pos;
g_status |= USTATUS;
follow(session);
}
// Scroll the view, by whole rows, until the cursor is within it
void follow(Session *session)
{
int data_size = size_of(session.rc.data_type);
long pos = align64up(session.position_cursor, data_size); // EOF slot
int g = session.rc.columns * data_size; // group size
int count = g * g_viewrows;
if (pos < session.position_view) // cursor is behind view
{
session.position_view = align64down(pos, g);
g_status |= UVIEW; // missing data
}
else if (pos >= session.position_view + count) // cursor is ahead of view
{
session.position_view = align64up(pos - count + data_size, g);
g_status |= UVIEW; // missing data
}
}
// Scroll the view so rows [start, end] sit within it with padding, when both
// fit. A match wider than a row would otherwise land flush against an edge.
void reveal(Session *session, long start, long end)
{
long g = session.rc.columns * size_of(session.rc.data_type);
long srow = start / g;
long erow = end / g;
long rows = g_viewrows;
long pad = min(CONFIG_FIND_PADDING, (rows - (erow - srow + 1)) / 2);
if (pad <= 0)
return;
long lastrow = session.editor.size() / g; // EOF slot
long top = session.position_view / g;
long want = top;
if (srow - pad < top)
want = max(srow - pad, 0);
else if (min(erow + pad, lastrow) >= top + rows)
want = min(erow + pad, lastrow) - rows + 1;
if (want == top)
return;
session.position_view = want * g;
g_status |= UVIEW;
}
// Padding: a match scrolled into view keeps context rows around it, but not
// past the EOF row, and not when the match plus padding cannot fit.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(new immutable(ubyte)[256]);
session.rc.columns = 16;
session.rc.data_type = DataType(BaseType.u8, Format.hex);
int oldrows = g_viewrows;
scope(exit) g_viewrows = oldrows;
g_viewrows = 6;
// Largest padding a 2-row match leaves room for in 6 rows
enum long P = min(CONFIG_FIND_PADDING, 2);
static if (P > 0)
{
// Ahead, spanning rows 8-9: bottom padding scrolls past row 9
reveal(&session, 0x88, 0x92);
assert(session.position_view == (4 + P) * 16);
// Behind, row 3: top padding
reveal(&session, 0x30, 0x30);
assert(session.position_view == (3 - P) * 16);
// Already comfortably visible: no scroll
reveal(&session, 0x30, 0x30);
assert(session.position_view == (3 - P) * 16);
// Near EOF (row 16): padding stops at the EOF row
reveal(&session, 0xF0, 0xF0);
assert(session.position_view == (16 - 5) * 16);
}
// Too tall to pad: left to follow()
session.position_view = 0;
reveal(&session, 0x80, 0xDF);
assert(session.position_view == 0);
}
// Snap cursor and view back onto the element and row grid after the data
// type or column count changed, otherwise rows start mid-element.
void realign(Session *session)
{
int data_size = size_of(session.rc.data_type);
int g = session.rc.columns * data_size;
if (session.position_cursor != session.editor.size())
session.position_cursor -= session.position_cursor % data_size;
session.position_view = align64down(session.position_view, g);
g_status |= UVIEW | USTATUS;
follow(session);
}
// TODO: Handle multiple messages.
// It COULD happen that multiple messages are sent before they
// are displayed. Right now, only the last message is taken into
// account.
// Easiest fix would be string[] or something similar.
/// Position as text in the address format setting, for messages.
string address_text(Session *session, long pos)
{
ElementText buf = void;
return AddressFormatter(session.rc.address_type).textual(buf, pos, 1).idup;
}
unittest
{
Session session;
assert(address_text(&session, 255) == "ff");
session.rc.address_type = AddressType.dec;
assert(address_text(&session, 255) == "255");
}
// Send a message within the editor to be displayed.
void message(A...)(string fmt, A args)
{
try
{
g_message = cast(string)sformat(g_messagebuf, fmt, args);
g_status |= UMESSAGE | USTATUS;
}
catch (Exception ex)
{
log("%s", ex);
// Re-formatting through message() would recurse until the stack
// overflows, because the error itself carries a format specifier
// (e.g. "Orphan format specifier: %d"), so it's copied in verbatim.
size_t len = min(ex.msg.length, g_messagebuf.length);
g_messagebuf[0..len] = ex.msg[0..len];
g_message = cast(string)g_messagebuf[0..len];
g_status |= UMESSAGE | USTATUS;
}
}
// A format string with more specifiers than arguments must report the error
// instead of recursing on it.
unittest
{
g_messagebuf.length = 4096;
message("%d bookmarked", 3);
assert(g_message == "3 bookmarked");
// Wording is Phobos', what matters is that this returns at all
string fmt = "%d bookmarked"; // runtime string: checked when formatted
message(fmt);
assert(g_message.length);
assert(g_message != "%d bookmarked");
}
// Render header bar on screen
void update_header(Session *session)
{
terminalCursor(0, 0);
BufferedWriter!((void *data, size_t size) {
terminalWrite(data, size);
}, 256) buffwriter;
AddressFormatter address = AddressFormatter(session.rc.address_type);
DataSpec dataspec = selectDataSpec(session.rc.data_type);
// Count what goes out ourselves. The writer flushes when it fills up, so
// its length() only counts what is still pending, and the header must never
// exceed the terminal width, or it wraps and pushes the view down a row.
int written;
void putText(const(char)[] text)
{
if (written >= g_cols) return;
if (text.length > g_cols - written)
text = text[0 .. g_cols - written];
buffwriter.put(text);
written += cast(int)text.length;
}
void putSpaces(int count)
{
if (count <= 0 || written >= g_cols) return;
if (count > g_cols - written)
count = g_cols - written;
buffwriter.repeat(' ', count);
written += count;
}
// Print spacers and current address type
import std.math : abs;
string atype = addressTypeToString(session.rc.address_type);
int prespaces = abs( session.rc.address_spacing ) - cast(int)atype.length;
if (session.rc.address_spacing < 0) // left-align
{
putText(atype);
putSpaces(prespaces);
}
else
{
putSpaces(prespaces);
putText(atype);
}
putSpaces(1);
ElementText buf = void;
int cols = session.rc.columns;
for (int col, ad; col < cols && written < g_cols; ++col, ad += dataspec.size_of)
{
putSpaces(1);
putText(address.textual(buf, ad, dataspec.spacing));
}
// Fill rest of upper bar with spaces
putSpaces(g_cols - written);
buffwriter.flush();
terminalFlush();
}
struct ElementState
{
// booleans are fine for now, not looking into high performance right now
bool isSelected;
bool isCursor;
bool isActiveEdit;
bool isZero;
bool isBookmarked;
ColorScheme dataScheme(PanelType panel, bool mirror)
{
if (isCursor && panel == PanelType.data)
return ColorScheme.cursor;
if (isSelected && (panel == PanelType.data || mirror))
return ColorScheme.selection;
if (isCursor && mirror && panel != PanelType.data)
return ColorScheme.mirror;
if (isBookmarked)
return ColorScheme.bookmark;
if (isZero)
return ColorScheme.zero;
return ColorScheme.normal;
}
ColorScheme textScheme(PanelType panel, bool mirror)
{
if (isCursor && panel == PanelType.text)
return ColorScheme.cursor;
if (isSelected && (panel == PanelType.text || mirror))
return ColorScheme.selection;
if (isCursor && mirror && panel != PanelType.text)
return ColorScheme.mirror;
if (isBookmarked)
return ColorScheme.bookmark;
if (isZero)
return ColorScheme.zero;
return ColorScheme.normal;
}
}
ElementState getElementState(int elementIndex, int viewpos, int sl0, int sl1,
bool selectionActive, size_t inputIndex,
bool zero, bool bookmarked)
{
bool isCursor = elementIndex == viewpos;
return ElementState(
selectionActive && elementIndex >= sl0 && elementIndex <= sl1,
isCursor,
inputIndex && isCursor,
zero,
bookmarked,
);
}
// Mark which bytes of the view starting at `base` are bookmarked. Built once
// per frame, since checking each element against the list is linear in the
// bookmarks before it, and that adds up quickly over a whole view.
void bookmark_mask(const(Bookmark)[] bookmarks, long base, bool[] mask)
{
mask[] = false;
long end = base + mask.length;
foreach (ref const(Bookmark) b; bookmarks)
{
if (b.address >= end) // sorted: rest is past us
break;
long lo = max(b.address, base);
long hi = min(b.address + b.length, end);
if (lo < hi)
mask[cast(size_t)(lo - base) .. cast(size_t)(hi - base)] = true;
}
}
unittest
{
bool[8] mask;
bookmark_mask([ Bookmark(0, 20), Bookmark(22, 2), Bookmark(27, 1), Bookmark(40, 4) ], 16, mask);
assert(mask == [ true, true, true, true, false, false, true, true ]);
}
// Rows to render: up to and including the one holding the EOF slot, which
// sits right after the last (possibly partial) element read.
int renderrows(int readlen, int size, int cols, int rows)
{
int eofelem = (readlen + size - 1) / size;
return min(rows, eofelem / cols + 1);
}
unittest
{
// x8, 16 columns, 2 rows
assert(renderrows( 0, 1, 16, 2) == 1);
assert(renderrows(10, 1, 16, 2) == 1);
assert(renderrows(16, 1, 16, 2) == 2);
assert(renderrows(32, 1, 16, 2) == 2);
// d32, 4 columns, 2 rows
assert(renderrows(10, 4, 4, 2) == 1);
assert(renderrows(16, 4, 4, 2) == 2);
assert(renderrows(24, 4, 4, 2) == 2);
assert(renderrows(32, 4, 4, 2) == 2);
}
// Element index of pos relative to the view, clamped to [-1, count] so that
// positions far outside the view cannot overflow into it.
int viewindex(long pos, long base, int size, int count)
{
if (pos < base)
return -1;
return cast(int)min((pos - base) / size, count);
}
unittest
{
assert(viewindex( 0, 16, 4, 8) == -1);
assert(viewindex( 16, 16, 4, 8) == 0);
assert(viewindex( 23, 16, 4, 8) == 1);
assert(viewindex(long.max, 0, 4, 8) == 8);
}
// Render view with data on screen
void update_view(Session *session)
{
int rows = g_viewrows;
// What do you want me to do with so little space?
if (rows < 1)
return;
DataSpec spec = selectDataSpec(session.rc.data_type);
int cols = session.rc.columns; /// elements per row
int count = rows * cols; /// elements on screen
int linesize = cols * spec.size_of; /// bytes per row
long address = session.position_view;
bool logging = logEnabled();
debug import std.datetime.stopwatch : StopWatch;
debug StopWatch sw;
// Kept across frames and only re-read on UVIEW (moved, resized, edited,
// undone); resizing reuses the allocation and skips the memset of `new`.
__gshared ubyte[] viewbuf;
__gshared ubyte[] result;
__gshared bool[] bmask;
size_t viewsize = count * spec.size_of;
if (viewbuf.length != viewsize)
{
viewbuf.length = viewsize;
bmask.length = viewsize;
g_status |= UVIEW;
}
if (g_status & UVIEW)
{
debug if (logging) sw.start();
result = session.editor.view(address, viewbuf);
debug if (logging)
{
sw.stop();
log("READ view=%s", sw.peek());
sw.reset();
}
}
int readlen = cast(int)result.length;
int erows = renderrows(readlen, spec.size_of, cols, rows);
// Getting bookmark range in one pass is much better than iterating the list
// on every byte/element. At 100K bookmarks: ~170 ms -> ~0.5 ms
bookmark_mask(session.bookmarks, address, bmask);
// Selection is byte-wise, the view is element-wise
Selection sel = selection(session);
bool selecting = session.selection.status != 0;
int sel_start = viewindex(sel.start, address, spec.size_of, count);
int sel_end = viewindex(sel.end, address, spec.size_of, count);
// Rounded up: an unaligned cursor is the EOF slot, past the partial element
int viewpos = viewindex(align64up(session.position_cursor, spec.size_of), address, spec.size_of, count);
PanelType panel = session.panel;
bool mirror = session.rc.mirror_cursor;
if (logging) // eager, avoids passing parameters just for logging to return when off
{
log("address=%d viewpos=%d cols=%d rows=%d count=%d readlen=%d panel=%s "~
"select.anchor=%d selection=%#x sel_start=%d sel_end=%d",
address, viewpos, cols, erows, count, readlen, panel,
session.selection.anchor, session.selection.status, sel_start, sel_end);
}
debug if (logging) sw.start();
int rowdisp = session.rc.header ? 1 : 0; // lazy hack if header is present
immutable(Charset)* cs = session.rc.charset;
DataFormatter dfmt = DataFormatter(session.rc.data_type, result.ptr, result.length);
AddressFormatter afmt = AddressFormatter(session.rc.address_type);
Line line = Line(128); // init with 128 segments
ElementText buf = void;
int row;
for (; row < erows; ++row, address += linesize)
{
line.reset();
size_t chars = line.normal(afmt.textual(buf, address, session.rc.address_spacing), " ");
// Scalar data
bool prev_selected;
bool prev_bookmarked;
for (int col; col < cols; col++)
{
// Past the terminal edge: nothing else on this row is visible, but
// the formatter still has to be moved to the end of the row, or the
// next row would start on the elements this one skipped.
if (chars > g_cols)
{
dfmt.skip(cols - col);
break;
}
bool zero = session.rc.highlight_zeros && dfmt.iszero();
int elemoff = (row * linesize) + (col * spec.size_of);
bool bookmarked = bmask[elemoff .. elemoff + spec.size_of].canFind(true);
ElementState state = getElementState((row * cols) + col, viewpos,
sel_start, sel_end, selecting, session.input.index, zero, bookmarked);
// Spacer takes the scheme of a run spanning both of its neighbours.
// Selection wins over bookmark when both apply.
ColorScheme spacerscheme = ColorScheme.normal;
if (col) // selection > 0 for joints
{
if (state.isSelected && prev_selected && panel == PanelType.data)
spacerscheme = ColorScheme.selection;
else if (state.isBookmarked && prev_bookmarked)
spacerscheme = ColorScheme.bookmark;
}
chars += line.add(" ", spacerscheme);
prev_selected = state.isSelected;
prev_bookmarked = state.isBookmarked;
string data = state.isActiveEdit ? session.input.format : dfmt.textual(buf);
assertion(data);
dfmt.step();
// In digit mode, only the cursor's digit is highlighted
if (state.isCursor && session.rc.writemode == WritingMode.digit
&& panel == PanelType.data && data.length >= spec.spacing)
{
int dp = g_digitpos;
int sp = spec.spacing;
ColorScheme rest = state.isZero ? ColorScheme.zero : ColorScheme.normal;
if (dp > 0)
chars += line.add(data[0..dp], rest);
chars += line.add(data[dp..dp+1], ColorScheme.cursor);
if (dp + 1 < sp)
chars += line.add(data[dp+1..sp], rest);
}
else
{
chars += line.add(data, state.dataScheme(panel, mirror));
}
}
chars += line.normal(" ");
// Text data
int rowoff = row * linesize;
for (int idx; idx < linesize && chars <= g_cols; idx++)
{
int off = rowoff + idx;
bool zero = session.rc.highlight_zeros && off < readlen && result[off] == 0;
bool bookmarked = bmask[off];
ElementState state = getElementState(off / spec.size_of, viewpos,
sel_start, sel_end, selecting, session.input.index, zero, bookmarked);
string text = off >= readlen ? " " : cs.printable(result[off]) ? cs.glyph(result[off]) : ".";
chars += line.add(text, state.textScheme(panel, mirror));
}
render_line(line, row + rowdisp);
// Tried fixing copying from VTE terminal for newlines...
// Adding "\n" didn't work. ddhx <0.5 makes that work.
// Def something with terminal config, adding OPOST + "\n" doesn't help
terminalFlush(); // important for fbcon, no-op on Windows
}
// terminalWriteChar does buffering on its own (stack buffer)
// Increased stack buffer size from 32 to 128 to help
int tcols = g_cols - 1;
for (; row < rows; ++row)
{
terminalCursor(0, row + rowdisp);
terminalWriteChar(' ', tcols);
}
// Important for fbcon
terminalFlush();
debug if (logging)
{
sw.stop();
log("RENDER update_view=%s", sw.peek());
}
}
// Render status bar on screen
void update_status(Session *session)
{
terminalCursor(0, g_rows - 1);
// Pending message: display verbatim, bypass format strings
if (g_status & UMESSAGE)
{
string msg = g_message;
int msglen = cast(int)msg.length;
int cols = g_cols;
if (msglen >= cols)
{
// TODO: scroll long message
// that might require forwarding key events...
terminalWrite(msg[0 .. min(cols, msg.length)]);
}
else
{
terminalWrite(msg.ptr, msglen);
int rem = cols - msglen;
if (rem > 0)
terminalWriteChar(' ', rem);
}
return;
}
// Format status bar using customizable format strings
BufferedWriter!((void *data, size_t size) {
terminalWrite(data, size);
}, 512) writer;
// With a selection: Select user's (or default) status bar format
Selection sel = selection(session);
const(char)[] fmt = sel.length ?
session.rc.status_fmt_selection :
session.rc.status_fmt_normal;
// Format, write, pad, flush
int written = formatStatus(writer, fmt, session, sel, g_cols);
if (written < g_cols)
writer.repeat(' ', g_cols - written);
writer.flush();
}
// Update all elements on screen depending on editor information
// status global indicates what needs to be updated
void update(Session *session)
{
// Right now, everything is updated unconditionally
// It's pointless to micro-optimize rendering processes while everything is WIP
TerminalSize termsize = terminalSize();
// Update terminal globals
g_rows = termsize.rows;
g_cols = termsize.columns;
g_viewrows = g_rows;
if (session.rc.header) g_viewrows--;
if (session.rc.status) g_viewrows--;
// Reserve rows for the inspector if visible and there is room.
// Need at least one row left for the data view.
int ins_h;
if (session.rc.inspector && g_viewrows > inspectorHeight() + 1)
{
ins_h = inspectorHeight();
g_viewrows -= ins_h;
}
// Reserve rows for the diff panel if a file is open and there is room.
// The panel takes half the rows left for the data view, separator included.
int diff_h;
if (session.diffdoc && g_viewrows >= 4)
{
diff_h = diffHeight(g_viewrows);
g_viewrows -= diff_h;
}
if (session.rc.header)
update_header(session);
update_view(session);
if (ins_h)
update_inspector(session);
if (diff_h)
{
int rowdisp = session.rc.header ? 1 : 0;
update_diff(session, rowdisp + g_viewrows + ins_h, diff_h);
}
if (session.rc.status || g_status & UMESSAGE)
update_status(session);
g_status = 0;
}
// Render the inspector below the data view, terminal-wide.
// Occupies inspectorHeight() rows: one separator line + one row per type.
void update_inspector(Session *session)
{
int rowdisp = session.rc.header ? 1 : 0;
int top = rowdisp + g_viewrows;
// Separator line across the terminal width.
terminalCursor(0, top);
terminalWriteChar('-', g_cols);
// Read up to 8 bytes from the cursor for interpretation.
ubyte[8] buffer = void;
ubyte[] bytes = session.editor.view(session.position_cursor, buffer);
import std.system : Endian;
Endian endian = session.rc.endian;
string endian_label = endian == Endian.littleEndian ? "LE" : "BE";
char[64] valbuf = void;
char[128] linebuf = void;
foreach (i, ref row; inspector_rows)
{
terminalCursor(0, top + 1 + cast(int)i);
string val = formatInspector(valbuf, row.type, bytes, endian);
// Single-byte rows ignore endian, show a blank marker for clarity.
string mark = byteSize(row.type) > 1 ? endian_label : " ";
const(char)[] line = sformat(linebuf, " %s %s %s", row.label, mark, val);
int written = cast(int)line.length;
if (written > g_cols)
{
terminalWrite(line[0 .. g_cols]);
written = g_cols;
}
else
{
terminalWrite(line);
}
if (written < g_cols)
terminalWriteChar(' ', g_cols - written);
}
terminalFlush();
}
// Total reserved height of the diff panel (separator + data rows): half of the
// rows otherwise available to the data view, leaving the rest to the view.
// `avail` is the data-view height before reservation.
//
// The separator line is paid for out of the panel's share, so both halves are
// counted in data rows only: the panel gets ceil((avail - 1) / 2) rows and the
// main view keeps the floor. That way an odd row goes to the panel, which
// matters most on short terminals where one row is a large fraction of it.
int diffHeight(int avail)
{
return 1 + (avail / 2);
}
unittest
{
// avail, expected panel height (separator + data), view rows, panel rows
static immutable int[3][] cases = [
// avail view rows panel data rows
[ 3, 1, 1 ],
[ 4, 1, 2 ],
[ 5, 2, 2 ],
[ 6, 2, 3 ],
[ 20, 9, 10 ],
[ 21, 10, 10 ],
];
foreach (ref c; cases)
{
int height = diffHeight(c[0]);
assert(c[0] - height == c[1]);
assert(height - 1 == c[2]);
}
}
// Render the diff panel at the bottom of the screen. It shows the bytes of
// session.diffdoc for the same base address as the main view ("follow main
// view"), painting elements that differ from the editor's bytes. The target
// file name is embedded in the separator line: "--name.bin-----------".
void update_diff(Session *session, int top, int height)
{
import std.path : baseName;
int cols = session.rc.columns;
DataSpec data_spec = selectDataSpec(session.rc.data_type);
int linesize = cols * data_spec.size_of;
// Separator line with the file name embedded after two leading dashes.
terminalCursor(0, top);
terminalResetColor();
string label = baseName(session.diffpath);
int used = cast(int)terminalWriteChar('-', 2);
if (used < g_cols)
{
if (label.length > g_cols - used)
label = label[0 .. g_cols - used];
used += cast(int)terminalWrite(label);
}
if (used < g_cols)
terminalWriteChar('-', g_cols - used);
int rows = height - 1; // data rows below the separator
// Read both sides for the same span: editor (current, with unsaved edits)
// and the diffed file on disk. Buffers are reused across frames.
__gshared ubyte[] minebuf;
__gshared ubyte[] theirbuf;
size_t span = rows * linesize;
if (minebuf.length < span)
{
minebuf.length = span;
theirbuf.length = span;
}
long base = session.position_view;
ubyte[] mine = session.editor.view(base, minebuf[0 .. span]);
ubyte[] theirs = session.diffdoc.readAt(base, theirbuf[0 .. span]);
// Mirror the view's cursor in the panel, so the element being looked at is
// easy to spot among highlights. The panel is shorter than the view, so the
// cursor is only mirrored while it lands within the panel's own span.
// Negative marks it as off-panel.
ptrdiff_t cursoroff = -1;
long cursorrel = session.position_cursor - base;
if (cursorrel >= 0 && cursorrel < span)
cursoroff = cast(ptrdiff_t)(cursorrel - (cursorrel % data_spec.size_of));
AddressFormatter afmt = AddressFormatter(session.rc.address_type);
DataFormatter dfmt = DataFormatter(session.rc.data_type, theirs.ptr, theirs.length);
Line line = Line(128);
ElementText buf = void;
long address = base;
for (int row; row < rows; ++row, address += linesize)
{
line.reset();
// Address + spacer
size_t chars = line.normal(afmt.textual(buf, address, session.rc.address_spacing), " ");
for (int col; col < cols; col++)
{
// Keep the formatter on the row boundary when the row is cut short
// by the terminal edge, same as the main view.
if (chars > g_cols)
{
dfmt.skip(cols - col);
break;
}
int byteoff = (row * linesize) + (col * data_spec.size_of);
// Compare this element's bytes between the two sides.
ColorScheme scheme = ColorScheme.normal;
for (int b; b < data_spec.size_of; b++)
{
size_t o = byteoff + b;
bool hasmine = o < mine.length;
bool hastheir = o < theirs.length;
if (hasmine != hastheir) // one side ran out
{
scheme = ColorScheme.diff_missing;
break;
}
if (hasmine && hastheir && mine[o] != theirs[o])
scheme = ColorScheme.diff_changed;
}
// Mirrored cursor wins over diff coloring, otherwise it would be
// invisible on a differing element (which is where it usually is).
if (byteoff == cursoroff)
scheme = ColorScheme.cursor;
// Spacer before element keeps the previous scheme run going only
// for normal; diff highlights stay tight to the element.
if (col)
chars += line.normal(" ");
string data = dfmt.textual(buf);
assertion(data);
dfmt.step();
chars += line.add(data, scheme);
}
// data-text spacer, then the text column (per byte, same diff coloring)
chars += line.normal(" ");
for (int idx; idx < linesize; idx++)
{
if (chars > g_cols)
break;
size_t o = (row * linesize) + idx;
bool hasmine = o < mine.length;
bool hastheir = o < theirs.length;
ColorScheme scheme = ColorScheme.normal;
if (hasmine != hastheir)
scheme = ColorScheme.diff_missing;
else if (hastheir && mine[o] != theirs[o])
scheme = ColorScheme.diff_changed;
ptrdiff_t so = cast(ptrdiff_t)o;
if (cursoroff >= 0 && so >= cursoroff && so < cursoroff + data_spec.size_of)
scheme = ColorScheme.cursor;
string text = " ";
if (hastheir)
{
immutable(Charset)* cs = session.rc.charset;
text = cs.printable(theirs[o]) ? cs.glyph(theirs[o]) : ".";
}
chars += line.add(text, scheme);
}
render_line(line, top + 1 + row);
}
terminalFlush();
}
// Render a prepared Line of colored segments on the given terminal row,
// truncating to width and clearing the remainder. Shared by the diff panel.
void render_line(ref Line line, int y)
{
terminalCursor(0, y);
ColorMap lastmap;
size_t rendered;
foreach (ref segment; line.segments)
{
if (rendered >= g_cols) break;
ColorMap map = g_colors.get(segment.scheme);
bool change = lastmap != map;
if (change)
terminalResetColor();
if (map.foreground.isNull == false && change)
terminalForeground(map.foreground.get);
if (map.background.isNull == false && change)
terminalBackground(map.background.get);
if (map.flags & COLORMAP_INVERTED && change)
terminalInvertColor();
size_t avail = g_cols - rendered;
if (segment.columns <= avail)
{
terminalWrite(segment.data);
rendered += segment.columns;
}
else
{
terminalWrite(segment.head(avail));
rendered += avail;
}
lastmap = map;
}
if (rendered < g_cols)
{
terminalResetColor();
terminalWriteChar(' ', cast(int)(g_cols - rendered));
}
}
// Special function to update progress
// (Closer to update() than update_* functions...)
void update_progress(Session *session, long position, long total)
{
__gshared int lastx;
assert(position <= total, "position <= total");
int width = g_cols - 2;
int x = cast(int)(width * (cast(double)position / total));
// Same position, avoid unnecessary I/O
if (x == lastx)
return;
lastx = x;
int rem = width - x;
log("w=%d p=%d t=%d x=%d r=%d",
width, position, total, x, rem);
terminalMove(0, g_rows - 1);
BufferedWriter!((void *data, size_t size) {
terminalWrite(data, size);
}, 256) buffwriter;
buffwriter.repeat('[', 1);
buffwriter.repeat('#', x);
buffwriter.repeat(' ', rem);
buffwriter.repeat(']', 1);
buffwriter.flush();
terminalFlush();
}
// Peek input if cancel key is requested, used in I/O intense scenarios,
// like the search function.
int cancelling()
{
int num = terminalHasInput();
if (num == 0)
return 0;
for (int i; i < num; i++)
{
TermInput r = terminalRead();
if (iscancelling(r))
return 1;
}
return 0;
}
//
// Search function
//
/// Search the session document, see searches.search. Shows progress and polls
/// the cancel key, unless flags has SEARCH_NON_INTERACTIVE.
SearchResult search(Session *session, Pattern needle, long position, int flags,
SearchAction delegate(SearchResult) onhit = null, long end = long.max)
{
void progress(long done, long total)
{
if (cancelling())
throw new Exception(MSG_CANCELED);
update_progress(session, done, total);
}
return searches.search(session.editor, needle, position, flags, onhit, end,
size_of(session.rc.data_type), flags & SEARCH_NON_INTERACTIVE ? null : &progress);
}
//
// ANCHOR Commands
//
// Run command
void prompt_command(Session *session, Argument[] args)
{
string line = promptline(">", toDelegate(&complete_line));
if (line.length == 0)
return;
Argument[] argv = arguments(line);
if (argv.length == 0)
return;
log("command='%s'", argv);
immutable(ubyte)[] name = argv[0].data;
argv = argv.length > 1 ? argv[1..$] : null;
// Looked up as bytes: a name that is not text simply misses, and "command
// not found" beats an encoding complaint about a typo.
const(void function(Session*, Argument[])) *com = cast(string)name in g_commands;
if (com == null)
{
throw new Exception(text(MSG_COMMAND_NOT_FOUND, printable(name)));
}
// Run command, it's ok if it throws, it's covered by main loop,
// including command prompt
(*com)(session, argv);
}
// Move back a single item
void move_left(Session *session, Argument[] args)
{
unselect(session);
if (session.rc.writemode == WritingMode.digit)
{
if (g_digitpos > 0)
{
g_digitpos--;
g_status |= USTATUS;
return;
}
if (session.position_cursor == 0)
return;
g_digitpos = spacing_of(session.rc.data_type) - 1;
}
if (session.position_cursor == 0)
return;
moverel(session, -size_of(session.rc.data_type));
}
// Move forward a single item
void move_right(Session *session, Argument[] args)
{
unselect(session);
if (session.rc.writemode == WritingMode.digit)
{
if (g_digitpos < spacing_of(session.rc.data_type) - 1)
{
g_digitpos++;
g_status |= USTATUS;
return;
}
g_digitpos = 0;
}
moverel(session, +size_of(session.rc.data_type));
}
// Move back a row
void move_up(Session *session, Argument[] args)
{
unselect(session);
if (session.position_cursor == 0)
return;
moverel(session, -(session.rc.columns * size_of(session.rc.data_type)));
}
// Move forward a row
void move_down(Session *session, Argument[] args)
{
unselect(session);
moverel(session, +(session.rc.columns * size_of(session.rc.data_type)));
}
// Move back a page
void move_pg_up(Session *session, Argument[] args)
{
unselect(session);
g_digitpos = 0;
if (session.position_cursor == 0)
return;
moverel(session, -(g_viewrows * (session.rc.columns * size_of(session.rc.data_type))));
}
// Move forward a page
void move_pg_down(Session *session, Argument[] args)
{
unselect(session);
g_digitpos = 0;
moverel(session, +(g_viewrows * (session.rc.columns * size_of(session.rc.data_type))));
}
// Move to start of line
void move_ln_start(Session *session, Argument[] args) // move to start of line
{
unselect(session);
g_digitpos = 0;
int g = session.rc.columns * size_of(session.rc.data_type);
moverel(session, -(session.position_cursor % g));
}
// Move to end of line
void move_ln_end(Session *session, Argument[] args) // move to end of line
{
unselect(session);
DataSpec spec = selectDataSpec(session.rc.data_type);
g_digitpos = spec.spacing - 1;
int g = (session.rc.columns * spec.size_of);
moverel(session, +(g - (session.position_cursor % g)) - 1);
}
// Move to absolute start of document
void move_abs_start(Session *session, Argument[] args)
{
unselect(session);
g_digitpos = 0;
moveabs(session, 0);
}
// Move to absolute end of document
void move_abs_end(Session *session, Argument[] args)
{
unselect(session);
g_digitpos = spacing_of(session.rc.data_type) - 1;
moveabs(session, session.editor.size());
}
// Move to different element backward
void move_skip_backward(Session *session, Argument[] args)
{
g_digitpos = 0;
long curpos = session.position_cursor;
// Nothing to really do... so avoid the necessary work
if (curpos == 0)
return;
// If cursor is at the very end of buffer, move it by one element
// back, because there's no data where the cursor points to.
if (session.position_cursor == session.editor.size())
curpos = align64down(curpos - 1, size_of(session.rc.data_type));
// Selection: needle
ubyte[] needle;
Selection sel = selection(session);
if (sel.length)
{
if (sel.length > CONFIG_NEEDLE_LIMIT)
throw new Exception(MSG_SELECTION_TOO_BIG);
needle.length = cast(size_t)sel.length;
needle = session.editor.view(sel.start, needle);
if (needle.length < sel.length)
return; // Nothing to do
}
else // data by cursor position
{
int sz = size_of(session.rc.data_type);
// Get current element
Element elem;
needle = session.editor.view(curpos, elem.raw.ptr, sz);
if (needle.length < sz)
return; // Nothing to do
sel.start = curpos;
}
session.selection.status = 0;
// Move even if nothing found, since it is the intent.
// In a text editor, if Ctrl+Left is hit (imagine a long line of same
// characters) the cursor still moves to the start of the document.
Pattern pneedle = Pattern.fromBytes(needle);
moveabs(session,
search(session, pneedle, sel.start - needle.length,
SEARCH_LASTPOS|SEARCH_DIFF|SEARCH_REVERSE|SEARCH_ALIGNED).pos);
}
// Move to different element forward
void move_skip_forward(Session *session, Argument[] args)
{
g_digitpos = 0;
long curpos = session.position_cursor;
long docsize = session.editor.size();
// Already at the end of document, nothing to do
if (curpos == docsize)
return;
// Selection: Needle
ubyte[] needle;
Selection sel = selection(session);
if (sel.length)
{
if (sel.length > CONFIG_NEEDLE_LIMIT)
throw new Exception(MSG_SELECTION_TOO_BIG);
needle.length = cast(size_t)sel.length;
needle = session.editor.view(sel.start, needle);
if (needle.length < sel.length)
return; // Nothing to do
}
else // data by cursor position
{
int sz = size_of(session.rc.data_type);
// Get current element
Element elem;
needle = session.editor.view(curpos, elem.raw.ptr, sz);
if (needle.length < sz)
return; // Nothing to do
sel.start = curpos;
}
session.selection.status = 0;
Pattern pneedle = Pattern.fromBytes(needle);
moveabs(session,
search(session, pneedle, sel.start + needle.length,
SEARCH_LASTPOS|SEARCH_DIFF|SEARCH_ALIGNED).pos);
}
// Move view up
void view_up(Session *session, Argument[] args)
{
if (session.position_view == 0)
return;
session.position_view -= session.rc.columns * size_of(session.rc.data_type);
if (session.position_view < 0)
session.position_view = 0;
g_status |= UVIEW;
}
// Move view down
void view_down(Session *session, Argument[] args)
{
int g = session.rc.columns * size_of(session.rc.data_type);
long max = session.editor.size() - (g * g_viewrows);
if (session.position_view > max)
return;
session.position_view += g;
g_status |= UVIEW;
}
// d32: scrolling the view and switching data type must keep rows on the grid,
// or moving down later shifts the cursor's column.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(new immutable(ubyte)[256]);
session.input = new InputFormatter;
session.rc.columns = 4;
session.rc.data_type = DataType(BaseType.u32, Format.dec);
int oldrows = g_viewrows;
scope(exit) g_viewrows = oldrows;
g_viewrows = 2;
view_down(&session, null);
assert(session.position_view == 16);
view_up(&session, null);
assert(session.position_view == 0);
session.rc.data_type = DataType(BaseType.u8, Format.hex);
session.position_cursor = 7;
session.position_view = 3;
session.rc.data_type = DataType(BaseType.u32, Format.dec);
realign(&session);
assert(session.position_cursor == 4);
assert(session.position_view == 0);
move_down(&session, null);
assert(session.position_cursor == 20);
move_down(&session, null);
assert(session.position_cursor == 36);
assert(session.position_view == 16);
}
// d32 on a 10-byte document: EOF (10) must be reachable to append, and
// stepping back from it lands on the trailing partial element (8).
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(new immutable(ubyte)[10]);
session.input = new InputFormatter;
session.rc.columns = 4;
session.rc.data_type = DataType(BaseType.u32, Format.dec);
int oldrows = g_viewrows;
scope(exit) g_viewrows = oldrows;
g_viewrows = 2;
move_abs_end(&session, null);
assert(session.position_cursor == 10);
move_left(&session, null);
assert(session.position_cursor == 8);
move_right(&session, null);
assert(session.position_cursor == 10);
move_right(&session, null);
assert(session.position_cursor == 10);
realign(&session);
assert(session.position_cursor == 10);
select_left(&session, null);
Selection sel = selection(&session);
assert(sel.start == 8);
assert(sel.length == 2); // partial element, 2 bytes left
}
//
// Deletion
//
void delete_front(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
Selection sel = selection(session);
if (args.length > 0)
{
Range r = askrange(args, 0, "Range: ");
session.editor.remove(r.start, r.length);
g_status |= UVIEW;
return;
}
else if (sel.length)
{
session.editor.remove(sel.start, sel.length);
unselect(session);
g_status |= UVIEW;
// HACK: force cursor to go back to start of selection
// Fixes cursor "disappearing"
moveabs(session, sel.start);
return;
}
// Delete element where cursor points to
long curpos = session.position_cursor;
if (curpos == session.editor.size()) // nothing to delete in front
return;
session.editor.remove(curpos, size_of(session.rc.data_type));
g_status |= UVIEW;
}
void delete_back(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
Selection sel = selection(session);
if (sel.length)
{
session.editor.remove(sel.start, sel.length);
unselect(session);
g_status |= UVIEW;
// See HACK command in delete_front
moveabs(session, sel.start);
return;
}
// Delete element behind cursor
if (session.position_cursor == 0) // nothing to delete behind cursor
return;
int s = size_of(session.rc.data_type);
moverel(session, -s);
session.editor.remove(session.position_cursor, s);
g_status |= UVIEW;
}
//
// Selection
//
/// Selection information
struct Selection
{
long start, end, length;
}
// Force a new selection (name to avoid conflicting with select(Session*,string[]))
void neselect(Session *session, long start, long end)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = start;
moveabs(session, end);
}
// Force unselection
void unselect(Session *session)
{
if (session.selection.status & SELECT_ONGOING)
return;
session.selection.status = 0;
}
// Get selection information
Selection selection(Session *session)
{
Selection sel;
if (session.selection.status == 0)
return sel;
int g = size_of(session.rc.data_type);
// Adjustment in moveabs right now fucks a little with sel.end
long anchor = session.selection.anchor - (session.selection.anchor % g); // EOF slot
sel.start = min(anchor, session.position_cursor);
sel.end = max(anchor, session.position_cursor);
long docsize = session.editor.size();
if (sel.end >= docsize)
sel.end -= g;
// End marker is inclusive, a partial last element stops at the document end
sel.length = min(sel.end - sel.start + g, docsize - sel.start);
return sel;
}
unittest
{
Session session;
import ddhx.editor.dummy : DummyDocumentEditor;
session.editor = new DummyDocumentEditor(); // needed for length
// Not selected
Selection sel = selection(&session);
assert(sel.length == 0);
// Emulate a selection where cursor is behind anchor
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 4;
session.position_cursor = 2;
session.rc.data_type = DataType(BaseType.u8, Format.hex);
sel = selection(&session);
assert(sel.length == 3);
assert(sel.start == 2);
assert(sel.end == 4);
// Emulate a selection where only one element is selected
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 2;
session.position_cursor = 2;
sel = selection(&session);
assert(sel.length == 1);
assert(sel.start == 2);
assert(sel.end == 2);
// x16: end is the start of the last element, length covers all of it
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 0;
session.position_cursor = 2;
session.rc.data_type = DataType(BaseType.u16, Format.hex);
sel = selection(&session);
assert(sel.length == 4);
assert(sel.start == 0);
assert(sel.end == 2);
// x16, cursor behind anchor, which is on the partial last element of "hello"
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 4;
session.position_cursor = 2;
sel = selection(&session);
assert(sel.length == 3);
assert(sel.start == 2);
assert(sel.end == 4);
}
// Selection commands stay on element boundaries and within the document.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.rc.columns = 8;
session.input = new InputFormatter;
session.rc.data_type = DataType(BaseType.u16, Format.hex);
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "0123456789abcdef");
Session *saved = g_session;
g_session = &session; // for askrange
scope(exit) g_session = saved;
Selection sel;
session.position_cursor = 4;
select_all(&session, null);
sel = selection(&session);
assert(sel.start == 0 && sel.length == 16);
session.selection.status = 0;
session.position_cursor = 4;
select_bottom(&session, null);
sel = selection(&session);
assert(sel.start == 4 && sel.length == 12);
session.selection.status = 0;
session.position_cursor = 4;
select_top(&session, null);
sel = selection(&session);
assert(sel.start == 0 && sel.length == 6);
session.selection.status = 0;
select(&session, [ Argument("2:5") ]);
sel = selection(&session);
assert(sel.start == 2 && sel.length == 4);
// A partial last element ends the selection at the document end
session.selection.status = 0;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "0123456789abcde");
select_all(&session, null);
sel = selection(&session);
assert(sel.start == 0 && sel.length == 15);
}
// Expand selection backward
void select_left(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moverel(session, -size_of(session.rc.data_type));
}
// Expand selection forward
void select_right(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moverel(session, +size_of(session.rc.data_type));
}
// Expand selection back a line
void select_up(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moverel(session, -(session.rc.columns * size_of(session.rc.data_type)));
}
// Expand selection forward a line
void select_down(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moverel(session, +(session.rc.columns * size_of(session.rc.data_type)));
}
// Expand selection to start of line
void select_home(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
int g = session.rc.columns * size_of(session.rc.data_type);
moverel(session, -(session.position_cursor % g));
}
// Expand selection to end of line
void select_end(Session *session, Argument[] args)
{
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
int g = session.rc.columns * size_of(session.rc.data_type);
moverel(session, +(g - (session.position_cursor % g)) - 1);
}
// Expand selection to start of document
void select_top(Session *session, Argument[] args)
{
if (session.editor.size() <= 0)
return;
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moveabs(session, 0);
}
// Expand selection to end of document
void select_bottom(Session *session, Argument[] args)
{
long docsize = session.editor.size();
if (docsize <= 0)
return;
if (!session.selection.status)
{
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = session.position_cursor;
}
moveabs(session, docsize); // lands on the last element
}
// Select all of document
void select_all(Session *session, Argument[] args)
{
long docsize = session.editor.size();
if (docsize <= 0)
return;
session.selection.anchor = 0;
session.selection.status = SELECT_ACTIVE;
moveabs(session, docsize); // lands on the last element
}
// Make an explicit selection
void select(Session *session, Argument[] args)
{
Range ran = askrange(args, 0, "Range: ");
session.selection.anchor = ran.start;
session.selection.status = SELECT_ACTIVE;
moveabs(session, ran.end);
}
// Start an active selection
void mark(Session *session, Argument[] args)
{
session.selection.status = SELECT_ACTIVE | SELECT_ONGOING;
session.selection.anchor = session.position_cursor;
}
// End the active selection
void unmark(Session *session, Argument[] args)
{
session.selection.status &= ~SELECT_ONGOING;
}
//
// Bookmarks
//
// Bookmarks are stored byte-precise (address + length), but the data panel
// paints them at element granularity: when any byte of an element intersects
// a bookmark, the whole element is colored. The text panel iterates per byte
// and shows the precise extent. Sub-element painting in the data panel would
// only be clean for hex types (fixed chars per byte); decimal/octal/signed
// formats have no fixed byte<->character mapping.
/// A single bookmarked region in the document.
struct Bookmark
{
long address; /// Start address (inclusive)
long length; /// Length in bytes (>= 1)
}
// Get a bookmark by range, assumed from the session:
// First args, then selection, and finally just at the cursor position
Bookmark bookmark_range(Session *session, Argument[] args)
{
if (args.length > 0)
{
Range r = askrange(args, 0, "Range: ");
return Bookmark(r.start, r.length);
}
Selection sel = selection(session);
if (sel.length)
return Bookmark(sel.start, sel.length);
// Bookmark an element entirely, looks weird otherwise
return Bookmark(session.position_cursor, size_of(session.rc.data_type));
}
// Sorted insert by address. Skip exact duplicates (same address+length).
void bookmark_insert(Session *session, Bookmark b)
{
// Could have used sorter but this is by address, *this* is the sorter
size_t i;
while (i < session.bookmarks.length && session.bookmarks[i].address < b.address)
++i;
// Skip exact duplicate at the insertion site
if (i < session.bookmarks.length &&
session.bookmarks[i].address == b.address &&
session.bookmarks[i].length == b.length)
return;
session.bookmarks.insertInPlace(i, b);
}
// Merge an address-sorted list of bookmarks into the session list, in one
// pass. Inserting them one by one costs a scan plus a move each, which turns
// quadratic on commands that add matches in bulk (find-bookmark), and a
// search has no upper bound on how many matches it reports.
// Exact duplicates (same address and length) are skipped, as with
// bookmark_insert.
// Returns: Number of bookmarks added.
size_t bookmark_merge(Session *session, const(Bookmark)[] news)
{
if (news.length == 0)
return 0;
const(Bookmark)[] olds = session.bookmarks;
Bookmark[] merged;
merged.reserve(olds.length + news.length);
size_t added;
while (olds.length || news.length)
{
// Existing entries go first on equal addresses, so the duplicate
// check below only has to look at what was just emitted.
if (news.length == 0 || (olds.length && olds[0].address <= news[0].address))
{
merged ~= olds[0];
olds = olds[1..$];
continue;
}
Bookmark b = news[0];
news = news[1..$];
// Skip exact duplicates, be they already in the list or repeated
// within the new list
bool dupe;
foreach_reverse (ref const(Bookmark) m; merged)
{
if (m.address != b.address)
break;
if (m.length == b.length)
{
dupe = true;
break;
}
}
if (dupe)
continue;
merged ~= b;
++added;
}
session.bookmarks = merged;
return added;
}
unittest
{
Session session;
// Into an empty list
assert(bookmark_merge(&session, [ Bookmark(0x10, 2), Bookmark(0x20, 2) ]) == 2);
assert(session.bookmarks == [ Bookmark(0x10, 2), Bookmark(0x20, 2) ]);
// Interleaved, and sorted by address afterwards
assert(bookmark_merge(&session, [ Bookmark(0x08, 1), Bookmark(0x18, 1), Bookmark(0x28, 1) ]) == 3);
assert(session.bookmarks == [
Bookmark(0x08, 1), Bookmark(0x10, 2), Bookmark(0x18, 1),
Bookmark(0x20, 2), Bookmark(0x28, 1) ]);
// Exact duplicates skipped, same address with another length kept
assert(bookmark_merge(&session, [ Bookmark(0x10, 2), Bookmark(0x10, 4) ]) == 1);
assert(session.bookmarks == [
Bookmark(0x08, 1), Bookmark(0x10, 2), Bookmark(0x10, 4), Bookmark(0x18, 1),
Bookmark(0x20, 2), Bookmark(0x28, 1) ]);
// Nothing to merge
assert(bookmark_merge(&session, null) == 0);
assert(session.bookmarks.length == 6);
}
// Add a bookmark covering args/selection/cursor.
void bookmark_set(Session *session, Argument[] args)
{
Bookmark bk = bookmark_range(session, args);
if (bk.length <= 0)
throw new Exception(MSG_BOOKMARK_LENGTH_MUST_BE_POSITIVE);
bookmark_insert(session, bk);
g_status |= UVIEW | USTATUS;
message("Bookmark set at %s (%d byte%s)", address_text(session, bk.address),
bk.length, bk.length == 1 ? "" : "s");
}
// True if any bookmark overlaps [start, start+length).
bool bookmark_overlaps(Session *session, long start, long length)
{
long end = start + length;
foreach (ref Bookmark b; session.bookmarks)
{
long b_end = b.address + b.length;
if (b_end > start && b.address < end)
return true;
}
return false;
}
// Jump cursor to the first bookmark whose address > current cursor.
// Wraps to the first bookmark if none found ahead.
void bookmark_next(Session *session, Argument[] args)
{
if (session.bookmarks.length == 0)
throw new Exception(MSG_NO_BOOKMARKS);
unselect(session); // Navigation, unselect
long cur = session.position_cursor;
foreach (ref Bookmark b; session.bookmarks)
{
if (b.address > cur)
{
moveabs(session, b.address);
message("Bookmark at %s", address_text(session, b.address));
return;
}
}
// Wrap
Bookmark first = session.bookmarks[0];
moveabs(session, first.address);
message("Bookmark at %s (wrapped)", address_text(session, first.address));
}
// Jump cursor to the last bookmark whose address < current cursor.
// Wraps to the last bookmark if none found behind.
void bookmark_prev(Session *session, Argument[] args)
{
if (session.bookmarks.length == 0)
throw new Exception(MSG_NO_BOOKMARKS);
unselect(session); // Navigation, unselect
long cur = session.position_cursor;
foreach_reverse (ref Bookmark b; session.bookmarks)
{
if (b.address < cur)
{
moveabs(session, b.address);
message("Bookmark at %s", address_text(session, b.address));
return;
}
}
// Wrap
Bookmark last = session.bookmarks[$ - 1];
moveabs(session, last.address);
message("Bookmark at %s (wrapped)", address_text(session, last.address));
}
// Toggle: unset overlapping bookmarks if any, otherwise set one.
void bookmark_toggle(Session *session, Argument[] args)
{
Bookmark bk = bookmark_range(session, args);
if (bk.length <= 0)
throw new Exception(MSG_RANGE_LENGTH_MUST_BE_POSITIVE);
if (bookmark_overlaps(session, bk.address, bk.length))
bookmark_unset(session, args);
else
bookmark_set(session, args);
}
// Remove every bookmark whose range overlaps args/selection/cursor.
void bookmark_unset(Session *session, Argument[] args)
{
Bookmark bk = bookmark_range(session, args);
if (bk.length <= 0)
throw new Exception(MSG_RANGE_LENGTH_MUST_BE_POSITIVE);
long end = bk.address + bk.length; // exclusive
size_t removed;
size_t i;
while (i < session.bookmarks.length)
{
Bookmark b = session.bookmarks[i];
long b_end = b.address + b.length; // exclusive
// Overlap test: !(b_end <= start || b.address >= end)
if (b_end > bk.address && b.address < end)
{
session.bookmarks = session.bookmarks[0..i] ~ session.bookmarks[i+1..$];
++removed;
continue;
}
++i;
}
if (removed == 0)
{
message("No bookmark in range");
return;
}
g_status |= UVIEW | USTATUS;
message("Removed %d bookmark%s", removed, removed == 1 ? "" : "s");
}
// Clear bookmark list
void bookmark_clear(Session *session, Argument[] args)
{
session.bookmarks.length = 0;
session.bookmarks = null;
}
// Save bookmarks to a text file: one bookmark per line as "0xADDR LENGTH".
// Lines starting with '#' and blank lines are ignored on load.
void bookmark_save(Session *session, Argument[] args)
{
if (session.bookmarks.length == 0)
throw new Exception(MSG_NO_BOOKMARKS_TO_SAVE);
string path = askstring(args, 0, "Save bookmarks to: ", &complete_path);
File f = File(path, "w"); // Overwrite
f.writeln("# ddhx bookmarks");
foreach (ref Bookmark b; session.bookmarks)
f.writefln("0x%x\t%d", b.address, b.length);
f.close();
message("Bookmarks saved");
}
// indexOf but considers whitespace
// returns index of first whitespace character or -1 if not found
ptrdiff_t indexOfSpace(string input) @safe pure
{
foreach (i, c ; input)
{
import std.uni : isWhite;
if (isWhite(c))
return i;
}
return -1;
}
unittest
{
assert(indexOfSpace("a b") == 1);
assert(indexOfSpace("ab") == -1);
assert(indexOfSpace("a\tb")== 1);
}
// Load bookmarks from a file produced by bookmark-save (or compatible).
// Each non-comment line: " ", both numbers as scan() reads
// them (0x hex, 0b binary, 0 octal, or decimal), then an optional note.
// Loaded entries are merged with existing ones.
void bookmark_load(Session *session, Argument[] args)
{
import std.string : strip, stripLeft;
import std.conv : ConvException;
string path = askstring(args, 0, "Load bookmarks from: ", &complete_path);
File f = File(path, "rt"); // text-mode just in case windows user hand-writes one
size_t lineno;
foreach (raw; f.byLine())
{
++lineno;
string line = strip(cast(string)raw);
if (line.length == 0 || line[0] == '#')
continue;
// std.array.split uses appender thus is GC-bound
// Right now, bookmarks only use integers, so no string copies needed
ptrdiff_t sepi = indexOfSpace(line);
if (sepi <= 0)
throw new Exception(text(MSG_BOOKMARK_LINE_PREFIX, lineno, ": expected ' '"));
string straddr = line[0..sepi];
string strlent = stripLeft(line[sepi..$]);
ptrdiff_t endi = indexOfSpace(strlent); // Text after the length is a note
if (endi > 0)
strlent = strlent[0..endi];
Bookmark bk;
try
{
bk.address = scan(straddr);
bk.length = scan(strlent);
}
catch (ConvException e)
{
throw new Exception(text(MSG_BOOKMARK_LINE_PREFIX, lineno, ": ", e.msg));
}
if (bk.address < 0 || bk.length <= 0)
throw new Exception(text(MSG_BOOKMARK_LINE_PREFIX, lineno, ": invalid address or length"));
bookmark_insert(session, bk);
}
g_status |= UVIEW | USTATUS;
message("Bookmarks loaded");
}
// Bookmark files take any scan() number, refuse text glued to one, and skip notes.
unittest
{
import std.file : remove, tempDir, write;
import std.path : buildPath;
import std.algorithm.searching : canFind;
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(new immutable(ubyte)[64]);
string path = buildPath(tempDir, "ddhx-bookmark-unittest");
scope(exit) remove(path);
write(path, "# ddhx bookmarks\n0x10\t0x4\n32 2 header\n");
bookmark_load(&session, [ Argument(path) ]);
assert(session.bookmarks == [ Bookmark(0x10, 4), Bookmark(32, 2) ]);
write(path, "0x10\t4abc\n");
try { bookmark_load(&session, [ Argument(path) ]); assert(false); }
catch (Exception e) assert(canFind(e.msg, "4abc"), e.msg);
}
//
// Etc
//
// Change writing mode
void change_writemode(Session *session, Argument[] args)
{
// Can't switch out of a restricted session (-R/--restrict)
if (session.rc.restricted)
throw new Exception(MSG_CANT_EDIT_READONLY);
// Optional argument
if (args.length > 0)
{
WritingMode mode = selectWritingMode(args[0].text);
if (mode == WritingMode.insert && fixedsize(session))
throw new Exception(MSG_INSERT_MODE_UNAVAILABLE);
session.rc.writemode = mode;
}
else
{
// Cycle: overwrite -> insert -> digit -> overwrite
final switch (session.rc.writemode) {
case WritingMode.overwrite:
// Fixed-size documents cannot insert; skip to digit mode
session.rc.writemode = fixedsize(session) ? WritingMode.digit : WritingMode.insert;
break;
case WritingMode.insert: session.rc.writemode = WritingMode.digit; break;
case WritingMode.digit: session.rc.writemode = WritingMode.overwrite; break;
// Only unrestricted sessions get here, so editing can be enabled back
case WritingMode.readonly: session.rc.writemode = WritingMode.overwrite; break;
}
}
g_digitpos = 0;
g_status |= USTATUS;
}
// Refresh screen
void refresh(Session *session, Argument[] args)
{
terminalClear(); // In case of a misrender
g_status |= UVIEW; // Force read new data into view buffer
update(session); // Update screen entirely
}
// Change active panel
void change_panel(Session *session, Argument[] args)
{
// First parameter could be panel name, still cycling to default
// But honestly this is fine for now
// Skip inspector in cycle if it's not currently visible.
do
{
session.panel++;
if (session.panel >= PanelType.max + 1)
session.panel = PanelType.init;
} while (session.panel == PanelType.inspector && session.rc.inspector == false);
}
void toggle_inspector(Session *session, Argument[] args)
{
session.rc.inspector = session.rc.inspector == false;
// Leave inspector focus if we just hid it.
if (session.rc.inspector == false && session.panel == PanelType.inspector)
session.panel = PanelType.data;
g_status |= UVIEW;
}
void toggle_endian(Session *session, Argument[] args)
{
import std.system : Endian;
session.rc.endian =
session.rc.endian == Endian.littleEndian ?
Endian.bigEndian : Endian.littleEndian;
g_status |= UVIEW;
}
// Open a file to diff against the current view, shown in a bottom panel.
// "diff-file PATH" opens (or replaces) the panel; bare "diff-file" while a
// panel is open closes it. Comparing the current file against its last-saved
// state is done by passing its own path (the on-disk copy is read fresh, while
// the view reflects unsaved edits).
void diff_file(Session *session, Argument[] args)
{
// No path given while a diff is active: close the panel.
if ((args is null || args.length == 0) && session.diffdoc)
{
diff_close(session);
return;
}
string path = askstring(args, 0, "Diff against file: ", &complete_path);
IDocument doc = new FileDocument(path, OFlags.read | OFlags.exists | OFlags.share);
// Replace any previously opened diff document.
if (session.diffdoc)
session.diffdoc.close();
session.diffdoc = doc;
session.diffpath = path;
g_status |= UVIEW;
}
void diff_close(Session *session)
{
if (session.diffdoc is null)
return;
session.diffdoc.close();
session.diffdoc = null;
session.diffpath = null;
g_status |= UVIEW;
}
enum {
/// Scan backward instead of forward.
DIFF_REVERSE = 1,
/// Do not check for a cancel key while scanning, and do not draw progress.
/// Used for unittests, because they run without an interactive terminal.
DIFF_DISALLOW_CANCEL = 2,
/// No difference found in the requested direction.
DIFF_RESULT_NOT_FOUND = -1,
}
// True if the element of `size` bytes at `offset` differs between the two
// buffers. A byte that exists on one side only (past the end of the shorter
// document) counts as a difference, matching what the panel paints with
// ColorScheme.diff_missing.
bool diff_element(ubyte[] mine, ubyte[] theirs, size_t offset, int size)
{
for (int b; b < size; ++b)
{
size_t o = offset + b;
bool hasmine = o < mine.length;
bool hastheir = o < theirs.length;
if (hasmine != hastheir) // one side ran out
return true;
if (hasmine && mine[o] != theirs[o])
return true;
}
return false;
}
/// Find the start of the diff hunk that follows (or precedes) `position`.
///
/// Akin to search function, but with diffs.
///
/// A hunk is a run of consecutive differing elements, and only its first
/// element is a stop, so a large modified region takes one jump instead of
/// hundreds. Comparisons are done at element granularity and aligned like the
/// view is, so results land on what the diff panel highlights.
///
/// Backward, a hunk start strictly below the cursor is returned, meaning that
/// a cursor sitting inside a hunk moves to that hunk's own start first.
///
/// Params:
/// session = Current session, with a diff document opened.
/// position = Starting position.
/// flags = Operation flags.
/// Returns: Address of the hunk start, or DIFF_RESULT_NOT_FOUND.
long diff_seek(Session *session, long position, int flags)
{
assertion(session.diffdoc, "Need diff document");
int esize = size_of(session.rc.data_type);
// Elements past the end of one side still count (as missing data), so
// both documents are scanned in full.
long limit = max(session.editor.size(), session.diffdoc.size());
if (limit <= 0)
return DIFF_RESULT_NOT_FOUND;
// Buffers are reused across invocations, like the diff panel does.
__gshared ubyte[] minebuf;
__gshared ubyte[] theirbuf;
if (minebuf.length < CONFIG_DIFFBUFSIZE)
{
minebuf.length = CONFIG_DIFFBUFSIZE;
theirbuf.length = CONFIG_DIFFBUFSIZE;
}
// Cursor can sit anywhere within an element, so align it down first.
long cursor = (position / esize) * esize;
log("position=%d cursor=%d esize=%d limit=%d flags=%#x", position, cursor, esize, limit, flags);
debug import std.datetime.stopwatch : StopWatch;
debug StopWatch sw;
debug sw.start;
debug scope(exit) { sw.stop(); log("diff_seek=%s", sw.peek()); }
if (flags & DIFF_REVERSE)
{
// Nothing below the first element
if (cursor <= 0)
return DIFF_RESULT_NOT_FOUND;
long end = cursor; // exclusive, candidates are below it
while (end > 0)
{
if ((flags & DIFF_DISALLOW_CANCEL) == 0 && cancelling())
throw new Exception(MSG_CANCELED);
long base = end - CONFIG_CHUNKSIZE;
if (base < 0)
base = 0;
// Read one element before the chunk, to tell whether the lowest
// candidate starts a hunk or continues one.
long readbase = base > 0 ? base - esize : 0;
size_t span = cast(size_t)(end - readbase);
ubyte[] mine = session.editor.view(readbase, minebuf[0..span]);
ubyte[] theirs = session.diffdoc.readAt(readbase, theirbuf[0..span]);
size_t low = cast(size_t)(base - readbase); // lowest candidate
size_t top = span - esize; // highest candidate
bool curdiff = diff_element(mine, theirs, top, esize);
for (size_t o = top; ; o -= esize)
{
// Element zero has nothing before it, so it starts a hunk
// whenever it differs.
bool prevdiff = readbase + o > 0 ?
diff_element(mine, theirs, o - esize, esize) : false;
if (curdiff && prevdiff == false)
return readbase + o;
curdiff = prevdiff;
if (o <= low)
break;
}
if ((flags & DIFF_DISALLOW_CANCEL) == 0)
update_progress(session, limit - base, limit);
end = base;
}
return DIFF_RESULT_NOT_FOUND;
}
// Forward: first candidate is the element after the cursor, and the
// element before it tells whether that candidate starts a hunk.
long readbase = cursor;
while (readbase < limit)
{
if ((flags & DIFF_DISALLOW_CANCEL) == 0 && cancelling())
throw new Exception(MSG_CANCELED);
size_t span = cast(size_t) min(CONFIG_CHUNKSIZE, limit - readbase);
if (span <= esize) // only the reference element left, no candidate
break;
ubyte[] mine = session.editor.view(readbase, minebuf[0..span]);
ubyte[] theirs = session.diffdoc.readAt(readbase, theirbuf[0..span]);
bool prevdiff = diff_element(mine, theirs, 0, esize);
for (size_t o = esize; o < span; o += esize)
{
bool curdiff = diff_element(mine, theirs, o, esize);
if (curdiff && prevdiff == false)
return readbase + o;
prevdiff = curdiff;
}
if ((flags & DIFF_DISALLOW_CANCEL) == 0)
update_progress(session, readbase + span, limit);
// Overlap by one element, so the run state carries into the next chunk
readbase += span - esize;
}
return DIFF_RESULT_NOT_FOUND;
}
// Hunks group consecutive differing elements: navigation stops on the first
// element of a run, forward and backward, and a cursor inside a run goes back
// to that run's own start.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
// "AAXXAAXXAA": hunks start at 2 and 6
Session session;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "AAAAAAAAAA");
session.diffdoc = new MemoryDocument(cast(const(ubyte)[]) "AAXXAAXXAA");
assert(diff_seek(&session, 0, DIFF_DISALLOW_CANCEL) == 2);
assert(diff_seek(&session, 2, DIFF_DISALLOW_CANCEL) == 6);
assert(diff_seek(&session, 3, DIFF_DISALLOW_CANCEL) == 6, "from inside a hunk");
assert(diff_seek(&session, 6, DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
assert(diff_seek(&session, 9, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == 6);
assert(diff_seek(&session, 7, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == 6, "from inside a hunk");
assert(diff_seek(&session, 6, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == 2);
assert(diff_seek(&session, 2, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
}
// A hunk starting at address zero has no element before it, and is still
// reported when scanning backward from further ahead.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "AAAA");
session.diffdoc = new MemoryDocument(cast(const(ubyte)[]) "XAAA");
assert(diff_seek(&session, 3, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == 0);
assert(diff_seek(&session, 0, DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
}
// Data existing on one side only counts as a difference, like the panel
// paints it, whichever side is the shorter one.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session shorter_diff;
shorter_diff.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "AAAA");
shorter_diff.diffdoc = new MemoryDocument(cast(const(ubyte)[]) "AA");
assert(diff_seek(&shorter_diff, 0, DIFF_DISALLOW_CANCEL) == 2);
Session shorter_editor;
shorter_editor.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "AA");
shorter_editor.diffdoc = new MemoryDocument(cast(const(ubyte)[]) "AAAA");
assert(diff_seek(&shorter_editor, 0, DIFF_DISALLOW_CANCEL) == 2);
}
// A hunk overlapping a chunk boundary is one hunk: the element of overlap
// between chunks must carry the run state, otherwise the part after the
// boundary is reported as a new hunk.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
enum SIZE = CONFIG_CHUNKSIZE * 2;
enum HUNK = CONFIG_CHUNKSIZE - 2; // spans the boundary by two bytes
ubyte[] mine = new ubyte[SIZE];
ubyte[] theirs = new ubyte[SIZE];
theirs[HUNK .. CONFIG_CHUNKSIZE + 2] = 0xff;
Session session;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) mine.idup);
session.diffdoc = new MemoryDocument(theirs);
assert(diff_seek(&session, 0, DIFF_DISALLOW_CANCEL) == HUNK);
assert(diff_seek(&session, HUNK, DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
assert(diff_seek(&session, SIZE - 1, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == HUNK);
}
// Identical documents have nothing to navigate to.
unittest
{
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "hello");
session.diffdoc = new MemoryDocument(cast(const(ubyte)[]) "hello");
assert(diff_seek(&session, 0, DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
assert(diff_seek(&session, 4, DIFF_REVERSE|DIFF_DISALLOW_CANCEL) == DIFF_RESULT_NOT_FOUND);
}
// Jump the cursor to the start of the next difference against the diffed file.
void diff_next(Session *session, Argument[] args)
{
if (session.diffdoc is null)
throw new Exception(MSG_NO_DIFF_OPEN);
unselect(session); // Navigation, unselect
long pos = diff_seek(session, session.position_cursor, 0);
if (pos < 0)
{
message(MSG_NO_MORE_DIFFERENCES);
return;
}
moveabs(session, pos);
message("Difference at %s", address_text(session, pos));
}
// Jump the cursor to the start of the previous difference against the diffed file.
void diff_prev(Session *session, Argument[] args)
{
if (session.diffdoc is null)
throw new Exception(MSG_NO_DIFF_OPEN);
unselect(session); // Navigation, unselect
long pos = diff_seek(session, session.position_cursor, DIFF_REVERSE);
if (pos < 0)
{
message(MSG_NO_MORE_DIFFERENCES);
return;
}
moveabs(session, pos);
message("Difference at %s", address_text(session, pos));
}
//
void undo(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
long pos = session.editor.undo();
if (pos < 0)
return;
unselect(session);
moveabs(session, pos);
g_status |= UVIEW; // new data
}
//
void redo(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
long pos = session.editor.redo();
if (pos < 0)
return;
unselect(session);
moveabs(session, pos);
g_status |= UVIEW; // new data
}
// Go to position in document
void goto_(Session *session, Argument[] args)
{
long position = void;
bool absolute = void;
// With arguments: Prioritize before selection
Selection sel = selection(session);
if (args.length == 0 && sel.length)
{
if (sel.length > long.sizeof)
throw new Exception(MSG_SELECTION_TOO_LARGE);
ubyte[8] raw;
ubyte[] res = session.editor.view(sel.start, raw.ptr, cast(size_t)sel.length);
absolute = true; // eh, just assuming
import std.system : Endian;
// Selected bytes as one unsigned number in the endian setting
ulong value;
if (session.rc.endian == Endian.bigEndian)
foreach (ubyte b; res)
value = value << 8 | b;
else
foreach_reverse (ubyte b; res)
value = value << 8 | b;
position = cast(long)value;
}
else
{
string off = askstring(args, 0, "offset: ");
// Number
switch (off[0]) {
case '+':
if (off.length <= 1)
throw new Exception(MSG_INCOMPLETE_NUMBER);
position = scan(off[1..$]);
absolute = false;
break;
case '-':
if (off.length <= 1)
throw new Exception(MSG_INCOMPLETE_NUMBER);
position = -scan(off[1..$]);
absolute = false;
break;
case '%':
if (off.length <= 1) // just '%'
throw new Exception(MSG_NEED_PERCENTAGE_NUMBER);
double per = to!double(off[1..$]);
if (per > 100.0) // Can't go beyond document (EOF)
throw new Exception(MSG_PERCENTAGE_OVER_100);
position = llpercentdivf(session.editor.size(), per);
absolute = true;
break;
default:
position = scan(off);
absolute = true;
}
}
// Force selection off, we're navigating somewhere
unselect(session);
g_digitpos = 0;
// Let's fucking go!
absolute ? moveabs(session, position) : moverel(session, position);
}
// goto takes its argument over the selection, reads the selection in the
// endian setting, and read-only refuses undo/redo.
unittest
{
import ddhx.editor.piecev5 : PieceV5DocumentEditor;
import ddhx.document.memory : MemoryDocument;
Session session;
session.input = new InputFormatter;
session.rc.columns = 8;
session.editor = new PieceV5DocumentEditor().open(
new MemoryDocument(cast(const(ubyte)[]) "\x03\x00\x05ABCDEFGHI"));
// Selection holds 3 as a u16, the argument wins
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 0;
session.position_cursor = 1;
goto_(&session, [ Argument("6") ]);
assert(session.position_cursor == 6);
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 0;
session.position_cursor = 1;
goto_(&session, null);
assert(session.position_cursor == 3);
// Bytes 00 05 are 5 in big endian, past the document in little endian
import std.system : Endian;
session.rc.endian = Endian.bigEndian;
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 1;
session.position_cursor = 2;
goto_(&session, null);
assert(session.position_cursor == 5);
session.editor.replace(4, "z".ptr, 1);
session.rc.writemode = WritingMode.readonly;
foreach (command_func f; [ &undo, &redo ])
{
try { f(&session, null); assert(false); }
catch (Exception e) {}
}
ubyte[1] b;
assert(session.editor.view(4, b[]) == "z");
}
// Report alternative statusbar using statusbar formatting
void report(Session *session, Argument[] args)
{
string fmt = args.length > 0 ? args[0].text : session.rc.status_fmt_report;
Selection sel = selection(session);
SliceWriter sw = SliceWriter(g_messagebuf); // uses message buffer
formatStatus(sw, fmt, session, sel, g_cols);
g_message = cast(string)g_messagebuf[0 .. sw.pos];
g_status |= UMESSAGE | USTATUS;
}
// Report document name on screen (as a reminder)
// Deprecated
void report_name(Session *session, Argument[] args)
{
import os.path : displayName;
message( session.target is null ? "(new buffer)" : displayName(session.target) );
}
// Report program version on screen
// Deprecated
void report_version(Session *session, Argument[] args)
{
message( DDHX_VERSION );
}
// Show single information, specified by argument
// Contrasts with report command (easier to remember)
void show(Session *session, Argument[] args)
{
if (args.length < 1)
{
message( "Need argument" );
return;
}
string arg = args[0].text; // used by default error
switch (arg) {
case "name":
import os.path : displayName;
message( session.target is null ? "(new buffer)" : displayName(session.target) );
break;
case "path":
message( session.target is null ? "(new buffer)" : session.target );
break;
case "size":
message( "%d", session.editor.size() );
break;
case "version":
message( DDHX_VERSION );
break;
default:
message( "Unknown show arg: %s", arg );
}
}
// Given parameters, suggest a number of columns that can fit in terminal.
// Layout: ADDRESS " " [" " DATA]×cols " " [TEXT]×(cols×size_of)
// Overhead: aspace + 3, per column: 1 + dspace + size_of
int suggestcols(int tcols, int aspace, int dspace, int size_of)
{
if (tcols < 20)
return 1;
int left = tcols - (aspace + 3); // address + spacers around data
return left / (1 + dspace + size_of);
}
unittest
{
// 80 cols terminal, 11 chars for address
// x8: 2 data chars, 1 byte -> (80-14)/4 = 16
// x16: 4 data chars, 2 bytes -> (80-14)/7 = 9
// x32: 8 data chars, 4 bytes -> (80-14)/13 = 5
// d8: 3 data chars, 1 byte -> (80-14)/5 = 13
// d16: 5 data chars, 2 bytes -> (80-14)/8 = 8
// d32: 10 data chars, 4 bytes -> (80-14)/15 = 4
// o8: 3 data chars, 1 byte -> (80-14)/5 = 13
// o16: 6 data chars, 2 bytes -> (80-14)/9 = 7
// o32: 11 data chars, 4 bytes -> (80-14)/16 = 4
assert(suggestcols(80, 11, 2, 1) == 16); // x8
assert(suggestcols(80, 11, 4, 2) == 9); // x16
assert(suggestcols(80, 11, 8, 4) == 5); // x32
assert(suggestcols(80, 11, 3, 1) == 13); // d8
assert(suggestcols(80, 11, 5, 2) == 8); // d16
assert(suggestcols(80, 11, 10, 4) == 4); // d32
assert(suggestcols(80, 11, 3, 1) == 13); // o8
assert(suggestcols(80, 11, 6, 2) == 7); // o16
assert(suggestcols(80, 11, 11, 4) == 4); // o32
assert(suggestcols(0, 11, 2, 1) == 1); // too small: 1
}
// Automatically size the number of columns that can fix on screen
// using the currently selected data mode.
void autosize(Session *session, Argument[] args)
{
import std.math : abs;
int adspacing = abs( session.rc.address_spacing );
DataSpec spec = selectDataSpec(session.rc.data_type);
TerminalSize tsize = terminalSize();
session.rc.columns = suggestcols(tsize.columns, adspacing, spec.spacing, spec.size_of);
}
// Export selected range to file
void export_range(Session *session, Argument[] args)
{
Selection sel = selection(session);
if (sel.length == 0)
throw new Exception(MSG_NEED_SELECTION);
string name = askstring(args, 0, "Name: ", &complete_path);
if (exists(name))
{
int key = promptkey("File exists, overwrite? [y/N] ");
switch (key) {
case 'y', 'Y': break;
default: return;
}
}
File output = File(name, "w");
// Re-using search alloc func because lazy
ubyte[] buf = (cast(ubyte*)malloc(CONFIG_CHUNKSIZE))[0..CONFIG_CHUNKSIZE];
if (buf is null)
throw new Exception(MSG_OUT_OF_MEMORY);
scope(exit) free(buf.ptr);
long end = sel.start + sel.length;
while (sel.start < end)
{
long want = min(end - sel.start, CONFIG_CHUNKSIZE);
ubyte[] res = session.editor.view(sel.start, buf.ptr, cast(size_t)want);
if (res.length == 0)
break;
output.rawWrite(res);
sel.start += res.length;
}
// Unfortunately to force the message through
unselect(session);
message("Saved as %s", name); // confirmation
}
/// Data bytes for the replace and insert commands, from pattern arguments,
/// refusing wildcards with globmsg.
ubyte[] edit_pattern(Session *session, Argument[] args, string globmsg)
{
if (args.length < 1)
throw new Exception(MSG_MISSING_PATTERN);
Pattern p = pattern(session.rc.endian, args);
if (p.flags & PATTERN_NOT_BYTES)
throw new Exception(globmsg);
return p.toBytes();
}
// Replace data using pattern, over the selection or at the cursor
void replace_(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
ubyte[] pb = edit_pattern(session, args, MSG_CANT_REPLACE_GLOBBING);
Selection sel = selection(session);
if (sel.length)
session.editor.patternReplace(sel.start, sel.length, pb.ptr, pb.length);
else
session.editor.patternReplace(session.position_cursor, pb.length, pb.ptr, pb.length);
g_status |= UVIEW | UHEADER | USTATUS;
}
// Insert data using pattern, as long as the selection or once at the cursor
void insert_(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
ubyte[] pb = edit_pattern(session, args, MSG_CANT_INSERT_GLOBBING);
Selection sel = selection(session);
if (sel.length)
session.editor.patternInsert(sel.start, sel.length, pb.ptr, pb.length);
else
session.editor.patternInsert(session.position_cursor, pb.length, pb.ptr, pb.length);
g_status |= UVIEW | UHEADER | USTATUS;
}
// Replace data in a range using pattern
void replace_range(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
if (args.length < 1)
throw new Exception(MSG_MISSING_RANGE);
Range r = askrange(args, 0, "Range: ");
ubyte[] pb = edit_pattern(session, args[1..$], MSG_CANT_REPLACE_GLOBBING);
session.editor.patternReplace(r.start, r.length, pb.ptr, pb.length);
g_status |= UVIEW | UHEADER | USTATUS;
}
// Insert data as long as a range using pattern, at its start
void insert_range(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
if (args.length < 1)
throw new Exception(MSG_MISSING_RANGE);
Range r = askrange(args, 0, "Range: ");
ubyte[] pb = edit_pattern(session, args[1..$], MSG_CANT_INSERT_GLOBBING);
session.editor.patternInsert(r.start, r.length, pb.ptr, pb.length);
g_status |= UVIEW | UHEADER | USTATUS;
}
// Range commands take their range over the selection, replace and insert
// take the selection, and all agree on missing argument messages.
unittest
{
import ddhx.editor.piecev5 : PieceV5DocumentEditor;
import ddhx.document.memory : MemoryDocument;
Session session;
session.input = new InputFormatter;
session.rc.columns = 8;
session.editor = new PieceV5DocumentEditor().open(
new MemoryDocument(cast(const(ubyte)[]) "ABCDEF"));
Session *saved = g_session;
g_session = &session; // for askrange
scope(exit) g_session = saved;
string text()
{
ubyte[16] buf;
return cast(string) session.editor.view(0, buf[]).idup;
}
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 4;
session.position_cursor = 5;
replace_range(&session, [ Argument("0:1"), Argument("utf8:z") ]);
assert(text() == "zzCDEF");
insert_range(&session, [ Argument("2"), Argument("utf8:y") ]);
assert(text() == "zzCDEyyF"); // at the cursor, which is 5
replace_(&session, [ Argument("utf8:x") ]);
assert(text() == "zzCDxxyF"); // over the selection, 4 to 5
foreach (command_func f; [ &replace_, &insert_, &replace_range, &insert_range ])
{
try { f(&session, null); assert(false); }
catch (Exception e)
assert(e.msg == (f == &replace_ || f == &insert_ ? MSG_MISSING_PATTERN : MSG_MISSING_RANGE));
}
try { replace_range(&session, [ Argument("0:1") ]); assert(false); }
catch (Exception e) assert(e.msg == MSG_MISSING_PATTERN);
}
// Replace data using file
void replace_file(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
string path = askstring(args, 0, "File: ", &complete_path);
IDocument file = new FileDocument(path, true);
session.documents ~= file;
session.editor.fileReplace(session.position_cursor, file);
g_status |= UVIEW;
}
// Insert data using file
void insert_file(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
string path = askstring(args, 0, "File: ", &complete_path);
IDocument file = new FileDocument(path, true);
session.documents ~= file;
long curpos = session.position_cursor;
session.editor.fileInsert(curpos, file);
g_status |= UVIEW;
}
/// Copy the selection, or the element at the cursor, into the clipboard,
/// returning where it starts, or -1 when nothing was copied.
long clip_store(Session *session)
{
long start;
size_t len;
Selection sel = selection(session);
if (sel.length)
{
// Address space range check (notably on 32-bit systems)
if (sel.length > MAXSIZE)
throw new Exception(MSG_CLIPBOARD_CANNOT_CONTAIN_SELECTION);
if (sel.length >= CONFIG_COPY_WORRY)
{
int k = promptkey("Copy >16 MiB into clipboard? [y/N] ");
switch (k) {
case 'y', 'Y': break;
default: return -1;
}
}
len = cast(size_t)sel.length;
start = sel.start;
}
else // No selection
{
len = size_of(session.rc.data_type);
start = session.position_cursor;
}
// Cursor on the EOF slot
if (start >= session.editor.size())
return -1;
log("Copying %u bytes...", len);
void *ptr = realloc(g_clipboard_ptr, len);
if (ptr == null)
throw new Exception(MSG_ALLOCATION_FAILED);
g_clipboard_ptr = cast(ubyte*)ptr;
// A partial last element reads short
g_clipboard_len = session.editor.view(start, g_clipboard_ptr[0..len]).length;
return start;
}
// Copy data into clipboard buffer
void clip_copy(Session *session, Argument[] args)
{
cast(void)clip_store(session);
}
// Cut data into clipboard buffer
void clip_cut(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
long start = clip_store(session);
if (start < 0)
return;
session.editor.remove(start, g_clipboard_len);
unselect(session);
moveabs(session, start); // like delete, cursor could be past the new end
g_status |= UVIEW; // force read
}
// Paste data from clipboard buffer
void clip_paste(Session *session, Argument[] args)
{
if (g_clipboard_ptr == null)
throw new Exception(MSG_CLIPBOARD_EMPTY);
// Checked before the selection is removed
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_DOCUMENT_READONLY);
// Typical behaviour with text editors: If we paste with a selection,
// (a) selection region gets removed and (b) new data is inserted
Selection sel = selection(session);
if (sel.length)
{
session.editor.remove(sel.start, sel.length);
// Force selection OFF even with an active marking
session.selection.status = 0;
// Editor isn't smart enough for positions after document
// So force the new position to be minimum value
session.position_cursor = sel.start;
}
// Depending on mode (modal), insert or overwrite
final switch (session.rc.writemode) {
case WritingMode.insert:
session.editor.insert(session.position_cursor, g_clipboard_ptr, g_clipboard_len);
break;
case WritingMode.overwrite:
case WritingMode.digit:
session.editor.replace(session.position_cursor, g_clipboard_ptr, g_clipboard_len);
break;
case WritingMode.readonly:
throw new Exception(MSG_DOCUMENT_READONLY);
}
// Move cursor to end of pasted data, which helps repeating the action of
// pasting over and over
long newpos = session.position_cursor + g_clipboard_len;
moveabs(session, newpos);
g_status |= UVIEW; // force read
}
// Clear clipboard buffer
void clip_clear(Session *session, Argument[] args)
{
if (g_clipboard_ptr == null)
return;
free(g_clipboard_ptr);
g_clipboard_ptr = null;
g_clipboard_len = 0;
}
// Clipboard and delete: copy takes an element, never past the document,
// and read-only refuses edits before touching anything.
unittest
{
import ddhx.editor.piecev5 : PieceV5DocumentEditor;
import ddhx.document.memory : MemoryDocument;
Session session;
session.input = new InputFormatter;
session.rc.columns = 8;
session.rc.data_type = DataType(BaseType.u16, Format.hex);
session.editor = new PieceV5DocumentEditor().open(
new MemoryDocument(cast(const(ubyte)[]) "ABCDE"));
scope(exit) clip_clear(&session, null);
string text()
{
ubyte[8] buf;
return cast(string) session.editor.view(0, buf[]).idup;
}
session.position_cursor = 2;
clip_copy(&session, null);
assert(g_clipboard_ptr[0 .. g_clipboard_len] == "CD");
// Partial last element, then the EOF slot keeps the clipboard
session.position_cursor = 4;
clip_copy(&session, null);
assert(g_clipboard_ptr[0 .. g_clipboard_len] == "E");
session.position_cursor = 5;
clip_copy(&session, null);
assert(g_clipboard_ptr[0 .. g_clipboard_len] == "E");
session.rc.writemode = WritingMode.readonly;
session.position_cursor = 2;
foreach (command_func f; [ &delete_front, &delete_back, &clip_cut ])
{
try { f(&session, null); assert(false); }
catch (Exception e) {}
}
session.selection.status = SELECT_ACTIVE;
session.selection.anchor = 0;
try { clip_paste(&session, null); assert(false); }
catch (Exception e) {}
assert(text() == "ABCDE");
session.rc.writemode = WritingMode.overwrite;
clip_cut(&session, null);
assert(text() == "E");
assert(g_clipboard_ptr[0 .. g_clipboard_len] == "ABCD");
assert(session.selection.status == 0 && session.position_cursor == 0);
}
// Save changes (assumes to a file)
void save(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_SAVE_READONLY);
// TODO: Document type check
// Some document types (ie, disk, process memory) cannot be saved to a file
// If target set: Destination is meant to be a file
// If FileDocument or MemoryDocument: See above
// If ProcessDocument or FileDocument is disk: new inplace function needed
// To assign after successful save
string target = session.target;
// No known path... Ask for one!
if (target is null)
{
// Ask for a filename
target = askstring(null, 0, "Name: ", &complete_path);
// Check if target exists to ask for overwrite
if (exists(target))
{
// Don't explicitly check if directory exists.
// The filesystem will report the error anyway.
switch (promptkey("Overwrite? [y/N] ")) {
case 'y', 'Y': // Continue
break;
default:
throw new Exception(MSG_CANCELED);
}
}
}
// Force updating the status bar to indicate that we're currently saving.
// It might take a while depending on the strategy used.
message("Saving...");
update_status(session);
// Volume of bytes an in-place save would write (and stash in memory
// to keep undo history valid), used to pick the saving strategy
long writevol;
foreach (ref piece; session.editor.dirtyPieceInfos(true))
writevol += piece.size;
// A full save replaces a file target wholesale; media without that
// capability (e.g., disk, process memory) can only be saved in-place
bool canreplace = session.ogdoc is null || (session.ogdoc.caps() & DocCaps.replace) != 0;
// If the original doc is file, try saving it in-place
try
{
// Fallback environment variable
if (environment.get("DDHX_NO_INPLACE_SAVE") == "1")
goto Lfallback;
// When most of the document needs rewriting anyway, the full
// save costs about the same I/O, stashes nothing, and replaces
// the file atomically
if (canreplace && prefer_inplace(writevol, session.editor.size()) == false)
goto Lfallback;
// It will fail if the target does not exist or
// fails a permission check (e.g., GVFS with O_RDWR)
save_inplace(session.editor, target);
goto Ldone;
}
catch (Exception ex)
{
// Indicator that save_inplace failed, and we're now going to fallback
log("[NOTE] save_inplace: '%s'", ex.msg);
// No fallback available: report the in-place failure itself
if (canreplace == false)
throw ex;
}
// Write document fully. If this one fails, it's caught by ddhx
Lfallback:
if (canreplace == false)
throw new Exception(MSG_CANNOT_SAVE_FULL);
save_to_file(session.editor, target);
Ldone:
session.target = target;
// If opened as memory document, since file is written on disk,
// reopen as file document
if (cast(MemoryDocument) session.ogdoc)
{
session.ogdoc.close();
FileDocument doc = new FileDocument(target, OFlags.read | OFlags.exists | OFlags.share);
session.editor.open(doc);
session.ogdoc = doc;
}
message("Saved");
}
// Save as file
void save_as(Session *session, Argument[] args)
{
string name = askstring(args, 0, "Save as: ", &complete_path);
message("Saving...");
update_status(session);
// Always SAVE AS new file
save_to_file(session.editor, name);
// See note in save().
if (cast(MemoryDocument) session.ogdoc)
{
session.ogdoc.close();
FileDocument doc = new FileDocument(name, OFlags.read | OFlags.exists | OFlags.share);
session.editor.open(doc);
session.ogdoc = doc;
}
message("Saved");
// Successful save, set as target
session.target = name;
}
/// Open a file, replacing the current document.
void open_(Session *session, Argument[] args)
{
string path = askstring(args, 0, "Open: ", &complete_path);
if (confirm_discard(session) == false)
return;
message(open_document(session, path));
demote_writemode(session);
}
/// Close the document, leaving an empty buffer.
void close_(Session *session, Argument[] args)
{
if (confirm_discard(session) == false)
return;
close_document(session);
message(MSG_NEW_BUFFER);
}
// Set runtime config
void set(Session *session, Argument[] args)
{
string setting = askstring(args, 0, "Setting: ", &complete_set);
if (args.length == 0) // so the value prompt completes for it
args = [ Argument(setting) ];
string value = askstring(args, 1, "Value: ", &complete_set);
configRC(session.rc, setting, value);
sync_settings();
if (session.rc.columns_auto) // also refits after a data type change
autosize(session, null);
realign(session);
demote_writemode(session);
}
// Bind key to action (command + parameters)
void bind(Session *session, Argument[] args)
{
int key = terminalKeybind( askstring(args, 0, "Key: ", &complete_key) );
// "bind ctrl+9 goto +1" as is, while a prompt or "bind ctrl+9 'goto +1'"
// has the command line in one string
Argument[] commands = args.length > 2 ? args[1..$] :
arguments( askline(args, 1, "Command: ", toDelegate(&complete_line)) );
bindkey(key, commands[0].text, commands.length > 1 ? commands[1..$] : null);
message("Key binded");
}
// Unbind key
void unbind(Session *session, Argument[] args)
{
int key = terminalKeybind( askstring(args, 0, "Key: ", &complete_key) );
unbindkey(key);
message("Key unbinded");
}
// Reset all keys
void reset_keys(Session *session, Argument[] args)
{
g_keys.clear();
initdefaults();
message("All keys reset");
}
// Set color scheme at runtime
void color(Session *session, Argument[] args)
{
if (args.length < 1)
throw new Exception(MSG_MISSING_SCHEME);
import std.traits : EnumMembers;
if (args[0].text == "reset") // reset all
{
foreach (scheme; EnumMembers!(ColorScheme))
{
setcolor(scheme, ColorMapper.default_(scheme));
}
return;
}
if (args.length < 2)
throw new Exception(MSG_MISSING_COLOR);
// reset: reset only for this scheme
ColorScheme scheme = getScheme(args[0].text);
setcolor(scheme,
args[1].text == "reset" ? ColorMapper.default_(scheme) : ColorMap.parse(args[1].text));
}
//
void find(Session *session, Argument[] args)
{
Selection sel = selection(session);
// With arguments: Prioritize before selection
if (args.length > 0)
{
g_needle = pattern(session.rc.endian, args);
sel.start = session.position_cursor + 1;
}
else if (sel.length) // search by selection
{
if (sel.length > CONFIG_NEEDLE_LIMIT)
throw new Exception(MSG_SELECTION_TOO_BIG);
ubyte[] buf = new ubyte[cast(size_t)sel.length];
g_needle = Pattern.fromBytes( session.editor.view(sel.start, buf) );
if (g_needle.length < sel.length)
return; // Nothing to do
sel.start += g_needle.length;
}
else
throw new Exception(MSG_NEED_SEARCH);
if (g_needle.length == 0)
return;
unselect(session);
message("Searching...");
update_status(session);
SearchResult r = search(session, g_needle, sel.start, SEARCH_ELEMENT);
if (r.pos < 0)
{
message("Not found");
return;
}
neselect(session, r.pos, r.pos + r.len - 1);
reveal(session, r.pos, r.pos + r.len - 1);
message("Found at %s", address_text(session, r.pos));
}
//
void find_back(Session *session, Argument[] args)
{
Selection sel = selection(session);
// If arguments: Take those before selection
if (args.length > 0)
{
g_needle = pattern(session.rc.endian, args);
sel.start = session.position_cursor - 1;
}
else if (sel.length) // selection
{
if (sel.length > CONFIG_NEEDLE_LIMIT)
throw new Exception(MSG_SELECTION_TOO_BIG);
ubyte[] buf = new ubyte[cast(size_t)sel.length];
g_needle = Pattern.fromBytes( session.editor.view(sel.start, buf) );
if (g_needle.length < sel.length)
return; // Nothing to do, couldn't read all of needle
sel.start -= g_needle.length;
}
else
throw new Exception(MSG_NEED_SEARCH);
unselect(session);
message("Searching...");
update_status(session);
SearchResult r = search(session, g_needle, sel.start, SEARCH_REVERSE | SEARCH_ELEMENT);
if (r.pos < 0)
{
message("Not found");
return;
}
neselect(session, r.pos, r.pos + r.len - 1);
reveal(session, r.pos, r.pos + r.len - 1);
message("Found at %s", address_text(session, r.pos));
}
//
void find_next(Session *session, Argument[] args)
{
if (g_needle.data is null)
return;
// Resume past the selection (the current match), or past the cursor
Selection sel = selection(session);
long start = sel.length ? sel.start + sel.length : session.position_cursor + 1;
unselect(session);
message("Searching...");
update_status(session);
SearchResult r = search(session, g_needle, start, SEARCH_ELEMENT);
if (r.pos < 0)
{
message("Not found");
return;
}
neselect(session, r.pos, r.pos + r.len - 1);
reveal(session, r.pos, r.pos + r.len - 1);
message("Found at %s", address_text(session, r.pos));
}
//
void find_prev(Session *session, Argument[] args)
{
if (g_needle.data is null)
return;
// Search before the selection (the current match), or before the cursor
Selection sel = selection(session);
long start = sel.length ? sel.start - 1 : session.position_cursor - 1;
long end = sel.length ? sel.start : long.max;
unselect(session);
message("Searching...");
update_status(session);
// Matches never overlap, so one before the selection must end before it
SearchResult r = search(session, g_needle, start, SEARCH_REVERSE | SEARCH_ELEMENT, null, end);
if (r.pos < 0)
{
message("Not found");
return;
}
neselect(session, r.pos, r.pos + r.len - 1);
reveal(session, r.pos, r.pos + r.len - 1);
message("Found at %s", address_text(session, r.pos));
}
// Find every occurrence of a pattern and bookmark each match.
//
// Unlike the other find commands, this one scans the whole document rather
// than starting at the cursor, and leaves the cursor where it is: the result
// is the bookmark list, navigable with bookmark-next/bookmark-prev.
void find_bookmark(Session *session, Argument[] args)
{
Selection sel = selection(session);
// With arguments: Prioritize before selection
if (args.length > 0)
{
g_needle = pattern(session.rc.endian, args);
}
else if (sel.length) // search by selection
{
if (sel.length > CONFIG_NEEDLE_LIMIT)
throw new Exception(MSG_SELECTION_TOO_BIG);
ubyte[] buf = new ubyte[cast(size_t)sel.length];
g_needle = Pattern.fromBytes( session.editor.view(sel.start, buf) );
if (g_needle.length < sel.length)
return; // Nothing to do, couldn't read all of needle
}
else
throw new Exception(MSG_NEED_SEARCH);
if (g_needle.length == 0)
return;
unselect(session);
message("Searching...");
update_status(session);
// A one-byte needle over a large document matches more times than there
// is memory (or patience) for, so the scan stops at the configured
// number of matches, which can be lifted entirely.
int limit = session.rc.find_bookmark_limit;
// Matches come in ascending order, so they are collected and merged in
// one pass: a sorted insert each would turn quadratic.
Bookmark[] found;
size_t count;
try
{
search(session, g_needle, 0, SEARCH_ELEMENT,
(SearchResult r) {
found ~= Bookmark(r.pos, r.len);
// Continues if limit is set and not reached
return limit == BOOKMARK_LIMIT_NONE || found.length < cast(size_t)limit ?
SearchAction.next : SearchAction.stop;
});
}
finally // A canceled search keeps whatever it found until then
{
count = bookmark_merge(session, found);
if (count)
g_status |= UVIEW | USTATUS;
}
if (found.length == 0)
{
message("Not found");
return;
}
// Matches can all be bookmarked already, from an earlier run
if (count == 0)
{
message("All matches already bookmarked");
return;
}
if (limit != BOOKMARK_LIMIT_NONE && found.length >= cast(size_t)limit)
{
message("%d bookmarked (limit reached)", count);
return;
}
message("%d bookmarked", count);
}
// Split find-replace args around the "--" separator into needle and
// replacement pattern argument lists.
void splitReplaceArgs(Argument[] args, out Argument[] needleArgs, out Argument[] replArgs)
{
size_t sep = size_t.max;
foreach (i, a; args)
{
if (a.text == "--") { sep = i; break; }
}
if (sep == size_t.max)
throw new Exception(MSG_NEED_NEEDLE_AND_REPLACEMENT);
needleArgs = args[0..sep];
replArgs = args[sep+1..$];
if (needleArgs.length == 0)
throw new Exception(MSG_MISSING_NEEDLE);
if (replArgs.length == 0)
throw new Exception(MSG_MISSING_REPLACEMENT);
}
//
void find_replace(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
// Allows find-replace to be repeated (typically via ^R)
if (args.length)
{
Argument[] needleArgs, replArgs;
splitReplaceArgs(args, needleArgs, replArgs);
g_needle = pattern(session.rc.endian, needleArgs);
if (g_needle.length == 0)
throw new Exception(MSG_EMPTY_NEEDLE);
g_replacement = pattern(session.rc.endian, replArgs);
if (g_replacement.flags & PATTERN_NOT_BYTES)
throw new Exception(MSG_CANT_REPLACE_GLOBBING);
}
else if (g_needle.data is null || g_replacement.data is null)
throw new Exception(MSG_NO_PREVIOUS_FIND_REPLACE);
Selection sel = selection(session);
long start = sel.length ? sel.start + sel.length : session.position_cursor;
unselect(session);
message("Searching...");
update_status(session);
SearchResult r = search(session, g_needle, start, SEARCH_ELEMENT);
if (r.pos < 0)
{
message("Not found");
return;
}
ubyte[] pb = g_replacement.toBytes();
session.editor.patternReplace(r.pos, r.len, pb.ptr, pb.length);
g_status |= UVIEW | UHEADER | USTATUS;
neselect(session, r.pos, r.pos + r.len - 1);
reveal(session, r.pos, r.pos + r.len - 1);
message("Replaced at %s", address_text(session, r.pos));
}
//
void find_replace_all(Session *session, Argument[] args)
{
if (session.rc.writemode == WritingMode.readonly)
throw new Exception(MSG_CANNOT_EDIT_READONLY);
if (args.length)
{
Argument[] needleArgs, replArgs;
splitReplaceArgs(args, needleArgs, replArgs);
g_needle = pattern(session.rc.endian, needleArgs);
if (g_needle.length == 0)
throw new Exception(MSG_EMPTY_NEEDLE);
g_replacement = pattern(session.rc.endian, replArgs);
if (g_replacement.flags & PATTERN_NOT_BYTES)
throw new Exception(MSG_CANT_REPLACE_GLOBBING);
}
else if (g_needle.data is null || g_replacement.data is null)
throw new Exception(MSG_NO_PREVIOUS_FIND_REPLACE);
ubyte[] pb = g_replacement.toBytes();
Selection sel = selection(session);
long start = sel.length ? sel.start : session.position_cursor;
long end = sel.length ? sel.start + sel.length : long.max;
unselect(session);
message("Searching...");
update_status(session);
long count;
// One undo step for the whole run, canceled or not
session.editor.beginGroup();
scope(exit) session.editor.endGroup();
for (;;)
{
// search already checks for cancellation
SearchResult r = search(session, g_needle, start, SEARCH_ELEMENT, null, end);
if (r.pos < 0)
break;
session.editor.patternReplace(r.pos, r.len, pb.ptr, pb.length);
start = r.pos + r.len;
count++;
}
g_status |= UVIEW | UHEADER | USTATUS;
if (count == 0)
message("Not found");
else
message("Replaced %d occurrence(s)", count);
}
// Quit app
void quit(Session *session, Argument[] args)
{
if (confirm_discard(session) == false)
return;
terminalRestore();
exit(0);
}
// A range is fixed-width, so a search reports its width as the match length.
unittest
{
import std.system : Endian;
import ddhx.editor.dummy : DummyDocumentEditor;
Session session;
session.editor = new DummyDocumentEditor(cast(immutable(ubyte)[]) "ab12cd");
Pattern needle = pattern(Endian.littleEndian, "u8:48..57", "u8:48..57");
SearchResult result = search(&session, needle, 0, SEARCH_NON_INTERACTIVE);
assert(result.pos == 2);
assert(result.len == 2);
result = search(&session, needle, 5, SEARCH_REVERSE | SEARCH_NON_INTERACTIVE);
assert(result.pos == 2);
}