//------------------------------------------------------------------------------ void save_history() { int max_history; char buffer[1024]; const char* c; if (get_clink_setting_int("persist_history") == 0) { return; } get_history_file_name(buffer, sizeof(buffer)); // Get max history size. c = rl_variable_value("history-size"); max_history = (c != NULL) ? atoi(c) : 1000; // Write new history to the file, and truncate to our maximum. if (append_history(g_new_history_count, buffer) != 0) { write_history(buffer); } history_truncate_file(buffer, max_history); }
static int console_update_history(const char *histfile) { int ret = 0; #ifdef HAVE_READLINE int max_history_length, truncate_entries; /* * Calculate how much we should keep in the current history file. */ max_history_length = (me) ? me->history_length : 100; truncate_entries = max_history_length - history_length; if (truncate_entries < 0) { truncate_entries = 0; } /* * First, try to truncate the history file, and if it * fails, the file is probably not present, and we * can use write_history to create it. */ if (history_truncate_file(histfile, truncate_entries) == 0) { ret = append_history(history_length, histfile); } else { ret = write_history(histfile); } #endif return ret; }
static int console_init_history(const char *histfile) { int ret = 0; #ifdef HAVE_READLINE int max_history_length; using_history(); /* * First truncate the history size to an reasonable size. */ max_history_length = (me) ? me->history_length : 100; history_truncate_file(histfile, max_history_length); /* * Read the content of the history file into memory. */ ret = read_history(histfile); /* * Tell the completer that we want a complete. */ rl_completion_entry_function = dummy_completion_function; rl_attempted_completion_function = readline_completion; rl_filename_completion_desired = 0; stifle_history(max_history_length); #endif return ret; }
void readline_constructor_impl::impl::stop() { if (current_readline == NULL) { // We're already stopped return; } assert(detail::current_readline == this); stdin_reader_.cancel(); redisplay_timer_.cancel(); rl_callback_handler_remove(); detail::current_readline = NULL; std::cout << std::endl; if (!history_file_.empty()) { boost::filesystem::create_directories(history_file_.parent_path()); if (0 == write_history(history_file_.c_str())) { if (0 != history_truncate_file( history_file_.c_str(), history_length )) { throw relasio_error("error truncating history\n"); } } else { throw relasio_error("error writing history\n"); } } }
static PyObject * append_history_file(PyObject *self, PyObject *args) { int nelements; PyObject *filename_obj = Py_None, *filename_bytes; char *filename; int err; if (!PyArg_ParseTuple(args, "i|O:append_history_file", &nelements, &filename_obj)) return NULL; if (filename_obj != Py_None) { if (!PyUnicode_FSConverter(filename_obj, &filename_bytes)) return NULL; filename = PyBytes_AsString(filename_bytes); } else { filename_bytes = NULL; filename = NULL; } errno = err = append_history(nelements, filename); if (!err && _history_length >= 0) history_truncate_file(filename, _history_length); Py_XDECREF(filename_bytes); errno = err; if (errno) return PyErr_SetFromErrno(PyExc_IOError); Py_RETURN_NONE; }
static void wrapper_for_write_history() { #if 1 /* Alternative code, saves one disk access */ if (history_is_stifled()) unstifle_history(); if (gnuplot_history_size >= 0) stifle_history (gnuplot_history_size); /* returns 0 on success */ if (write_history(expanded_history_filename)) fprintf (stderr, "Warning: Could not write history file!!!\n"); unstifle_history(); #else /* if writing was successful, truncate history * to gnuplot_history_size lines */ if (write_history(expanded_history_filename)) { if (gnuplot_history_size >= 0) history_truncate_file(expanded_history_filename, gnuplot_history_size); } #endif }
void attribute_hidden Rstd_savehistory(SEXP call, SEXP op, SEXP args, SEXP env) { SEXP sfile; char file[PATH_MAX]; const char *p; sfile = CAR(args); if (!isString(sfile) || LENGTH(sfile) < 1) errorcall(call, _("invalid '%s' argument"), "file"); p = R_ExpandFileName(translateChar(STRING_ELT(sfile, 0))); if(strlen(p) > PATH_MAX - 1) errorcall(call, _("'file' argument is too long")); strcpy(file, p); #if defined(HAVE_LIBREADLINE) && defined(HAVE_READLINE_HISTORY_H) if(R_Interactive && UsingReadline) { int err; err = write_history(file); if(err) error(_("problem in saving the history file '%s'"), file); /* Note that q() uses stifle_history, but here we do not want * to truncate the active history when saving during a session */ #ifdef HAVE_HISTORY_TRUNCATE_FILE R_setupHistory(); /* re-read the history size */ err = history_truncate_file(file, R_HistorySize); if(err) warning(_("problem in truncating the history file")); #endif } else errorcall(call, _("no history available to save")); #else errorcall(call, _("no history available to save")); #endif }
//------------------------------------------------------------------------------ void save_history() { int max_history; char buffer[512]; get_history_file_name(buffer, sizeof(buffer)); // Get max history size. max_history = get_clink_setting_int("history_file_lines"); max_history = (max_history == 0) ? INT_MAX : max_history; if (max_history < 0) { unlink(buffer); return; } // Write new history to the file, and truncate to our maximum. if (append_history(g_new_history_count, buffer) != 0) { write_history(buffer); } if (max_history != INT_MAX) { history_truncate_file(buffer, max_history); } g_new_history_count = 0; }
void halcmd_save_history() { char path[PATH_MAX]; snprintf(path,sizeof(path),"%s/%s", getenv("HOME"), HALCMD_HISTORY); if ((write_history (path))) perror(path); history_truncate_file (path, MAX_HISTORY); }
value caml_history_truncate_file(value name, value nlines) { CAMLparam2(name, nlines); int result; result = history_truncate_file( String_val(name), Long_val(nlines) ); if (result != 0) { CAMLlocal1(error); error = copy_string(strerror( result )); raise_sys_error( error ); } CAMLreturn(Val_unit); }
static PyObject * write_history_file(PyObject *self, PyObject *args) { char *s = NULL; if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) return NULL; errno = write_history(s); if (!errno && _history_length >= 0) history_truncate_file(s, _history_length); if (errno) return PyErr_SetFromErrno(PyExc_IOError); Py_RETURN_NONE; }
//------------------------------------------------------------------------------ void save_history() { static const int max_history = 200; char buffer[1024]; get_history_file_name(buffer, sizeof(buffer)); // Write new history to the file, and truncate to our maximum. if (append_history(g_new_history_count, buffer) != 0) { write_history(buffer); } history_truncate_file(buffer, max_history); }
static SeedValue seed_readline(SeedContext ctx, SeedObject function, SeedObject this_object, size_t argument_count, const SeedValue arguments[], SeedValue * exception) { SeedValue valstr = 0; gchar *str = NULL; gchar *buf; const gchar *histfname = g_get_home_dir(); gchar *path = g_build_filename(histfname, ".seed_history", NULL); if (!readline_has_initialized) { read_history(path); readline_has_initialized = TRUE; } CHECK_ARG_COUNT("readline.readline", 1); buf = seed_value_to_string(ctx, arguments[0], exception); str = readline(buf); if (str && *str) { add_history(str); valstr = seed_value_from_string(ctx, str, exception); g_free(str); } write_history(path); history_truncate_file(path, 1000); g_free(buf); g_free(path); if (valstr == 0) valstr = seed_make_null(ctx); return valstr; }
void Yap_CloseReadline(void) { #if USE_READLINE write_history(history_file); history_truncate_file(history_file, 300); #endif }
int repl() { #ifdef HAVE_READLINE history_truncate_file(history_filename(), 1000); read_history(history_filename()); #endif // HAVE_READLINE // Eingabeschleife als REPL(read-eval-print loop) -> Eingabe, Verarbeitung, Ausgabe do { char *user_input = NULL; ////////////////////// // read ////////////////////// #ifdef HAVE_READLINE user_input = readline("?: "); if (!user_input) break; strim(user_input); if (*user_input) add_history(user_input); #else // Eingabepuffer als "String" mit Maximallänge user_input = calloc(LINE_BUFFER_SIZE, sizeof(char)); printf("?: "); // Bei end-of-file oder Lesefehler gibt fgets NULL zurück // und das Programm soll beendet werden (analog zur Shell) // // break ist eigentlich nicht schön (=nicht im Struktogramm // abbildbar ;) ), dient aber hier der Klarheit, da einige // if entfallen können if (!fgets(user_input, LINE_BUFFER_SIZE, stdin)) break; strim(user_input); #endif // HAVE_READLINE ////////////////////// // eval ////////////////////// // Abbruch durch User? if (strcmp(user_input, "\\quit") == 0) break; // 1. Parsen parse_context *p_ctx = start_parse(user_input); // 2. Baum traversieren if (parse(p_ctx) == 0) { eval_context *e_ctx = eval(p_ctx->ast_root); if (e_ctx == NULL) fprintf(stderr, "Fatal evaluation error.\n"); if (e_ctx->success) { ////////////////////// // print ////////////////////// printf("-> %.50Lg\n", e_ctx->result); } else { print_eval_errors(e_ctx); } end_eval(e_ctx); } else { print_parse_errors(p_ctx); } // Aufräumen end_parse(p_ctx); free(user_input); } while (1); // loop.... #ifdef HAVE_READLINE write_history(history_filename()); #endif // HAVE_READLINE printf("End.\n"); return 0; }
/* * This function saves the readline history when user * runs \s command or when psql exits. * * fname: pathname of history file. (Should really be "const char *", * but some ancient versions of readline omit the const-decoration.) * * max_lines: if >= 0, limit history file to that many entries. * * appendFlag: if true, try to append just our new lines to the file. * If false, write the whole available history. * * encodeFlag: whether to encode \n as \x01. For \s calls we don't wish * to do that, but must do so when saving the final history file. */ bool saveHistory(char *fname, int max_lines, bool appendFlag, bool encodeFlag) { #ifdef USE_READLINE /* * Suppressing the write attempt when HISTFILE is set to /dev/null may * look like a negligible optimization, but it's necessary on e.g. Darwin, * where write_history will fail because it tries to chmod the target * file. */ if (useHistory && fname && strcmp(fname, DEVNULL) != 0) { if (encodeFlag) encode_history(); /* * On newer versions of libreadline, truncate the history file as * needed and then append what we've added. This avoids overwriting * history from other concurrent sessions (although there are still * race conditions when two sessions exit at about the same time). If * we don't have those functions, fall back to write_history(). * * Note: return value of write_history is not standardized across GNU * readline and libedit. Therefore, check for errno becoming set to * see if the write failed. Similarly for append_history. */ #if defined(HAVE_HISTORY_TRUNCATE_FILE) && defined(HAVE_APPEND_HISTORY) if (appendFlag) { int nlines; int fd; /* truncate previous entries if needed */ if (max_lines >= 0) { nlines = Max(max_lines - history_lines_added, 0); (void) history_truncate_file(fname, nlines); } /* append_history fails if file doesn't already exist :-( */ fd = open(fname, O_CREAT | O_WRONLY | PG_BINARY, 0600); if (fd >= 0) close(fd); /* append the appropriate number of lines */ if (max_lines >= 0) nlines = Min(max_lines, history_lines_added); else nlines = history_lines_added; errno = 0; (void) append_history(nlines, fname); if (errno == 0) return true; } else #endif { /* truncate what we have ... */ if (max_lines >= 0) stifle_history(max_lines); /* ... and overwrite file. Tough luck for concurrent sessions. */ errno = 0; (void) write_history(fname); if (errno == 0) return true; } psql_error("could not save history to file \"%s\": %s\n", fname, strerror(errno)); } #else /* only get here in \s case, so complain */ psql_error("history is not supported by this installation\n"); #endif return false; }
char *getline() { char *prompt; int len; char *home; int fdh; /* If initialization hasn't been done, do it now: * - We don't want TAB completion */ if (!done_init) { rl_bind_key('\t', rl_insert); /* get history from file */ home = getenv("FVWM_USERDIR"); h_file = safemalloc(strlen(home) + sizeof(HISTFILE) + 1); strcpy(h_file, home); strcat(h_file, HISTFILE); if( access( h_file, F_OK) < 0) { /* if it doesn't exist create it */ fdh = creat( h_file, S_IRUSR | S_IWUSR ); if( fdh != -1 ) { close( fdh ); } } else { read_history_range( h_file, 0, HISTSIZE ); } done_init = 1; } /* Empty out the previous info */ len = 0; *cmd = '\0'; prompt = PS1; while (1) { int linelen = 0; /* If the buffer has already been allocated, free the memory. */ if (line != (char *)NULL) free(line); /* Get a line from the user. */ line = readline(prompt); if (line == NULL) return (NULL); /* Make sure we have enough space for the new line */ linelen = strlen(line); if (len + linelen > MAX_COMMAND_SIZE-2 ) { fprintf( stderr, "line too long %d chars max %d \a\n", len+linelen, MAX_COMMAND_SIZE-2 ); strncat(cmd, line, MAX_COMMAND_SIZE-len-2); add_history(cmd); break; } /* Copy the new line onto the end of the current line */ strcat(cmd, line); /* If the current line doesn't end with a backslash, we're done */ len = strlen(cmd); if (cmd[len-1] != '\\') break; /* Otherwise, remove it and wait for more (add a space if needed) */ prompt = PS2; cmd[len-1] = (cmd[len-2]==' ' || cmd[len-2]=='\t') ? '\0' : ' '; } /* If the command has any text in it, save it on the history. */ if (*cmd != '\0') { add_history(cmd); append_history( 1,h_file ); history_truncate_file( h_file, HISTSIZE ); } cmd[len] = '\n'; cmd[len+1] = '\0'; return (cmd); }
static bool saveHistory(char *fname, int max_lines) { int errnum; /* * Suppressing the write attempt when HISTFILE is set to /dev/null may * look like a negligible optimization, but it's necessary on e.g. Darwin, * where write_history will fail because it tries to chmod the target * file. */ if (strcmp(fname, DEVNULL) != 0) { /* * Encode \n, since otherwise readline will reload multiline history * entries as separate lines. (libedit doesn't really need this, but * we do it anyway since it's too hard to tell which implementation we * are using.) */ encode_history(); /* * On newer versions of libreadline, truncate the history file as * needed and then append what we've added. This avoids overwriting * history from other concurrent sessions (although there are still * race conditions when two sessions exit at about the same time). If * we don't have those functions, fall back to write_history(). */ #if defined(HAVE_HISTORY_TRUNCATE_FILE) && defined(HAVE_APPEND_HISTORY) { int nlines; int fd; /* truncate previous entries if needed */ if (max_lines >= 0) { nlines = Max(max_lines - history_lines_added, 0); (void) history_truncate_file(fname, nlines); } /* append_history fails if file doesn't already exist :-( */ fd = open(fname, O_CREAT | O_WRONLY | PG_BINARY, 0600); if (fd >= 0) close(fd); /* append the appropriate number of lines */ if (max_lines >= 0) nlines = Min(max_lines, history_lines_added); else nlines = history_lines_added; errnum = append_history(nlines, fname); if (errnum == 0) return true; } #else /* don't have append support */ { /* truncate what we have ... */ if (max_lines >= 0) stifle_history(max_lines); /* ... and overwrite file. Tough luck for concurrent sessions. */ errnum = write_history(fname); if (errnum == 0) return true; } #endif psql_error("could not save history to file \"%s\": %s\n", fname, strerror(errnum)); } return false; }
/* VTY shell main routine. */ int main (int argc, char **argv, char **env) { char *p; int opt; int dryrun = 0; int boot_flag = 0; const char *daemon_name = NULL; struct cmd_rec { const char *line; struct cmd_rec *next; } *cmd = NULL; struct cmd_rec *tail = NULL; int echo_command = 0; int no_error = 0; /* Preserve name of myself. */ progname = ((p = strrchr (argv[0], '/')) ? ++p : argv[0]); /* if logging open now */ if ((p = getenv("VTYSH_LOG")) != NULL) logfile = fopen(p, "a"); /* Option handling. */ while (1) { opt = getopt_long (argc, argv, "be:c:d:nEhC", longopts, 0); if (opt == EOF) break; switch (opt) { case 0: break; case 'b': boot_flag = 1; break; case 'e': case 'c': { struct cmd_rec *cr; cr = XMALLOC(0, sizeof(*cr)); cr->line = optarg; cr->next = NULL; if (tail) tail->next = cr; else cmd = cr; tail = cr; } break; case 'd': daemon_name = optarg; break; case 'n': no_error = 1; break; case 'E': echo_command = 1; break; case 'C': dryrun = 1; break; case 'h': usage (0); break; default: usage (1); break; } } /* Initialize user input buffer. */ line_read = NULL; setlinebuf(stdout); /* Signal and others. */ vtysh_signal_init (); init_timer_mgr (); /* Make vty structure and register commands. */ vtysh_init_vty (); vtysh_init_cmd (); vtysh_user_init (); vtysh_config_init (); vty_init_vtysh (); sort_node (); /* Read vtysh configuration file before connecting to daemons. */ vtysh_read_config (config_default); /* Start execution only if not in dry-run mode */ if(dryrun) return(0); /* Ignore error messages */ if (no_error) freopen("/dev/null", "w", stdout); /* Make sure we pass authentication before proceeding. */ vtysh_auth (); /* Do not connect until we have passed authentication. */ if (vtysh_connect_all (daemon_name) <= 0) { fprintf(stderr, "Exiting: NetworkOS not initialized.\n"); exit(1); } /* If eval mode. */ if (cmd) { /* Enter into enable node. */ vtysh_execute ("enable"); while (cmd != NULL) { int ret; char *eol; while ((eol = strchr(cmd->line, '\n')) != NULL) { *eol = '\0'; if (echo_command) printf("%s%s\n", vtysh_prompt(), cmd->line); if (logfile) log_it(cmd->line); ret = vtysh_execute_no_pager(cmd->line); if (!no_error && ! (ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON || ret == CMD_WARNING)) exit(1); cmd->line = eol+1; } if (echo_command) printf("%s%s\n", vtysh_prompt(), cmd->line); if (logfile) log_it(cmd->line); ret = vtysh_execute_no_pager(cmd->line); if (!no_error && ! (ret == CMD_SUCCESS || ret == CMD_SUCCESS_DAEMON || ret == CMD_WARNING)) exit(1); { struct cmd_rec *cr; cr = cmd; cmd = cmd->next; XFREE(0, cr); } } exit (0); } /* Boot startup configuration file. */ if (boot_flag) { if (vtysh_read_config (integrate_default)) { fprintf (stderr, "Can't open configuration file [%s]\n", integrate_default); exit (1); } else exit (0); } vtysh_pager_init (); vtysh_readline_init (); vty_hello (vty); /* Enter into enable node. */ //vtysh_execute ("enable"); /* Preparation for longjmp() in sigtstp(). */ sigsetjmp (jmpbuf, 1); jmpflag = 1; snprintf(history_file, sizeof(history_file), "%s/.history_quagga", getenv("HOME")); read_history(history_file); /* Main command loop. */ while (vtysh_rl_gets ()) vtysh_execute (line_read); history_truncate_file(history_file,1000); printf ("\n"); /* Rest in peace. */ exit (0); }