]> git.lizzy.rs Git - linenoise.git/blobdiff - linenoise.c
Ctrl-l support to clear the screen. New sequences added documented.
[linenoise.git] / linenoise.c
index 0ebef2e910f8772cfc9c35a7d5d858c227bccef5..dd43413661ca9677c51667ca657daeca50706307 100644 (file)
@@ -9,6 +9,8 @@
  * the 2010 UNIX computers around.
  *
  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
+ * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
+ *
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * CUF (CUrsor Forward)
  *    Sequence: ESC [ n C
  *    Effect: moves cursor forward of n chars
+ *
+ * The following are used to clear the screen: ESC [ H ESC [ 2 J
+ * This is actually composed of two sequences:
+ *
+ * cursorhome
+ *    Sequence: ESC [ H
+ *    Effect: moves the cursor to upper left corner
+ *
+ * ED2 (Clear entire screen)
+ *    Sequence: ESC [ 2 J
+ *    Effect: clear the whole screen
  * 
  */
 
@@ -243,10 +256,14 @@ static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, si
                     if (i == lc.len) beep();
                     break;
                 case 27: /* escape */
+                    /* Re-show original buffer */
+                    if (i < lc.len) {
+                        refreshLine(fd,prompt,buf,*len,*pos,cols);
+                    }
                     stop = 1;
                     break;
                 default:
-                    /* update buffer and return */
+                    /* Update buffer and return */
                     if (i < lc.len) {
                         nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
                         *len = *pos = nwritten;
@@ -261,6 +278,10 @@ static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, si
     return c; /* Return last read character */
 }
 
+void linenoiseClearScreen(void) {
+    write(STDIN_FILENO,"\x1b[H\x1b[2J",7);
+}
+
 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
     size_t plen = strlen(prompt);
     size_t pos = 0;
@@ -428,6 +449,9 @@ up_down_arrow:
             pos = len;
             refreshLine(fd,prompt,buf,len,pos,cols);
             break;
+        case 12: /* ctrl+l, clear screen */
+            linenoiseClearScreen();
+            refreshLine(fd,prompt,buf,len,pos,cols);
         }
     }
     return len;