Search code examples
linuxcarriage-return

How to set carriage return location or equivalent?


I am looking for a way to set where the carriage return, returns to or an equivalent way to do so.

For example I have a line like this:

^ denotes cursor location

myshell>cat file.txt
                    ^

After carriage return it should look like this.

myshell>cat file.txt
        ^

Solution

  • You're probably after what's collectively called ANSI escape sequences. Its hard to search for if you really have no idea what you're after.

    This tiny example saves/restores cursor position:

    #include <stdio.h>
    
    int main(int argc, char**argv)
    {
      char cmd_buf[100];
      cmd_buf[0]=0;
      while(strncmp(cmd_buf, "quit", 4))
      {
        printf("mypromt>\033[s <-Cursor should go there\033[u");
        fflush(stdout);
        fgets(cmd_buf, sizeof(cmd_buf), stdin);
        printf("\nYou entered: %s\n", cmd_buf);
      }
    }
    

    Note that in terminator, gnome-terminal and xterm on Ubuntu, this "magically" supports CTRL+U as-is, but not CTRL+A or CTRL+E.

    There are many, many more sequences available. The wikipedia page is probably the simplest reference to get you started.

    Update: Also, unless you're doing this as a learning exercise (which I get the impression Benjamin is), to build an interactive shell, you should probably use one of the two well established libraries for shell-style line editing, namely:

    • readline (GPLv3, but far more popular)
    • editline (BSD licensed, closest "second place")

    They are the libraries that provide the emacs-style (typical default) and vi-style keybindings and history features we all know and love from bash, python, lua, perl, node, etc, etc.