diff --git a/CMakeLists.txt b/CMakeLists.txt index 0c935b3c2a19..9451eaa89799 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,246 +1,245 @@ cmake_minimum_required(VERSION 3.9) get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(is_multi_config) set(CMAKE_CONFIGURATION_TYPES Debug Release CACHE STRING "Semicolon separated list of supported configuration types") mark_as_advanced(CMAKE_CONFIGURATION_TYPES) elseif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_C_FLAGS) message(WARNING "No CMAKE_BUILD_TYPE is selected") endif() project(nvi2 C) include(CheckIncludeFiles) include(CheckFunctionExists) include(CheckSymbolExists) include(CheckStructHasMember) include(CheckCSourceCompiles) include(CheckCCompilerFlag) mark_as_advanced(CMAKE_INSTALL_PREFIX) option(USE_WIDECHAR "Enable wide character support" ON) option(USE_ICONV "Enable iconv support" ON) check_c_compiler_flag(-fcolor-diagnostics USE_FCOLOR_DIAGNOSTICS) if(USE_FCOLOR_DIAGNOSTICS) add_compile_options(-fcolor-diagnostics) endif() add_compile_options($<$:-Wall>) add_compile_options($<$:-Wno-parentheses>) add_compile_options($<$:-Wno-uninitialized>) add_compile_options($<$:-Wmissing-prototypes>) if (NOT APPLE) add_compile_options($<$:-Wsystem-headers>) endif() add_compile_options($<$:-Wuninitialized>) add_compile_options($<$:-Wno-dangling-else>) -add_compile_options(-Wno-string-compare) add_compile_options(-Wstack-protector -fstack-protector) add_compile_options(-Wstrict-aliasing -fstrict-aliasing) include_directories(${CMAKE_CURRENT_BINARY_DIR}) set(MAIN_PROTOS cl/extern.h common/extern.h ex/extern.h vi/extern.h common/options_def.h ex/ex_def.h ex/version.h) set(CL_SRCS cl/cl_funcs.c cl/cl_main.c cl/cl_read.c cl/cl_screen.c cl/cl_term.c) set(COMMON_SRCS common/conv.c common/cut.c common/delete.c common/encoding.c common/exf.c common/key.c common/line.c common/log.c common/main.c common/mark.c common/msg.c common/options.c common/options_f.c common/put.c common/recover.c common/screen.c common/search.c common/seq.c common/util.c) set(EX_SRCS ex/ex.c ex/ex_abbrev.c ex/ex_append.c ex/ex_args.c ex/ex_argv.c ex/ex_at.c ex/ex_bang.c ex/ex_cd.c ex/ex_cmd.c ex/ex_cscope.c ex/ex_delete.c ex/ex_display.c ex/ex_edit.c ex/ex_equal.c ex/ex_file.c ex/ex_filter.c ex/ex_global.c ex/ex_init.c ex/ex_join.c ex/ex_map.c ex/ex_mark.c ex/ex_mkexrc.c ex/ex_move.c ex/ex_open.c ex/ex_preserve.c ex/ex_print.c ex/ex_put.c ex/ex_quit.c ex/ex_read.c ex/ex_screen.c ex/ex_script.c ex/ex_set.c ex/ex_shell.c ex/ex_shift.c ex/ex_source.c ex/ex_stop.c ex/ex_subst.c ex/ex_tag.c ex/ex_txt.c ex/ex_undo.c ex/ex_usage.c ex/ex_util.c ex/ex_version.c ex/ex_visual.c ex/ex_write.c ex/ex_yank.c ex/ex_z.c) set(VI_SRCS vi/getc.c vi/v_at.c vi/v_ch.c vi/v_cmd.c vi/v_delete.c vi/v_ex.c vi/v_increment.c vi/v_init.c vi/v_itxt.c vi/v_left.c vi/v_mark.c vi/v_match.c vi/v_paragraph.c vi/v_put.c vi/v_redraw.c vi/v_replace.c vi/v_right.c vi/v_screen.c vi/v_scroll.c vi/v_search.c vi/v_section.c vi/v_sentence.c vi/v_status.c vi/v_txt.c vi/v_ulcase.c vi/v_undo.c vi/v_util.c vi/v_word.c vi/v_xchar.c vi/v_yank.c vi/v_z.c vi/v_zexit.c vi/vi.c vi/vs_line.c vi/vs_msg.c vi/vs_refresh.c vi/vs_relative.c vi/vs_smap.c vi/vs_split.c) set(REGEX_SRCS regex/regcomp.c regex/regerror.c regex/regexec.c regex/regfree.c) # commands to generate the public headers set(extract_protos sed -n 's/^ \\* PUBLIC: \\\(.*\\\)/\\1/p') set(extract_version sed -n 's/^.*version \\\([^\)]*\)\\\).*/\#define VI_VERSION \\\"\\1\\\"/p') add_custom_command(OUTPUT cl/extern.h COMMAND ${extract_protos} ${CL_SRCS} > cl/extern.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${CL_SRCS}) add_custom_command(OUTPUT common/extern.h COMMAND ${extract_protos} ${COMMON_SRCS} > common/extern.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${COMMON_SRCS}) add_custom_command(OUTPUT ex/extern.h COMMAND ${extract_protos} ${EX_SRCS} > ex/extern.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${EX_SRCS}) add_custom_command(OUTPUT vi/extern.h COMMAND ${extract_protos} ${VI_SRCS} > vi/extern.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${VI_SRCS}) add_custom_command(OUTPUT common/options_def.h COMMAND awk -f common/options.awk common/options.c > common/options_def.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS common/options.c) add_custom_command(OUTPUT ex/ex_def.h COMMAND awk -f ex/ex.awk ex/ex_cmd.c > ex/ex_def.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ex/ex_cmd.c) add_custom_command(OUTPUT ex/version.h COMMAND ${extract_version} README > ex/version.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS README) add_executable(nvi) target_sources(nvi PRIVATE ${MAIN_PROTOS} ${CL_SRCS} ${COMMON_SRCS} ${EX_SRCS} ${VI_SRCS}) target_compile_definitions(nvi PRIVATE $<$:DEBUG> $<$:COMLOG>) check_function_exists(openpty UTIL_IN_LIBC) if(NOT UTIL_IN_LIBC) find_library(UTIL_LIBRARY util) target_link_libraries(nvi PRIVATE ${UTIL_LIBRARY}) endif() check_function_exists(__b64_ntop RESOLV_IN_LIBC) if(NOT RESOLV_IN_LIBC) find_library(RESOLV_LIBRARY resolv) target_link_libraries(nvi PRIVATE ${RESOLV_LIBRARY}) endif() check_symbol_exists(asprintf "stdio.h" ASPRINTF_IN_STDIO_H) if(NOT ASPRINTF_IN_STDIO_H) target_compile_definitions(nvi PRIVATE _GNU_SOURCE) endif() if(USE_WIDECHAR) find_library(CURSES_LIBRARY NAMES ncursesw cursesw curses HINTS /usr/lib) find_library(TERMINFO_LIBRARY NAMES tinfow terminfo HINTS /usr/lib) # link to the wchar_t awared BSD libregex.a add_library(regex STATIC) target_sources(regex PRIVATE ${REGEX_SRCS}) target_include_directories(regex PUBLIC regex) target_compile_definitions(regex PUBLIC __REGEX_PRIVATE) # The macro _XOPEN_SOURCE_EXTENDED is needed to get the waddnwstr() # definition on at least FreeBSD and recent macOS. target_compile_definitions(nvi PRIVATE _XOPEN_SOURCE_EXTENDED) target_link_libraries(nvi PRIVATE regex) else() find_library(CURSES_LIBRARY NAMES ncurses curses HINTS /usr/lib) find_library(TERMINFO_LIBRARY NAMES tinfo terminfo HINTS /usr/lib) target_compile_options(nvi PRIVATE -Wno-pointer-sign) endif() target_link_libraries(nvi PRIVATE ${CURSES_LIBRARY}) if(TERMINFO_LIBRARY) target_link_libraries(nvi PRIVATE ${TERMINFO_LIBRARY}) endif() if(USE_ICONV) check_function_exists(iconv ICONV_IN_LIBC) if(NOT ICONV_IN_LIBC) find_path(ICONV_INCLUDE_DIR iconv.h) find_library(ICONV_LIBRARY iconv) endif() # detect the prototype of iconv(3) set(CMAKE_C_FLAGS_BACKUP "${CMAKE_C_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror") set(CMAKE_REQUIRED_INCLUDES "${ICONV_INCLUDE_DIR}") set(CMAKE_REQUIRED_LIBRARIES "${ICONV_LIBRARY}") check_c_source_compiles(" #include int main() { iconv_t conv = 0; char* in = 0; size_t ilen = 0; char* out = 0; size_t olen = 0; iconv(conv, &in, &ilen, &out, &olen); return 0; } " ICONV_TRADITIONAL) set(CMAKE_REQUIRED_INCLUDES) set(CMAKE_REQUIRED_LIBRARIES) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS_BACKUP}") target_include_directories(nvi PRIVATE ${ICONV_INCLUDE_DIR}) target_link_libraries(nvi PRIVATE ${ICONV_LIBRARY}) endif() check_function_exists(getprogname GETPROGNAME_IN_LIBC) check_function_exists(strlcpy STRLCPY_IN_LIBC) if(NOT GETPROGNAME_IN_LIBC OR NOT STRLCPY_IN_LIBC) find_package(PkgConfig REQUIRED) pkg_check_modules(LIBBSD libbsd-overlay) add_definitions(${LIBBSD_CFLAGS}) target_link_libraries(nvi PRIVATE ${LIBBSD_LIBRARIES}) endif() check_function_exists(dbopen DBOPEN_IN_LIBC) if(NOT DBOPEN_IN_LIBC) target_link_libraries(nvi PRIVATE db1) endif() if (APPLE) # Avoid using an incompatible db.h installed to /usr/local (since this is # part of the default search path on macOS) set(DB_H_GUESS "${CMAKE_OSX_SYSROOT}/usr/include/db.h") if (NOT EXISTS ${DB_H_GUESS}) message(FATAL_ERROR "Could not find db.h at the expected path (${DB_H_GUESS}).") endif() add_definitions("-DDB_H_ABS_PATH=<${DB_H_GUESS}>") else() find_path(DB_INCLUDE_DIR db.h PATH_SUFFIXES db1) target_include_directories(nvi PRIVATE ${DB_INCLUDE_DIR}) endif() check_include_files(libutil.h HAVE_LIBUTIL_H) check_include_files(ncurses.h HAVE_NCURSES_H) check_include_files(ncursesw/ncurses.h HAVE_NCURSESW_NCURSES_H) check_include_files(pty.h HAVE_PTY_H) check_include_files(term.h HAVE_TERM_H) check_struct_has_member("struct dirent" d_namlen dirent.h HAVE_DIRENT_D_NAMLEN LANGUAGE C) check_struct_has_member("struct stat" st_mtimespec "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIMESPEC LANGUAGE C) check_struct_has_member("struct stat" st_mtim "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIM LANGUAGE C) configure_file(files/config.h.in config.h) set(vi_cv_path_preserve /var/tmp/vi.recover/) if(APPLE) set(vi_cv_path_msgcat /usr/local/share/vi/catalog/) else() set(vi_cv_path_msgcat /usr/share/vi/catalog/) endif() configure_file(files/pathnames.h.in pathnames.h) configure_file(files/recover.in recover @ONLY) diff --git a/common/common.h b/common/common.h index 45f22fb49d1b..fd97a4655cf5 100644 --- a/common/common.h +++ b/common/common.h @@ -1,94 +1,95 @@ /*- * Copyright (c) 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 1991, 1993, 1994, 1995, 1996 * Keith Bostic. All rights reserved. * * See the LICENSE file for redistribution information. */ #ifndef TCSASOFT #define TCSASOFT 0 #endif #ifdef DB_H_ABS_PATH #include DB_H_ABS_PATH #else #include #endif #include /* May refer to the bundled regex. */ +#include /* * Forward structure declarations. Not pretty, but the include files * are far too interrelated for a clean solution. */ typedef struct _cb CB; typedef struct _csc CSC; typedef struct _conv CONV; typedef struct _conv_win CONVWIN; typedef struct _event EVENT; typedef struct _excmd EXCMD; typedef struct _exf EXF; typedef struct _fref FREF; typedef struct _gs GS; typedef struct _lmark LMARK; typedef struct _mark MARK; typedef struct _msg MSGS; typedef struct _option OPTION; typedef struct _optlist OPTLIST; typedef struct _scr SCR; typedef struct _script SCRIPT; typedef struct _seq SEQ; typedef struct _tag TAG; typedef struct _tagf TAGF; typedef struct _tagq TAGQ; typedef struct _text TEXT; /* Autoindent state. */ typedef enum { C_NOTSET, C_CARATSET, C_ZEROSET } carat_t; /* Busy message types. */ typedef enum { BUSY_ON = 1, BUSY_OFF, BUSY_UPDATE } busy_t; /* * Routines that return a confirmation return: * * CONF_NO User answered no. * CONF_QUIT User answered quit, eof or an error. * CONF_YES User answered yes. */ typedef enum { CONF_NO, CONF_QUIT, CONF_YES } conf_t; /* Directions. */ typedef enum { NOTSET, FORWARD, BACKWARD } dir_t; /* Line operations. */ typedef enum { LINE_APPEND, LINE_DELETE, LINE_INSERT, LINE_RESET } lnop_t; /* Lock return values. */ typedef enum { LOCK_FAILED, LOCK_SUCCESS, LOCK_UNAVAIL } lockr_t; /* Sequence types. */ typedef enum { SEQ_ABBREV, SEQ_COMMAND, SEQ_INPUT } seq_t; /* * Local includes. */ #include "key.h" /* Required by args.h. */ #include "args.h" /* Required by options.h. */ #include "options.h" /* Required by screen.h. */ #include "msg.h" /* Required by gs.h. */ #include "cut.h" /* Required by gs.h. */ #include "seq.h" /* Required by screen.h. */ #include "util.h" /* Required by ex.h. */ #include "mark.h" /* Required by gs.h. */ #include "conv.h" /* Required by ex.h and screen.h */ #include "../ex/ex.h" /* Required by gs.h. */ #include "gs.h" /* Required by screen.h. */ #include "screen.h" /* Required by exf.h. */ #include "exf.h" #include "log.h" #include "mem.h" #include "extern.h" diff --git a/common/log.c b/common/log.c index 96b246efad02..7aad94d7e74a 100644 --- a/common/log.c +++ b/common/log.c @@ -1,736 +1,723 @@ /*- * Copyright (c) 1992, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 1992, 1993, 1994, 1995, 1996 * Keith Bostic. All rights reserved. * * See the LICENSE file for redistribution information. */ #include "config.h" #include #include #include #include #include #include #include #include -#include #include #include #include #include "common.h" /* * The log consists of records, each containing a type byte and a variable * length byte string, as follows: * * LOG_CURSOR_INIT MARK * LOG_CURSOR_END MARK * LOG_LINE_APPEND recno_t char * * LOG_LINE_DELETE recno_t char * * LOG_LINE_INSERT recno_t char * * LOG_LINE_RESET_F recno_t char * * LOG_LINE_RESET_B recno_t char * * LOG_MARK LMARK * * We do before image physical logging. This means that the editor layer * MAY NOT modify records in place, even if simply deleting or overwriting * characters. Since the smallest unit of logging is a line, we're using * up lots of space. This may eventually have to be reduced, probably by * doing logical logging, which is a much cooler database phrase. * * The implementation of the historic vi 'u' command, using roll-forward and * roll-back, is simple. Each set of changes has a LOG_CURSOR_INIT record, * followed by a number of other records, followed by a LOG_CURSOR_END record. * LOG_LINE_RESET records come in pairs. The first is a LOG_LINE_RESET_B * record, and is the line before the change. The second is LOG_LINE_RESET_F, * and is the line after the change. Roll-back is done by backing up to the * first LOG_CURSOR_INIT record before a change. Roll-forward is done in a * similar fashion. * * The 'U' command is implemented by rolling backward to a LOG_CURSOR_END * record for a line different from the current one. It should be noted that * this means that a subsequent 'u' command will make a change based on the * new position of the log's cursor. This is okay, and, in fact, historic vi * behaved that way. */ static int log_cursor1(SCR *, int); static void log_err(SCR *, char *, int); #if defined(DEBUG) && 0 static void log_trace(SCR *, char *, recno_t, u_char *); #endif static int apply_with(int (*)(SCR *, recno_t, CHAR_T *, size_t), SCR *, recno_t, u_char *, size_t); /* Try and restart the log on failure, i.e. if we run out of memory. */ #define LOG_ERR do { \ log_err(sp, __FILE__, __LINE__); \ return (1); \ } while (0) /* offset of CHAR_T string in log needs to be aligned on some systems * because it is passed to db_set as a string */ typedef struct { char data[sizeof(u_char) /* type */ + sizeof(recno_t)]; CHAR_T str[1]; } log_t; #define CHAR_T_OFFSET ((char *)(((log_t*)0)->str) - (char *)0) /* * log_init -- * Initialize the logging subsystem. * * PUBLIC: int log_init(SCR *, EXF *); */ int log_init(SCR *sp, EXF *ep) { /* * !!! * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER. * * Initialize the buffer. The logging subsystem has its own * buffers because the global ones are almost by definition * going to be in use when the log runs. */ ep->l_lp = NULL; ep->l_len = 0; ep->l_cursor.lno = 1; /* XXX Any valid recno. */ ep->l_cursor.cno = 0; ep->l_high = ep->l_cur = 1; ep->log = dbopen(NULL, O_CREAT | O_NONBLOCK | O_RDWR, S_IRUSR | S_IWUSR, DB_RECNO, NULL); if (ep->log == NULL) { msgq(sp, M_SYSERR, "009|Log file"); F_SET(ep, F_NOLOG); return (1); } return (0); } /* * log_end -- * Close the logging subsystem. * * PUBLIC: int log_end(SCR *, EXF *); */ int log_end(SCR *sp, EXF *ep) { /* * !!! * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER. */ if (ep->log != NULL) { (void)(ep->log->close)(ep->log); ep->log = NULL; } free(ep->l_lp); ep->l_lp = NULL; ep->l_len = 0; ep->l_cursor.lno = 1; /* XXX Any valid recno. */ ep->l_cursor.cno = 0; ep->l_high = ep->l_cur = 1; return (0); } /* * log_cursor -- * Log the current cursor position, starting an event. * * PUBLIC: int log_cursor(SCR *); */ int log_cursor(SCR *sp) { EXF *ep; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) return (0); /* * If any changes were made since the last cursor init, * put out the ending cursor record. */ if (ep->l_cursor.lno == OOBLNO) { ep->l_cursor.lno = sp->lno; ep->l_cursor.cno = sp->cno; return (log_cursor1(sp, LOG_CURSOR_END)); } ep->l_cursor.lno = sp->lno; ep->l_cursor.cno = sp->cno; return (0); } /* * log_cursor1 -- * Actually push a cursor record out. */ static int log_cursor1(SCR *sp, int type) { DBT data, key; EXF *ep; ep = sp->ep; BINC_RETC(sp, ep->l_lp, ep->l_len, sizeof(u_char) + sizeof(MARK)); ep->l_lp[0] = type; memmove(ep->l_lp + sizeof(u_char), &ep->l_cursor, sizeof(MARK)); key.data = &ep->l_cur; key.size = sizeof(recno_t); data.data = ep->l_lp; data.size = sizeof(u_char) + sizeof(MARK); if (ep->log->put(ep->log, &key, &data, 0) == -1) LOG_ERR; #if defined(DEBUG) && 0 TRACE(sp, "%lu: %s: %u/%u\n", ep->l_cur, type == LOG_CURSOR_INIT ? "log_cursor_init" : "log_cursor_end", sp->lno, sp->cno); #endif /* Reset high water mark. */ ep->l_high = ++ep->l_cur; return (0); } /* * log_line -- * Log a line change. * * PUBLIC: int log_line(SCR *, recno_t, u_int); */ int log_line(SCR *sp, recno_t lno, u_int action) { DBT data, key; EXF *ep; size_t len; CHAR_T *lp; recno_t lcur; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) return (0); /* * XXX * * Kluge for vi. Clear the EXF undo flag so that the * next 'u' command does a roll-back, regardless. */ F_CLR(ep, F_UNDO); /* Put out one initial cursor record per set of changes. */ if (ep->l_cursor.lno != OOBLNO) { if (log_cursor1(sp, LOG_CURSOR_INIT)) return (1); ep->l_cursor.lno = OOBLNO; } /* * Put out the changes. If it's a LOG_LINE_RESET_B call, it's a * special case, avoid the caches. Also, if it fails and it's * line 1, it just means that the user started with an empty file, * so fake an empty length line. */ if (action == LOG_LINE_RESET_B) { if (db_get(sp, lno, DBG_NOCACHE, &lp, &len)) { if (lno != 1) { db_err(sp, lno); return (1); } len = 0; lp = L(""); } } else if (db_get(sp, lno, DBG_FATAL, &lp, &len)) return (1); BINC_RETC(sp, ep->l_lp, ep->l_len, len * sizeof(CHAR_T) + CHAR_T_OFFSET); ep->l_lp[0] = action; memmove(ep->l_lp + sizeof(u_char), &lno, sizeof(recno_t)); memmove(ep->l_lp + CHAR_T_OFFSET, lp, len * sizeof(CHAR_T)); lcur = ep->l_cur; key.data = &lcur; key.size = sizeof(recno_t); data.data = ep->l_lp; data.size = len * sizeof(CHAR_T) + CHAR_T_OFFSET; if (ep->log->put(ep->log, &key, &data, 0) == -1) LOG_ERR; #if defined(DEBUG) && 0 switch (action) { case LOG_LINE_APPEND: TRACE(sp, "%lu: log_line: append: %lu {%u}\n", ep->l_cur, lno, len); break; case LOG_LINE_DELETE: TRACE(sp, "%lu: log_line: delete: %lu {%u}\n", ep->l_cur, lno, len); break; case LOG_LINE_INSERT: TRACE(sp, "%lu: log_line: insert: %lu {%u}\n", ep->l_cur, lno, len); break; case LOG_LINE_RESET_F: TRACE(sp, "%lu: log_line: reset_f: %lu {%u}\n", ep->l_cur, lno, len); break; case LOG_LINE_RESET_B: TRACE(sp, "%lu: log_line: reset_b: %lu {%u}\n", ep->l_cur, lno, len); break; } #endif /* Reset high water mark. */ ep->l_high = ++ep->l_cur; return (0); } /* * log_mark -- * Log a mark position. For the log to work, we assume that there * aren't any operations that just put out a log record -- this * would mean that undo operations would only reset marks, and not * cause any other change. * * PUBLIC: int log_mark(SCR *, LMARK *); */ int log_mark(SCR *sp, LMARK *lmp) { DBT data, key; EXF *ep; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) return (0); /* Put out one initial cursor record per set of changes. */ if (ep->l_cursor.lno != OOBLNO) { if (log_cursor1(sp, LOG_CURSOR_INIT)) return (1); ep->l_cursor.lno = OOBLNO; } BINC_RETC(sp, ep->l_lp, ep->l_len, sizeof(u_char) + sizeof(LMARK)); ep->l_lp[0] = LOG_MARK; memmove(ep->l_lp + sizeof(u_char), lmp, sizeof(LMARK)); key.data = &ep->l_cur; key.size = sizeof(recno_t); data.data = ep->l_lp; data.size = sizeof(u_char) + sizeof(LMARK); if (ep->log->put(ep->log, &key, &data, 0) == -1) LOG_ERR; #if defined(DEBUG) && 0 TRACE(sp, "%lu: mark %c: %lu/%u\n", ep->l_cur, lmp->name, lmp->lno, lmp->cno); #endif /* Reset high water mark. */ ep->l_high = ++ep->l_cur; return (0); } /* * Log_backward -- * Roll the log backward one operation. * * PUBLIC: int log_backward(SCR *, MARK *); */ int log_backward(SCR *sp, MARK *rp) { DBT key, data; EXF *ep; LMARK lm; MARK m; recno_t lno; int didop; u_char *p; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) { msgq(sp, M_ERR, "010|Logging not being performed, undo not possible"); return (1); } if (ep->l_cur == 1) { msgq(sp, M_BERR, "011|No changes to undo"); return (1); } F_SET(ep, F_NOLOG); /* Turn off logging. */ key.data = &ep->l_cur; /* Initialize db request. */ key.size = sizeof(recno_t); for (didop = 0;;) { --ep->l_cur; if (ep->log->get(ep->log, &key, &data, 0)) LOG_ERR; #if defined(DEBUG) && 0 log_trace(sp, "log_backward", ep->l_cur, data.data); #endif switch (*(p = (u_char *)data.data)) { case LOG_CURSOR_INIT: if (didop) { memmove(rp, p + sizeof(u_char), sizeof(MARK)); F_CLR(ep, F_NOLOG); return (0); } break; case LOG_CURSOR_END: break; case LOG_LINE_APPEND: case LOG_LINE_INSERT: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (db_delete(sp, lno)) goto err; ++sp->rptlines[L_DELETED]; break; case LOG_LINE_DELETE: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (apply_with(db_insert, sp, lno, p + CHAR_T_OFFSET, data.size - CHAR_T_OFFSET)) goto err; ++sp->rptlines[L_ADDED]; break; case LOG_LINE_RESET_F: break; case LOG_LINE_RESET_B: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (apply_with(db_set, sp, lno, p + CHAR_T_OFFSET, data.size - CHAR_T_OFFSET)) goto err; if (sp->rptlchange != lno) { sp->rptlchange = lno; ++sp->rptlines[L_CHANGED]; } break; case LOG_MARK: didop = 1; memmove(&lm, p + sizeof(u_char), sizeof(LMARK)); m.lno = lm.lno; m.cno = lm.cno; if (mark_set(sp, lm.name, &m, 0)) goto err; break; default: abort(); } } err: F_CLR(ep, F_NOLOG); return (1); } /* * Log_setline -- * Reset the line to its original appearance. * * XXX * There's a bug in this code due to our not logging cursor movements * unless a change was made. If you do a change, move off the line, * then move back on and do a 'U', the line will be restored to the way * it was before the original change. * * PUBLIC: int log_setline(SCR *); */ int log_setline(SCR *sp) { DBT key, data; EXF *ep; LMARK lm; MARK m; recno_t lno; u_char *p; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) { msgq(sp, M_ERR, "012|Logging not being performed, undo not possible"); return (1); } if (ep->l_cur == 1) return (1); F_SET(ep, F_NOLOG); /* Turn off logging. */ key.data = &ep->l_cur; /* Initialize db request. */ key.size = sizeof(recno_t); for (;;) { --ep->l_cur; if (ep->log->get(ep->log, &key, &data, 0)) LOG_ERR; #if defined(DEBUG) && 0 log_trace(sp, "log_setline", ep->l_cur, data.data); #endif switch (*(p = (u_char *)data.data)) { case LOG_CURSOR_INIT: memmove(&m, p + sizeof(u_char), sizeof(MARK)); if (m.lno != sp->lno || ep->l_cur == 1) { F_CLR(ep, F_NOLOG); return (0); } break; case LOG_CURSOR_END: memmove(&m, p + sizeof(u_char), sizeof(MARK)); if (m.lno != sp->lno) { ++ep->l_cur; F_CLR(ep, F_NOLOG); return (0); } break; case LOG_LINE_APPEND: case LOG_LINE_INSERT: case LOG_LINE_DELETE: case LOG_LINE_RESET_F: break; case LOG_LINE_RESET_B: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (lno == sp->lno && apply_with(db_set, sp, lno, p + CHAR_T_OFFSET, data.size - CHAR_T_OFFSET)) goto err; if (sp->rptlchange != lno) { sp->rptlchange = lno; ++sp->rptlines[L_CHANGED]; } case LOG_MARK: memmove(&lm, p + sizeof(u_char), sizeof(LMARK)); m.lno = lm.lno; m.cno = lm.cno; if (mark_set(sp, lm.name, &m, 0)) goto err; break; default: abort(); } } err: F_CLR(ep, F_NOLOG); return (1); } /* * Log_forward -- * Roll the log forward one operation. * * PUBLIC: int log_forward(SCR *, MARK *); */ int log_forward(SCR *sp, MARK *rp) { DBT key, data; EXF *ep; LMARK lm; MARK m; recno_t lno; int didop; u_char *p; ep = sp->ep; if (F_ISSET(ep, F_NOLOG)) { msgq(sp, M_ERR, "013|Logging not being performed, roll-forward not possible"); return (1); } if (ep->l_cur == ep->l_high) { msgq(sp, M_BERR, "014|No changes to re-do"); return (1); } F_SET(ep, F_NOLOG); /* Turn off logging. */ key.data = &ep->l_cur; /* Initialize db request. */ key.size = sizeof(recno_t); for (didop = 0;;) { ++ep->l_cur; if (ep->log->get(ep->log, &key, &data, 0)) LOG_ERR; #if defined(DEBUG) && 0 log_trace(sp, "log_forward", ep->l_cur, data.data); #endif switch (*(p = (u_char *)data.data)) { case LOG_CURSOR_END: if (didop) { ++ep->l_cur; memmove(rp, p + sizeof(u_char), sizeof(MARK)); F_CLR(ep, F_NOLOG); return (0); } break; case LOG_CURSOR_INIT: break; case LOG_LINE_APPEND: case LOG_LINE_INSERT: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (apply_with(db_insert, sp, lno, p + CHAR_T_OFFSET, data.size - CHAR_T_OFFSET)) goto err; ++sp->rptlines[L_ADDED]; break; case LOG_LINE_DELETE: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (db_delete(sp, lno)) goto err; ++sp->rptlines[L_DELETED]; break; case LOG_LINE_RESET_B: break; case LOG_LINE_RESET_F: didop = 1; memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); if (apply_with(db_set, sp, lno, p + CHAR_T_OFFSET, data.size - CHAR_T_OFFSET)) goto err; if (sp->rptlchange != lno) { sp->rptlchange = lno; ++sp->rptlines[L_CHANGED]; } break; case LOG_MARK: didop = 1; memmove(&lm, p + sizeof(u_char), sizeof(LMARK)); m.lno = lm.lno; m.cno = lm.cno; if (mark_set(sp, lm.name, &m, 0)) goto err; break; default: abort(); } } err: F_CLR(ep, F_NOLOG); return (1); } /* * log_err -- * Try and restart the log on failure, i.e. if we run out of memory. */ static void log_err(SCR *sp, char *file, int line) { EXF *ep; msgq(sp, M_SYSERR, "015|%s/%d: log put error", basename(file), line); ep = sp->ep; (void)ep->log->close(ep->log); if (!log_init(sp, ep)) msgq(sp, M_ERR, "267|Log restarted"); } #if defined(DEBUG) && 0 static void log_trace(SCR *sp, char *msg, recno_t rno, u_char *p) { LMARK lm; MARK m; recno_t lno; switch (*p) { case LOG_CURSOR_INIT: memmove(&m, p + sizeof(u_char), sizeof(MARK)); TRACE(sp, "%lu: %s: C_INIT: %u/%u\n", rno, msg, m.lno, m.cno); break; case LOG_CURSOR_END: memmove(&m, p + sizeof(u_char), sizeof(MARK)); TRACE(sp, "%lu: %s: C_END: %u/%u\n", rno, msg, m.lno, m.cno); break; case LOG_LINE_APPEND: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); TRACE(sp, "%lu: %s: APPEND: %lu\n", rno, msg, lno); break; case LOG_LINE_INSERT: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); TRACE(sp, "%lu: %s: INSERT: %lu\n", rno, msg, lno); break; case LOG_LINE_DELETE: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); TRACE(sp, "%lu: %s: DELETE: %lu\n", rno, msg, lno); break; case LOG_LINE_RESET_F: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); TRACE(sp, "%lu: %s: RESET_F: %lu\n", rno, msg, lno); break; case LOG_LINE_RESET_B: memmove(&lno, p + sizeof(u_char), sizeof(recno_t)); TRACE(sp, "%lu: %s: RESET_B: %lu\n", rno, msg, lno); break; case LOG_MARK: memmove(&lm, p + sizeof(u_char), sizeof(LMARK)); TRACE(sp, "%lu: %s: MARK: %u/%u\n", rno, msg, lm.lno, lm.cno); break; default: abort(); } } #endif /* * apply_with -- * Apply a realigned line from the log db to the file db. */ static int apply_with(int (*db_func)(SCR *, recno_t, CHAR_T *, size_t), SCR *sp, recno_t lno, u_char *p, size_t len) { #ifdef USE_WIDECHAR - typedef unsigned long nword; - static size_t blen; - static nword *bp; - nword *lp = (nword *)((uintptr_t)p / sizeof(nword) * sizeof(nword)); - - if (lp != (nword *)p) { - int offl = ((uintptr_t)p - (uintptr_t)lp) << 3; - int offr = (sizeof(nword) << 3) - offl; - size_t i, cnt = (len + sizeof(nword) / 2) / sizeof(nword); + static u_char *bp; + if (!is_aligned(p, sizeof(unsigned long))) { if (len > blen) { blen = p2roundup(MAX(len, 512)); - REALLOC(sp, bp, nword *, blen); + REALLOC(sp, bp, u_char *, blen); if (bp == NULL) return (1); } - for (i = 0; i < cnt; ++i) -#if BYTE_ORDER == BIG_ENDIAN - bp[i] = (lp[i] << offl) ^ (lp[i+1] >> offr); -#else - bp[i] = (lp[i] >> offl) ^ (lp[i+1] << offr); -#endif - p = (u_char *)bp; + memmove(bp, p, len); + p = bp; } #endif return db_func(sp, lno, (CHAR_T *)p, len / sizeof(CHAR_T)); } diff --git a/common/mem.h b/common/mem.h index d24ec0b50b09..0c83b70dec2f 100644 --- a/common/mem.h +++ b/common/mem.h @@ -1,217 +1,229 @@ /*- * Copyright (c) 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 1993, 1994, 1995, 1996 * Keith Bostic. All rights reserved. * * See the LICENSE file for redistribution information. */ #ifdef DEBUG #define CHECK_TYPE(type, var) \ type L__lp __attribute__((unused)) = var; #else #define CHECK_TYPE(type, var) #endif /* Increase the size of a malloc'd buffer. Two versions, one that * returns, one that jumps to an error label. */ #define BINC_GOTO(sp, type, lp, llen, nlen) do { \ CHECK_TYPE(type *, lp) \ void *L__bincp; \ if ((nlen) > llen) { \ if ((L__bincp = binc(sp, lp, &(llen), nlen)) == NULL) \ goto alloc_err; \ /* \ * !!! \ * Possible pointer conversion. \ */ \ lp = L__bincp; \ } \ } while (0) #define BINC_GOTOC(sp, lp, llen, nlen) \ BINC_GOTO(sp, char, lp, llen, nlen) #define BINC_GOTOW(sp, lp, llen, nlen) \ BINC_GOTO(sp, CHAR_T, lp, llen, (nlen) * sizeof(CHAR_T)) #define BINC_RET(sp, type, lp, llen, nlen) do { \ CHECK_TYPE(type *, lp) \ void *L__bincp; \ if ((nlen) > llen) { \ if ((L__bincp = binc(sp, lp, &(llen), nlen)) == NULL) \ return (1); \ /* \ * !!! \ * Possible pointer conversion. \ */ \ lp = L__bincp; \ } \ } while (0) #define BINC_RETC(sp, lp, llen, nlen) \ BINC_RET(sp, char, lp, llen, nlen) #define BINC_RETW(sp, lp, llen, nlen) \ BINC_RET(sp, CHAR_T, lp, llen, (nlen) * sizeof(CHAR_T)) /* * Get some temporary space, preferably from the global temporary buffer, * from a malloc'd buffer otherwise. Two versions, one that returns, one * that jumps to an error label. */ #define GET_SPACE_GOTO(sp, type, bp, blen, nlen) do { \ CHECK_TYPE(type *, bp) \ GS *L__gp = (sp) == NULL ? NULL : (sp)->gp; \ if (L__gp == NULL || F_ISSET(L__gp, G_TMP_INUSE)) { \ bp = NULL; \ blen = 0; \ BINC_GOTO(sp, type, bp, blen, nlen); \ } else { \ BINC_GOTOC(sp, L__gp->tmp_bp, L__gp->tmp_blen, nlen); \ bp = (type *) L__gp->tmp_bp; \ blen = L__gp->tmp_blen; \ F_SET(L__gp, G_TMP_INUSE); \ } \ } while (0) #define GET_SPACE_GOTOC(sp, bp, blen, nlen) \ GET_SPACE_GOTO(sp, char, bp, blen, nlen) #define GET_SPACE_GOTOW(sp, bp, blen, nlen) \ GET_SPACE_GOTO(sp, CHAR_T, bp, blen, (nlen) * sizeof(CHAR_T)) #define GET_SPACE_RET(sp, type, bp, blen, nlen) do { \ CHECK_TYPE(type *, bp) \ GS *L__gp = (sp) == NULL ? NULL : (sp)->gp; \ if (L__gp == NULL || F_ISSET(L__gp, G_TMP_INUSE)) { \ bp = NULL; \ blen = 0; \ BINC_RET(sp, type, bp, blen, nlen); \ } else { \ BINC_RETC(sp, L__gp->tmp_bp, L__gp->tmp_blen, nlen); \ bp = (type *) L__gp->tmp_bp; \ blen = L__gp->tmp_blen; \ F_SET(L__gp, G_TMP_INUSE); \ } \ } while (0) #define GET_SPACE_RETC(sp, bp, blen, nlen) \ GET_SPACE_RET(sp, char, bp, blen, nlen) #define GET_SPACE_RETW(sp, bp, blen, nlen) \ GET_SPACE_RET(sp, CHAR_T, bp, blen, (nlen) * sizeof(CHAR_T)) /* * Add space to a GET_SPACE returned buffer. Two versions, one that * returns, one that jumps to an error label. */ #define ADD_SPACE_GOTO(sp, type, bp, blen, nlen) do { \ CHECK_TYPE(type *, bp) \ GS *L__gp = (sp) == NULL ? NULL : (sp)->gp; \ if (L__gp == NULL || bp == (type *)L__gp->tmp_bp) { \ F_CLR(L__gp, G_TMP_INUSE); \ BINC_GOTOC(sp, L__gp->tmp_bp, L__gp->tmp_blen, nlen); \ bp = (type *) L__gp->tmp_bp; \ blen = L__gp->tmp_blen; \ F_SET(L__gp, G_TMP_INUSE); \ } else \ BINC_GOTO(sp, type, bp, blen, nlen); \ } while (0) #define ADD_SPACE_GOTOC(sp, bp, blen, nlen) \ ADD_SPACE_GOTO(sp, char, bp, blen, nlen) #define ADD_SPACE_GOTOW(sp, bp, blen, nlen) \ ADD_SPACE_GOTO(sp, CHAR_T, bp, blen, (nlen) * sizeof(CHAR_T)) #define ADD_SPACE_RET(sp, type, bp, blen, nlen) do { \ CHECK_TYPE(type *, bp) \ GS *L__gp = (sp) == NULL ? NULL : (sp)->gp; \ if (L__gp == NULL || bp == (type *)L__gp->tmp_bp) { \ F_CLR(L__gp, G_TMP_INUSE); \ BINC_RETC(sp, L__gp->tmp_bp, L__gp->tmp_blen, nlen); \ bp = (type *) L__gp->tmp_bp; \ blen = L__gp->tmp_blen; \ F_SET(L__gp, G_TMP_INUSE); \ } else \ BINC_RET(sp, type, bp, blen, nlen); \ } while (0) #define ADD_SPACE_RETC(sp, bp, blen, nlen) \ ADD_SPACE_RET(sp, char, bp, blen, nlen) #define ADD_SPACE_RETW(sp, bp, blen, nlen) \ ADD_SPACE_RET(sp, CHAR_T, bp, blen, (nlen) * sizeof(CHAR_T)) /* Free a GET_SPACE returned buffer. */ #define FREE_SPACE(sp, bp, blen) do { \ GS *L__gp = (sp) == NULL ? NULL : (sp)->gp; \ if (L__gp != NULL && bp == L__gp->tmp_bp) \ F_CLR(L__gp, G_TMP_INUSE); \ else \ free(bp); \ } while (0) #define FREE_SPACEW(sp, bp, blen) do { \ CHECK_TYPE(CHAR_T *, bp) \ FREE_SPACE(sp, (char *)bp, blen); \ } while (0) /* * Malloc a buffer, casting the return pointer. Various versions. */ #define CALLOC(sp, p, nmemb, size) do { \ if ((p = calloc(nmemb, size)) == NULL) \ msgq(sp, M_SYSERR, NULL); \ } while (0) #define CALLOC_GOTO(sp, p, nmemb, size) do { \ if ((p = calloc(nmemb, size)) == NULL) \ goto alloc_err; \ } while (0) #define CALLOC_RET(sp, p, nmemb, size) do { \ if ((p = calloc(nmemb, size)) == NULL) { \ msgq(sp, M_SYSERR, NULL); \ return (1); \ } \ } while (0) #define MALLOC(sp, p, size) do { \ if ((p = malloc(size)) == NULL) \ msgq(sp, M_SYSERR, NULL); \ } while (0) #define MALLOC_GOTO(sp, p, size) do { \ if ((p = malloc(size)) == NULL) \ goto alloc_err; \ } while (0) #define MALLOC_RET(sp, p, size) do { \ if ((p = malloc(size)) == NULL) { \ msgq(sp, M_SYSERR, NULL); \ return (1); \ } \ } while (0) /* * Resize a buffer, free any already held memory if we can't get more. * FreeBSD's reallocf(3) does the same thing, but it's not portable yet. */ #define REALLOC(sp, p, cast, size) do { \ cast newp; \ if ((newp = realloc(p, size)) == NULL) { \ free(p); \ msgq(sp, M_SYSERR, NULL); \ } \ p = newp; \ } while (0) /* * p2roundup -- * Get next power of 2; convenient for realloc. * * Reference: FreeBSD /usr/src/lib/libc/stdio/getdelim.c */ static __inline size_t p2roundup(size_t n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; #if SIZE_T_MAX > 0xffffffffU n |= n >> 32; #endif n++; return (n); } +/* + * is_aligned -- + * Determine whether the program can safely read an object with an + * alignment requirement from ptr. + * + * See also: https://clang.llvm.org/docs/LanguageExtensions.html#alignment-builtins + */ +static __inline int +is_aligned(void *ptr, size_t alignment) { + return ((uintptr_t)ptr % alignment) == 0; +} + /* Additional TAILQ helper. */ #define TAILQ_ENTRY_ISVALID(elm, field) \ ((elm)->field.tqe_prev != NULL) diff --git a/common/options.c b/common/options.c index c3d1f7343f9a..87d5c5a88521 100644 --- a/common/options.c +++ b/common/options.c @@ -1,1168 +1,1170 @@ /*- * Copyright (c) 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 1991, 1993, 1994, 1995, 1996 * Keith Bostic. All rights reserved. * * See the LICENSE file for redistribution information. */ #include "config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "../vi/vi.h" #include "pathnames.h" static int opts_abbcmp(const void *, const void *); static int opts_cmp(const void *, const void *); static int opts_print(SCR *, OPTLIST const *); #ifdef USE_WIDECHAR #define OPT_WC 0 #else #define OPT_WC (OPT_NOSAVE | OPT_NDISP) #endif /* * O'Reilly noted options and abbreviations are from "Learning the VI Editor", * Fifth Edition, May 1992. There's no way of knowing what systems they are * actually from. * * HPUX noted options and abbreviations are from "The Ultimate Guide to the * VI and EX Text Editors", 1990. */ OPTLIST const optlist[] = { /* O_ALTNOTATION */ {L("altnotation"), f_print, OPT_0BOOL, 0}, /* O_ALTWERASE 4.4BSD */ {L("altwerase"), f_altwerase, OPT_0BOOL, 0}, /* O_AUTOINDENT 4BSD */ {L("autoindent"), NULL, OPT_0BOOL, 0}, /* O_AUTOPRINT 4BSD */ {L("autoprint"), NULL, OPT_1BOOL, 0}, /* O_AUTOWRITE 4BSD */ {L("autowrite"), NULL, OPT_0BOOL, 0}, /* O_BACKUP 4.4BSD */ {L("backup"), NULL, OPT_STR, 0}, /* O_BEAUTIFY 4BSD */ {L("beautify"), NULL, OPT_0BOOL, 0}, /* O_CDPATH 4.4BSD */ {L("cdpath"), NULL, OPT_STR, 0}, /* O_CEDIT 4.4BSD */ {L("cedit"), NULL, OPT_STR, 0}, /* O_COLUMNS 4.4BSD */ {L("columns"), f_columns, OPT_NUM, OPT_NOSAVE}, /* O_COMBINED */ {L("combined"), NULL, OPT_0BOOL, OPT_NOSET|OPT_WC}, /* O_COMMENT 4.4BSD */ {L("comment"), NULL, OPT_0BOOL, 0}, /* O_TMPDIR 4BSD */ {L("directory"), NULL, OPT_STR, 0}, /* O_EDCOMPATIBLE 4BSD */ {L("edcompatible"),NULL, OPT_0BOOL, 0}, /* O_ERRORBELLS 4BSD */ {L("errorbells"), NULL, OPT_0BOOL, 0}, /* O_ESCAPETIME 4.4BSD */ {L("escapetime"), NULL, OPT_NUM, 0}, /* O_EXPANDTAB NetBSD 5.0 */ {L("expandtab"), NULL, OPT_0BOOL, 0}, /* O_EXRC System V (undocumented) */ {L("exrc"), NULL, OPT_0BOOL, 0}, /* O_EXTENDED 4.4BSD */ {L("extended"), f_recompile, OPT_0BOOL, 0}, /* O_FILEC 4.4BSD */ {L("filec"), NULL, OPT_STR, 0}, /* O_FILEENCODING */ {L("fileencoding"),f_encoding, OPT_STR, OPT_WC}, /* O_FLASH HPUX */ {L("flash"), NULL, OPT_1BOOL, 0}, /* O_HARDTABS 4BSD */ {L("hardtabs"), NULL, OPT_NUM, 0}, /* O_ICLOWER 4.4BSD */ {L("iclower"), f_recompile, OPT_0BOOL, 0}, /* O_IGNORECASE 4BSD */ {L("ignorecase"), f_recompile, OPT_0BOOL, 0}, /* O_INPUTENCODING */ {L("inputencoding"),f_encoding, OPT_STR, OPT_WC}, /* O_KEYTIME 4.4BSD */ {L("keytime"), NULL, OPT_NUM, 0}, /* O_LEFTRIGHT 4.4BSD */ {L("leftright"), f_reformat, OPT_0BOOL, 0}, /* O_LINES 4.4BSD */ {L("lines"), f_lines, OPT_NUM, OPT_NOSAVE}, /* O_LISP 4BSD * XXX * When the lisp option is implemented, delete the OPT_NOSAVE flag, * so that :mkexrc dumps it. */ {L("lisp"), f_lisp, OPT_0BOOL, OPT_NOSAVE}, /* O_LIST 4BSD */ {L("list"), f_reformat, OPT_0BOOL, 0}, /* O_LOCKFILES 4.4BSD * XXX * Locking isn't reliable enough over NFS to require it, in addition, * it's a serious startup performance problem over some remote links. */ {L("lock"), NULL, OPT_1BOOL, 0}, /* O_MAGIC 4BSD */ {L("magic"), NULL, OPT_1BOOL, 0}, /* O_MATCHCHARS NetBSD 2.0 */ {L("matchchars"), NULL, OPT_STR, OPT_PAIRS}, /* O_MATCHTIME 4.4BSD */ {L("matchtime"), NULL, OPT_NUM, 0}, /* O_MESG 4BSD */ {L("mesg"), NULL, OPT_1BOOL, 0}, /* O_MODELINE 4BSD * !!! * This has been documented in historical systems as both "modeline" * and as "modelines". Regardless of the name, this option represents * a security problem of mammoth proportions, not to mention a stunning * example of what your intro CS professor referred to as the perils of * mixing code and data. Don't add it, or I will kill you. */ {L("modeline"), NULL, OPT_0BOOL, OPT_NOSET}, /* O_MSGCAT 4.4BSD */ {L("msgcat"), f_msgcat, OPT_STR, 0}, /* O_NOPRINT 4.4BSD */ {L("noprint"), f_print, OPT_STR, 0}, /* O_NUMBER 4BSD */ {L("number"), f_reformat, OPT_0BOOL, 0}, /* O_OCTAL 4.4BSD */ {L("octal"), f_print, OPT_0BOOL, 0}, /* O_OPEN 4BSD */ {L("open"), NULL, OPT_1BOOL, 0}, /* O_OPTIMIZE 4BSD */ {L("optimize"), NULL, OPT_1BOOL, 0}, /* O_PARAGRAPHS 4BSD */ {L("paragraphs"), NULL, OPT_STR, OPT_PAIRS}, /* O_PATH 4.4BSD */ {L("path"), NULL, OPT_STR, 0}, /* O_PRINT 4.4BSD */ {L("print"), f_print, OPT_STR, 0}, /* O_PROMPT 4BSD */ {L("prompt"), NULL, OPT_1BOOL, 0}, /* O_READONLY 4BSD (undocumented) */ {L("readonly"), f_readonly, OPT_0BOOL, OPT_ALWAYS}, /* O_RECDIR 4.4BSD */ {L("recdir"), NULL, OPT_STR, 0}, /* O_REDRAW 4BSD */ {L("redraw"), NULL, OPT_0BOOL, 0}, /* O_REMAP 4BSD */ {L("remap"), NULL, OPT_1BOOL, 0}, /* O_REPORT 4BSD */ {L("report"), NULL, OPT_NUM, 0}, /* O_RULER 4.4BSD */ {L("ruler"), NULL, OPT_0BOOL, 0}, /* O_SCROLL 4BSD */ {L("scroll"), NULL, OPT_NUM, 0}, /* O_SEARCHINCR 4.4BSD */ {L("searchincr"), NULL, OPT_0BOOL, 0}, /* O_SECTIONS 4BSD */ {L("sections"), NULL, OPT_STR, OPT_PAIRS}, /* O_SECURE 4.4BSD */ {L("secure"), NULL, OPT_0BOOL, OPT_NOUNSET}, /* O_SHELL 4BSD */ {L("shell"), NULL, OPT_STR, 0}, /* O_SHELLMETA 4.4BSD */ {L("shellmeta"), NULL, OPT_STR, 0}, /* O_SHIFTWIDTH 4BSD */ {L("shiftwidth"), NULL, OPT_NUM, OPT_NOZERO}, +/* O_SHOWFILENAME */ + {L("showfilename"), NULL, OPT_0BOOL, 0}, /* O_SHOWMATCH 4BSD */ {L("showmatch"), NULL, OPT_0BOOL, 0}, /* O_SHOWMODE 4.4BSD */ {L("showmode"), NULL, OPT_0BOOL, 0}, /* O_SIDESCROLL 4.4BSD */ {L("sidescroll"), NULL, OPT_NUM, OPT_NOZERO}, /* O_SLOWOPEN 4BSD */ {L("slowopen"), NULL, OPT_0BOOL, 0}, /* O_SOURCEANY 4BSD (undocumented) * !!! * Historic vi, on startup, source'd $HOME/.exrc and ./.exrc, if they * were owned by the user. The sourceany option was an undocumented * feature of historic vi which permitted the startup source'ing of * .exrc files the user didn't own. This is an obvious security problem, * and we ignore the option. */ {L("sourceany"), NULL, OPT_0BOOL, OPT_NOSET}, /* O_TABSTOP 4BSD */ {L("tabstop"), f_reformat, OPT_NUM, OPT_NOZERO}, /* O_TAGLENGTH 4BSD */ {L("taglength"), NULL, OPT_NUM, 0}, /* O_TAGS 4BSD */ {L("tags"), NULL, OPT_STR, 0}, /* O_TERM 4BSD * !!! * By default, the historic vi always displayed information about two * options, redraw and term. Term seems sufficient. */ {L("term"), NULL, OPT_STR, OPT_ADISP|OPT_NOSAVE}, /* O_TERSE 4BSD */ {L("terse"), NULL, OPT_0BOOL, 0}, /* O_TILDEOP 4.4BSD */ {L("tildeop"), NULL, OPT_0BOOL, 0}, /* O_TIMEOUT 4BSD (undocumented) */ {L("timeout"), NULL, OPT_1BOOL, 0}, /* O_TTYWERASE 4.4BSD */ {L("ttywerase"), f_ttywerase, OPT_0BOOL, 0}, /* O_VERBOSE 4.4BSD */ {L("verbose"), NULL, OPT_0BOOL, 0}, /* O_W1200 4BSD */ {L("w1200"), f_w1200, OPT_NUM, OPT_NDISP|OPT_NOSAVE}, /* O_W300 4BSD */ {L("w300"), f_w300, OPT_NUM, OPT_NDISP|OPT_NOSAVE}, /* O_W9600 4BSD */ {L("w9600"), f_w9600, OPT_NUM, OPT_NDISP|OPT_NOSAVE}, /* O_WARN 4BSD */ {L("warn"), NULL, OPT_1BOOL, 0}, /* O_WINDOW 4BSD */ {L("window"), f_window, OPT_NUM, 0}, /* O_WINDOWNAME 4BSD */ {L("windowname"), NULL, OPT_0BOOL, 0}, /* O_WRAPLEN 4.4BSD */ {L("wraplen"), NULL, OPT_NUM, 0}, /* O_WRAPMARGIN 4BSD */ {L("wrapmargin"), NULL, OPT_NUM, 0}, /* O_WRAPSCAN 4BSD */ {L("wrapscan"), NULL, OPT_1BOOL, 0}, /* O_WRITEANY 4BSD */ {L("writeany"), NULL, OPT_0BOOL, 0}, {NULL}, }; typedef struct abbrev { CHAR_T *name; int offset; } OABBREV; static OABBREV const abbrev[] = { {L("ai"), O_AUTOINDENT}, /* 4BSD */ {L("ap"), O_AUTOPRINT}, /* 4BSD */ {L("aw"), O_AUTOWRITE}, /* 4BSD */ {L("bf"), O_BEAUTIFY}, /* 4BSD */ {L("co"), O_COLUMNS}, /* 4.4BSD */ {L("dir"), O_TMPDIR}, /* 4BSD */ {L("eb"), O_ERRORBELLS}, /* 4BSD */ {L("ed"), O_EDCOMPATIBLE}, /* 4BSD */ {L("et"), O_EXPANDTAB}, /* NetBSD 5.0 */ {L("ex"), O_EXRC}, /* System V (undocumented) */ {L("fe"), O_FILEENCODING}, {L("ht"), O_HARDTABS}, /* 4BSD */ {L("ic"), O_IGNORECASE}, /* 4BSD */ {L("ie"), O_INPUTENCODING}, {L("li"), O_LINES}, /* 4.4BSD */ {L("modelines"), O_MODELINE}, /* HPUX */ {L("nu"), O_NUMBER}, /* 4BSD */ {L("opt"), O_OPTIMIZE}, /* 4BSD */ {L("para"), O_PARAGRAPHS}, /* 4BSD */ {L("re"), O_REDRAW}, /* O'Reilly */ {L("ro"), O_READONLY}, /* 4BSD (undocumented) */ {L("scr"), O_SCROLL}, /* 4BSD (undocumented) */ {L("sect"), O_SECTIONS}, /* O'Reilly */ {L("sh"), O_SHELL}, /* 4BSD */ {L("slow"), O_SLOWOPEN}, /* 4BSD */ {L("sm"), O_SHOWMATCH}, /* 4BSD */ {L("smd"), O_SHOWMODE}, /* 4BSD */ {L("sw"), O_SHIFTWIDTH}, /* 4BSD */ {L("tag"), O_TAGS}, /* 4BSD (undocumented) */ {L("tl"), O_TAGLENGTH}, /* 4BSD */ {L("to"), O_TIMEOUT}, /* 4BSD (undocumented) */ {L("ts"), O_TABSTOP}, /* 4BSD */ {L("tty"), O_TERM}, /* 4BSD (undocumented) */ {L("ttytype"), O_TERM}, /* 4BSD (undocumented) */ {L("w"), O_WINDOW}, /* O'Reilly */ {L("wa"), O_WRITEANY}, /* 4BSD */ {L("wi"), O_WINDOW}, /* 4BSD (undocumented) */ {L("wl"), O_WRAPLEN}, /* 4.4BSD */ {L("wm"), O_WRAPMARGIN}, /* 4BSD */ {L("ws"), O_WRAPSCAN}, /* 4BSD */ {NULL}, }; /* * opts_init -- * Initialize some of the options. * * PUBLIC: int opts_init(SCR *, int *); */ int opts_init(SCR *sp, int *oargs) { ARGS *argv[2], a, b; OPTLIST const *op; u_long v; int cnt, optindx = 0; char *s; CHAR_T b2[1024]; a.bp = b2; b.bp = NULL; a.len = b.len = 0; argv[0] = &a; argv[1] = &b; /* Set numeric and string default values. */ #define OI(indx, str) do { \ a.len = STRLEN(str); \ - if ((CHAR_T*)str != b2) /* GCC puts strings in text-space. */ \ + if (STRCMP((CHAR_T*)str, b2) != 0) \ (void)MEMCPY(b2, str, a.len+1); \ if (opts_set(sp, argv, NULL)) { \ optindx = indx; \ goto err; \ } \ } while (0) /* * Indirect global options to global space. Specifically, set up * terminal, lines, columns first, they're used by other options. * Note, don't set the flags until we've set up the indirection. */ if (o_set(sp, O_TERM, 0, NULL, GO_TERM)) goto err; F_SET(&sp->opts[O_TERM], OPT_GLOBAL); if (o_set(sp, O_LINES, 0, NULL, GO_LINES)) goto err; F_SET(&sp->opts[O_LINES], OPT_GLOBAL); if (o_set(sp, O_COLUMNS, 0, NULL, GO_COLUMNS)) goto err; F_SET(&sp->opts[O_COLUMNS], OPT_GLOBAL); if (o_set(sp, O_SECURE, 0, NULL, GO_SECURE)) goto err; F_SET(&sp->opts[O_SECURE], OPT_GLOBAL); /* Initialize string values. */ (void)SPRINTF(b2, SIZE(b2), L("cdpath=%s"), (s = getenv("CDPATH")) == NULL ? ":" : s); OI(O_CDPATH, b2); OI(O_CEDIT, L("cedit=\033")); /* * !!! * Vi historically stored temporary files in /var/tmp. We store them * in /tmp by default, hoping it's a memory based file system. There * are two ways to change this -- the user can set either the directory * option or the TMPDIR environmental variable. */ (void)SPRINTF(b2, SIZE(b2), L("directory=%s"), (s = getenv("TMPDIR")) == NULL ? _PATH_TMP : s); OI(O_TMPDIR, b2); OI(O_ESCAPETIME, L("escapetime=6")); OI(O_FILEC, L("filec=\t")); OI(O_KEYTIME, L("keytime=6")); OI(O_MATCHCHARS, L("matchchars=()[]{}")); OI(O_MATCHTIME, L("matchtime=7")); (void)SPRINTF(b2, SIZE(b2), L("msgcat=%s"), _PATH_MSGCAT); OI(O_MSGCAT, b2); OI(O_REPORT, L("report=5")); OI(O_PARAGRAPHS, L("paragraphs=IPLPPPQPP LIpplpipbp")); (void)SPRINTF(b2, SIZE(b2), L("path=%s"), ""); OI(O_PATH, b2); (void)SPRINTF(b2, SIZE(b2), L("recdir=%s"), NVI_PATH_PRESERVE); OI(O_RECDIR, b2); OI(O_SECTIONS, L("sections=NHSHH HUnhsh")); (void)SPRINTF(b2, SIZE(b2), L("shell=%s"), (s = getenv("SHELL")) == NULL ? _PATH_BSHELL : s); OI(O_SHELL, b2); OI(O_SHELLMETA, L("shellmeta=~{[*?$`'\"\\")); OI(O_SHIFTWIDTH, L("shiftwidth=8")); OI(O_SIDESCROLL, L("sidescroll=16")); OI(O_TABSTOP, L("tabstop=8")); (void)SPRINTF(b2, SIZE(b2), L("tags=%s"), _PATH_TAGS); OI(O_TAGS, b2); /* * XXX * Initialize O_SCROLL here, after term; initializing term should * have created a LINES/COLUMNS value. */ if ((v = (O_VAL(sp, O_LINES) - 1) / 2) == 0) v = 1; (void)SPRINTF(b2, SIZE(b2), L("scroll=%ld"), v); OI(O_SCROLL, b2); /* * The default window option values are: * 8 if baud rate <= 600 * 16 if baud rate <= 1200 * LINES - 1 if baud rate > 1200 * * Note, the windows option code will correct any too-large value * or when the O_LINES value is 1. */ if (sp->gp->scr_baud(sp, &v)) return (1); if (v <= 600) v = 8; else if (v <= 1200) v = 16; else if ((v = O_VAL(sp, O_LINES) - 1) == 0) v = 1; (void)SPRINTF(b2, SIZE(b2), L("window=%lu"), v); OI(O_WINDOW, b2); /* * Set boolean default values, and copy all settings into the default * information. OS_NOFREE is set, we're copying, not replacing. */ for (op = optlist, cnt = 0; op->name != NULL; ++op, ++cnt) { if (F_ISSET(op, OPT_GLOBAL)) continue; switch (op->type) { case OPT_0BOOL: break; case OPT_1BOOL: O_SET(sp, cnt); O_D_SET(sp, cnt); break; case OPT_NUM: o_set(sp, cnt, OS_DEF, NULL, O_VAL(sp, cnt)); break; case OPT_STR: if (O_STR(sp, cnt) != NULL && o_set(sp, cnt, OS_DEF | OS_NOFREE | OS_STRDUP, O_STR(sp, cnt), 0)) goto err; break; default: abort(); } } /* * !!! * Some options can be initialized by the command name or the * command-line arguments. They don't set the default values, * it's historic practice. */ for (; *oargs != -1; ++oargs) OI(*oargs, optlist[*oargs].name); #undef OI return (0); err: msgq_wstr(sp, M_ERR, optlist[optindx].name, "031|Unable to set default %s option"); return (1); } /* * opts_set -- * Change the values of one or more options. * * PUBLIC: int opts_set(SCR *, ARGS *[], char *); */ int opts_set(SCR *sp, ARGS *argv[], char *usage) { enum optdisp disp; enum nresult nret; OPTLIST const *op; OPTION *spo; u_long isset, turnoff, value; int ch, equals, nf, nf2, offset, qmark, rval; CHAR_T *endp, *name, *p, *sep; char *p2, *t2; char *np; size_t nlen; disp = NO_DISPLAY; for (rval = 0; argv[0]->len != 0; ++argv) { /* * The historic vi dumped the options for each occurrence of * "all" in the set list. Puhleeze. */ if (!STRCMP(argv[0]->bp, L("all"))) { disp = ALL_DISPLAY; continue; } /* Find equals sign or question mark. */ for (sep = NULL, equals = qmark = 0, p = name = argv[0]->bp; (ch = *p) != '\0'; ++p) if (ch == '=' || ch == '?') { if (p == name) { if (usage != NULL) msgq(sp, M_ERR, "032|Usage: %s", usage); return (1); } sep = p; if (ch == '=') equals = 1; else qmark = 1; break; } turnoff = 0; op = NULL; if (sep != NULL) *sep++ = '\0'; /* Search for the name, then name without any leading "no". */ if ((op = opts_search(name)) == NULL && name[0] == 'n' && name[1] == 'o') { turnoff = 1; name += 2; op = opts_search(name); } if (op == NULL) { opts_nomatch(sp, name); rval = 1; continue; } /* Find current option values. */ offset = op - optlist; spo = sp->opts + offset; /* * !!! * Historically, the question mark could be a separate * argument. */ if (!equals && !qmark && argv[1]->len == 1 && argv[1]->bp[0] == '?') { ++argv; qmark = 1; } /* Set name, value. */ switch (op->type) { case OPT_0BOOL: case OPT_1BOOL: /* Some options may not be reset. */ if (F_ISSET(op, OPT_NOUNSET) && turnoff) { msgq_wstr(sp, M_ERR, name, "291|set: the %s option may not be turned off"); rval = 1; break; } /* Some options may not be set. */ if (F_ISSET(op, OPT_NOSET) && !turnoff) { msgq_wstr(sp, M_ERR, name, "313|set: the %s option may never be turned on"); rval = 1; break; } if (equals) { msgq_wstr(sp, M_ERR, name, "034|set: [no]%s option doesn't take a value"); rval = 1; break; } if (qmark) { if (!disp) disp = SELECT_DISPLAY; F_SET(spo, OPT_SELECTED); break; } /* * Do nothing if the value is unchanged, the underlying * functions can be expensive. */ isset = !turnoff; if (!F_ISSET(op, OPT_ALWAYS)) { if (isset) { if (O_ISSET(sp, offset)) break; } else if (!O_ISSET(sp, offset)) break; } /* Report to subsystems. */ if ((op->func != NULL && op->func(sp, spo, NULL, &isset)) || ex_optchange(sp, offset, NULL, &isset) || v_optchange(sp, offset, NULL, &isset) || sp->gp->scr_optchange(sp, offset, NULL, &isset)) { rval = 1; break; } /* Set the value. */ if (isset) O_SET(sp, offset); else O_CLR(sp, offset); break; case OPT_NUM: if (turnoff) { msgq_wstr(sp, M_ERR, name, "035|set: %s option isn't a boolean"); rval = 1; break; } if (qmark || !equals) { if (!disp) disp = SELECT_DISPLAY; F_SET(spo, OPT_SELECTED); break; } if (!ISDIGIT(sep[0])) goto badnum; if ((nret = nget_uslong(&value, sep, &endp, 10)) != NUM_OK) { INT2CHAR(sp, name, STRLEN(name) + 1, np, nlen); p2 = msg_print(sp, np, &nf); INT2CHAR(sp, sep, STRLEN(sep) + 1, np, nlen); t2 = msg_print(sp, np, &nf2); switch (nret) { case NUM_ERR: msgq(sp, M_SYSERR, "036|set: %s option: %s", p2, t2); break; case NUM_OVER: msgq(sp, M_ERR, "037|set: %s option: %s: value overflow", p2, t2); break; case NUM_OK: case NUM_UNDER: abort(); } if (nf) FREE_SPACE(sp, p2, 0); if (nf2) FREE_SPACE(sp, t2, 0); rval = 1; break; } if (*endp && !cmdskip(*endp)) { badnum: INT2CHAR(sp, name, STRLEN(name) + 1, np, nlen); p2 = msg_print(sp, np, &nf); INT2CHAR(sp, sep, STRLEN(sep) + 1, np, nlen); t2 = msg_print(sp, np, &nf2); msgq(sp, M_ERR, "038|set: %s option: %s is an illegal number", p2, t2); if (nf) FREE_SPACE(sp, p2, 0); if (nf2) FREE_SPACE(sp, t2, 0); rval = 1; break; } /* Some options may never be set to zero. */ if (F_ISSET(op, OPT_NOZERO) && value == 0) { msgq_wstr(sp, M_ERR, name, "314|set: the %s option may never be set to 0"); rval = 1; break; } /* * Do nothing if the value is unchanged, the underlying * functions can be expensive. */ if (!F_ISSET(op, OPT_ALWAYS) && O_VAL(sp, offset) == value) break; /* Report to subsystems. */ INT2CHAR(sp, sep, STRLEN(sep) + 1, np, nlen); if ((op->func != NULL && op->func(sp, spo, np, &value)) || ex_optchange(sp, offset, np, &value) || v_optchange(sp, offset, np, &value) || sp->gp->scr_optchange(sp, offset, np, &value)) { rval = 1; break; } /* Set the value. */ if (o_set(sp, offset, 0, NULL, value)) rval = 1; break; case OPT_STR: if (turnoff) { msgq_wstr(sp, M_ERR, name, "039|set: %s option isn't a boolean"); rval = 1; break; } if (qmark || !equals) { if (!disp) disp = SELECT_DISPLAY; F_SET(spo, OPT_SELECTED); break; } /* Check for strings that must have even length. */ if (F_ISSET(op, OPT_PAIRS) && STRLEN(sep) & 1) { msgq_wstr(sp, M_ERR, name, "047|The %s option must be in two character groups"); rval = 1; break; } /* * Do nothing if the value is unchanged, the underlying * functions can be expensive. */ INT2CHAR(sp, sep, STRLEN(sep) + 1, np, nlen); if (!F_ISSET(op, OPT_ALWAYS) && O_STR(sp, offset) != NULL && !strcmp(O_STR(sp, offset), np)) break; /* Report to subsystems. */ if ((op->func != NULL && op->func(sp, spo, np, NULL)) || ex_optchange(sp, offset, np, NULL) || v_optchange(sp, offset, np, NULL) || sp->gp->scr_optchange(sp, offset, np, NULL)) { rval = 1; break; } /* Set the value. */ if (o_set(sp, offset, OS_STRDUP, np, 0)) rval = 1; break; default: abort(); } } if (disp != NO_DISPLAY) opts_dump(sp, disp); return (rval); } /* * o_set -- * Set an option's value. * * PUBLIC: int o_set(SCR *, int, u_int, char *, u_long); */ int o_set(SCR *sp, int opt, u_int flags, char *str, u_long val) { OPTION *op; /* Set a pointer to the options area. */ op = F_ISSET(&sp->opts[opt], OPT_GLOBAL) ? &sp->gp->opts[sp->opts[opt].o_cur.val] : &sp->opts[opt]; /* Copy the string, if requested. */ if (LF_ISSET(OS_STRDUP) && (str = strdup(str)) == NULL) { msgq(sp, M_SYSERR, NULL); return (1); } /* Free the previous string, if requested, and set the value. */ if LF_ISSET(OS_DEF) if (LF_ISSET(OS_STR | OS_STRDUP)) { if (!LF_ISSET(OS_NOFREE)) free(op->o_def.str); op->o_def.str = str; } else op->o_def.val = val; else if (LF_ISSET(OS_STR | OS_STRDUP)) { if (!LF_ISSET(OS_NOFREE)) free(op->o_cur.str); op->o_cur.str = str; } else op->o_cur.val = val; return (0); } /* * opts_empty -- * Return 1 if the string option is invalid, 0 if it's OK. * * PUBLIC: int opts_empty(SCR *, int, int); */ int opts_empty(SCR *sp, int off, int silent) { char *p; if ((p = O_STR(sp, off)) == NULL || p[0] == '\0') { if (!silent) msgq_wstr(sp, M_ERR, optlist[off].name, "305|No %s edit option specified"); return (1); } return (0); } /* * opts_dump -- * List the current values of selected options. * * PUBLIC: void opts_dump(SCR *, enum optdisp); */ void opts_dump(SCR *sp, enum optdisp type) { OPTLIST const *op; int base, b_num, cnt, col, colwidth, curlen, s_num; int numcols, numrows, row; int b_op[O_OPTIONCOUNT], s_op[O_OPTIONCOUNT]; char nbuf[20]; /* * Options are output in two groups -- those that fit in a column and * those that don't. Output is done on 6 character "tab" boundaries * for no particular reason. (Since we don't output tab characters, * we can ignore the terminal's tab settings.) Ignore the user's tab * setting because we have no idea how reasonable it is. * * Find a column width we can live with, testing from 10 columns to 1. */ for (numcols = 10; numcols > 1; --numcols) { colwidth = sp->cols / numcols & ~(STANDARD_TAB - 1); if (colwidth >= 10) { colwidth = (colwidth + STANDARD_TAB) & ~(STANDARD_TAB - 1); numcols = sp->cols / colwidth; break; } colwidth = 0; } /* * Get the set of options to list, entering them into * the column list or the overflow list. */ for (b_num = s_num = 0, op = optlist; op->name != NULL; ++op) { cnt = op - optlist; /* If OPT_NDISP set, it's never displayed. */ if (F_ISSET(op, OPT_NDISP)) continue; switch (type) { case ALL_DISPLAY: /* Display all. */ break; case CHANGED_DISPLAY: /* Display changed. */ /* If OPT_ADISP set, it's always "changed". */ if (F_ISSET(op, OPT_ADISP)) break; switch (op->type) { case OPT_0BOOL: case OPT_1BOOL: case OPT_NUM: if (O_VAL(sp, cnt) == O_D_VAL(sp, cnt)) continue; break; case OPT_STR: if (O_STR(sp, cnt) == O_D_STR(sp, cnt) || (O_D_STR(sp, cnt) != NULL && !strcmp(O_STR(sp, cnt), O_D_STR(sp, cnt)))) continue; break; } break; case SELECT_DISPLAY: /* Display selected. */ if (!F_ISSET(&sp->opts[cnt], OPT_SELECTED)) continue; break; default: case NO_DISPLAY: abort(); } F_CLR(&sp->opts[cnt], OPT_SELECTED); curlen = STRLEN(op->name); switch (op->type) { case OPT_0BOOL: case OPT_1BOOL: if (!O_ISSET(sp, cnt)) curlen += 2; break; case OPT_NUM: (void)snprintf(nbuf, sizeof(nbuf), "%ld", O_VAL(sp, cnt)); curlen += strlen(nbuf); break; case OPT_STR: if (O_STR(sp, cnt) != NULL) curlen += strlen(O_STR(sp, cnt)); curlen += 3; break; } /* Offset by 2 so there's a gap. */ if (curlen <= colwidth - 2) s_op[s_num++] = cnt; else b_op[b_num++] = cnt; } if (s_num > 0) { /* Figure out the number of rows. */ if (s_num > numcols) { numrows = s_num / numcols; if (s_num % numcols) ++numrows; } else numrows = 1; /* Display the options in sorted order. */ for (row = 0; row < numrows;) { for (base = row, col = 0; col < numcols; ++col) { cnt = opts_print(sp, &optlist[s_op[base]]); if ((base += numrows) >= s_num) break; (void)ex_printf(sp, "%*s", (int)(colwidth - cnt), ""); } if (++row < numrows || b_num) (void)ex_puts(sp, "\n"); } } for (row = 0; row < b_num;) { (void)opts_print(sp, &optlist[b_op[row]]); if (++row < b_num) (void)ex_puts(sp, "\n"); } (void)ex_puts(sp, "\n"); } /* * opts_print -- * Print out an option. */ static int opts_print(SCR *sp, OPTLIST const *op) { int curlen, offset; const char *p; curlen = 0; offset = op - optlist; switch (op->type) { case OPT_0BOOL: case OPT_1BOOL: curlen += ex_printf(sp, "%s"WS, O_ISSET(sp, offset) ? "" : "no", op->name); break; case OPT_NUM: curlen += ex_printf(sp, WS"=%ld", op->name, O_VAL(sp, offset)); break; case OPT_STR: curlen += ex_printf(sp, WS"=\"", op->name); p = O_STR(sp, offset); /* Keep correct count for unprintable character sequences */ if (p != NULL) for (; *p != '\0'; ++p) curlen += ex_puts(sp, unctrl(*p)); curlen += ex_puts(sp, "\""); break; } return (curlen); } /* * opts_save -- * Write the current configuration to a file. * * PUBLIC: int opts_save(SCR *, FILE *); */ int opts_save(SCR *sp, FILE *fp) { OPTLIST const *op; CHAR_T ch, *p; char nch, *np; int cnt; for (op = optlist; op->name != NULL; ++op) { if (F_ISSET(op, OPT_NOSAVE)) continue; cnt = op - optlist; switch (op->type) { case OPT_0BOOL: case OPT_1BOOL: if (O_ISSET(sp, cnt)) (void)fprintf(fp, "set "WS"\n", op->name); else (void)fprintf(fp, "set no"WS"\n", op->name); break; case OPT_NUM: (void)fprintf(fp, "set "WS"=%-3ld\n", op->name, O_VAL(sp, cnt)); break; case OPT_STR: if (O_STR(sp, cnt) == NULL) break; (void)fprintf(fp, "set "); for (p = op->name; (ch = *p) != '\0'; ++p) { if (cmdskip(ch) || ch == '\\') (void)putc('\\', fp); fprintf(fp, WC, ch); } (void)putc('=', fp); for (np = O_STR(sp, cnt); (nch = *np) != '\0'; ++np) { if (cmdskip(nch) || nch == '\\') (void)putc('\\', fp); (void)putc(nch, fp); } (void)putc('\n', fp); break; } if (ferror(fp)) { msgq(sp, M_SYSERR, NULL); return (1); } } return (0); } /* * opts_search -- * Search for an option. * * PUBLIC: OPTLIST const *opts_search(CHAR_T *); */ OPTLIST const * opts_search(CHAR_T *name) { OPTLIST const *op, *found; OABBREV atmp, *ap; OPTLIST otmp; size_t len; /* Check list of abbreviations. */ atmp.name = name; if ((ap = bsearch(&atmp, abbrev, sizeof(abbrev) / sizeof(OABBREV) - 1, sizeof(OABBREV), opts_abbcmp)) != NULL) return (optlist + ap->offset); /* Check list of options. */ otmp.name = name; if ((op = bsearch(&otmp, optlist, sizeof(optlist) / sizeof(OPTLIST) - 1, sizeof(OPTLIST), opts_cmp)) != NULL) return (op); /* * Check to see if the name is the prefix of one (and only one) * option. If so, return the option. */ len = STRLEN(name); for (found = NULL, op = optlist; op->name != NULL; ++op) { if (op->name[0] < name[0]) continue; if (op->name[0] > name[0]) break; if (!MEMCMP(op->name, name, len)) { if (found != NULL) return (NULL); found = op; } } return (found); } /* * opts_nomatch -- * Standard nomatch error message for options. * * PUBLIC: void opts_nomatch(SCR *, CHAR_T *); */ void opts_nomatch(SCR *sp, CHAR_T *name) { msgq_wstr(sp, M_ERR, name, "033|set: no %s option: 'set all' gives all option values"); } static int opts_abbcmp(const void *a, const void *b) { return(STRCMP(((OABBREV *)a)->name, ((OABBREV *)b)->name)); } static int opts_cmp(const void *a, const void *b) { return(STRCMP(((OPTLIST *)a)->name, ((OPTLIST *)b)->name)); } /* * opts_copy -- * Copy a screen's OPTION array. * * PUBLIC: int opts_copy(SCR *, SCR *); */ int opts_copy(SCR *orig, SCR *sp) { int cnt, rval; /* Copy most everything without change. */ memcpy(sp->opts, orig->opts, sizeof(orig->opts)); /* Copy the string edit options. */ for (cnt = rval = 0; cnt < O_OPTIONCOUNT; ++cnt) { if (optlist[cnt].type != OPT_STR || F_ISSET(&sp->opts[cnt], OPT_GLOBAL)) continue; /* * If never set, or already failed, NULL out the entries -- * have to continue after failure, otherwise would have two * screens referencing the same memory. */ if (rval || O_STR(sp, cnt) == NULL) { o_set(sp, cnt, OS_NOFREE | OS_STR, NULL, 0); o_set(sp, cnt, OS_DEF | OS_NOFREE | OS_STR, NULL, 0); continue; } /* Copy the current string. */ if (o_set(sp, cnt, OS_NOFREE | OS_STRDUP, O_STR(sp, cnt), 0)) { o_set(sp, cnt, OS_DEF | OS_NOFREE | OS_STR, NULL, 0); goto nomem; } /* Copy the default string. */ if (O_D_STR(sp, cnt) != NULL && o_set(sp, cnt, OS_DEF | OS_NOFREE | OS_STRDUP, O_D_STR(sp, cnt), 0)) { nomem: msgq(orig, M_SYSERR, NULL); rval = 1; } } return (rval); } /* * opts_free -- * Free all option strings * * PUBLIC: void opts_free(SCR *); */ void opts_free(SCR *sp) { int cnt; for (cnt = 0; cnt < O_OPTIONCOUNT; ++cnt) { if (optlist[cnt].type != OPT_STR || F_ISSET(&sp->opts[cnt], OPT_GLOBAL)) continue; free(O_STR(sp, cnt)); free(O_D_STR(sp, cnt)); } } diff --git a/man/vi.1 b/man/vi.1 index 0fa49224353f..596657319eee 100644 --- a/man/vi.1 +++ b/man/vi.1 @@ -1,2802 +1,2807 @@ .\" Copyright (c) 1994 .\" The Regents of the University of California. All rights reserved. .\" Copyright (c) 1994, 1995, 1996 .\" Keith Bostic. All rights reserved. .\" Copyright (c) 2011 .\" Zhihao Yuan. All rights reserved. .\" .\" The vi program is freely redistributable. .\" You are welcome to copy, modify and share it with others .\" under the conditions listed in the LICENSE file. .\" If any company (not individual!) finds vi sufficiently useful .\" that you would have purchased it, or if any company wishes to .\" redistribute it, contributions to the authors would be appreciated. .\" -.Dd November 2, 2013 +.Dd April 18, 2024 .Dt VI 1 .Os .Sh NAME -.Nm ex , vi , view +.Nm ex , +.Nm vi , +.Nm view .Nd text editors .Sh SYNOPSIS .Nm ex .Op Fl FRrSsv .Op Fl c Ar cmd .Op Fl t Ar tag .Op Fl w Ar size .Op Ar .Nm vi\ \& .Op Fl eFRrS .Op Fl c Ar cmd .Op Fl t Ar tag .Op Fl w Ar size .Op Ar .Nm view .Op Fl eFrS .Op Fl c Ar cmd .Op Fl t Ar tag .Op Fl w Ar size .Op Ar .Sh DESCRIPTION .Nm vi is a screen-oriented text editor. .Nm ex is a line-oriented text editor. .Nm ex and .Nm vi are different interfaces to the same program, and it is possible to switch back and forth during an edit session. .Nm view is the equivalent of using the .Fl R .Pq read-only option of .Nm vi . .Pp This manual page is the one provided with the .Nm nex Ns / Ns Nm nvi versions of the .Nm ex Ns / Ns Nm vi text editors. .Nm nex Ns / Ns Nm nvi are intended as bug-for-bug compatible replacements for the original Fourth Berkeley Software Distribution .Pq 4BSD .Nm ex and .Nm vi programs. For the rest of this manual page, .Nm nex Ns / Ns Nm nvi is used only when it's necessary to distinguish it from the historic implementations of .Nm ex Ns / Ns Nm vi . .Pp This manual page is intended for users already familiar with .Nm ex Ns / Ns Nm vi . Anyone else should almost certainly read a good tutorial on the editor before this manual page. If you're in an unfamiliar environment, and you absolutely have to get work done immediately, read the section after the options description, entitled .Sx FAST STARTUP . It's probably enough to get you going. .Pp The following options are available: .Bl -tag -width "-w size " .It Fl c Ar cmd Execute .Ar cmd on the first file loaded. Particularly useful for initial positioning in the file, although .Ar cmd is not limited to positioning commands. This is the POSIX 1003.2 interface for the historic .Dq +cmd syntax. .Nm nex Ns / Ns Nm nvi supports both the old and new syntax. .It Fl e Start editing in ex mode, as if the command name were .Nm ex . .It Fl F Don't copy the entire file when first starting to edit. (The default is to make a copy in case someone else modifies the file during your edit session.) .\" .It Fl l .\" Start editing with the lisp and showmatch options set. .It Fl R Start editing in read-only mode, as if the command name was .Nm view , or the .Cm readonly option was set. .It Fl r Recover the specified files, or, if no files are specified, list the files that could be recovered. If no recoverable files by the specified name exist, the file is edited as if the .Fl r option had not been specified. .It Fl S Run with the .Cm secure edit option set, disallowing all access to external programs. .It Fl s Enter batch mode; applicable only to .Nm ex edit sessions. Batch mode is useful when running .Nm ex scripts. Prompts, informative messages and other user oriented messages are turned off, and no startup files or environment variables are read. This is the POSIX 1003.2 interface for the historic .Dq - argument. .Nm nex Ns / Ns Nm nvi supports both the old and new syntax. .It Fl t Ar tag Start editing at the specified .Ar tag .Pq see Xr ctags 1 . .It Fl v Start editing in vi mode, as if the command name was .Nm vi . .It Fl w Ar size Set the initial window size to the specified number of lines. .El .Pp Command input for .Nm ex Ns / Ns Nm vi is read from the standard input. In the .Nm vi interface, it is an error if standard input is not a terminal. In the .Nm ex interface, if standard input is not a terminal, .Nm ex will read commands from it regardless; however, the session will be a batch mode session, exactly as if the .Fl s option had been specified. .Sh FAST STARTUP This section will tell you the minimum amount that you need to do simple editing tasks using .Nm vi . If you've never used any screen editor before, you're likely to have problems even with this simple introduction. In that case you should find someone that already knows .Nm vi and have them walk you through this section. .Pp .Nm vi is a screen editor. This means that it takes up almost the entire screen, displaying part of the file on each screen line, except for the last line of the screen. The last line of the screen is used for you to give commands to .Nm vi , and for .Nm vi to give information to you. .Pp The other fact that you need to understand is that .Nm vi is a modeful editor, i.e., you are either entering text or you are executing commands, and you have to be in the right mode to do one or the other. You will be in command mode when you first start editing a file. There are commands that switch you into input mode. There is only one key that takes you out of input mode, and that is the .Aq escape key. .Pp In this manual, key names are denoted with \(la and \(ra, e.g., .Aq escape means the .Dq escape key, usually labeled .Dq Esc on your terminal's keyboard. If you're ever confused as to which mode you're in, keep entering the .Aq escape key until .Nm vi beeps at you. Generally, .Nm vi will beep at you if you try and do something that's not allowed. It will also display error messages. .Pp To start editing a file, enter the following command: .Pp .Dl $ vi file .Pp The command you should enter as soon as you start editing is: .Pp .Dl :set verbose showmode .Pp This will make the editor give you verbose error messages and display the current mode at the bottom of the screen. .Pp The commands to move around the file are: .Bl -tag -width Ds .It Cm h Move the cursor left one character. .It Cm j Move the cursor down one line. .It Cm k Move the cursor up one line. .It Cm l Move the cursor right one character. .It Aq Cm cursor-arrows The cursor arrow keys should work, too. .It Cm / Ns Ar text Search for the string .Dq Ar text in the file, and move the cursor to its first character. .El .Pp The commands to enter new text are: .Bl -tag -width "" .It Cm a Append new text, after the cursor. .It Cm i Insert new text, before the cursor. .It Cm o Open a new line below the line the cursor is on, and start entering text. .It Cm O Open a new line above the line the cursor is on, and start entering text. .It Aq Cm escape Once you've entered input mode using one of the .Cm a , .Cm i , .Cm o or .Cm O commands, use .Aq Cm escape to quit entering text and return to command mode. .El .Pp The commands to copy text are: .Bl -tag -width Ds .It Cm yy Copy the line the cursor is on. .It Cm p Append the copied line after the line the cursor is on. .El .Pp The commands to delete text are: .Bl -tag -width Ds .It Cm dd Delete the line the cursor is on. .It Cm x Delete the character the cursor is on. .El .Pp The commands to write the file are: .Bl -tag -width Ds .It Cm :w Write the file back to the file with the name that you originally used as an argument on the .Nm vi command line. .It Cm :w Ar file_name Write the file back to the file with the name .Ar file_name . .El .Pp The commands to quit editing and exit the editor are: .Bl -tag -width Ds .It Cm :q Quit editing and leave .Nm vi (if you've modified the file, but not saved your changes, .Nm vi will refuse to quit). -.It Cm :q! +.It Cm :q\&! Quit, discarding any modifications that you may have made. .El .Pp One final caution: Unusual characters can take up more than one column on the screen, and long lines can take up more than a single screen line. The above commands work on .Dq physical characters and lines, i.e., they affect the entire line no matter how many screen lines it takes up and the entire character no matter how many screen columns it takes up. .Sh REGULAR EXPRESSIONS .Nm ex Ns / Ns Nm vi supports regular expressions .Pq REs , as documented in .Xr re_format 7 , for line addresses, as the first part of the .Nm ex Cm substitute , .Cm global and .Cm v commands, and in search patterns. Basic regular expressions .Pq BREs are enabled by default; extended regular expressions .Pq EREs are used if the .Cm extended option is enabled. The use of regular expressions can be largely disabled using the .Cm magic option. .Pp The following strings have special meanings in the .Nm ex Ns / Ns Nm vi version of regular expressions: .Bl -bullet -offset 6u .It An empty regular expression is equivalent to the last regular expression used. .It .Sq \e< matches the beginning of the word. .It .Sq \e> matches the end of the word. .It .Sq \(ti matches the replacement part of the last .Cm substitute command. .El .Sh BUFFERS A buffer is an area where commands can save changed or deleted text for later use. .Nm vi buffers are named with a single character preceded by a double quote, for example .Cm \&" Ns Aq Ar c ; .Nm ex buffers are the same, but without the double quote. .Nm nex Ns / Ns Nm nvi permits the use of any character without another meaning in the position where a buffer name is expected. .Pp All buffers are either in .Em line mode or .Em character mode . Inserting a buffer in line mode into the text creates new lines for each of the lines it contains, while a buffer in character mode creates new lines for any lines .Em other than the first and last lines it contains. The first and last lines are inserted at the current cursor position, becoming part of the current line. If there is more than one line in the buffer, the current line itself will be split. All .Nm ex commands which store text into buffers do so in line mode. The behaviour of .Nm vi commands depend on their associated motion command: .Bl -bullet -offset 6u .It .Aq Cm control-A , .Cm h , .Cm l , .Cm ,\& , .Cm 0 , .Cm B , .Cm E , .Cm F , .Cm T , .Cm W , .Cm \(ha , .Cm b , .Cm e , .Cm f and .Cm t make the destination buffer character-oriented. .It .Cm j , .Aq Cm control-M , .Cm k , .Cm \(aq , .Cm - , .Cm G , .Cm H , .Cm L , .Cm M , .Cm _ and .Cm |\& make the destination buffer line-oriented. .It .Cm $ , .Cm % , .Cm \` , .Cm (\& , .Cm )\& , .Cm / , .Cm ?\& , .Cm [[ , .Cm ]] , .Cm { and .Cm } make the destination buffer character-oriented, unless the starting and end positions are the first and last characters on a line. In that case, the buffer is line-oriented. .El .Pp The .Nm ex command .Cm display buffers displays the current mode for each buffer. .Pp Buffers named .Sq a through .Sq z may be referred to using their uppercase equivalent, in which case new content will be appended to the buffer, instead of replacing it. .Pp Buffers named .Sq 1 through .Sq 9 are special. A region of text modified using the .Cm c .Pq change or .Cm d .Pq delete commands is placed into the numeric buffer .Sq 1 if no other buffer is specified and if it meets one of the following conditions: .Bl -bullet -offset 6u .It It includes characters from more than one line. .It It is specified using a line-oriented motion. .It It is specified using one of the following motion commands: .Aq Cm control-A , .Cm \` Ns Aq Ar character , .Cm n , .Cm N , .Cm % , .Cm / , .Cm { , .Cm } , .Cm \&( , .Cm \&) , and .Cm \&? . .El .Pp Before this copy is done, the previous contents of buffer .Sq 1 are moved into buffer .Sq 2 , .Sq 2 into buffer .Sq 3 , and so on. The contents of buffer .Sq 9 are discarded. Note that this rotation occurs .Em regardless of the user specifying another buffer. In .Nm vi , text may be explicitly stored into the numeric buffers. In this case, the buffer rotation occurs before the replacement of the buffer's contents. The numeric buffers are only available in .Nm vi mode. .Sh VI COMMANDS The following section describes the commands available in the command mode of the .Nm vi editor. The following words have a special meaning in the commands description: .Pp .Bl -tag -width bigword -compact -offset 3u .It Ar bigword A set of non-whitespace characters. .It Ar buffer Temporary area where commands may place text. If not specified, the default buffer is used. See also .Sx BUFFERS , above. .It Ar count A positive number used to specify the desired number of iterations of a command. It defaults to 1 if not specified. .It Ar motion A cursor movement command which indicates the other end of the affected region of text, the first being the current cursor position. Repeating the command character makes it affect the whole current line. .It Ar word A sequence of letters, digits or underscores. .El .Pp .Ar buffer and .Ar count , if both present, may be specified in any order. .Ar motion and .Ar count , if both present, are effectively multiplied together and considered part of the motion. .Pp .Bl -tag -width Ds -compact .It Xo .Aq Cm control-A .Xc Search forward for the word starting at the cursor position. .Pp .It Xo .Op Ar count .Aq Cm control-B .Xc Page backwards .Ar count screens. Two lines of overlap are maintained, if possible. .Pp .It Xo .Op Ar count .Aq Cm control-D .Xc Scroll forward .Ar count lines. If .Ar count is not given, scroll forward the number of lines specified by the last .Aq Cm control-D or .Aq Cm control-U command. If this is the first .Aq Cm control-D command, scroll half the number of lines in the current screen. .Pp .It Xo .Op Ar count .Aq Cm control-E .Xc Scroll forward .Ar count lines, leaving the current line and column as is, if possible. .Pp .It Xo .Op Ar count .Aq Cm control-F .Xc Page forward .Ar count screens. Two lines of overlap are maintained, if possible. .Pp .It Aq Cm control-G Display the following file information: the file name .Pq as given to Nm vi ; whether the file has been modified since it was last written; if the file is read-only; the current line number; the total number of lines in the file; and the current line number as a percentage of the total lines in the file. .Pp .It Xo .Op Ar count .Aq Cm control-H .Xc .It Xo .Op Ar count .Cm h .Xc Move the cursor back .Ar count characters in the current line. .Pp .It Xo .Op Ar count .Aq Cm control-J .Xc .It Xo .Op Ar count .Aq Cm control-N .Xc .It Xo .Op Ar count .Cm j .Xc Move the cursor down .Ar count lines without changing the current column. .Pp .It Aq Cm control-L .It Aq Cm control-R Repaint the screen. .Pp .It Xo .Op Ar count .Aq Cm control-M .Xc .It Xo .Op Ar count .Cm + .Xc Move the cursor down .Ar count lines to the first non-blank character of that line. .Pp .It Xo .Op Ar count .Aq Cm control-P .Xc .It Xo .Op Ar count .Cm k .Xc Move the cursor up .Ar count lines, without changing the current column. .Pp .It Aq Cm control-T Return to the most recent tag context. .Pp .It Xo .Op Ar count .Aq Cm control-U .Xc Scroll backwards .Ar count lines. If .Ar count is not given, scroll backwards the number of lines specified by the last .Aq Cm control-D or .Aq Cm control-U command. If this is the first .Aq Cm control-U command, scroll half the number of lines in the current screen. .Pp .It Aq Cm control-W Switch to the next lower screen in the window, or to the first screen if there are no lower screens in the window. .Pp .It Xo .Op Ar count .Aq Cm control-Y .Xc Scroll backwards .Ar count lines, leaving the current line and column as is, if possible. .Pp .It Aq Cm control-Z Suspend the current editor session. .Pp .It Aq Cm escape Execute the .Nm ex command being entered, or cancel it if it is only partial. .Pp -.It Aq Cm control-] +.It Aq Cm control-\(rB Push a tag reference onto the tag stack. .Pp .It Aq Cm control-\(ha Switch to the most recently edited file. .Pp .It Xo .Op Ar count .Aq Cm space .Xc .It Xo .Op Ar count .Cm l .Xc Move the cursor forward .Ar count characters without changing the current line. .Pp .It Xo .Op Ar count .Cm !\& .Ar motion shell-argument(s) .Aq Li carriage-return .Xc Replace the lines spanned by .Ar count and .Ar motion with the output .Pq standard output and standard error of the program named by the .Cm shell option, called with a .Fl c flag followed by the .Ar shell-argument(s) .Pq bundled into a single argument . Within .Ar shell-argument(s) , the .Sq % , .Sq # and .Sq !\& characters are expanded to the current file name, the previous current file name, and the command text of the previous .Cm !\& or .Cm :! commands, respectively. The special meaning of .Sq % , .Sq # and .Sq !\& can be overridden by escaping them with a backslash. .Pp .It Xo .Op Ar count .Cm # .Sm off .Cm # | + | - .Sm on .Xc Increment .Pq trailing So # Sc or So + Sc or decrement .Pq trailing Sq - the number under the cursor by .Ar count , starting at the cursor position or at the first non-blank character following it. Numbers with a leading .Sq 0x or .Sq 0X are interpreted as hexadecimal numbers. Numbers with a leading .Sq 0 are interpreted as octal numbers unless they contain a non-octal digit. Other numbers may be prefixed with a .Sq + or .Sq - sign. .Pp .It Xo .Op Ar count .Cm $ .Xc Move the cursor to the end of a line. If .Ar count is specified, additionally move the cursor down .Ar count \(mi 1 lines. .Pp .It Cm % Move to the .Cm matchchars character matching the one found at the cursor position or the closest to the right of it. .Pp .It Cm & Repeat the previous substitution command on the current line. .Pp .It Xo .Cm \(aq Ns Aq Ar character .Xc .It Xo .Cm \` Ns Aq Ar character .Xc Return to the cursor position marked by the character .Ar character , or, if .Ar character is .Sq \(aq or .Sq \` , to the position of the cursor before the last of the following commands: .Aq Cm control-A , .Aq Cm control-T , -.Aq Cm control-] , +.Aq Cm control-\(rB , .Cm % , .Cm \(aq , .Cm \` , .Cm (\& , .Cm )\& , .Cm / , .Cm ?\& , .Cm G , .Cm H , .Cm L , .Cm [[ , .Cm ]] , .Cm { , .Cm } . The first form returns to the first non-blank character of the line marked by .Ar character . The second form returns to the line and column marked by .Ar character . .Pp .It Xo .Op Ar count .Cm \&( .Xc .It Xo .Op Ar count .Cm \&) .Xc Move .Ar count sentences backward or forward, respectively. A sentence is an area of text that begins with the first nonblank character following the previous sentence, paragraph, or section boundary and continues until the next period, exclamation point, or question mark character, followed by any number of closing parentheses, brackets, double or single quote characters, followed by either an end-of-line or two whitespace characters. Groups of empty lines .Pq or lines containing only whitespace characters are treated as a single sentence. .Pp .It Xo .Op Ar count .Cm ,\& .Xc Reverse find character .Pq i.e., the last Cm F , f , T No or Cm t No command .Ar count times. .Pp .It Xo .Op Ar count .Cm - .Xc Move to the first non-blank character of the previous line, .Ar count times. .Pp .It Xo .Op Ar count .Cm .\& .Xc Repeat the last .Nm vi command that modified text. .Ar count replaces both the .Ar count argument of the repeated command and that of the associated .Ar motion . If the .Cm .\& command repeats the .Cm u command, the change log is rolled forward or backward, depending on the action of the .Cm u command. .Pp .It Xo .Pf / Ns Ar RE .Aq Li carriage-return .Xc .It Xo .Pf / Ns Ar RE Ns / .Op Ar offset .Op Cm z .Aq Li carriage-return .Xc .It Xo .Pf ?\& Ns Ar RE .Aq Li carriage-return .Xc .It Xo .Pf ?\& Ns Ar RE Ns ?\& .Op Ar offset .Op Cm z .Aq Li carriage-return .Xc .It Cm N .It Cm n Search forward .Pq Sq / or backward .Pq Sq ?\& for a regular expression. .Cm n and .Cm N repeat the last search in the same or opposite directions, respectively. If .Ar RE is empty, the last search regular expression is used. If .Ar offset is specified, the cursor is placed .Ar offset lines before or after the matched regular expression. If either .Cm n or .Cm N commands are used as motion components for the .Cm !\& command, there will be no prompt for the text of the command and the previous .Cm !\& will be executed. Multiple search patterns may be grouped together by delimiting them with semicolons and zero or more whitespace characters. These patterns are evaluated from left to right with the final cursor position determined by the last search pattern. A .Cm z command may be appended to the closed search expressions to reposition the result line. .Pp .It Cm 0 Move to the first character in the current line. .Pp .It Cm :\& Execute an .Nm ex command. .Pp .It Xo .Op Ar count .Cm ;\& .Xc Repeat the last character find (i.e., the last .Cm F , f , T or .Cm t command) .Ar count times. .Pp .It Xo .Op Ar count .Cm < .Ar motion .Xc .It Xo .Op Ar count .Cm > .Ar motion .Xc Shift .Ar count lines left or right, respectively, by an amount of .Cm shiftwidth . .Pp .It Cm @ Ar buffer Execute a named .Ar buffer as .Nm vi commands. The buffer may include .Nm ex commands too, but they must be expressed as a .Cm \&: command. If .Ar buffer is .Sq @ or .Sq * , then the last buffer executed shall be used. .Pp .It Xo .Op Ar count .Cm A .Xc Enter input mode, appending the text after the end of the line. If a .Ar count argument is given, the characters input are repeated .Ar count \(mi 1 times after input mode is exited. .Pp .It Xo .Op Ar count .Cm B .Xc Move backwards .Ar count bigwords. .Pp .It Xo .Op Ar buffer .Cm C .Xc Change text from the current position to the end-of-line. If .Ar buffer is specified, .Dq yank the deleted text into .Ar buffer . .Pp .It Xo .Op Ar buffer .Cm D .Xc Delete text from the current position to the end-of-line. If .Ar buffer is specified, .Dq yank the deleted text into .Ar buffer . .Pp .It Xo .Op Ar count .Cm E .Xc Move forward .Ar count end-of-bigwords. .Pp .It Xo .Op Ar count .Cm F Aq Ar character .Xc Search .Ar count times backward through the current line for .Aq Ar character . .Pp .It Xo .Op Ar count .Cm G .Xc Move to line .Ar count , or the last line of the file if .Ar count is not specified. .Pp .It Xo .Op Ar count .Cm H .Xc Move to the screen line .Ar count \(mi 1 lines below the top of the screen. .Pp .It Xo .Op Ar count .Cm I .Xc Enter input mode, inserting the text at the beginning of the line. If a .Ar count argument is given, the characters input are repeated .Ar count \(mi 1 more times. .Pp .It Xo .Op Ar count .Cm J .Xc Join .Ar count lines with the current line. The spacing between two joined lines is set to two whitespace characters if the former ends with a question mark, a period or an exclamation point. It is set to one whitespace character otherwise. .Pp .It Xo .Op Ar count .Cm L .Xc Move to the screen line .Ar count \(mi 1 lines above the bottom of the screen. .Pp .It Cm M Move to the screen line in the middle of the screen. .Pp .It Xo .Op Ar count .Cm O .Xc Enter input mode, appending text in a new line above the current line. If a .Ar count argument is given, the characters input are repeated .Ar count \(mi 1 more times. .Pp .It Xo .Op Ar buffer .Cm P .Xc Insert text from .Ar buffer before the current column if .Ar buffer is character-oriented or before the current line if it is line-oriented. .Pp .It Cm Q Exit .Nm vi .Pq or visual mode and switch to .Nm ex mode. .Pp .It Xo .Op Ar count .Cm R .Xc Enter input mode, replacing the characters in the current line. If a .Ar count argument is given, the characters input are repeated .Ar count \(mi 1 more times upon exit from insert mode. .Pp .It Xo .Op Ar buffer .Op Ar count .Cm S .Xc Substitute .Ar count lines. If .Ar buffer is specified, .Dq yank the deleted text into .Ar buffer . .Pp .It Xo .Op Ar count .Cm T .Aq Ar character .Xc Search backwards, .Ar count times, through the current line for the character after the specified .Aq Ar character . .Pp .It Cm U Restore the current line to its state before the cursor last moved to it. .Pp .It Xo .Op Ar count .Cm W .Xc Move forward .Ar count bigwords. .Pp .It Xo .Op Ar buffer .Op Ar count .Cm X .Xc Delete .Ar count characters before the cursor, on the current line. If .Ar buffer is specified, .Dq yank the deleted text into .Ar buffer . .Pp .It Xo .Op Ar buffer .Op Ar count .Cm Y .Xc Copy .Pq or Dq yank .Ar count lines into .Ar buffer . .Pp .It Cm ZZ Write the file and exit .Nm vi if there are no more files to edit. Entering two .Dq quit commands in a row ignores any remaining file to edit. .Pp .It Xo .Op Ar count .Cm [[ .Xc Back up .Ar count section boundaries. .Pp .It Xo .Op Ar count .Cm ]] .Xc Move forward .Ar count section boundaries. .Pp .It Cm \(ha Move to the first non-blank character on the current line. .Pp .It Xo .Op Ar count .Cm _ .Xc Move down .Ar count \(mi 1 lines, to the first non-blank character. .Pp .It Xo .Op Ar count .Cm a .Xc Enter input mode, appending the text after the cursor. If a .Ar count argument is given, the characters input are repeated .Ar count number of times. .Pp .It Xo .Op Ar count .Cm b .Xc Move backwards .Ar count words. .Pp .It Xo .Op Ar buffer .Op Ar count .Cm c .Ar motion .Xc Change the region of text described by .Ar count and .Ar motion . If .Ar buffer is specified, .Dq yank the changed text into .Ar buffer . .Pp .It Xo .Op Ar buffer .Op Ar count .Cm d .Ar motion .Xc Delete the region of text described by .Ar count and .Ar motion . If .Ar buffer is specified, .Dq yank the deleted text into .Ar buffer . .Pp .It Xo .Op Ar count .Cm e .Xc Move forward .Ar count end-of-words. .Pp .It Xo .Op Ar count .Cm f Aq Ar character .Xc Search forward, .Ar count times, through the rest of the current line for .Aq Ar character . .Pp .It Xo .Op Ar count .Cm i .Xc Enter input mode, inserting the text before the cursor. If a .Ar count argument is given, the characters input are repeated .Ar count number of times. .Pp .It Xo .Cm m .Aq Ar character .Xc Save the current context .Pq line and column as .Aq Ar character . .Pp .It Xo .Op Ar count .Cm o .Xc Enter input mode, appending text in a new line under the current line. If a .Ar count argument is given, the characters input are repeated .Ar count \(mi 1 more times. .Pp .It Xo .Op Ar buffer .Cm p .Xc Append text from .Ar buffer . Text is appended after the current column if .Ar buffer is character oriented, or after the current line otherwise. .Pp .It Xo .Op Ar count .Cm r .Aq Ar character .Xc Replace .Ar count characters with .Ar character . .Pp .It Xo .Op Ar buffer .Op Ar count .Cm s .Xc Substitute .Ar count characters in the current line starting with the current character. If .Ar buffer is specified, .Dq yank the substituted text into .Ar buffer . .Pp .It Xo .Op Ar count .Cm t .Aq Ar character .Xc Search forward, .Ar count times, through the current line for the character immediately before .Aq Ar character . .Pp .It Cm u Undo the last change made to the file. If repeated, the .Cm u command alternates between these two states. The .Cm .\& command, when used immediately after .Cm u , causes the change log to be rolled forward or backward, depending on the action of the .Cm u command. .Pp .It Xo .Op Ar count .Cm w .Xc Move forward .Ar count words. .Pp .It Xo .Op Ar buffer .Op Ar count .Cm x .Xc Delete .Ar count characters at the current cursor position, but no more than there are till the end of the line. .Pp .It Xo .Op Ar buffer .Op Ar count .Cm y .Ar motion .Xc Copy .Pq or Dq yank a text region specified by .Ar count and .Ar motion into a buffer. .Pp .It Xo .Op Ar count1 .Cm z .Op Ar count2 .Cm type .Xc Redraw, optionally repositioning and resizing the screen. If .Ar count2 is specified, limit the screen size to .Ar count2 lines. The following .Cm type characters may be used: .Bl -tag -width Ds .It Cm + If .Ar count1 is specified, place the line .Ar count1 at the top of the screen. Otherwise, display the screen after the current screen. .It Aq Cm carriage-return Place the line .Ar count1 at the top of the screen. .It Cm .\& Place the line .Ar count1 in the center of the screen. .It Cm - Place the line .Ar count1 at the bottom of the screen. .It Cm \(ha If .Ar count1 is given, display the screen before the screen before .Ar count1 .Pq i.e., 2 screens before . Otherwise, display the screen before the current screen. .El .Pp .It Xo .Op Ar count .Cm {\& .Xc Move backward .Ar count paragraphs. .Pp .It Xo .Op Ar column .Cm |\& .Xc Move to a specific .Ar column position on the current line. If .Ar column is omitted, move to the start of the current line. .Pp .It Xo .Op Ar count .Cm }\& .Xc Move forward .Ar count paragraphs. .Pp .It Xo .Op Ar count .Cm \(ti .Ar motion .Xc If the .Cm tildeop option is not set, reverse the case of the next .Ar count character(s) and no .Ar motion can be specified. Otherwise .Ar motion is mandatory and .Cm \(ti reverses the case of the characters in a text region specified by the .Ar count and .Ar motion . .Pp .It Aq Cm interrupt Interrupt the current operation. The .Aq interrupt character is usually .Aq control-C . .El .Sh VI TEXT INPUT COMMANDS The following section describes the commands available in the text input mode of the .Nm vi editor. .Pp .Bl -tag -width Ds -compact .It Aq Cm nul Replay the previous input. .Pp .It Aq Cm control-D Erase to the previous .Ar shiftwidth column boundary. .Pp .It Cm \(ha Ns Aq Cm control-D Erase all of the autoindent characters, and reset the autoindent level. .Pp .It Cm 0 Ns Aq Cm control-D Erase all of the autoindent characters. .Pp .It Aq Cm control-T Insert sufficient .Aq tab and .Aq space characters to move forward to the next .Ar shiftwidth column boundary. If the .Cm expandtab option is set, only insert .Aq space characters. .Pp .It Aq Cm erase .It Aq Cm control-H Erase the last character. .Pp .It Aq Cm literal next Escape the next character from any special meaning. The .Aq literal\ \&next character is usually .Aq control-V . .Pp .It Aq Cm escape Resolve all text input into the file, and return to command mode. .Pp .It Aq Cm line erase Erase the current line. .Pp .It Aq Cm control-W .It Aq Cm word erase Erase the last word. The definition of word is dependent on the .Cm altwerase and .Cm ttywerase options. .Pp .Sm off .It Xo .Aq Cm control-X .Bq Cm 0-9A-Fa-f .Cm + .Xc .Sm on Insert a character with the specified hexadecimal value into the text. .Pp .It Aq Cm interrupt Interrupt text input mode, returning to command mode. The .Aq interrupt character is usually .Aq control-C . .El .Sh EX COMMANDS The following section describes the commands available in the .Nm ex editor. In each entry below, the tag line is a usage synopsis for the command. .Pp .Bl -tag -width Ds -compact .It Aq Cm end-of-file Scroll the screen. .Pp .It Cm !\& Ar argument(s) .It Xo .Op Ar range .Cm !\& .Ar argument(s) .Xc Execute a shell command, or filter lines through a shell command. .Pp .It Cm \&" A comment. .Pp .It Xo .Op Ar range .Cm nu Ns Op Cm mber .Op Ar count .Op Ar flags .Xc .It Xo .Op Ar range .Cm # .Op Ar count .Op Ar flags .Xc Display the selected lines, each preceded with its line number. .Pp .It Cm @ Ar buffer .It Cm * Ar buffer Execute a buffer. .Pp .It Xo .Op Ar range .Cm < Ns Op Cm < ... .Op Ar count .Op Ar flags .Xc Shift lines left. .Pp .It Xo .Op Ar line .Cm = .Op Ar flags .Xc Display the line number of .Ar line . If .Ar line is not specified, display the line number of the last line in the file. .Pp .It Xo .Op Ar range .Cm > Ns Op Cm > ... .Op Ar count .Op Ar flags .Xc Shift lines right. .Pp .It Xo .Cm ab Ns Op Cm breviate .Ar lhs rhs .Xc .Nm vi only. Add .Ar lhs as an abbreviation for .Ar rhs to the abbreviation list. .Pp .It Xo .Op Ar line .Cm a Ns Op Cm ppend Ns .Op Cm !\& .Xc The input text is appended after the specified line. .Pp .It Cm ar Ns Op Cm gs Display the argument list. .Pp .It Cm bg .Nm vi only. Background the current screen. .Pp .It Xo .Op Ar range .Cm c Ns Op Cm hange Ns .Op Cm !\& .Op Ar count .Xc The input text replaces the specified range. .Pp .It Xo .Cm chd Ns Op Cm ir Ns .Op Cm !\& .Op Ar directory .Xc .It Xo .Cm cd Ns Op Cm !\& .Op Ar directory .Xc Change the current working directory. .Pp .It Xo .Op Ar range .Cm co Ns Op Cm py .Ar line .Op Ar flags .Xc .It Xo .Op Ar range .Cm t .Ar line .Op Ar flags .Xc Copy the specified lines after the destination .Ar line . .Pp .It Xo .Cm cs Ns Op Cm cope .Cm add | find | help | kill | reset .Xc Execute a Cscope command. .Pp .It Xo .Op Ar range .Cm d Ns Op Cm elete .Op Ar buffer .Op Ar count .Op Ar flags .Xc Delete the lines from the file. .Pp .It Xo .Cm di Ns Op Cm splay .Cm b Ns Oo Cm uffers Oc | .Cm c Ns Oo Cm onnections Oc | .Cm s Ns Oo Cm creens Oc | .Cm t Ns Op Cm ags .Xc Display buffers, Cscope connections, screens or tags. .Pp .It Xo .Op Cm Ee Ns .Op Cm dit Ns .Op Cm !\& .Op Ar +cmd .Op Ar file .Xc .It Xo .Op Cm Ee Ns .Cm x Ns Op Cm !\& .Op Ar +cmd .Op Ar file .Xc -Edit a different file. The capitalized command opens a new screen below the -current screen. +Edit a different file. +The capitalized command opens a new screen below the current screen. .Pp .It Xo .Cm exu Ns Op Cm sage .Op Ar command .Xc Display usage for an .Nm ex command. .Pp .It Xo .Cm f Ns Op Cm ile .Op Ar file .Xc Display and optionally change the file name. .Pp .It Xo .Op Cm Ff Ns .Cm g .Op Ar name .Xc .Nm vi mode only. -Foreground the specified screen. The capitalized command opens a new screen -below the current screen. +Foreground the specified screen. +The capitalized command opens a new screen below the current screen. .Pp .It Xo .Op Ar range .Cm g Ns Op Cm lobal .No / Ns Ar pattern Ns / .Op Ar commands .Xc .It Xo .Op Ar range .Cm v .No / Ns Ar pattern Ns / .Op Ar commands .Xc Apply commands to lines matching .Pq Sq global or not matching .Pq Sq v a pattern. .Pp .It Cm he Ns Op Cm lp Display a help message. .Pp .It Xo .Op Ar line .Cm i Ns Op Cm nsert Ns .Op Cm !\& .Xc The input text is inserted before the specified line. .Pp .It Xo .Op Ar range .Cm j Ns Op Cm oin Ns .Op Cm !\& .Op Ar count .Op Ar flags .Xc Join lines of text together. .Pp .It Xo .Op Ar range .Cm l Ns Op Cm ist .Op Ar count .Op Ar flags .Xc Display the lines unambiguously. .Pp .It Xo .Cm map Ns Op Cm !\& .Op Ar lhs rhs .Xc Define or display maps .Pq for Nm vi No only . .Pp .It Xo .Op Ar line .Cm ma Ns Op Cm rk .Aq Ar character .Xc .It Xo .Op Ar line .Cm k Aq Ar character .Xc Mark the line with the mark .Aq Ar character . .Pp .It Xo .Op Ar range .Cm m Ns Op Cm ove .Ar line .Xc Move the specified lines after the target line. .Pp .It Xo .Cm mk Ns Op Cm exrc Ns .Op Cm !\& .Ar file .Xc Write the abbreviations, editor options and maps to the specified .Ar file . .Pp .It Xo .Op Cm Nn Ns .Op Cm ext Ns .Op Cm !\& .Op Ar .Xc -Edit the next file from the argument list. The capitalized command opens a -new screen below the current screen. +Edit the next file from the argument list. +The capitalized command opens a new screen below the current screen. .\" .Pp .\" .It Xo .\" .Op Ar line .\" .Cm o Ns Op Cm pen .\" .No / Ns Ar pattern Ns / .\" .Op Ar flags .\" .Xc .\" Enter open mode. .Pp .It Cm pre Ns Op Cm serve Save the file in a form that can later be recovered using the .Nm ex .Fl r option. .Pp .It Xo .Op Cm \&Pp Ns .Cm rev Ns Op Cm ious Ns .Op Cm !\& .Xc -Edit the previous file from the argument list. The capitalized command opens -a new screen below the current screen. +Edit the previous file from the argument list. +The capitalized command opens a new screen below the current screen. .Pp .It Xo .Op Ar range .Cm p Ns Op Cm rint .Op Ar count .Op Ar flags .Xc Display the specified lines. .Pp .It Xo .Op Ar line .Cm pu Ns Op Cm t .Op Ar buffer .Xc Append buffer contents to the current line. .Pp .It Xo .Cm q Ns Op Cm uit Ns .Op Cm !\& .Xc End the editing session. .Pp .It Xo .Op Ar line .Cm r Ns Op Cm ead Ns .Op Cm !\& .Op Ar file .Xc Read a file. .Pp .It Xo .Cm rec Ns Op Cm over .Ar file .Xc Recover .Ar file if it was previously saved. .Pp .It Xo .Cm res Ns Op Cm ize .Op Cm + Ns | Ns Cm - Ns .Ar size .Xc .Nm vi mode only. Grow or shrink the current screen. .Pp .It Xo .Cm rew Ns Op Cm ind Ns .Op Cm !\& .Xc Rewind the argument list. .Pp .It Xo .Cm se Ns Op Cm t .Sm off .Op option Oo = Oo value Oc Oc \ \&... .Sm on .Pf \ \& Op nooption ... .Op option? ... .Op Ar all .Xc Display or set editor options. .Pp .It Cm sh Ns Op Cm ell Run a shell program. .Pp .It Xo .Cm so Ns Op Cm urce .Ar file .Xc Read and execute .Nm ex commands from a file. .Pp .It Xo .Op Ar range .Cm s Ns Op Cm ubstitute .Sm off .Op / Ar pattern No / Ar replace No / .Sm on .Pf \ \& Op Ar options .Op Ar count .Op Ar flags .Xc .It Xo .Op Ar range .Cm & .Op Ar options .Op Ar count .Op Ar flags .Xc .It Xo .Op Ar range .Cm \(ti .Op Ar options .Op Ar count .Op Ar flags .Xc Make substitutions. The .Ar replace field may contain any of the following sequences: .Bl -tag -width Ds .It Sq \*(Am The text matched by .Ar pattern . .It Sq \(ti The replacement part of the previous .Cm substitute command. .It Sq % If this is the entire .Ar replace pattern, the replacement part of the previous .Cm substitute command. .It Sq \e Ns Ar \(sh Where .Sq Ar \(sh is an integer from 1 to 9, the text matched by the .Ar # Ns 'th subexpression in .Ar pattern . .It Sq \eL Causes the characters up to the end of the line of the next occurrence of .Sq \eE or .Sq \ee to be converted to lowercase. .It Sq \el Causes the next character to be converted to lowercase. .It Sq \eU Causes the characters up to the end of the line of the next occurrence of .Sq \eE or .Sq \ee to be converted to uppercase. .It Sq \eu Causes the next character to be converted to uppercase. .El .Pp .It Xo .Cm su Ns Op Cm spend Ns .Op Cm !\& .Xc .It Xo .Cm st Ns Op Cm op Ns .Op Cm !\& .Xc .It Aq Cm suspend Suspend the edit session. The .Aq suspend character is usually .Aq control-Z . .Pp .It Xo .Op Cm Tt Ns .Cm a Ns Op Cm g Ns .Op Cm !\& .Ar tagstring .Xc -Edit the file containing the specified tag. The capitalized command opens a -new screen below the current screen. +Edit the file containing the specified tag. +The capitalized command opens a new screen below the current screen. .Pp .It Xo .Cm tagn Ns Op Cm ext Ns .Op Cm !\& .Xc Edit the file containing the next context for the current tag. .Pp .It Xo .Cm tagp Ns Op Cm op Ns .Op Cm !\& .Op Ar file | number .Xc Pop to the specified tag in the tags stack. .Pp .It Xo .Cm tagpr Ns Op Cm ev Ns .Op Cm !\& .Xc Edit the file containing the previous context for the current tag. .Pp .It Xo .Cm tagt Ns Op Cm op Ns .Op Cm !\& .Xc Pop to the least recent tag on the tags stack, clearing the stack. .Pp .It Xo .Cm una Ns Op Cm bbreviate .Ar lhs .Xc .Nm vi only. Delete an abbreviation. .Pp .It Cm u Ns Op Cm ndo Undo the last change made to the file. .Pp .It Xo .Cm unm Ns Op Cm ap Ns .Op Cm !\& .Ar lhs .Xc Unmap a mapped string. .Pp .It Cm ve Ns Op Cm rsion Display the version of the .Nm ex Ns / Ns Nm vi editor. .Pp .It Xo .Op Ar line .Cm vi Ns Op Cm sual .Op Ar type .Op Ar count .Op Ar flags .Xc .Nm ex mode only. Enter .Nm vi . .Pp .It Xo .Cm Vi Ns .Op Cm sual Ns .Op Cm !\& .Op Ar +cmd .Op Ar file .Xc .Nm vi -mode only. Edit a different file by opening a new screen below the current -screen. +mode only. +Edit a different file by opening a new screen below the current screen. .Pp .It Xo .Cm viu Ns Op Cm sage .Op Ar command .Xc Display usage for a .Nm vi command. .Pp .It Xo .Cm vs Ns Op Cm plit .Op Ar +cmd .Op Ar file .Xc Edit a different file by opening a new screen to the right of the current screen. .Pp .It Xo .Op Ar range .Cm w Ns Op Cm rite Ns .Op Cm !\& .Op >> .Op Ar file .Xc .It Xo .Op Ar range .Cm w Ns Op Cm rite .Cm !\& Ns Ar shell-command .Xc .It Xo .Op Ar range .Cm wn Ns Op Cm !\& .Op >> .Op Ar file .Xc .It Xo .Op Ar range .Cm wq Ns Op Cm !\& .Op >> .Op Ar file .Xc Write the entire file, or .Ar range . .Sq !\& overwrites a different, preexisting file. .Sq >> -appends to a file that may preexist. Whitespace followed by +appends to a file that may preexist. +Whitespace followed by .Sq !\& pipes the file to .Ar shell-command . .Cm wn moves to the next file if writing succeeds. .Cm wq exits the editor if writing succeeds, unless there are more files to edit; .Sq !\& exits regardless. .Pp .It Xo .Op Ar range .Cm x Ns Op Cm it Ns .Op Cm !\& .Op Ar file .Xc Exit the editor, writing the file if it has been modified. .Pp .It Xo .Op Ar range .Cm ya Ns Op Cm nk .Op Ar buffer .Op Ar count .Xc Copy the specified lines to a buffer. .Pp .It Xo .Op Ar line .Cm z .Op Ar type .Op Ar count .Op Ar flags .Xc Adjust the window. .El .Sh SET OPTIONS There are a large number of options that may be set .Pq or unset to change the editor's behavior. This section describes the options, their abbreviations and their default values. .Pp In each entry below, the first part of the tag line is the full name of the option, followed by any equivalent abbreviations. The part in square brackets is the default value of the option. Most of the options are boolean, i.e., they are either on or off, and do not have an associated value. .Pp Options apply to both .Nm ex and .Nm vi modes, unless otherwise specified. .Bl -tag -width Ds .It Cm altnotation Bq off Display control characters less than 0x20 in notations. Carriage feed, escape, and delete are marked as , , and , respectively. .It Cm altwerase Bq off .Nm vi only. Select an alternate word erase algorithm. .It Cm autoindent , ai Bq off Automatically indent new lines. .It Cm autoprint , ap Bq on .Nm ex only. Display the current line automatically. .It Cm autowrite , aw Bq off Write modified files automatically when changing files or suspending the editor session. .It Cm backup Bq \&"\&" Back up files before they are overwritten. .It Cm beautify , bf Bq off Discard control characters. .It Cm cdpath Bo environment variable Ev CDPATH , or current directory Bc The directory paths used as path prefixes for the .Cm cd command. .It Cm cedit Bq no default Set the character to edit the colon command-line history. .It Cm columns , co Bq 80 Set the number of columns in the screen. .It Cm comment Bq off .Nm vi only. Skip leading comments in shell, C and C++ language files. .It Cm directory , dir Bo environment variable Ev TMPDIR , or Pa /tmp Bc The directory where temporary files are created. .It Cm edcompatible , ed Bq off Remember the values of the .Sq c and .Sq g suffixes to the .Cm substitute commands, instead of initializing them as unset for each new command. .It Cm errorbells , eb Bq off .Nm ex only. Announce error messages with a bell. .It Cm escapetime Bq 1 The tenths of a second .Nm ex Ns / Ns Nm vi waits for a subsequent key to complete an .Aq escape key mapping. .It Cm expandtab , et Bq off Expand .Aq tab characters to .Aq space when inserting, replacing or shifting text, autoindenting, indenting with .Aq Ic control-T , outdenting with .Aq Ic control-D , or when filtering lines with the .Cm !\& command. .It Cm exrc , ex Bq off Read the startup files in the local directory. .It Cm extended Bq off Use extended regular expressions .Pq EREs rather than basic regular expressions .Pq BREs . See .Xr re_format 7 for more information on regular expressions. .It Cm filec Bq Aq tab Set the character to perform file path completion on the colon command line. .It Cm fileencoding , fe Bq auto detect Set the encoding of the current file. .It Cm flash Bq on Flash the screen instead of beeping the keyboard on error. .It Cm hardtabs, ht Bq 0 Set the spacing between hardware tab settings. This option currently has no effect. .It Cm iclower Bq off Makes all regular expressions case-insensitive, as long as an upper-case letter does not appear in the search string. .It Cm ignorecase , ic Bq off Ignore case differences in regular expressions. .It Cm inputencoding , ie Bq locale Set the encoding of your input characters. .It Cm keytime Bq 6 The tenths of a second .Nm ex Ns / Ns Nm vi waits for a subsequent key to complete a key mapping. .It Cm leftright Bq off .Nm vi only. Do left-right scrolling. .It Cm lines , li Bq 24 .Nm vi only. Set the number of lines in the screen. .It Cm lisp Bq off .Nm vi only. Modify various search commands and options to work with Lisp. This option is not yet implemented. .It Cm list Bq off Display lines in an unambiguous fashion. .It Cm lock Bq on Attempt to get an exclusive lock on any file being edited, read or written. .It Cm magic Bq on When turned off, all regular expression characters except for .Sq \(ha and .Sq \(Do are treated as ordinary characters. Preceding individual characters by .Sq \e re-enables them. .It Cm matchchars Bq []{}() Character pairs looked for by the .Cm % command. .It Cm matchtime Bq 7 .Nm vi only. The tenths of a second .Nm ex Ns / Ns Nm vi pauses on the matching character when the .Cm showmatch option is set. .It Cm mesg Bq on Permit messages from other users. .It Cm msgcat Bq /usr/share/vi/catalog/ Selects a message catalog to be used to display error and informational messages in a specified language. .It Cm modelines , modeline Bq off Read the first and last few lines of each file for .Nm ex commands. This option will never be implemented. .It Cm noprint Bq \&"\&" Characters that are never handled as printable characters. .It Cm number , nu Bq off Precede each line displayed with its current line number. .It Cm octal Bq off Display unknown characters as octal numbers, instead of the default hexadecimal. .It Cm open Bq on .Nm ex only. If this option is not set, the .Cm open and .Cm visual commands are disallowed. .It Cm optimize , opt Bq on .Nm vi only. Optimize text throughput to dumb terminals. This option is not yet implemented. .It Cm paragraphs , para Bq "IPLPPPQPP LIpplpipbp" .Nm vi only. Define additional paragraph boundaries for the .Cm {\& and .Cm }\& commands. .It Cm path Bq \&"\&" Define additional directories to search for files being edited. .It Cm print Bq \&"\&" Characters that are always handled as printable characters. .It Cm prompt Bq on .Nm ex only. Display a command prompt. .It Cm readonly , ro Bq off Mark the file and session as read-only. .It Cm recdir Bq /var/tmp/vi.recover The directory where recovery files are stored. .It Cm redraw , re Bq off .Nm vi only. Simulate an intelligent terminal on a dumb one. This option is not yet implemented. .It Cm remap Bq on Remap keys until resolved. .It Cm report Bq 5 Set the number of lines about which the editor reports changes or yanks. .It Cm ruler Bq off .Nm vi only. -Display a row/column ruler on the colon command line. +Display a row/column/percentage ruler on the colon command line. .It Cm scroll , scr Bq "window size / 2" Set the number of lines scrolled. .It Cm searchincr Bq off Makes the .Cm / and .Cm ?\& commands incremental. .It Cm sections , sect Bq "NHSHH HUnhsh" .Nm vi only. Define additional section boundaries for the .Cm [[ and .Cm ]] commands. .It Cm secure Bq off Turns off all access to external programs. .It Cm shell , sh Bo environment variable Ev SHELL , or Pa /bin/sh Bc Select the shell used by the editor. .It Cm shellmeta Bq \(ti{[*?$\`\(aq\&"\e Set the meta characters checked to determine if file name expansion is necessary. .It Cm shiftwidth , sw Bq 8 Set the autoindent and shift command indentation width. +.It Cm showfilename Bq off +.Nm vi +only. +Display the file name on the colon command line. .It Cm showmatch , sm Bq off .Nm vi only. Note the left matching characters when the right ones are inserted. .It Cm showmode , smd Bq off .Nm vi only. Display the current editor mode and a .Dq modified flag. .It Cm sidescroll Bq 16 .Nm vi only. Set the amount a left-right scroll will shift. .It Cm slowopen , slow Bq off Delay display updating during text input. This option is not yet implemented. .It Cm sourceany Bq off Read startup files not owned by the current user. This option will never be implemented. .It Cm tabstop , ts Bq 8 This option sets tab widths for the editor display. .It Cm taglength , tl Bq 0 Set the number of significant characters in tag names. .It Cm tags , tag Bq tags Set the list of tags files. .It Xo .Cm term , ttytype , tty .Bq environment variable Ev TERM .Xc Set the terminal type. .It Cm terse Bq off This option has historically made editor messages less verbose. It has no effect in this implementation. .It Cm tildeop Bq off Modify the .Cm \(ti command to take an associated motion. .It Cm timeout , to Bq on Time out on keys which may be mapped. .It Cm ttywerase Bq off .Nm vi only. Select an alternate erase algorithm. .It Cm verbose Bq off .Nm vi only. Display an error message for every error. .It Cm w300 Bq no default .Nm vi only. Set the window size if the baud rate is less than 1200 baud. .It Cm w1200 Bq no default .Nm vi only. Set the window size if the baud rate is equal to 1200 baud. .It Cm w9600 Bq no default .Nm vi only. Set the window size if the baud rate is greater than 1200 baud. .It Cm warn Bq on .Nm ex only. This option causes a warning message to be printed on the terminal if the file has been modified since it was last written, before a .Cm !\& command. .It Xo .Cm window , w , wi .Bq environment variable Ev LINES No \(mi 1 .Xc Set the window size for the screen. .It Cm windowname Bq off Change the icon/window name to the current file name. .It Cm wraplen , wl Bq 0 .Nm vi only. Break lines automatically, the specified number of columns from the left-hand margin. If both the .Cm wraplen and .Cm wrapmargin edit options are set, the .Cm wrapmargin value is used. .It Cm wrapmargin , wm Bq 0 .Nm vi only. Break lines automatically, the specified number of columns from the right-hand margin. If both the .Cm wraplen and .Cm wrapmargin edit options are set, the .Cm wrapmargin value is used. .It Cm wrapscan , ws Bq on Set searches to wrap around the end or beginning of the file. .It Cm writeany , wa Bq off Turn off file-overwriting checks. .El .Sh ENVIRONMENT .Bl -tag -width "COLUMNS" .It Ev COLUMNS The number of columns on the screen. This value overrides any system or terminal specific values. If the .Ev COLUMNS environment variable is not set when .Nm ex Ns / Ns Nm vi runs, or the .Cm columns option is explicitly reset by the user, .Nm ex Ns / Ns Nm vi enters the value into the environment. .It Ev EXINIT A list of .Nm ex startup commands, read after .Pa /etc/vi.exrc unless the variable .Ev NEXINIT is also set. .It Ev HOME The user's home directory, used as the initial directory path for the startup .Pa $HOME/.nexrc and .Pa $HOME/.exrc files. This value is also used as the default directory for the .Cm cd command. .It Ev LINES The number of rows on the screen. This value overrides any system or terminal specific values. If the .Ev LINES environment variable is not set when .Nm ex Ns / Ns Nm vi runs, or the .Cm lines option is explicitly reset by the user, .Nm ex Ns / Ns Nm vi enters the value into the environment. .It Ev NEXINIT A list of .Nm ex startup commands, read after .Pa /etc/vi.exrc . .It Ev SHELL The user's shell of choice .Pq see also the Cm shell No option . .It Ev TERM The user's terminal type. The default is the type .Dq unknown . If the .Ev TERM environment variable is not set when .Nm ex Ns / Ns Nm vi runs, or the .Cm term option is explicitly reset by the user, .Nm ex Ns / Ns Nm vi enters the value into the environment. .It Ev TMPDIR The location used to store temporary files .Pq see also the Cm directory No edit option . .El .Sh ASYNCHRONOUS EVENTS .Bl -tag -width "SIGWINCH" -compact .It Dv SIGALRM .Nm vi Ns / Ns Nm ex uses this signal for periodic backups of file modifications and to display .Dq busy messages when operations are likely to take a long time. .Pp .It Dv SIGHUP .It Dv SIGTERM If the current buffer has changed since it was last written in its entirety, the editor attempts to save the modified file so it can be later recovered. See the .Nm vi Ns / Ns Nm ex reference manual section .Sx Recovery for more information. .Pp .It Dv SIGINT When an interrupt occurs, the current operation is halted and the editor returns to the command level. If interrupted during text input, the text already input is resolved into the file as if the text input had been normally terminated. .Pp .It Dv SIGWINCH The screen is resized. See the .Nm vi Ns / Ns Nm ex reference manual section .Sx Sizing the Screen for more information. .\" .Pp .\" .It Dv SIGCONT .\" .It Dv SIGTSTP .\" .Nm vi Ns / Ns Nm ex .\" ignores these signals. .El .Sh FILES .Bl -tag -width "/var/tmp/vi.recover" .It Pa /bin/sh The default user shell. .It Pa /etc/vi.exrc System-wide .Nm vi startup file. It is read for .Nm ex commands first in the startup sequence. Must be owned by root or the user, and writable only by the owner. .It Pa /tmp Temporary file directory. .It Pa /var/tmp/vi.recover The default recovery file directory. .It Pa $HOME/.nexrc First choice for user's home directory startup file, read for .Nm ex commands right after .Pa /etc/vi.exrc unless either .Ev NEXINIT or .Ev EXINIT are set. Must be owned by root or the user, and writable only by the owner. .It Pa $HOME/.exrc Second choice for user's home directory startup file, read for .Nm ex commands under the same conditions as .Pa $HOME/.nexrc . .It Pa .nexrc First choice for local directory startup file, read for .Nm ex commands at the end of the startup sequence if the .Cm exrc option was turned on earlier. Must be owned by the user and writable only by the owner. .It Pa .exrc Second choice for local directory startup file, read for .Nm ex commands under the same conditions as .Pa .nexrc . .El .Sh EXIT STATUS The .Nm ex and .Nm vi utilities exit 0 on success, and \*(Gt0 if an error occurs. .Sh SEE ALSO .Xr ctags 1 , .Xr iconv 1 , .Xr re_format 7 -.Rs -.%T vi/ex reference manual -.%U https://docs.freebsd.org/44doc/usd/13.viref/paper.pdf -.Re +.Pp +.Lk https://docs.freebsd.org/44doc/usd/13.viref/paper.pdf "Vi/Ex Reference Manual" .Sh STANDARDS .Nm nex Ns / Ns Nm nvi is close to .St -p1003.1-2008 . That document differs from historical .Nm ex Ns / Ns Nm vi practice in several places; there are changes to be made on both sides. .Sh HISTORY The .Nm ex editor first appeared in .Bx 1 . The .Nm nex Ns / Ns Nm nvi replacements for the .Nm ex Ns / Ns Nm vi editor first appeared in .Bx 4.4 . .Sh AUTHORS .An Bill Joy wrote the original version of .Nm ex in 1977. diff --git a/vi/vs_refresh.c b/vi/vs_refresh.c index b64ec7392cbb..406a89ad7d9d 100644 --- a/vi/vs_refresh.c +++ b/vi/vs_refresh.c @@ -1,886 +1,893 @@ /*- * Copyright (c) 1992, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 1992, 1993, 1994, 1995, 1996 * Keith Bostic. All rights reserved. * * See the LICENSE file for redistribution information. */ #include "config.h" #include #include #include #include #include #include #include #include #include #include #include "../common/common.h" #include "vi.h" #define UPDATE_CURSOR 0x01 /* Update the cursor. */ #define UPDATE_SCREEN 0x02 /* Flush to screen. */ static void vs_modeline(SCR *); static int vs_paint(SCR *, u_int); /* * v_repaint -- * Repaint selected lines from the screen. * * PUBLIC: int vs_repaint(SCR *, EVENT *); */ int vs_repaint( SCR *sp, EVENT *evp) { SMAP *smp; for (; evp->e_flno <= evp->e_tlno; ++evp->e_flno) { smp = HMAP + evp->e_flno - 1; SMAP_FLUSH(smp); if (vs_line(sp, smp, NULL, NULL)) return (1); } return (0); } /* * vs_refresh -- * Refresh all screens. * * PUBLIC: int vs_refresh(SCR *, int); */ int vs_refresh( SCR *sp, int forcepaint) { GS *gp; SCR *tsp; int need_refresh = 0; u_int priv_paint, pub_paint; gp = sp->gp; /* * 1: Refresh the screen. * * If SC_SCR_REDRAW is set in the current screen, repaint everything * that we can find, including status lines. */ if (F_ISSET(sp, SC_SCR_REDRAW)) TAILQ_FOREACH(tsp, gp->dq, q) if (tsp != sp) F_SET(tsp, SC_SCR_REDRAW | SC_STATUS); /* * 2: Related or dirtied screens, or screens with messages. * * If related screens share a view into a file, they may have been * modified as well. Refresh any screens that aren't exiting that * have paint or dirty bits set. Always update their screens, we * are not likely to get another chance. Finally, if we refresh any * screens other than the current one, the cursor will be trashed. */ pub_paint = SC_SCR_REFORMAT | SC_SCR_REDRAW; priv_paint = VIP_CUR_INVALID | VIP_N_REFRESH; if (O_ISSET(sp, O_NUMBER)) priv_paint |= VIP_N_RENUMBER; TAILQ_FOREACH(tsp, gp->dq, q) if (tsp != sp && !F_ISSET(tsp, SC_EXIT | SC_EXIT_FORCE) && (F_ISSET(tsp, pub_paint) || F_ISSET(VIP(tsp), priv_paint))) { (void)vs_paint(tsp, (F_ISSET(VIP(tsp), VIP_CUR_INVALID) ? UPDATE_CURSOR : 0) | UPDATE_SCREEN); F_SET(VIP(sp), VIP_CUR_INVALID); } /* * 3: Refresh the current screen. * * Always refresh the current screen, it may be a cursor movement. * Also, always do it last -- that way, SC_SCR_REDRAW can be set * in the current screen only, and the screen won't flash. */ if (vs_paint(sp, UPDATE_CURSOR | (!forcepaint && F_ISSET(sp, SC_SCR_VI) && KEYS_WAITING(sp) ? 0 : UPDATE_SCREEN))) return (1); /* * 4: Paint any missing status lines. * * XXX * This is fairly evil. Status lines are written using the vi message * mechanism, since we have no idea how long they are. Since we may be * painting screens other than the current one, we don't want to make * the user wait. We depend heavily on there not being any other lines * currently waiting to be displayed and the message truncation code in * the msgq_status routine working. * * And, finally, if we updated any status lines, make sure the cursor * gets back to where it belongs. */ TAILQ_FOREACH(tsp, gp->dq, q) if (F_ISSET(tsp, SC_STATUS)) { need_refresh = 1; vs_resolve(tsp, sp, 0); } if (need_refresh) (void)gp->scr_refresh(sp, 0); /* * A side-effect of refreshing the screen is that it's now ready * for everything else, i.e. messages. */ F_SET(sp, SC_SCR_VI); return (0); } /* * vs_paint -- * This is the guts of the vi curses screen code. The idea is that * the SCR structure passed in contains the new coordinates of the * screen. What makes this hard is that we don't know how big * characters are, doing input can put the cursor in illegal places, * and we're frantically trying to avoid repainting unless it's * absolutely necessary. If you change this code, you'd better know * what you're doing. It's subtle and quick to anger. */ static int vs_paint( SCR *sp, u_int flags) { GS *gp; SMAP *smp, tmp; VI_PRIVATE *vip; recno_t lastline, lcnt; size_t cwtotal, cnt, len, notused, off, y; int ch = 0, didpaint, isempty, leftright_warp; CHAR_T *p; #define LNO sp->lno /* Current file line. */ #define OLNO vip->olno /* Remembered file line. */ #define CNO sp->cno /* Current file column. */ #define OCNO vip->ocno /* Remembered file column. */ #define SCNO vip->sc_col /* Current screen column. */ gp = sp->gp; vip = VIP(sp); didpaint = leftright_warp = 0; /* * 5: Reformat the lines. * * If the lines themselves have changed (:set list, for example), * fill in the map from scratch. Adjust the screen that's being * displayed if the leftright flag is set. */ if (F_ISSET(sp, SC_SCR_REFORMAT)) { /* Invalidate the line size cache. */ VI_SCR_CFLUSH(vip); /* Toss vs_line() cached information. */ if (F_ISSET(sp, SC_SCR_TOP)) { if (vs_sm_fill(sp, LNO, P_TOP)) return (1); } else if (F_ISSET(sp, SC_SCR_CENTER)) { if (vs_sm_fill(sp, LNO, P_MIDDLE)) return (1); } else if (vs_sm_fill(sp, OOBLNO, P_TOP)) return (1); F_SET(sp, SC_SCR_REDRAW); } /* * 6: Line movement. * * Line changes can cause the top line to change as well. As * before, if the movement is large, the screen is repainted. * * 6a: Small screens. * * Users can use the window, w300, w1200 and w9600 options to make * the screen artificially small. The behavior of these options * in the historic vi wasn't all that consistent, and, in fact, it * was never documented how various screen movements affected the * screen size. Generally, one of three things would happen: * 1: The screen would expand in size, showing the line * 2: The screen would scroll, showing the line * 3: The screen would compress to its smallest size and * repaint. * In general, scrolling didn't cause compression (200^D was handled * the same as ^D), movement to a specific line would (:N where N * was 1 line below the screen caused a screen compress), and cursor * movement would scroll if it was 11 lines or less, and compress if * it was more than 11 lines. (And, no, I have no idea where the 11 * comes from.) * * What we do is try and figure out if the line is less than half of * a full screen away. If it is, we expand the screen if there's * room, and then scroll as necessary. The alternative is to compress * and repaint. * * !!! * This code is a special case from beginning to end. Unfortunately, * home modems are still slow enough that it's worth having. * * XXX * If the line a really long one, i.e. part of the line is on the * screen but the column offset is not, we'll end up in the adjust * code, when we should probably have compressed the screen. */ if (IS_SMALL(sp)) { if (LNO < HMAP->lno) { lcnt = vs_sm_nlines(sp, HMAP, LNO, sp->t_maxrows); if (lcnt <= HALFSCREEN(sp)) for (; lcnt && sp->t_rows != sp->t_maxrows; --lcnt, ++sp->t_rows) { ++TMAP; if (vs_sm_1down(sp)) return (1); } else goto small_fill; } else if (LNO > TMAP->lno) { lcnt = vs_sm_nlines(sp, TMAP, LNO, sp->t_maxrows); if (lcnt <= HALFSCREEN(sp)) for (; lcnt && sp->t_rows != sp->t_maxrows; --lcnt, ++sp->t_rows) { if (vs_sm_next(sp, TMAP, TMAP + 1)) return (1); ++TMAP; if (vs_line(sp, TMAP, NULL, NULL)) return (1); } else { small_fill: (void)gp->scr_move(sp, LASTLINE(sp), 0); (void)gp->scr_clrtoeol(sp); for (; sp->t_rows > sp->t_minrows; --sp->t_rows, --TMAP) { (void)gp->scr_move(sp, TMAP - HMAP, 0); (void)gp->scr_clrtoeol(sp); } if (vs_sm_fill(sp, LNO, P_FILL)) return (1); F_SET(sp, SC_SCR_REDRAW); goto adjust; } } } /* * 6b: Line down, or current screen. */ if (LNO >= HMAP->lno) { /* Current screen. */ if (LNO <= TMAP->lno) goto adjust; if (F_ISSET(sp, SC_SCR_TOP)) goto top; if (F_ISSET(sp, SC_SCR_CENTER)) goto middle; /* * If less than half a screen above the line, scroll down * until the line is on the screen. */ lcnt = vs_sm_nlines(sp, TMAP, LNO, HALFTEXT(sp)); if (lcnt < HALFTEXT(sp)) { while (lcnt--) if (vs_sm_1up(sp)) return (1); goto adjust; } goto bottom; } /* * 6c: If not on the current screen, may request center or top. */ if (F_ISSET(sp, SC_SCR_TOP)) goto top; if (F_ISSET(sp, SC_SCR_CENTER)) goto middle; /* * 6d: Line up. */ lcnt = vs_sm_nlines(sp, HMAP, LNO, HALFTEXT(sp)); if (lcnt < HALFTEXT(sp)) { /* * If less than half a screen below the line, scroll up until * the line is the first line on the screen. Special check so * that if the screen has been emptied, we refill it. */ if (db_exist(sp, HMAP->lno)) { while (lcnt--) if (vs_sm_1down(sp)) return (1); goto adjust; } else goto top; /* XXX No such line. */ /* * If less than a half screen from the bottom of the file, * put the last line of the file on the bottom of the screen. */ bottom: if (db_last(sp, &lastline)) return (1); tmp.lno = LNO; tmp.coff = HMAP->coff; tmp.soff = 1; lcnt = vs_sm_nlines(sp, &tmp, lastline, sp->t_rows); if (lcnt < HALFTEXT(sp)) { if (vs_sm_fill(sp, lastline, P_BOTTOM)) return (1); F_SET(sp, SC_SCR_REDRAW); goto adjust; } /* It's not close, just put the line in the middle. */ goto middle; } /* * If less than half a screen from the top of the file, put the first * line of the file at the top of the screen. Otherwise, put the line * in the middle of the screen. */ tmp.lno = 1; tmp.coff = HMAP->coff; tmp.soff = 1; lcnt = vs_sm_nlines(sp, &tmp, LNO, HALFTEXT(sp)); if (lcnt < HALFTEXT(sp)) { if (vs_sm_fill(sp, 1, P_TOP)) return (1); } else middle: if (vs_sm_fill(sp, LNO, P_MIDDLE)) return (1); if (0) { top: if (vs_sm_fill(sp, LNO, P_TOP)) return (1); } F_SET(sp, SC_SCR_REDRAW); /* * At this point we know part of the line is on the screen. Since * scrolling is done using logical lines, not physical, all of the * line may not be on the screen. While that's not necessarily bad, * if the part the cursor is on isn't there, we're going to lose. * This can be tricky; if the line covers the entire screen, lno * may be the same as both ends of the map, that's why we test BOTH * the top and the bottom of the map. This isn't a problem for * left-right scrolling, the cursor movement code handles the problem. * * There's a performance issue here if editing *really* long lines. * This gets to the right spot by scrolling, and, in a binary, by * scrolling hundreds of lines. If the adjustment looks like it's * going to be a serious problem, refill the screen and repaint. */ adjust: if (!O_ISSET(sp, O_LEFTRIGHT) && (LNO == HMAP->lno || LNO == TMAP->lno)) { cnt = vs_screens(sp, LNO, &CNO); if (LNO == HMAP->lno && cnt < HMAP->soff) { if ((HMAP->soff - cnt) > HALFTEXT(sp)) { HMAP->soff = cnt; vs_sm_fill(sp, OOBLNO, P_TOP); F_SET(sp, SC_SCR_REDRAW); } else while (cnt < HMAP->soff) if (vs_sm_1down(sp)) return (1); } if (LNO == TMAP->lno && cnt > TMAP->soff) { if ((cnt - TMAP->soff) > HALFTEXT(sp)) { TMAP->soff = cnt; vs_sm_fill(sp, OOBLNO, P_BOTTOM); F_SET(sp, SC_SCR_REDRAW); } else while (cnt > TMAP->soff) if (vs_sm_1up(sp)) return (1); } } /* * If the screen needs to be repainted, skip cursor optimization. * However, in the code above we skipped leftright scrolling on * the grounds that the cursor code would handle it. Make sure * the right screen is up. */ if (F_ISSET(sp, SC_SCR_REDRAW)) { if (O_ISSET(sp, O_LEFTRIGHT)) goto slow; goto paint; } /* * 7: Cursor movements (current screen only). */ if (!LF_ISSET(UPDATE_CURSOR)) goto number; /* * Decide cursor position. If the line has changed, the cursor has * moved over a tab, or don't know where the cursor was, reparse the * line. Otherwise, we've just moved over fixed-width characters, * and can calculate the left/right scrolling and cursor movement * without reparsing the line. Note that we don't know which (if any) * of the characters between the old and new cursor positions changed. * * XXX * With some work, it should be possible to handle tabs quickly, at * least in obvious situations, like moving right and encountering * a tab, without reparsing the whole line. * * If the line we're working with has changed, reread it.. */ if (F_ISSET(vip, VIP_CUR_INVALID) || LNO != OLNO) goto slow; /* Otherwise, if nothing's changed, ignore the cursor. */ if (CNO == OCNO) goto fast; /* * Get the current line. If this fails, we either have an empty * file and can just repaint, or there's a real problem. This * isn't a performance issue because there aren't any ways to get * here repeatedly. */ if (db_eget(sp, LNO, &p, &len, &isempty)) { if (isempty) goto slow; return (1); } #ifdef DEBUG /* Sanity checking. */ if (CNO >= len && len != 0) { msgq(sp, M_ERR, "Error: %s/%d: cno (%zu) >= len (%zu)", basename(__FILE__), __LINE__, CNO, len); return (1); } #endif /* * The basic scheme here is to look at the characters in between * the old and new positions and decide how big they are on the * screen, and therefore, how many screen positions to move. */ if (CNO < OCNO) { /* * 7a: Cursor moved left. * * Point to the old character. The old cursor position can * be past EOL if, for example, we just deleted the rest of * the line. In this case, since we don't know the width of * the characters we traversed, we have to do it slowly. */ p += OCNO; cnt = (OCNO - CNO) + 1; if (OCNO >= len) goto slow; /* * Quick sanity check -- it's hard to figure out exactly when * we cross a screen boundary as we do in the cursor right * movement. If cnt is so large that we're going to cross the * boundary no matter what, stop now. */ if (SCNO + 1 + MAX_CHARACTER_COLUMNS < cnt) goto slow; /* * Count up the widths of the characters. If it's a tab * character, go do it the slow way. */ for (cwtotal = 0; cnt--; cwtotal += KEY_COL(sp, ch)) if ((ch = *(UCHAR_T *)p--) == '\t') goto slow; /* * Decrement the screen cursor by the total width of the * characters minus 1. */ cwtotal -= 1; /* * If we're moving left, and there's a wide character in the * current position, go to the end of the character. */ if (KEY_COL(sp, ch) > 1) cwtotal -= KEY_COL(sp, ch) - 1; /* * If the new column moved us off of the current logical line, * calculate a new one. If doing leftright scrolling, we've * moved off of the current screen, as well. */ if (SCNO < cwtotal) goto slow; SCNO -= cwtotal; } else { /* * 7b: Cursor moved right. * * Point to the first character to the right. */ p += OCNO + 1; cnt = CNO - OCNO; /* * Count up the widths of the characters. If it's a tab * character, go do it the slow way. If we cross a * screen boundary, we can quit. */ for (cwtotal = SCNO; cnt--;) { if ((ch = *(UCHAR_T *)p++) == '\t') goto slow; if ((cwtotal += KEY_COL(sp, ch)) >= SCREEN_COLS(sp)) break; } /* * Increment the screen cursor by the total width of the * characters. */ SCNO = cwtotal; /* See screen change comment in section 6a. */ if (SCNO >= SCREEN_COLS(sp)) goto slow; } /* * 7c: Fast cursor update. * * We have the current column, retrieve the current row. */ fast: (void)gp->scr_cursor(sp, &y, ¬used); goto done_cursor; /* * 7d: Slow cursor update. * * Walk through the map and find the current line. */ slow: for (smp = HMAP; smp->lno != LNO; ++smp); /* * 7e: Leftright scrolling adjustment. * * If doing left-right scrolling and the cursor movement has changed * the displayed screen, scroll the screen left or right, unless we're * updating the info line in which case we just scroll that one line. * We adjust the offset up or down until we have a window that covers * the current column, making sure that we adjust differently for the * first screen as compared to subsequent ones. */ if (O_ISSET(sp, O_LEFTRIGHT)) { /* * Get the screen column for this character, and correct * for the number option offset. */ cnt = vs_columns(sp, NULL, LNO, &CNO, NULL); if (O_ISSET(sp, O_NUMBER)) cnt -= O_NUMBER_LENGTH; /* Adjust the window towards the beginning of the line. */ off = smp->coff; if (off >= cnt) { do { if (off >= O_VAL(sp, O_SIDESCROLL)) off -= O_VAL(sp, O_SIDESCROLL); else { off = 0; break; } } while (off >= cnt); goto shifted; } /* Adjust the window towards the end of the line. */ if ((off == 0 && off + SCREEN_COLS(sp) < cnt) || (off != 0 && off + sp->cols < cnt)) { do { off += O_VAL(sp, O_SIDESCROLL); } while (off + sp->cols < cnt); shifted: /* Fill in screen map with the new offset. */ if (F_ISSET(sp, SC_TINPUT_INFO)) smp->coff = off; else { for (smp = HMAP; smp <= TMAP; ++smp) smp->coff = off; leftright_warp = 1; } goto paint; } /* * We may have jumped here to adjust a leftright screen because * redraw was set. If so, we have to paint the entire screen. */ if (F_ISSET(sp, SC_SCR_REDRAW)) goto paint; } /* * Update the screen lines for this particular file line until we * have a new screen cursor position. */ for (y = -1, vip->sc_smap = NULL; smp <= TMAP && smp->lno == LNO; ++smp) { if (vs_line(sp, smp, &y, &SCNO)) return (1); if (y != -1) { vip->sc_smap = smp; break; } } goto done_cursor; /* * 8: Repaint the entire screen. * * Lost big, do what you have to do. We flush the cache, since * SC_SCR_REDRAW gets set when the screen isn't worth fixing, and * it's simpler to repaint. So, don't trust anything that we * think we know about it. */ paint: for (smp = HMAP; smp <= TMAP; ++smp) SMAP_FLUSH(smp); for (y = -1, vip->sc_smap = NULL, smp = HMAP; smp <= TMAP; ++smp) { if (vs_line(sp, smp, &y, &SCNO)) return (1); if (y != -1 && vip->sc_smap == NULL) vip->sc_smap = smp; } /* * If it's a small screen and we're redrawing, clear the unused lines, * ex may have overwritten them. */ if (F_ISSET(sp, SC_SCR_REDRAW) && IS_SMALL(sp)) for (cnt = sp->t_rows; cnt <= sp->t_maxrows; ++cnt) { (void)gp->scr_move(sp, cnt, 0); (void)gp->scr_clrtoeol(sp); } didpaint = 1; done_cursor: /* * Sanity checking. When the repainting code messes up, the usual * result is we don't repaint the cursor and so sc_smap will be * NULL. If we're debugging, die, otherwise restart from scratch. */ #ifdef DEBUG if (vip->sc_smap == NULL) abort(); #else if (vip->sc_smap == NULL) { F_SET(sp, SC_SCR_REFORMAT); return (vs_paint(sp, flags)); } #endif /* * 9: Set the remembered cursor values. */ OCNO = CNO; OLNO = LNO; /* * 10: Repaint the line numbers. * * If O_NUMBER is set and the VIP_N_RENUMBER bit is set, and we * didn't repaint the screen, repaint all of the line numbers, * they've changed. */ number: if (O_ISSET(sp, O_NUMBER) && F_ISSET(vip, VIP_N_RENUMBER) && !didpaint && vs_number(sp)) return (1); /* * 11: Update the mode line, position the cursor, and flush changes. * * If we warped the screen, we have to refresh everything. */ if (leftright_warp) LF_SET(UPDATE_CURSOR | UPDATE_SCREEN); if (LF_ISSET(UPDATE_SCREEN) && !IS_ONELINE(sp) && !F_ISSET(vip, VIP_S_MODELINE) && !F_ISSET(sp, SC_TINPUT_INFO)) vs_modeline(sp); if (LF_ISSET(UPDATE_CURSOR)) { (void)gp->scr_move(sp, y, SCNO); /* * XXX * If the screen shifted, we recalculate the "most favorite" * cursor position. Vi won't know that we've warped the * screen, so it's going to have a wrong idea about where the * cursor should be. This is vi's problem, and fixing it here * is a gross layering violation. */ if (leftright_warp) (void)vs_column(sp, &sp->rcm); } if (LF_ISSET(UPDATE_SCREEN)) (void)gp->scr_refresh(sp, F_ISSET(vip, VIP_N_EX_PAINT)); /* 12: Clear the flags that are handled by this routine. */ F_CLR(sp, SC_SCR_CENTER | SC_SCR_REDRAW | SC_SCR_REFORMAT | SC_SCR_TOP); F_CLR(vip, VIP_CUR_INVALID | VIP_N_EX_PAINT | VIP_N_REFRESH | VIP_N_RENUMBER | VIP_S_MODELINE); return (0); #undef LNO #undef OLNO #undef CNO #undef OCNO #undef SCNO } /* * vs_modeline -- * Update the mode line. */ static void vs_modeline(SCR *sp) { static char * const modes[] = { "215|Append", /* SM_APPEND */ "216|Change", /* SM_CHANGE */ "217|Command", /* SM_COMMAND */ "218|Insert", /* SM_INSERT */ "219|Replace", /* SM_REPLACE */ }; GS *gp; size_t cols, curcol, curlen, endpoint, len, midpoint; const char *t = NULL; int ellipsis; - char buf[20]; + char buf[30]; + recno_t last; gp = sp->gp; /* * We put down the file name, the ruler, the mode and the dirty flag. * If there's not enough room, there's not enough room, we don't play * any special games. We try to put the ruler in the middle and the * mode and dirty flag at the end. * * !!! * Leave the last character blank, in case it's a really dumb terminal * with hardware scroll. Second, don't paint the last character in the * screen, SunOS 4.1.1 and Ultrix 4.2 curses won't let you. * * Move to the last line on the screen. */ (void)gp->scr_move(sp, LASTLINE(sp), 0); /* If more than one screen in the display, show the file name. */ curlen = 0; - if (IS_SPLIT(sp)) { + if (IS_SPLIT(sp) || O_ISSET(sp, O_SHOWFILENAME)) { CHAR_T *wp, *p; size_t l; CHAR2INT(sp, sp->frp->name, strlen(sp->frp->name) + 1, wp, l); p = wp + l; for (ellipsis = 0, cols = sp->cols / 2; --p > wp;) { if (*p == '/') { ++p; break; } if ((curlen += KEY_COL(sp, *p)) > cols) { ellipsis = 3; curlen += KEY_LEN(sp, '.') * 3 + KEY_LEN(sp, ' '); while (curlen > cols) { ++p; curlen -= KEY_COL(sp, *p); } break; } } if (ellipsis) { while (ellipsis--) (void)gp->scr_addstr(sp, KEY_NAME(sp, '.'), KEY_LEN(sp, '.')); (void)gp->scr_addstr(sp, KEY_NAME(sp, ' '), KEY_LEN(sp, ' ')); } for (; *p != '\0'; ++p) (void)gp->scr_addstr(sp, KEY_NAME(sp, *p), KEY_COL(sp, *p)); } /* Clear the rest of the line. */ (void)gp->scr_clrtoeol(sp); /* * Display the ruler. If we're not at the midpoint yet, move there. * Otherwise, add in two extra spaces. * * Adjust the current column for the fact that the editor uses it as * a zero-based number. * * XXX * Assume that numbers, commas, and spaces only take up a single * column on the screen. */ cols = sp->cols - 1; if (O_ISSET(sp, O_RULER)) { vs_column(sp, &curcol); - len = snprintf(buf, sizeof(buf), "%lu,%lu", - (u_long)sp->lno, (u_long)(curcol + 1)); + + if (db_last(sp, &last) || last == 0) + len = snprintf(buf, sizeof(buf), "%lu,%zu", + (u_long)sp->lno, curcol + 1); + else + len = snprintf(buf, sizeof(buf), "%lu,%zu %lu%%", + (u_long)sp->lno, curcol + 1, + (u_long)(sp->lno * 100) / last); midpoint = (cols - ((len + 1) / 2)) / 2; if (curlen < midpoint) { (void)gp->scr_move(sp, LASTLINE(sp), midpoint); curlen += len; } else if (curlen + 2 + len < cols) { (void)gp->scr_addstr(sp, " ", 2); curlen += 2 + len; } (void)gp->scr_addstr(sp, buf, len); } /* * Display the mode and the modified flag, as close to the end of the * line as possible, but guaranteeing at least two spaces between the * ruler and the modified flag. */ #define MODESIZE 9 endpoint = cols; if (O_ISSET(sp, O_SHOWMODE)) { if (F_ISSET(sp->ep, F_MODIFIED)) --endpoint; t = msg_cat(sp, modes[sp->showmode], &len); endpoint -= len; } if (endpoint > curlen + 2) { (void)gp->scr_move(sp, LASTLINE(sp), endpoint); if (O_ISSET(sp, O_SHOWMODE)) { if (F_ISSET(sp->ep, F_MODIFIED)) (void)gp->scr_addstr(sp, KEY_NAME(sp, '*'), KEY_LEN(sp, '*')); (void)gp->scr_addstr(sp, t, len); } } }