Skip to content
Advertisement

Prevent output of carriage return with readline

I’m new to the Gnu Readline library.

I need to call the readline() function when the cursor is at the very last line of the console. But I need to prevent scrolling down when the Return key is pressed; so I’m looking for a way to prevent the output of the carriage return : I’m sure it’s possible, but can’t find the way to do it.

I tried to use my own rl_getc_function() to trap the Return key (the example below traps y and z keys, but it’s just for test purposes) and treat this key in a special way:

  • My first idea was to run the accept-line command directly, thinking it would not output a carriage return, but actually, it does
  • My second idea was to redirect the output to /dev/null before calling the accept-line command; but the redirection doesn’t seem to apply when the readline() function is already running.

Here is an example of my tests:

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

FILE *devnull; // To test output redirecting

int my_getc(FILE *file)
{
    int c = getc(file);

    // Let's test something when the 'y' key is pressed:
    if (c == 'y') {
        // I was thinking that calling "accept-line" directly
        // would prevent the output of a carriage return:
        rl_command_func_t *accept_func = rl_named_function("accept-line");
        accept_func(1, 0);
        return 0;
    }

    // Another test, when 'z' key is pressed:
    if (c == 'z') {
        // Try a redirection:
        rl_outstream = devnull;
        // As the redirection didn't work unless I set it before
        // the readline() call, I tried to add this call,
        // but it doesn't initialize the output stream:
        rl_initialize();
        return 'z';

    }
    return c;
}

int main()
{
    devnull = fopen("/dev/null", "w");

    // Using my function to handle key input:
    rl_getc_function = my_getc;

    // Redirection works if I uncomment the following line:
    // rl_outstream = devnull;

    readline("> "); // No freeing for this simplified example
    printf("How is it possible to remove the carriage return before this line?n");

    return 0;
}

I’m sure I missed the right way to do it; any help would be appreciated.

Advertisement

Answer

I found it : the rl_done variable is made for this.

If I add this code to my my_getc() function, it works well:

if (c == 'r') {
    rl_done = 1;
    return 0;

}

No carriage return is then inserted, and my next printf() call displays just after the last char I typed.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement