Skip to content

Commit

Permalink
Allow shortcuts for jumping the cursor over words
Browse files Browse the repository at this point in the history
linenoise is extended to allow for jumping the cursor over words with
the Ctrl-Left Ctrl-Right keys. On macOS, the key binding would be
Controll-Command-Left and Controll-Command-Right.
  • Loading branch information
jserv committed Feb 2, 2023
1 parent 1f00e44 commit 21e408c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
57 changes: 54 additions & 3 deletions linenoise.c
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,7 @@ void linenoiseEditBackspace(struct linenoiseState *l)
}
}

/* Delete the previosu word, maintaining the cursor at the start of the
/* Delete the previous word, maintaining the cursor at the start of the
* current word. */
void linenoiseEditDeletePrevWord(struct linenoiseState *l)
{
Expand All @@ -844,6 +844,37 @@ void linenoiseEditDeletePrevWord(struct linenoiseState *l)
refreshLine(l);
}

/* Jump to the begining of the previous word */
static void linenoiseEditPrevWord(struct linenoiseState *l)
{
while (l->pos > 0 && l->buf[l->pos - 1] == ' ')
l->pos--;
while (l->pos > 0 && l->buf[l->pos - 1] != ' ')
l->pos--;
refreshLine(l);
}

/* Jump to the space after the current word */
static void linenoiseEditNextWord(struct linenoiseState *l)
{
while (l->pos < l->len) {
if (l->buf[l->pos] != ' ')
break;
l->pos++;
}

while (l->pos < l->len) {
if (l->buf[l->pos] == ' ')
break;
if (l->buf[l->pos] == '\0')
break;

l->pos++;
}

refreshLine(l);
}

/* This function is the core of the line editing capability of linenoise.
* It expects 'fd' to be already in "raw mode" so that every key pressed
* will be returned ASAP to read().
Expand Down Expand Up @@ -887,7 +918,7 @@ static int linenoiseEdit(int stdin_fd,
while (1) {
signed char c;
int nread;
char seq[3];
char seq[5];

nread = read(l.ifd, &c, 1);
if (nread <= 0)
Expand Down Expand Up @@ -975,12 +1006,32 @@ static int linenoiseEdit(int stdin_fd,
/* Extended escape, read additional byte. */
if (read(l.ifd, seq + 2, 1) == -1)
break;
if (seq[2] == '~') {
switch (seq[2]) {
case '~':
switch (seq[1]) {
case '3': /* Delete key. */
linenoiseEditDelete(&l);
break;
}
break;

case ';':
/* Even more extended escape, read additional 2 bytes */
if (read(l.ifd, seq + 3, 1) == -1)
break;
if (read(l.ifd, seq + 4, 1) == -1)
break;
if (seq[3] == '5') {
switch (seq[4]) {
case 'D': /* Ctrl Left */
linenoiseEditPrevWord(&l);
break;
case 'C': /* Ctrl Right */
linenoiseEditNextWord(&l);
break;
}
}
break;
}
} else {
switch (seq[1]) {
Expand Down
1 change: 1 addition & 0 deletions scripts/aspell-pws
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,4 @@ offsetof
rbtree
vfprintf
vla
ctrl

0 comments on commit 21e408c

Please sign in to comment.