diff options
Diffstat (limited to 'src')
100 files changed, 2981 insertions, 1996 deletions
diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt index ac982e8be8..b95709526b 100755 --- a/src/nvim/CMakeLists.txt +++ b/src/nvim/CMakeLists.txt @@ -1,25 +1,341 @@ -option(USE_GCOV "Enable gcov support" OFF) +add_library(main_lib INTERFACE) +add_executable(nvim main.c) + +add_library(libuv_lib INTERFACE) +find_package(LibUV 1.28.0 REQUIRED) +target_include_directories(libuv_lib SYSTEM BEFORE INTERFACE ${LIBUV_INCLUDE_DIRS}) +target_link_libraries(libuv_lib INTERFACE ${LIBUV_LIBRARIES}) + +find_package(Msgpack 1.0.0 REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${MSGPACK_INCLUDE_DIRS}) +target_link_libraries(main_lib INTERFACE ${MSGPACK_LIBRARIES}) + +find_package(LibLUV 1.43.0 REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LIBLUV_INCLUDE_DIRS}) +# Use "luv" as imported library, to work around CMake using "-lluv" for +# "luv.so". #10407 +add_library(luv UNKNOWN IMPORTED) +set_target_properties(luv PROPERTIES IMPORTED_LOCATION ${LIBLUV_LIBRARIES}) +target_link_libraries(main_lib INTERFACE luv) + +find_package(TreeSitter REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${TreeSitter_INCLUDE_DIRS}) +target_link_libraries(main_lib INTERFACE ${TreeSitter_LIBRARIES}) + +find_package(UNIBILIUM 2.0 REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${UNIBILIUM_INCLUDE_DIRS}) +target_link_libraries(main_lib INTERFACE ${UNIBILIUM_LIBRARIES}) + +find_package(LibTermkey 0.22 REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LIBTERMKEY_INCLUDE_DIRS}) +target_link_libraries(main_lib INTERFACE ${LIBTERMKEY_LIBRARIES}) + +find_package(LIBVTERM 0.3 REQUIRED) +target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LIBVTERM_INCLUDE_DIRS}) +target_link_libraries(main_lib INTERFACE ${LIBVTERM_LIBRARIES}) + +if(Iconv_FOUND) + target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${Iconv_INCLUDE_DIRS}) + if(Iconv_LIBRARIES) + target_link_libraries(main_lib INTERFACE ${Iconv_LIBRARIES}) + endif() +endif() + +option(ENABLE_LIBINTL "enable libintl" ON) +if(ENABLE_LIBINTL) + # LibIntl (not Intl) selects our FindLibIntl.cmake script. #8464 + find_package(LibIntl REQUIRED) + target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LibIntl_INCLUDE_DIRS}) + if (LibIntl_FOUND) + target_link_libraries(main_lib INTERFACE ${LibIntl_LIBRARY}) + endif() +endif() + +# The unit test lib requires LuaJIT; it will be skipped if LuaJIT is missing. +option(PREFER_LUA "Prefer Lua over LuaJIT in the nvim executable." OFF) +if(PREFER_LUA) + find_package(Lua 5.1 EXACT REQUIRED) + target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LUA_INCLUDE_DIR}) + target_link_libraries(main_lib INTERFACE ${LUA_LIBRARIES}) + # Passive (not REQUIRED): if LUAJIT_FOUND is not set, nvim-test is skipped. + find_package(LuaJit) +else() + find_package(LuaJit REQUIRED) + target_include_directories(main_lib SYSTEM BEFORE INTERFACE ${LUAJIT_INCLUDE_DIRS}) + target_link_libraries(main_lib INTERFACE ${LUAJIT_LIBRARIES}) +endif() + +# Determine platform's threading library. Set CMAKE_THREAD_PREFER_PTHREAD +# explicitly to indicate a strong preference for pthread. +set(CMAKE_THREAD_PREFER_PTHREAD ON) +find_package(Threads REQUIRED) +target_link_libraries(main_lib INTERFACE ${CMAKE_THREAD_LIBS_INIT}) + +option(ENABLE_IWYU "Run include-what-you-use with the compiler." OFF) +if(ENABLE_IWYU) + find_program(IWYU_PRG NAMES include-what-you-use iwyu) + if(NOT IWYU_PRG) + message(FATAL_ERROR "ENABLE_IWYU is ON but include-what-you-use is not found!") + endif() + + set(iwyu_flags "${IWYU_PRG};") + string(APPEND iwyu_flags "-Xiwyu;--no_default_mappings;") + string(APPEND iwyu_flags "-Xiwyu;--mapping_file=${PROJECT_SOURCE_DIR}/cmake.config/iwyu/mapping.imp;") + string(APPEND iwyu_flags "-Xiwyu;--mapping_file=${PROJECT_SOURCE_DIR}/cmake.config/iwyu/gcc.libc.imp;") + string(APPEND iwyu_flags "-Xiwyu;--mapping_file=${PROJECT_SOURCE_DIR}/cmake.config/iwyu/gcc.symbols.imp") + + set_target_properties(nvim PROPERTIES C_INCLUDE_WHAT_YOU_USE "${iwyu_flags}") + target_compile_definitions(nvim PRIVATE EXITFREE) +endif() + +if(MSVC) + # XXX: /W4 gives too many warnings. #3241 + target_compile_options(main_lib INTERFACE -W1 -wd4311) + target_compile_definitions(main_lib INTERFACE _CRT_SECURE_NO_WARNINGS _CRT_NONSTDC_NO_DEPRECATE) +else() + target_compile_options(main_lib INTERFACE -Wall -Wextra -pedantic -Wno-unused-parameter + -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion + -Wdouble-promotion + -Wmissing-noreturn + -Wmissing-format-attribute + -Wmissing-prototypes) +endif() + +# On FreeBSD 64 math.h uses unguarded C11 extension, which taints clang +# 3.4.1 used there. +if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" AND CMAKE_C_COMPILER_ID MATCHES "Clang") + target_compile_options(main_lib INTERFACE -Wno-c11-extensions) +endif() + +check_c_compiler_flag(-Wimplicit-fallthrough HAVE_WIMPLICIT_FALLTHROUGH_FLAG) +if(HAVE_WIMPLICIT_FALLTHROUGH_FLAG) + target_compile_options(main_lib INTERFACE -Wimplicit-fallthrough) +endif() + +option(ENABLE_COMPILER_SUGGESTIONS "Enable -Wsuggest compiler warnings" OFF) +if(ENABLE_COMPILER_SUGGESTIONS) + # Clang doesn't have -Wsuggest-attribute so check for each one. + check_c_compiler_flag(-Wsuggest-attribute=pure HAVE_WSUGGEST_ATTRIBUTE_PURE) + if(HAVE_WSUGGEST_ATTRIBUTE_PURE) + target_compile_options(main_lib INTERFACE -Wsuggest-attribute=pure) + endif() + + check_c_compiler_flag(-Wsuggest-attribute=const HAVE_WSUGGEST_ATTRIBUTE_CONST) + if(HAVE_WSUGGEST_ATTRIBUTE_CONST) + target_compile_options(main_lib INTERFACE -Wsuggest-attribute=const) + endif() + + check_c_compiler_flag(-Wsuggest-attribute=malloc HAVE_WSUGGEST_ATTRIBUTE_MALLOC) + if(HAVE_WSUGGEST_ATTRIBUTE_MALLOC) + target_compile_options(main_lib INTERFACE -Wsuggest-attribute=malloc) + endif() + + check_c_compiler_flag(-Wsuggest-attribute=cold HAVE_WSUGGEST_ATTRIBUTE_COLD) + if(HAVE_WSUGGEST_ATTRIBUTE_COLD) + target_compile_options(main_lib INTERFACE -Wsuggest-attribute=cold) + endif() +endif() + +if(MINGW) + # Use POSIX compatible stdio in Mingw + target_compile_definitions(main_lib INTERFACE __USE_MINGW_ANSI_STDIO) +endif() +if(WIN32) + # Windows Vista is the minimum supported version + target_compile_definitions(main_lib INTERFACE _WIN32_WINNT=0x0600 MSWIN) +endif() + +# OpenBSD's GCC (4.2.1) doesn't have -Wvla +check_c_compiler_flag(-Wvla HAS_WVLA_FLAG) +if(HAS_WVLA_FLAG) + target_compile_options(main_lib INTERFACE -Wvla) +endif() + +check_c_compiler_flag(-fno-common HAVE_FNO_COMMON) +if (HAVE_FNO_COMMON) + target_compile_options(main_lib INTERFACE -fno-common) +endif() + +check_c_compiler_flag(-fdiagnostics-color=auto HAS_DIAG_COLOR_FLAG) +if(HAS_DIAG_COLOR_FLAG) + if(CMAKE_GENERATOR MATCHES "Ninja") + target_compile_options(main_lib INTERFACE -fdiagnostics-color=always) + else() + target_compile_options(main_lib INTERFACE -fdiagnostics-color=auto) + endif() +endif() + +option(CI_BUILD "CI, extra flags will be set" OFF) +if(CI_BUILD) + message(STATUS "CI build enabled") + if(MSVC) + target_compile_options(main_lib INTERFACE -WX) + else() + target_compile_options(main_lib INTERFACE -Werror) + if(DEFINED ENV{BUILD_UCHAR}) + # Get some test coverage for unsigned char + target_compile_options(main_lib INTERFACE -funsigned-char) + endif() + endif() +endif() + +list(APPEND CMAKE_REQUIRED_INCLUDES "${UNIBILIUM_INCLUDE_DIRS}") +list(APPEND CMAKE_REQUIRED_LIBRARIES "${UNIBILIUM_LIBRARIES}") +check_c_source_compiles(" +#include <unibilium.h> + +int +main(void) +{ + unibi_str_from_var(unibi_var_from_str(\"\")); + return unibi_num_from_var(unibi_var_from_num(0)); +} +" UNIBI_HAS_VAR_FROM) +list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES "${UNIBILIUM_INCLUDE_DIRS}") +list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "${UNIBILIUM_LIBRARIES}") +if(UNIBI_HAS_VAR_FROM) + target_compile_definitions(main_lib INTERFACE NVIM_UNIBI_HAS_VAR_FROM) +endif() + +list(APPEND CMAKE_REQUIRED_INCLUDES "${MSGPACK_INCLUDE_DIRS}") +check_c_source_compiles(" +#include <msgpack.h> + +int +main(void) +{ + return MSGPACK_OBJECT_FLOAT32; +} +" MSGPACK_HAS_FLOAT32) +list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES "${MSGPACK_INCLUDE_DIRS}") +if(MSGPACK_HAS_FLOAT32) + target_compile_definitions(main_lib INTERFACE NVIM_MSGPACK_HAS_FLOAT32) +endif() + +list(APPEND CMAKE_REQUIRED_INCLUDES "${TreeSitter_INCLUDE_DIRS}") +list(APPEND CMAKE_REQUIRED_LIBRARIES "${TreeSitter_LIBRARIES}") +check_c_source_compiles(" +#include <tree_sitter/api.h> +int +main(void) +{ + TSQueryCursor *cursor = ts_query_cursor_new(); + ts_query_cursor_set_match_limit(cursor, 32); + return 0; +} +" TS_HAS_SET_MATCH_LIMIT) +if(TS_HAS_SET_MATCH_LIMIT) + target_compile_definitions(main_lib INTERFACE NVIM_TS_HAS_SET_MATCH_LIMIT) +endif() +check_c_source_compiles(" +#include <stdlib.h> +#include <tree_sitter/api.h> +int +main(void) +{ + ts_set_allocator(malloc, calloc, realloc, free); + return 0; +} +" TS_HAS_SET_ALLOCATOR) +if(TS_HAS_SET_ALLOCATOR) + target_compile_definitions(main_lib INTERFACE NVIM_TS_HAS_SET_ALLOCATOR) +endif() +list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES "${TreeSitter_INCLUDE_DIRS}") +list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "${TreeSitter_LIBRARIES}") + +# Include <string.h> because some toolchains define _FORTIFY_SOURCE=2 in +# internal header files, which should in turn be #included by <string.h>. +check_c_source_compiles(" +#include <string.h> + +#if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 1 +#error \"_FORTIFY_SOURCE > 1\" +#endif +int +main(void) +{ + return 0; +} +" HAS_ACCEPTABLE_FORTIFY) + +if(NOT HAS_ACCEPTABLE_FORTIFY) + message(STATUS "Unsupported _FORTIFY_SOURCE found, forcing _FORTIFY_SOURCE=1") + # Extract possible prefix to _FORTIFY_SOURCE (e.g. -Wp,-D_FORTIFY_SOURCE). + string(REGEX MATCH "[^\ ]+-D_FORTIFY_SOURCE" _FORTIFY_SOURCE_PREFIX "${CMAKE_C_FLAGS}") + string(REPLACE "-D_FORTIFY_SOURCE" "" _FORTIFY_SOURCE_PREFIX "${_FORTIFY_SOURCE_PREFIX}" ) + if(NOT _FORTIFY_SOURCE_PREFIX STREQUAL "") + message(STATUS "Detected _FORTIFY_SOURCE Prefix=${_FORTIFY_SOURCE_PREFIX}") + endif() + # -U in add_definitions doesn't end up in the correct spot, so we add it to + # the flags variable instead. + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_FORTIFY_SOURCE_PREFIX}-U_FORTIFY_SOURCE ${_FORTIFY_SOURCE_PREFIX}-D_FORTIFY_SOURCE=1") +endif() + +target_compile_definitions(main_lib INTERFACE INCLUDE_GENERATED_DECLARATIONS) + +# Remove --sort-common from linker flags, as this seems to cause bugs (see #2641, #3374). +# TODO: Figure out the root cause. +if(CMAKE_EXE_LINKER_FLAGS MATCHES "--sort-common" OR + CMAKE_SHARED_LINKER_FLAGS MATCHES "--sort-common" OR + CMAKE_MODULE_LINKER_FLAGS MATCHES "--sort-common") + message(STATUS "Removing --sort-common from linker flags") + string(REGEX REPLACE ",--sort-common(=[^,]+)?" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}") + string(REGEX REPLACE ",--sort-common(=[^,]+)?" "" CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}") + string(REGEX REPLACE ",--sort-common(=[^,]+)?" "" CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS}") + + # If no linker flags remain for a -Wl argument, remove it. + # '-Wl$' will match LDFLAGS="-Wl,--sort-common", + # '-Wl ' will match LDFLAGS="-Wl,--sort-common -Wl,..." + string(REGEX REPLACE "-Wl($| )" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}") + string(REGEX REPLACE "-Wl($| )" "" CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}") + string(REGEX REPLACE "-Wl($| )" "" CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS}") +endif() + +if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + if(CMAKE_SYSTEM_NAME STREQUAL "SunOS") + target_link_libraries(nvim PRIVATE -Wl,--no-undefined -lsocket) + elseif(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") + target_link_libraries(nvim PRIVATE -Wl,--no-undefined) + endif() + + # For O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW flags on older systems + # (pre POSIX.1-2008: glibc 2.11 and earlier). #4042 + # For ptsname(). #6743 + target_compile_definitions(main_lib INTERFACE _GNU_SOURCE) +endif() +option(USE_GCOV "Enable gcov support" OFF) if(USE_GCOV) if(CLANG_TSAN) # GCOV and TSAN results in false data race reports message(FATAL_ERROR "USE_GCOV cannot be used with CLANG_TSAN") endif() message(STATUS "Enabling gcov support") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --coverage") - add_definitions(-DUSE_GCOV) + target_compile_options(main_lib INTERFACE --coverage) + target_link_libraries(main_lib INTERFACE --coverage) + target_compile_definitions(main_lib INTERFACE USE_GCOV) endif() if(WIN32) if(MINGW) # Enable wmain - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -municode") + target_link_libraries(nvim PRIVATE -municode) endif() elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -framework CoreServices") - set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -framework CoreServices") + target_link_libraries(nvim PRIVATE "-framework CoreServices") +endif() + +if(UNIX) + # -fstack-protector breaks non Unix builds even in Mingw-w64 + check_c_compiler_flag(-fstack-protector-strong HAS_FSTACK_PROTECTOR_STRONG_FLAG) + check_c_compiler_flag(-fstack-protector HAS_FSTACK_PROTECTOR_FLAG) + if(HAS_FSTACK_PROTECTOR_STRONG_FLAG) + target_compile_options(main_lib INTERFACE -fstack-protector-strong) + target_link_libraries(main_lib INTERFACE -fstack-protector-strong) + elseif(HAS_FSTACK_PROTECTOR_FLAG) + target_compile_options(main_lib INTERFACE -fstack-protector --param ssp-buffer-size=4) + target_link_libraries(main_lib INTERFACE -fstack-protector --param ssp-buffer-size=4) + endif() endif() set(GENERATOR_DIR ${CMAKE_CURRENT_LIST_DIR}/generators) @@ -66,31 +382,21 @@ set(LUA_FILETYPE_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/filetype.lu set(LUA_INIT_PACKAGES_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/_init_packages.lua) set(LUA_KEYMAP_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/keymap.lua) set(CHAR_BLOB_GENERATOR ${GENERATOR_DIR}/gen_char_blob.lua) -set(LINT_SUPPRESS_FILE ${PROJECT_BINARY_DIR}/errors.json) -set(LINT_SUPPRESS_URL_BASE "https://raw.githubusercontent.com/neovim/doc/gh-pages/reports/clint") -set(LINT_SUPPRESS_URL "${LINT_SUPPRESS_URL_BASE}/errors.json") -set(LINT_PRG ${PROJECT_SOURCE_DIR}/src/clint.py) -set(DOWNLOAD_SCRIPT ${PROJECT_SOURCE_DIR}/cmake/Download.cmake) -set(LINT_SUPPRESSES_ROOT ${PROJECT_BINARY_DIR}/errors) -set(LINT_SUPPRESSES_URL "${LINT_SUPPRESS_URL_BASE}/errors.tar.gz") -set(LINT_SUPPRESSES_ARCHIVE ${LINT_SUPPRESSES_ROOT}/errors.tar.gz) -set(LINT_SUPPRESSES_TOUCH_FILE "${TOUCHES_DIR}/unpacked-clint-errors-archive") -set(CLINT_REPORT_PATH ${LINT_SUPPRESSES_ROOT}/src/home/runner/work/doc/doc/gh-pages/reports/clint) glob_wrapper(UNICODE_FILES ${UNICODE_DIR}/*.txt) glob_wrapper(API_HEADERS api/*.h) list(REMOVE_ITEM API_HEADERS ${CMAKE_CURRENT_LIST_DIR}/api/ui_events.in.h) glob_wrapper(MSGPACK_RPC_HEADERS msgpack_rpc/*.h) -include_directories(${GENERATED_DIR}) -include_directories(${CACHED_GENERATED_DIR}) -include_directories(${GENERATED_INCLUDES_DIR}) +target_include_directories(main_lib INTERFACE ${GENERATED_DIR}) +target_include_directories(main_lib INTERFACE ${CACHED_GENERATED_DIR}) +target_include_directories(main_lib INTERFACE ${GENERATED_INCLUDES_DIR}) +target_include_directories(main_lib INTERFACE "${PROJECT_BINARY_DIR}/cmake.config") +target_include_directories(main_lib INTERFACE "${PROJECT_SOURCE_DIR}/src") file(MAKE_DIRECTORY ${TOUCHES_DIR}) file(MAKE_DIRECTORY ${GENERATED_DIR}) file(MAKE_DIRECTORY ${GENERATED_INCLUDES_DIR}) -file(MAKE_DIRECTORY ${LINT_SUPPRESSES_ROOT}) -file(MAKE_DIRECTORY ${LINT_SUPPRESSES_ROOT}/src) glob_wrapper(NVIM_SOURCES *.c) glob_wrapper(NVIM_HEADERS *.h) @@ -118,8 +424,6 @@ foreach(subdir list(APPEND NVIM_HEADERS ${headers}) endforeach() -glob_wrapper(UNIT_TEST_FIXTURES ${PROJECT_SOURCE_DIR}/test/unit/fixtures/*.c) - # Sort file lists to ensure generated files are created in the same order from # build to build. list(SORT NVIM_SOURCES) @@ -158,22 +462,22 @@ if(NOT MSVC) endif() if(NOT "${MIN_LOG_LEVEL}" MATCHES "^$") - add_definitions(-DMIN_LOG_LEVEL=${MIN_LOG_LEVEL}) + target_compile_definitions(main_lib INTERFACE MIN_LOG_LEVEL=${MIN_LOG_LEVEL}) endif() if(CLANG_ASAN_UBSAN OR CLANG_MSAN OR CLANG_TSAN) - add_definitions(-DEXITFREE) + target_compile_definitions(main_lib INTERFACE EXITFREE) endif() -get_directory_property(gen_cdefs COMPILE_DEFINITIONS) -foreach(gen_cdef ${gen_cdefs} DO_NOT_DEFINE_EMPTY_ATTRIBUTES) +get_target_property(prop main_lib INTERFACE_COMPILE_DEFINITIONS) +foreach(gen_cdef DO_NOT_DEFINE_EMPTY_ATTRIBUTES ${prop}) if(NOT ${gen_cdef} MATCHES "INCLUDE_GENERATED_DECLARATIONS") list(APPEND gen_cflags "-D${gen_cdef}") endif() endforeach() -get_directory_property(gen_includes INCLUDE_DIRECTORIES) -foreach(gen_include ${gen_includes} ${LUA_PREFERRED_INCLUDE_DIRS}) +get_target_property(prop main_lib INTERFACE_INCLUDE_DIRECTORIES) +foreach(gen_include ${prop}) list(APPEND gen_cflags "-I${gen_include}") endforeach() if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND CMAKE_OSX_SYSROOT) @@ -185,14 +489,6 @@ separate_arguments(C_FLAGS_ARRAY UNIX_COMMAND ${CMAKE_C_FLAGS}) separate_arguments(C_FLAGS_${build_type}_ARRAY UNIX_COMMAND ${CMAKE_C_FLAGS_${build_type}}) set(gen_cflags ${gen_cflags} ${C_FLAGS_${build_type}_ARRAY} ${C_FLAGS_ARRAY}) -function(get_preproc_output varname iname) - if(MSVC) - set(${varname} /P /Fi${iname} /nologo PARENT_SCOPE) - else() - set(${varname} -E -o ${iname} PARENT_SCOPE) - endif() -endfunction() - set(NVIM_VERSION_GIT_H ${PROJECT_BINARY_DIR}/cmake.config/auto/versiondef_git.h) add_custom_target(update_version_stamp COMMAND ${CMAKE_COMMAND} @@ -233,7 +529,11 @@ foreach(sfile ${NVIM_SOURCES} set(gf_h_h "${GENERATED_INCLUDES_DIR}/${r}.h.generated.h") set(gf_i "${GENERATED_DIR}/${r}.i") - get_preproc_output(PREPROC_OUTPUT ${gf_i}) + if(MSVC) + set(PREPROC_OUTPUT /P /Fi${gf_i} /nologo) + else() + set(PREPROC_OUTPUT -E -o ${gf_i}) + endif() set(depends "${HEADER_GENERATOR}" "${sfile}") if("${f}" STREQUAL "version.c") @@ -388,77 +688,44 @@ endforeach() # Our dependencies come first. if (CMAKE_SYSTEM_NAME MATCHES "OpenBSD") - list(APPEND NVIM_LINK_LIBRARIES pthread c++abi) -endif() - -if (LibIntl_FOUND) - list(APPEND NVIM_LINK_LIBRARIES ${LibIntl_LIBRARY}) -endif() - -if(Iconv_LIBRARIES) - list(APPEND NVIM_LINK_LIBRARIES ${Iconv_LIBRARIES}) + target_link_libraries(main_lib INTERFACE pthread c++abi) endif() if(WIN32) - list(APPEND NVIM_LINK_LIBRARIES netapi32) + target_link_libraries(main_lib INTERFACE netapi32) endif() -# Use "luv" as imported library, to work around CMake using "-lluv" for -# "luv.so". #10407 -add_library(luv UNKNOWN IMPORTED) -set_property(TARGET luv PROPERTY IMPORTED_LOCATION ${LIBLUV_LIBRARIES}) - -# Put these last on the link line, since multiple things may depend on them. -list(APPEND NVIM_LINK_LIBRARIES - luv - ${LIBUV_LIBRARIES} - ${MSGPACK_LIBRARIES} - ${LIBVTERM_LIBRARIES} - ${LIBTERMKEY_LIBRARIES} - ${UNIBILIUM_LIBRARIES} - ${UTF8PROC_LIBRARIES} - ${TreeSitter_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} -) - if(UNIX) - list(APPEND NVIM_LINK_LIBRARIES - m) + target_link_libraries(main_lib INTERFACE m) if (NOT CMAKE_SYSTEM_NAME STREQUAL "SunOS") - list(APPEND NVIM_LINK_LIBRARIES - util) + target_link_libraries(main_lib INTERFACE util) endif() endif() -set(NVIM_EXEC_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES} ${LUA_PREFERRED_LIBRARIES}) - -add_executable(nvim ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} +target_sources(nvim PRIVATE ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} ${NVIM_GENERATED_SOURCES} ${NVIM_SOURCES} ${NVIM_HEADERS} ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS}) set_target_properties(nvim PROPERTIES - EXPORT_COMPILE_COMMANDS ON) + EXPORT_COMPILE_COMMANDS ON + ENABLE_EXPORTS TRUE) if(${CMAKE_VERSION} VERSION_LESS 3.20) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) endif() -target_link_libraries(nvim ${NVIM_EXEC_LINK_LIBRARIES}) +target_link_libraries(nvim PRIVATE main_lib PUBLIC libuv_lib) install_helper(TARGETS nvim) if(MSVC) install(FILES $<TARGET_PDB_FILE:nvim> DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL) endif() -set_property(TARGET nvim APPEND PROPERTY - INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS}) -set_property(TARGET nvim PROPERTY ENABLE_EXPORTS TRUE) - if(ENABLE_LTO) include(CheckIPOSupported) check_ipo_supported(RESULT IPO_SUPPORTED) if(IPO_SUPPORTED AND (NOT CMAKE_BUILD_TYPE MATCHES Debug)) - set_property(TARGET nvim PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) + set_target_properties(nvim PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE) endif() endif() @@ -580,8 +847,6 @@ add_library( ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS} ) -set_property(TARGET libnvim APPEND PROPERTY - INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS}) if(MSVC) set(LIBNVIM_NAME libnvim) else() @@ -593,12 +858,13 @@ set_target_properties( POSITION_INDEPENDENT_CODE ON OUTPUT_NAME ${LIBNVIM_NAME} ) -target_compile_options(libnvim PRIVATE -DMAKE_LIB) +target_compile_definitions(libnvim PRIVATE MAKE_LIB) +target_link_libraries(libnvim PRIVATE main_lib PUBLIC libuv_lib) if(NOT LUAJIT_FOUND) message(STATUS "luajit not found, skipping nvim-test (unit tests) target") else() - set(NVIM_TEST_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES} ${LUAJIT_LIBRARIES}) + glob_wrapper(UNIT_TEST_FIXTURES ${PROJECT_SOURCE_DIR}/test/unit/fixtures/*.c) add_library( nvim-test MODULE @@ -608,39 +874,46 @@ else() ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS} ${UNIT_TEST_FIXTURES} ) - target_link_libraries(nvim-test ${NVIM_TEST_LINK_LIBRARIES}) - target_link_libraries(libnvim ${NVIM_TEST_LINK_LIBRARIES}) - set_property( - TARGET nvim-test - APPEND PROPERTY INCLUDE_DIRECTORIES ${LUAJIT_INCLUDE_DIRS} - ) + target_link_libraries(nvim-test PRIVATE ${LUAJIT_LIBRARIES} main_lib PUBLIC libuv_lib) + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + target_link_libraries(nvim-test PRIVATE "-framework CoreServices") + endif() + target_include_directories(nvim-test PRIVATE ${LUAJIT_INCLUDE_DIRS}) set_target_properties( nvim-test PROPERTIES POSITION_INDEPENDENT_CODE ON ) - target_compile_options(nvim-test PRIVATE -DUNIT_TESTING) + target_compile_definitions(nvim-test PRIVATE UNIT_TESTING) endif() if(CLANG_ASAN_UBSAN) message(STATUS "Enabling Clang address sanitizer and undefined behavior sanitizer for nvim.") if(CI_BUILD) # Try to recover from all sanitize issues so we get reports about all failures - set(SANITIZE_RECOVER -fsanitize-recover=all) + target_compile_options(nvim PRIVATE -fsanitize-recover=all) else() - set(SANITIZE_RECOVER -fno-sanitize-recover=all) + target_compile_options(nvim PRIVATE -fno-sanitize-recover=all) endif() - set_property(TARGET nvim APPEND PROPERTY COMPILE_OPTIONS ${SANITIZE_RECOVER} -fno-omit-frame-pointer -fno-optimize-sibling-calls -fsanitize=address -fsanitize=undefined -fsanitize-blacklist=${PROJECT_SOURCE_DIR}/src/.asan-blacklist) - set_property(TARGET nvim APPEND_STRING PROPERTY LINK_FLAGS "-fsanitize=address -fsanitize=undefined ") + target_compile_options(nvim PRIVATE + -fno-omit-frame-pointer + -fno-optimize-sibling-calls + -fsanitize=address + -fsanitize=undefined + -fsanitize-blacklist=${PROJECT_SOURCE_DIR}/src/.asan-blacklist) + target_link_libraries(nvim PRIVATE -fsanitize=address -fsanitize=undefined) elseif(CLANG_MSAN) message(STATUS "Enabling Clang memory sanitizer for nvim.") - set_property(TARGET nvim APPEND PROPERTY COMPILE_OPTIONS -fsanitize=memory -fsanitize-memory-track-origins -fno-omit-frame-pointer -fno-optimize-sibling-calls) - set_property(TARGET nvim APPEND_STRING PROPERTY LINK_FLAGS "-fsanitize=memory -fsanitize-memory-track-origins ") + target_compile_options(nvim PRIVATE + -fsanitize=memory + -fsanitize-memory-track-origins + -fno-omit-frame-pointer + -fno-optimize-sibling-calls) + target_link_libraries(nvim PRIVATE -fsanitize=memory -fsanitize-memory-track-origins) elseif(CLANG_TSAN) message(STATUS "Enabling Clang thread sanitizer for nvim.") - set_property(TARGET nvim APPEND PROPERTY COMPILE_OPTIONS -fsanitize=thread) - set_property(TARGET nvim APPEND PROPERTY COMPILE_OPTIONS -fPIE) - set_property(TARGET nvim APPEND_STRING PROPERTY LINK_FLAGS "-fsanitize=thread ") + target_compile_options(nvim PRIVATE -fsanitize=thread -fPIE) + target_link_libraries(nvim PRIVATE -fsanitize=thread) endif() function(get_test_target prefix sfile relative_path_var target_var) @@ -683,10 +956,7 @@ foreach(hfile ${NVIM_HEADERS}) ${texe} EXCLUDE_FROM_ALL ${tsource} ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_HEADERS}) - set_property( - TARGET ${texe} - APPEND PROPERTY INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS} - ) + target_link_libraries(${texe} PRIVATE main_lib) set_target_properties(${texe} PROPERTIES FOLDER test) list(FIND NO_SINGLE_CHECK_HEADERS "${relative_path}" hfile_exclude_idx) @@ -697,55 +967,17 @@ foreach(hfile ${NVIM_HEADERS}) endforeach() add_custom_target(check-single-includes DEPENDS ${HEADER_CHECK_TARGETS}) -function(add_download output url allow_failure) - add_custom_command( - OUTPUT "${output}" - COMMAND - ${CMAKE_COMMAND} - -DURL=${url} -DFILE=${output} - -DALLOW_FAILURE=${allow_failure} - -P ${DOWNLOAD_SCRIPT} - DEPENDS ${DOWNLOAD_SCRIPT} - ) -endfunction() - -add_download(${LINT_SUPPRESSES_ARCHIVE} ${LINT_SUPPRESSES_URL} off) - -add_custom_command( - OUTPUT ${LINT_SUPPRESSES_TOUCH_FILE} - WORKING_DIRECTORY ${LINT_SUPPRESSES_ROOT}/src - COMMAND ${CMAKE_COMMAND} -E tar xfz ${LINT_SUPPRESSES_ARCHIVE} - COMMAND ${CMAKE_COMMAND} -E copy_directory ${CLINT_REPORT_PATH} "${LINT_SUPPRESSES_ROOT}" - COMMAND ${CMAKE_COMMAND} -E touch ${LINT_SUPPRESSES_TOUCH_FILE} - DEPENDS ${LINT_SUPPRESSES_ARCHIVE} -) - -add_download(${LINT_SUPPRESS_FILE} ${LINT_SUPPRESS_URL} off) - if(CI_BUILD) set(LINT_OUTPUT_FORMAT gh_action) else() set(LINT_OUTPUT_FORMAT vs7) endif() -set(LINT_NVIM_REL_SOURCES) -foreach(sfile ${LINT_NVIM_SOURCES}) - get_test_target("" "${sfile}" r suffix) - set(suppress_file ${LINT_SUPPRESSES_ROOT}/${suffix}.json) - set(suppress_url "${LINT_SUPPRESS_URL_BASE}/${suffix}.json") - set(rsfile src/nvim/${r}) - set(touch_file "${TOUCHES_DIR}/ran-clint-${suffix}") - add_custom_command( - OUTPUT ${touch_file} - COMMAND ${LINT_PRG} --suppress-errors=${suppress_file} --output=${LINT_OUTPUT_FORMAT} ${rsfile} - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - COMMAND ${CMAKE_COMMAND} -E touch ${touch_file} - DEPENDS ${LINT_PRG} ${sfile} ${LINT_SUPPRESSES_TOUCH_FILE} - ) - list(APPEND LINT_TARGETS ${touch_file}) - list(APPEND LINT_NVIM_REL_SOURCES ${rsfile}) -endforeach() -add_custom_target(lintc DEPENDS ${LINT_TARGETS}) +add_glob_target( + TARGET lintc-clint + COMMAND ${PROJECT_SOURCE_DIR}/src/clint.py + FLAGS --output=${LINT_OUTPUT_FORMAT} + FILES ${LINT_NVIM_SOURCES}) add_custom_target(uncrustify-version COMMAND ${CMAKE_COMMAND} @@ -754,12 +986,14 @@ add_custom_target(uncrustify-version -P ${PROJECT_SOURCE_DIR}/cmake/CheckUncrustifyVersion.cmake) add_glob_target( - TARGET lintuncrustify + TARGET lintc-uncrustify COMMAND ${UNCRUSTIFY_PRG} FLAGS -c "${PROJECT_SOURCE_DIR}/src/uncrustify.cfg" -q --check - FILES ${LINT_NVIM_SOURCES} - ) -add_dependencies(lintuncrustify uncrustify-version) + FILES ${LINT_NVIM_SOURCES}) +add_dependencies(lintc-uncrustify uncrustify-version) + +add_custom_target(lintc) +add_dependencies(lintc lintc-clint lintc-uncrustify) add_custom_target(formatc COMMAND ${CMAKE_COMMAND} @@ -769,14 +1003,6 @@ add_custom_target(formatc WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) add_dependencies(formatc uncrustify-version) -add_custom_target( - lintcfull - COMMAND - ${LINT_PRG} --suppress-errors=${LINT_SUPPRESS_FILE} --output=${LINT_OUTPUT_FORMAT} ${LINT_NVIM_REL_SOURCES} - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - DEPENDS ${LINT_PRG} ${LINT_NVIM_SOURCES} ${LINT_SUPPRESS_FILE} lintuncrustify -) - add_custom_target(generated-sources DEPENDS ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} diff --git a/src/nvim/api/autocmd.c b/src/nvim/api/autocmd.c index ada042e654..931363e199 100644 --- a/src/nvim/api/autocmd.c +++ b/src/nvim/api/autocmd.c @@ -940,7 +940,7 @@ static bool get_patterns_from_pattern_or_buf(Array *patterns, Object pattern, Ob patlen = aucmd_pattern_length(pat); } } else if (v->type == kObjectTypeArray) { - if (!check_autocmd_string_array(*patterns, "pattern", err)) { + if (!check_autocmd_string_array(v->data.array, "pattern", err)) { return false; } diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 65b08ecade..13c8e162b6 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -1834,7 +1834,7 @@ Dictionary nvim__stats(void) /// - "width" Requested width of the UI /// - "rgb" true if the UI uses RGB colors (false implies |cterm-colors|) /// - "ext_..." Requested UI extensions, see |ui-option| -/// - "chan" Channel id of remote UI or 0 for TUI +/// - "chan" |channel-id| of remote UI Array nvim_list_uis(void) FUNC_API_SINCE(4) { diff --git a/src/nvim/assert.h b/src/nvim/assert.h index ad92d9a2af..1941f4c33c 100644 --- a/src/nvim/assert.h +++ b/src/nvim/assert.h @@ -61,7 +61,7 @@ # define STATIC_ASSERT_STATEMENT(cond, msg) _Static_assert(cond, msg) // if we're dealing with gcc >= 4.6 in C99 mode, we can still use // _Static_assert but we need to suppress warnings, this is pretty ugly. -#elif (!defined(__clang__) && !defined(__INTEL_COMPILER)) && \ +#elif (!defined(__clang__) && !defined(__INTEL_COMPILER)) && /* NOLINT(whitespace/parens)*/ \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) # define STATIC_ASSERT_STATEMENT(cond, msg) _Static_assert(cond, msg) diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index c794b88229..f01edd1ad2 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -1426,7 +1426,7 @@ struct statuscol { int sign_attr[SIGN_SHOW_MAX + 1]; ///< attributes used for signs int truncate; ///< truncated width bool draw; ///< draw statuscolumn or not - char fold_text[10]; ///< text in fold column (%C) + char fold_text[9 * 4 + 1]; ///< text in fold column (%C) char *sign_text[SIGN_SHOW_MAX + 1]; ///< text in sign column (%s) char text[MAXPATHL]; ///< text in status column char *textp; ///< current position in text diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index d603e964e5..ca19d6de95 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -73,7 +73,7 @@ typedef char *(*CompleteListItemGetter)(expand_T *, int); /// Type used by call_user_expand_func -typedef void *(*user_expand_func_T)(const char_u *, int, typval_T *); +typedef void *(*user_expand_func_T)(const char *, int, typval_T *); #ifdef INCLUDE_GENERATED_DECLARATIONS # include "cmdexpand.c.generated.h" @@ -89,6 +89,10 @@ static int compl_match_arraysize; static int compl_startcol; static int compl_selected; +#define SHOW_MATCH(m) (showtail ? showmatches_gettail(matches[m], false) : matches[m]) + +/// Sort function for the completion matches. +/// <SNR> functions should be sorted to the end. static int sort_func_compare(const void *s1, const void *s2) { char *p1 = *(char **)s1; @@ -104,71 +108,75 @@ static int sort_func_compare(const void *s1, const void *s2) } /// Escape special characters in the cmdline completion matches. -static void ExpandEscape(expand_T *xp, char_u *str, int numfiles, char **files, int options) +static void wildescape(expand_T *xp, const char *str, int numfiles, char **files) { - int i; char *p; const int vse_what = xp->xp_context == EXPAND_BUFFERS ? VSE_BUFFER : VSE_NONE; - // May change home directory back to "~" - if (options & WILD_HOME_REPLACE) { - tilde_replace(str, numfiles, files); - } - - if (options & WILD_ESCAPE) { - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_FILES_IN_PATH - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS - || xp->xp_context == EXPAND_DIRECTORIES) { - // Insert a backslash into a file name before a space, \, %, # - // and wildmatch characters, except '~'. - for (i = 0; i < numfiles; i++) { - // for ":set path=" we need to escape spaces twice - if (xp->xp_backslash == XP_BS_THREE) { - p = (char *)vim_strsave_escaped((char_u *)files[i], (char_u *)" "); - xfree(files[i]); - files[i] = p; + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_FILES_IN_PATH + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS + || xp->xp_context == EXPAND_DIRECTORIES) { + // Insert a backslash into a file name before a space, \, %, # + // and wildmatch characters, except '~'. + for (int i = 0; i < numfiles; i++) { + // for ":set path=" we need to escape spaces twice + if (xp->xp_backslash == XP_BS_THREE) { + p = vim_strsave_escaped(files[i], " "); + xfree(files[i]); + files[i] = p; #if defined(BACKSLASH_IN_FILENAME) - p = vim_strsave_escaped(files[i], (char_u *)" "); - xfree(files[i]); - files[i] = p; + p = vim_strsave_escaped(files[i], " "); + xfree(files[i]); + files[i] = p; #endif - } + } #ifdef BACKSLASH_IN_FILENAME - p = vim_strsave_fnameescape((const char *)files[i], vse_what); + p = vim_strsave_fnameescape(files[i], vse_what); #else - p = vim_strsave_fnameescape((const char *)files[i], - xp->xp_shell ? VSE_SHELL : vse_what); + p = vim_strsave_fnameescape(files[i], xp->xp_shell ? VSE_SHELL : vse_what); #endif - xfree(files[i]); - files[i] = p; + xfree(files[i]); + files[i] = p; - // If 'str' starts with "\~", replace "~" at start of - // files[i] with "\~". - if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~') { - escape_fname(&files[i]); - } + // If 'str' starts with "\~", replace "~" at start of + // files[i] with "\~". + if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~') { + escape_fname(&files[i]); } - xp->xp_backslash = XP_BS_NONE; + } + xp->xp_backslash = XP_BS_NONE; - // If the first file starts with a '+' escape it. Otherwise it - // could be seen as "+cmd". - if (*files[0] == '+') { - escape_fname(&files[0]); - } - } else if (xp->xp_context == EXPAND_TAGS) { - // Insert a backslash before characters in a tag name that - // would terminate the ":tag" command. - for (i = 0; i < numfiles; i++) { - p = (char *)vim_strsave_escaped((char_u *)files[i], (char_u *)"\\|\""); - xfree(files[i]); - files[i] = p; - } + // If the first file starts with a '+' escape it. Otherwise it + // could be seen as "+cmd". + if (*files[0] == '+') { + escape_fname(&files[0]); + } + } else if (xp->xp_context == EXPAND_TAGS) { + // Insert a backslash before characters in a tag name that + // would terminate the ":tag" command. + for (int i = 0; i < numfiles; i++) { + p = vim_strsave_escaped(files[i], "\\|\""); + xfree(files[i]); + files[i] = p; } } } +/// Escape special characters in the cmdline completion matches. +static void ExpandEscape(expand_T *xp, char *str, int numfiles, char **files, int options) +{ + // May change home directory back to "~" + if (options & WILD_HOME_REPLACE) { + tilde_replace(str, numfiles, files); + } + + if (options & WILD_ESCAPE) { + wildescape(xp, str, numfiles, files); + } +} + /// Return FAIL if this is not an appropriate context in which to do /// completion of anything, return OK if it is (even if there are no matches). /// For the caller, this means that the character is just passed through like a @@ -209,7 +217,9 @@ int nextwild(expand_T *xp, int type, int options, bool escape) assert(ccline->cmdpos >= i); xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i; - if (type == WILD_NEXT || type == WILD_PREV || type == WILD_PUM_WANT) { + if (type == WILD_NEXT || type == WILD_PREV + || type == WILD_PAGEUP || type == WILD_PAGEDOWN + || type == WILD_PUM_WANT) { // Get next/previous match for a previous expanded pattern. p2 = ExpandOne(xp, NULL, NULL, 0, type); } else { @@ -279,19 +289,54 @@ int nextwild(expand_T *xp, int type, int options, bool escape) return OK; } +/// Create and display a cmdline completion popup menu with items from +/// "matches". +static int cmdline_pum_create(CmdlineInfo *ccline, expand_T *xp, char **matches, int numMatches, + int showtail) +{ + assert(numMatches >= 0); + // Add all the completion matches + compl_match_arraysize = numMatches; + compl_match_array = xmalloc(sizeof(pumitem_T) * (size_t)compl_match_arraysize); + for (int i = 0; i < numMatches; i++) { + compl_match_array[i] = (pumitem_T){ + .pum_text = SHOW_MATCH(i), + .pum_info = NULL, + .pum_extra = NULL, + .pum_kind = NULL, + }; + } + + // Compute the popup menu starting column + char *endpos = showtail ? showmatches_gettail(xp->xp_pattern, true) : xp->xp_pattern; + if (ui_has(kUICmdline)) { + compl_startcol = (int)(endpos - ccline->cmdbuff); + } else { + compl_startcol = cmd_screencol((int)(endpos - ccline->cmdbuff)); + } + + // no default selection + compl_selected = -1; + + cmdline_pum_display(true); + + return EXPAND_OK; +} + void cmdline_pum_display(bool changed_array) { pum_display(compl_match_array, compl_match_arraysize, compl_selected, changed_array, compl_startcol); } +/// Returns true if the cmdline completion popup menu is being displayed. bool cmdline_pum_active(void) { // compl_match_array != NULL should already imply pum_visible() in Nvim. return compl_match_array != NULL; } -/// Remove the cmdline completion popup menu +/// Remove the cmdline completion popup menu (if present), free the list of items. void cmdline_pum_remove(void) { pum_undisplay(true); @@ -306,9 +351,9 @@ void cmdline_pum_cleanup(CmdlineInfo *cclp) /// Return the number of characters that should be skipped in the wildmenu /// These are backslashes used for escaping. Do show backslashes in help tags. -static int skip_wildmenu_char(expand_T *xp, char_u *s) +static int skip_wildmenu_char(expand_T *xp, char *s) { - if ((rem_backslash((char *)s) && xp->xp_context != EXPAND_HELP) + if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP) || ((xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES) && (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL)))) { #ifndef BACKSLASH_IN_FILENAME @@ -326,7 +371,7 @@ static int skip_wildmenu_char(expand_T *xp, char_u *s) } /// Get the length of an item as it will be shown in the status line. -static int wildmenu_match_len(expand_T *xp, char_u *s) +static int wildmenu_match_len(expand_T *xp, char *s) { int len = 0; @@ -334,13 +379,13 @@ static int wildmenu_match_len(expand_T *xp, char_u *s) || xp->xp_context == EXPAND_MENUNAMES); // Check for menu separators - replace with '|'. - if (emenu && menu_is_separator((char *)s)) { + if (emenu && menu_is_separator(s)) { return 1; } while (*s != NUL) { s += skip_wildmenu_char(xp, s); - len += ptr2cells((char *)s); + len += ptr2cells(s); MB_PTR_ADV(s); } @@ -356,7 +401,6 @@ static int wildmenu_match_len(expand_T *xp, char_u *s) /// @param matches list of matches static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int match, int showtail) { -#define L_MATCH(m) (showtail ? showmatches_gettail(matches[m], false) : matches[m]) int row; char *buf; int len; @@ -385,7 +429,7 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m highlight = false; } // count 1 for the ending ">" - clen = wildmenu_match_len(xp, (char_u *)L_MATCH(match)) + 3; + clen = wildmenu_match_len(xp, SHOW_MATCH(match)) + 3; if (match == 0) { first_match = 0; } else if (match < first_match) { @@ -395,7 +439,7 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m } else { // check if match fits on the screen for (i = first_match; i < match; i++) { - clen += wildmenu_match_len(xp, (char_u *)L_MATCH(i)) + 2; + clen += wildmenu_match_len(xp, SHOW_MATCH(i)) + 2; } if (first_match > 0) { clen += 2; @@ -406,7 +450,7 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m // if showing the last match, we can add some on the left clen = 2; for (i = match; i < num_matches; i++) { - clen += wildmenu_match_len(xp, (char_u *)L_MATCH(i)) + 2; + clen += wildmenu_match_len(xp, SHOW_MATCH(i)) + 2; if ((long)clen >= Columns) { break; } @@ -418,7 +462,7 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m } if (add_left) { while (first_match > 0) { - clen += wildmenu_match_len(xp, (char_u *)L_MATCH(first_match - 1)) + 2; + clen += wildmenu_match_len(xp, SHOW_MATCH(first_match - 1)) + 2; if ((long)clen >= Columns) { break; } @@ -438,13 +482,13 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m clen = len; i = first_match; - while (clen + wildmenu_match_len(xp, (char_u *)L_MATCH(i)) + 2 < Columns) { + while (clen + wildmenu_match_len(xp, SHOW_MATCH(i)) + 2 < Columns) { if (i == match) { selstart = buf + len; selstart_col = clen; } - s = L_MATCH(i); + s = SHOW_MATCH(i); // Check for menu separators - replace with '|' emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES); @@ -455,7 +499,7 @@ static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int m clen += l; } else { for (; *s != NUL; s++) { - s += skip_wildmenu_char(xp, (char_u *)s); + s += skip_wildmenu_char(xp, s); clen += ptr2cells(s); if ((l = utfc_ptr2len(s)) > 1) { strncpy(buf + len, s, (size_t)l); // NOLINT(runtime/printf) @@ -551,6 +595,44 @@ static char *get_next_or_prev_match(int mode, expand_T *xp, int *p_findex, char findex--; } else if (mode == WILD_NEXT) { findex++; + } else if (mode == WILD_PAGEUP) { + if (findex == 0) { + // at the first entry, don't select any entries + findex = -1; + } else if (findex == -1) { + // no entry is selected. select the last entry + findex = xp->xp_numfiles - 1; + } else { + // go up by the pum height + int ht = pum_get_height(); + if (ht > 3) { + ht -= 2; + } + findex -= ht; + if (findex < 0) { + // few entries left, select the first entry + findex = 0; + } + } + } else if (mode == WILD_PAGEDOWN) { + if (findex == xp->xp_numfiles - 1) { + // at the last entry, don't select any entries + findex = -1; + } else if (findex == -1) { + // no entry is selected. select the first entry + findex = 0; + } else { + // go down by the pum height + int ht = pum_get_height(); + if (ht > 3) { + ht -= 2; + } + findex += ht; + if (findex >= xp->xp_numfiles) { + // few entries left, select the last entry + findex = xp->xp_numfiles - 1; + } + } } else { // mode == WILD_PUM_WANT assert(pum_want.active); findex = pum_want.item; @@ -589,7 +671,7 @@ static char *ExpandOne_start(int mode, expand_T *xp, char *str, int options) char *ss = NULL; // Do the expansion. - if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files, options) == FAIL) { + if (ExpandFromContext(xp, str, &xp->xp_files, &xp->xp_numfiles, options) == FAIL) { #ifdef FNAME_ILLEGAL // Illegal file name has been silently skipped. But when there // are wildcards, the real problem is that there was no match, @@ -604,11 +686,10 @@ static char *ExpandOne_start(int mode, expand_T *xp, char *str, int options) } } else { // Escape the matches for use on the command line. - ExpandEscape(xp, (char_u *)str, xp->xp_numfiles, xp->xp_files, options); + ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options); // Check for matching suffixes in file names. - if (mode != WILD_ALL && mode != WILD_ALL_KEEP - && mode != WILD_LONGEST) { + if (mode != WILD_ALL && mode != WILD_ALL_KEEP && mode != WILD_LONGEST) { if (xp->xp_numfiles) { non_suf_match = xp->xp_numfiles; } else { @@ -729,7 +810,9 @@ char *ExpandOne(expand_T *xp, char *str, char *orig, int options, int mode) int i; // first handle the case of using an old match - if (mode == WILD_NEXT || mode == WILD_PREV || mode == WILD_PUM_WANT) { + if (mode == WILD_NEXT || mode == WILD_PREV + || mode == WILD_PAGEUP || mode == WILD_PAGEDOWN + || mode == WILD_PUM_WANT) { return get_next_or_prev_match(mode, xp, &findex, orig_save); } @@ -820,37 +903,99 @@ void ExpandCleanup(expand_T *xp) } } +/// Display one line of completion matches. Multiple matches are displayed in +/// each line (used by wildmode=list and CTRL-D) +/// +/// @param matches list of completion match names +/// @param numMatches number of completion matches in "matches" +/// @param lines number of output lines +/// @param linenr line number of matches to display +/// @param maxlen maximum number of characters in each line +/// @param showtail display only the tail of the full path of a file name +/// @param dir_attr highlight attribute to use for directory names +static void showmatches_oneline(expand_T *xp, char **matches, int numMatches, int lines, int linenr, + int maxlen, int showtail, int dir_attr) +{ + char *p; + int lastlen = 999; + for (int j = linenr; j < numMatches; j += lines) { + if (xp->xp_context == EXPAND_TAGS_LISTFILES) { + msg_outtrans_attr(matches[j], HL_ATTR(HLF_D)); + p = matches[j] + strlen(matches[j]) + 1; + msg_advance(maxlen + 1); + msg_puts((const char *)p); + msg_advance(maxlen + 3); + msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); + break; + } + for (int i = maxlen - lastlen; --i >= 0;) { + msg_putchar(' '); + } + bool isdir; + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS) { + // highlight directories + if (xp->xp_numfiles != -1) { + // Expansion was done before and special characters + // were escaped, need to halve backslashes. Also + // $HOME has been replaced with ~/. + char *exp_path = (char *)expand_env_save_opt(matches[j], true); + char *path = exp_path != NULL ? exp_path : matches[j]; + char *halved_slash = backslash_halve_save(path); + isdir = os_isdir(halved_slash); + xfree(exp_path); + if (halved_slash != path) { + xfree(halved_slash); + } + } else { + // Expansion was done here, file names are literal. + isdir = os_isdir(matches[j]); + } + if (showtail) { + p = SHOW_MATCH(j); + } else { + home_replace(NULL, matches[j], NameBuff, MAXPATHL, true); + p = NameBuff; + } + } else { + isdir = false; + p = SHOW_MATCH(j); + } + lastlen = msg_outtrans_attr(p, isdir ? dir_attr : 0); + } + if (msg_col > 0) { // when not wrapped around + msg_clr_eos(); + msg_putchar('\n'); + } +} + /// Show all matches for completion on the command line. /// Returns EXPAND_NOTHING when the character that triggered expansion should /// be inserted like a normal character. int showmatches(expand_T *xp, int wildmenu) { CmdlineInfo *const ccline = get_cmdline_info(); -#define L_SHOWFILE(m) (showtail \ - ? showmatches_gettail(files_found[m], false) \ - : files_found[m]) - int num_files; - char **files_found; - int i, j, k; + int numMatches; + char **matches; + int i, j; int maxlen; int lines; int columns; - char *p; - int lastlen; int attr; int showtail; if (xp->xp_numfiles == -1) { set_expand_context(xp); i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos, - &num_files, &files_found); + &numMatches, &matches); showtail = expand_showtail(xp); if (i != EXPAND_OK) { return i; } } else { - num_files = xp->xp_numfiles; - files_found = xp->xp_files; + numMatches = xp->xp_numfiles; + matches = xp->xp_files; showtail = cmd_showtail; } @@ -860,26 +1005,8 @@ int showmatches(expand_T *xp, int wildmenu) || ui_has(kUIWildmenu); if (compl_use_pum) { - assert(num_files >= 0); - compl_match_arraysize = num_files; - compl_match_array = xmalloc(sizeof(pumitem_T) * (size_t)compl_match_arraysize); - for (i = 0; i < num_files; i++) { - compl_match_array[i] = (pumitem_T){ - .pum_text = (char_u *)L_SHOWFILE(i), - .pum_info = NULL, - .pum_extra = NULL, - .pum_kind = NULL, - }; - } - char *endpos = showtail ? showmatches_gettail(xp->xp_pattern, true) : xp->xp_pattern; - if (ui_has(kUICmdline)) { - compl_startcol = (int)(endpos - ccline->cmdbuff); - } else { - compl_startcol = cmd_screencol((int)(endpos - ccline->cmdbuff)); - } - compl_selected = -1; - cmdline_pum_display(true); - return EXPAND_OK; + // cmdline completion popup menu (with wildoptions=pum) + return cmdline_pum_create(ccline, xp, matches, numMatches, showtail); } if (!wildmenu) { @@ -895,18 +1022,18 @@ int showmatches(expand_T *xp, int wildmenu) if (got_int) { got_int = false; // only int. the completion, not the cmd line } else if (wildmenu) { - redraw_wildmenu(xp, num_files, files_found, -1, showtail); + redraw_wildmenu(xp, numMatches, matches, -1, showtail); } else { // find the length of the longest file name maxlen = 0; - for (i = 0; i < num_files; i++) { + for (i = 0; i < numMatches; i++) { if (!showtail && (xp->xp_context == EXPAND_FILES || xp->xp_context == EXPAND_SHELLCMD || xp->xp_context == EXPAND_BUFFERS)) { - home_replace(NULL, files_found[i], NameBuff, MAXPATHL, true); + home_replace(NULL, matches[i], NameBuff, MAXPATHL, true); j = vim_strsize(NameBuff); } else { - j = vim_strsize(L_SHOWFILE(i)); + j = vim_strsize(SHOW_MATCH(i)); } if (j > maxlen) { maxlen = j; @@ -914,7 +1041,7 @@ int showmatches(expand_T *xp, int wildmenu) } if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - lines = num_files; + lines = numMatches; } else { // compute the number of columns and lines for the listing maxlen += 2; // two spaces between file names @@ -922,7 +1049,7 @@ int showmatches(expand_T *xp, int wildmenu) if (columns < 1) { columns = 1; } - lines = (num_files + columns - 1) / columns; + lines = (numMatches + columns - 1) / columns; } attr = HL_ATTR(HLF_D); // find out highlighting for directories @@ -936,56 +1063,7 @@ int showmatches(expand_T *xp, int wildmenu) // list the files line by line for (i = 0; i < lines; i++) { - lastlen = 999; - for (k = i; k < num_files; k += lines) { - if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - msg_outtrans_attr(files_found[k], HL_ATTR(HLF_D)); - p = files_found[k] + strlen(files_found[k]) + 1; - msg_advance(maxlen + 1); - msg_puts((const char *)p); - msg_advance(maxlen + 3); - msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); - break; - } - for (j = maxlen - lastlen; --j >= 0;) { - msg_putchar(' '); - } - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS) { - // highlight directories - if (xp->xp_numfiles != -1) { - // Expansion was done before and special characters - // were escaped, need to halve backslashes. Also - // $HOME has been replaced with ~/. - char *exp_path = (char *)expand_env_save_opt((char_u *)files_found[k], true); - char *path = exp_path != NULL ? exp_path : files_found[k]; - char *halved_slash = backslash_halve_save(path); - j = os_isdir(halved_slash); - xfree(exp_path); - if (halved_slash != path) { - xfree(halved_slash); - } - } else { - // Expansion was done here, file names are literal. - j = os_isdir(files_found[k]); - } - if (showtail) { - p = L_SHOWFILE(k); - } else { - home_replace(NULL, files_found[k], NameBuff, MAXPATHL, true); - p = NameBuff; - } - } else { - j = false; - p = L_SHOWFILE(k); - } - lastlen = msg_outtrans_attr(p, j ? attr : 0); - } - if (msg_col > 0) { // when not wrapped around - msg_clr_eos(); - msg_putchar('\n'); - } + showmatches_oneline(xp, matches, numMatches, lines, i, maxlen, showtail, attr); if (got_int) { got_int = false; break; @@ -998,7 +1076,7 @@ int showmatches(expand_T *xp, int wildmenu) } if (xp->xp_numfiles == -1) { - FreeWild(num_files, files_found); + FreeWild(numMatches, matches); } return EXPAND_OK; @@ -1245,7 +1323,7 @@ void set_expand_context(expand_T *xp) xp->xp_context = EXPAND_NOTHING; return; } - set_cmd_context(xp, (char_u *)ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true); + set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true); } /// Sets the index of a built-in or user defined command "cmd" in eap->cmdidx. @@ -1423,17 +1501,228 @@ static void set_context_for_wildcard_arg(exarg_T *eap, const char *arg, bool use } } +/// Set the completion context for the :filter command. Returns a pointer to the +/// next command after the :filter command. +static const char *set_context_in_filter_cmd(expand_T *xp, const char *arg) +{ + if (*arg != NUL) { + arg = (const char *)skip_vimgrep_pat((char *)arg, NULL, NULL); + } + if (arg == NULL || *arg == NUL) { + xp->xp_context = EXPAND_NOTHING; + return NULL; + } + return (const char *)skipwhite(arg); +} + +/// Set the completion context for the :match command. Returns a pointer to the +/// next command after the :match command. +static const char *set_context_in_match_cmd(expand_T *xp, const char *arg) +{ + if (*arg == NUL || !ends_excmd(*arg)) { + // also complete "None" + set_context_in_echohl_cmd(xp, arg); + arg = (const char *)skipwhite(skiptowhite(arg)); + if (*arg != NUL) { + xp->xp_context = EXPAND_NOTHING; + arg = (const char *)skip_regexp((char *)arg + 1, (uint8_t)(*arg), magic_isset()); + } + } + return (const char *)find_nextcmd(arg); +} + +/// Returns a pointer to the next command after a :global or a :v command. +/// Returns NULL if there is no next command. +static const char *find_cmd_after_global_cmd(const char *arg) +{ + const int delim = (uint8_t)(*arg); // Get the delimiter. + if (delim) { + arg++; // Skip delimiter if there is one. + } + + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } + arg++; + } + if (arg[0] != NUL) { + return arg + 1; + } + + return NULL; +} + +/// Returns a pointer to the next command after a :substitute or a :& command. +/// Returns NULL if there is no next command. +static const char *find_cmd_after_substitute_cmd(const char *arg) +{ + const int delim = (uint8_t)(*arg); + if (delim) { + // Skip "from" part. + arg++; + arg = (const char *)skip_regexp((char *)arg, delim, magic_isset()); + + if (arg[0] != NUL && arg[0] == delim) { + // Skip "to" part. + arg++; + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } + arg++; + } + if (arg[0] != NUL) { // Skip delimiter. + arg++; + } + } + } + while (arg[0] && strchr("|\"#", arg[0]) == NULL) { + arg++; + } + if (arg[0] != NUL) { + return arg; + } + + return NULL; +} + +/// Returns a pointer to the next command after a :isearch/:dsearch/:ilist +/// :dlist/:ijump/:psearch/:djump/:isplit/:dsplit command. +/// Returns NULL if there is no next command. +static const char *find_cmd_after_isearch_cmd(expand_T *xp, const char *arg) +{ + // Skip count. + arg = (const char *)skipwhite(skipdigits(arg)); + if (*arg != '/') { + return NULL; + } + + // Match regexp, not just whole words. + for (++arg; *arg && *arg != '/'; arg++) { + if (*arg == '\\' && arg[1] != NUL) { + arg++; + } + } + if (*arg) { + arg = (const char *)skipwhite(arg + 1); + + // Check for trailing illegal characters. + if (*arg == NUL || strchr("|\"\n", *arg) == NULL) { + xp->xp_context = EXPAND_NOTHING; + } else { + return arg; + } + } + + return NULL; +} + +/// Set the completion context for the :unlet command. Always returns NULL. +static const char *set_context_in_unlet_cmd(expand_T *xp, const char *arg) +{ + while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { + arg = (const char *)xp->xp_pattern + 1; + } + + xp->xp_context = EXPAND_USER_VARS; + xp->xp_pattern = (char *)arg; + + if (*xp->xp_pattern == '$') { + xp->xp_context = EXPAND_ENV_VARS; + xp->xp_pattern++; + } + + return NULL; +} + +/// Set the completion context for the :language command. Always returns NULL. +static const char *set_context_in_lang_cmd(expand_T *xp, const char *arg) +{ + const char *p = (const char *)skiptowhite(arg); + if (*p == NUL) { + xp->xp_context = EXPAND_LANGUAGE; + xp->xp_pattern = (char *)arg; + } else { + if (strncmp(arg, "messages", (size_t)(p - arg)) == 0 + || strncmp(arg, "ctype", (size_t)(p - arg)) == 0 + || strncmp(arg, "time", (size_t)(p - arg)) == 0 + || strncmp(arg, "collate", (size_t)(p - arg)) == 0) { + xp->xp_context = EXPAND_LOCALES; + xp->xp_pattern = skipwhite(p); + } else { + xp->xp_context = EXPAND_NOTHING; + } + } + + return NULL; +} + +static enum { + EXP_BREAKPT_ADD, ///< expand ":breakadd" sub-commands + EXP_BREAKPT_DEL, ///< expand ":breakdel" sub-commands + EXP_PROFDEL, ///< expand ":profdel" sub-commands +} breakpt_expand_what; + +/// Set the completion context for the :breakadd command. Always returns NULL. +static const char *set_context_in_breakadd_cmd(expand_T *xp, const char *arg, cmdidx_T cmdidx) +{ + xp->xp_context = EXPAND_BREAKPOINT; + xp->xp_pattern = (char *)arg; + + if (cmdidx == CMD_breakadd) { + breakpt_expand_what = EXP_BREAKPT_ADD; + } else if (cmdidx == CMD_breakdel) { + breakpt_expand_what = EXP_BREAKPT_DEL; + } else { + breakpt_expand_what = EXP_PROFDEL; + } + + const char *p = skipwhite(arg); + if (*p == NUL) { + return NULL; + } + const char *subcmd_start = p; + + if (strncmp("file ", p, 5) == 0 || strncmp("func ", p, 5) == 0) { + // :breakadd file [lnum] <filename> + // :breakadd func [lnum] <funcname> + p += 4; + p = skipwhite(p); + + // skip line number (if specified) + if (ascii_isdigit(*p)) { + p = skipdigits(p); + if (*p != ' ') { + xp->xp_context = EXPAND_NOTHING; + return NULL; + } + p = skipwhite(p); + } + if (strncmp("file", subcmd_start, 4) == 0) { + xp->xp_context = EXPAND_FILES; + } else { + xp->xp_context = EXPAND_USER_FUNC; + } + xp->xp_pattern = (char *)p; + } else if (strncmp("expr ", p, 5) == 0) { + // :breakadd expr <expression> + xp->xp_context = EXPAND_EXPRESSION; + xp->xp_pattern = skipwhite(p + 5); + } + + return NULL; +} + /// Set the completion context in "xp" for command "cmd" with index "cmdidx". /// The argument to the command is "arg" and the argument flags is "argt". /// For user-defined commands and for environment variables, "context" has the /// completion type. /// /// @return a pointer to the next command, or NULL if there is no next command. -static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, const char *arg, - uint32_t argt, int context, expand_T *xp, bool forceit) +static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, expand_T *xp, + const char *arg, uint32_t argt, int context, bool forceit) { - const char *p; - switch (cmdidx) { case CMD_find: case CMD_sfind: @@ -1495,26 +1784,10 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons return arg; case CMD_filter: - if (*arg != NUL) { - arg = (const char *)skip_vimgrep_pat((char *)arg, NULL, NULL); - } - if (arg == NULL || *arg == NUL) { - xp->xp_context = EXPAND_NOTHING; - return NULL; - } - return (const char *)skipwhite(arg); + return set_context_in_filter_cmd(xp, arg); case CMD_match: - if (*arg == NUL || !ends_excmd(*arg)) { - // also complete "None" - set_context_in_echohl_cmd(xp, arg); - arg = (const char *)skipwhite(skiptowhite(arg)); - if (*arg != NUL) { - xp->xp_context = EXPAND_NOTHING; - arg = (const char *)skip_regexp((char *)arg + 1, (uint8_t)(*arg), magic_isset()); - } - } - return (const char *)find_nextcmd(arg); + return set_context_in_match_cmd(xp, arg); // All completion for the +cmdline_compl feature goes here. @@ -1527,53 +1800,11 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons break; case CMD_global: - case CMD_vglobal: { - const int delim = (uint8_t)(*arg); // Get the delimiter. - if (delim) { - arg++; // Skip delimiter if there is one. - } - - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { - arg++; - } - arg++; - } - if (arg[0] != NUL) { - return arg + 1; - } - break; - } + case CMD_vglobal: + return find_cmd_after_global_cmd(arg); case CMD_and: - case CMD_substitute: { - const int delim = (uint8_t)(*arg); - if (delim) { - // Skip "from" part. - arg++; - arg = (const char *)skip_regexp((char *)arg, delim, magic_isset()); - - if (arg[0] != NUL && arg[0] == delim) { - // Skip "to" part. - arg++; - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { - arg++; - } - arg++; - } - if (arg[0] != NUL) { // Skip delimiter. - arg++; - } - } - } - while (arg[0] && strchr("|\"#", arg[0]) == NULL) { - arg++; - } - if (arg[0] != NUL) { - return arg; - } - break; - } + case CMD_substitute: + return find_cmd_after_substitute_cmd(arg); case CMD_isearch: case CMD_dsearch: case CMD_ilist: @@ -1583,29 +1814,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons case CMD_djump: case CMD_isplit: case CMD_dsplit: - // Skip count. - arg = (const char *)skipwhite(skipdigits(arg)); - if (*arg != '/') { - return NULL; - } - - // Match regexp, not just whole words. - for (++arg; *arg && *arg != '/'; arg++) { - if (*arg == '\\' && arg[1] != NUL) { - arg++; - } - } - if (*arg) { - arg = (const char *)skipwhite(arg + 1); - - // Check for trailing illegal characters. - if (*arg == NUL || strchr("|\"\n", *arg) == NULL) { - xp->xp_context = EXPAND_NOTHING; - } else { - return arg; - } - } - break; + return find_cmd_after_isearch_cmd(xp, arg); case CMD_autocmd: return (const char *)set_context_in_autocmd(xp, (char *)arg, false); @@ -1668,20 +1877,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons break; case CMD_unlet: - while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { - arg = (const char *)xp->xp_pattern + 1; - } - - xp->xp_context = EXPAND_USER_VARS; - xp->xp_pattern = (char *)arg; - - if (*xp->xp_pattern == '$') { - xp->xp_context = EXPAND_ENV_VARS; - xp->xp_pattern++; - } - - break; - + return set_context_in_unlet_cmd(xp, arg); case CMD_function: case CMD_delfunction: xp->xp_context = EXPAND_USER_FUNC; @@ -1720,34 +1916,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons case CMD_USER: case CMD_USER_BUF: - if (context != EXPAND_NOTHING) { - // EX_XFILE: file names are handled above. - if (!(argt & EX_XFILE)) { - if (context == EXPAND_MENUS) { - return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); - } else if (context == EXPAND_COMMANDS) { - return arg; - } else if (context == EXPAND_MAPPINGS) { - return (const char *)set_context_in_map_cmd(xp, "map", (char *)arg, forceit, - false, false, - CMD_map); - } - // Find start of last argument. - p = arg; - while (*p) { - if (*p == ' ') { - // argument starts after a space - arg = p + 1; - } else if (*p == '\\' && *(p + 1) != NUL) { - p++; // skip over escaped character - } - MB_PTR_ADV(p); - } - xp->xp_pattern = (char *)arg; - } - xp->xp_context = context; - } - break; + return set_context_in_user_cmdarg(cmd, arg, argt, context, xp, forceit); case CMD_map: case CMD_noremap: @@ -1863,22 +2032,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons #ifdef HAVE_WORKING_LIBINTL case CMD_language: - p = (const char *)skiptowhite(arg); - if (*p == NUL) { - xp->xp_context = EXPAND_LANGUAGE; - xp->xp_pattern = (char *)arg; - } else { - if (strncmp(arg, "messages", (size_t)(p - arg)) == 0 - || strncmp(arg, "ctype", (size_t)(p - arg)) == 0 - || strncmp(arg, "time", (size_t)(p - arg)) == 0 - || strncmp(arg, "collate", (size_t)(p - arg)) == 0) { - xp->xp_context = EXPAND_LOCALES; - xp->xp_pattern = skipwhite(p); - } else { - xp->xp_context = EXPAND_NOTHING; - } - } - break; + return set_context_in_lang_cmd(xp, arg); #endif case CMD_profile: set_context_in_profile_cmd(xp, arg); @@ -1914,6 +2068,11 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons xp->xp_pattern = (char *)arg; break; + case CMD_breakadd: + case CMD_profdel: + case CMD_breakdel: + return set_context_in_breakadd_cmd(xp, arg, cmdidx); + case CMD_lua: xp->xp_context = EXPAND_LUA; break; @@ -2097,17 +2256,19 @@ static const char *set_one_cmd_context(expand_T *xp, const char *buff) } // Switch on command name. - return set_context_by_cmdname(cmd, ea.cmdidx, arg, ea.argt, context, xp, forceit); + return set_context_by_cmdname(cmd, ea.cmdidx, xp, arg, ea.argt, context, forceit); } +/// Set the completion context in "xp" for command "str" +/// /// @param str start of command line /// @param len length of command line (excl. NUL) /// @param col position of cursor /// @param use_ccline use ccline for info -void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline) +void set_cmd_context(expand_T *xp, char *str, int len, int col, int use_ccline) { CmdlineInfo *const ccline = get_cmdline_info(); - char_u old_char = NUL; + char old_char = NUL; // Avoid a UMR warning from Purify, only save the character if it has been // written before. @@ -2119,7 +2280,7 @@ void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline if (use_ccline && ccline->cmdfirstc == '=') { // pass CMD_SIZE because there is no real command - set_context_for_expression(xp, (char *)str, CMD_SIZE); + set_context_for_expression(xp, str, CMD_SIZE); } else if (use_ccline && ccline->input_fn) { xp->xp_context = ccline->xp_context; xp->xp_pattern = ccline->cmdbuff; @@ -2132,7 +2293,7 @@ void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline // Store the string here so that call_user_expand_func() can get to them // easily. - xp->xp_line = (char *)str; + xp->xp_line = str; xp->xp_col = col; str[col] = old_char; @@ -2176,7 +2337,7 @@ int expand_cmdline(expand_T *xp, const char *str, int col, int *matchcount, char } // find all files that match the description - if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL) { + if (ExpandFromContext(xp, file_str, matches, matchcount, options) == FAIL) { *matchcount = 0; *matches = NULL; } @@ -2186,8 +2347,8 @@ int expand_cmdline(expand_T *xp, const char *str, int col, int *matchcount, char } /// Expand file or directory names. -static int expand_files_and_dirs(expand_T *xp, char *pat, char ***file, int *num_file, int flags, - int options) +static int expand_files_and_dirs(expand_T *xp, char *pat, char ***matches, int *numMatches, + int flags, int options) { bool free_pat = false; @@ -2223,14 +2384,14 @@ static int expand_files_and_dirs(expand_T *xp, char *pat, char ***file, int *num } // Expand wildcards, supporting %:h and the like. - int ret = expand_wildcards_eval(&pat, num_file, file, flags); + int ret = expand_wildcards_eval(&pat, numMatches, matches, flags); if (free_pat) { xfree(pat); } #ifdef BACKSLASH_IN_FILENAME if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0) { - for (int j = 0; j < *num_file; j++) { - char *ptr = (*file)[j]; + for (int j = 0; j < *numMatches; j++) { + char *ptr = (*matches)[j]; while (*ptr != NUL) { if (p_csl[0] == 's' && *ptr == '\\') { *ptr = '/'; @@ -2259,6 +2420,32 @@ static char *get_behave_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) } /// Function given to ExpandGeneric() to obtain the possible arguments of the +/// ":breakadd {expr, file, func, here}" command. +/// ":breakdel {func, file, here}" command. +static char *get_breakadd_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + char *opts[] = { "expr", "file", "func", "here" }; + + if (idx >= 0 && idx <= 3) { + // breakadd {expr, file, func, here} + if (breakpt_expand_what == EXP_BREAKPT_ADD) { + return opts[idx]; + } else if (breakpt_expand_what == EXP_BREAKPT_DEL) { + // breakdel {func, file, here} + if (idx <= 2) { + return opts[idx + 1]; + } + } else { + // profdel {func, file} + if (idx <= 1) { + return opts[idx + 1]; + } + } + } + return NULL; +} + +/// Function given to ExpandGeneric() to obtain the possible arguments of the /// ":messages {clear}" command. static char *get_messages_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) { @@ -2303,7 +2490,7 @@ static char *get_healthcheck_names(expand_T *xp FUNC_ATTR_UNUSED, int idx) } /// Do the expansion based on xp->xp_context and "rmp". -static int ExpandOther(expand_T *xp, regmatch_T *rmp, int *num_file, char ***file) +static int ExpandOther(expand_T *xp, regmatch_T *rmp, char ***matches, int *numMatches) { typedef CompleteListItemGetter ExpandFunc; static struct expgen { @@ -2342,6 +2529,7 @@ static int ExpandOther(expand_T *xp, regmatch_T *rmp, int *num_file, char ***fil { EXPAND_ENV_VARS, get_env_name, true, true }, { EXPAND_USER, get_users, true, false }, { EXPAND_ARGLIST, get_arglist_name, true, false }, + { EXPAND_BREAKPOINT, get_breakadd_arg, true, true }, { EXPAND_CHECKHEALTH, get_healthcheck_names, true, false }, }; int ret = FAIL; @@ -2353,7 +2541,7 @@ static int ExpandOther(expand_T *xp, regmatch_T *rmp, int *num_file, char ***fil if (tab[i].ic) { rmp->rm_ic = true; } - ExpandGeneric(xp, rmp, num_file, file, tab[i].func, tab[i].escaped); + ExpandGeneric(xp, rmp, matches, numMatches, tab[i].func, tab[i].escaped); ret = OK; break; } @@ -2362,16 +2550,10 @@ static int ExpandOther(expand_T *xp, regmatch_T *rmp, int *num_file, char ***fil return ret; } -/// Do the expansion based on xp->xp_context and "pat". -/// -/// @param options WILD_ flags -static int ExpandFromContext(expand_T *xp, char *pat, int *num_file, char ***file, int options) +/// Map wild expand options to flags for expand_wildcards() +static int map_wildopts_to_ewflags(int options) { - regmatch_T regmatch; - int ret; - int flags; - - flags = EW_DIR; // include directories + int flags = EW_DIR; // include directories if (options & WILD_LIST_NOTFOUND) { flags |= EW_NOTFOUND; } @@ -2391,68 +2573,79 @@ static int ExpandFromContext(expand_T *xp, char *pat, int *num_file, char ***fil flags |= EW_ALLLINKS; } + return flags; +} + +/// Do the expansion based on xp->xp_context and "pat". +/// +/// @param options WILD_ flags +static int ExpandFromContext(expand_T *xp, char *pat, char ***matches, int *numMatches, int options) +{ + regmatch_T regmatch; + int ret; + int flags = map_wildopts_to_ewflags(options); + if (xp->xp_context == EXPAND_FILES || xp->xp_context == EXPAND_DIRECTORIES || xp->xp_context == EXPAND_FILES_IN_PATH) { - return expand_files_and_dirs(xp, pat, file, num_file, flags, options); + return expand_files_and_dirs(xp, pat, matches, numMatches, flags, options); } - *file = NULL; - *num_file = 0; + *matches = NULL; + *numMatches = 0; if (xp->xp_context == EXPAND_HELP) { // With an empty argument we would get all the help tags, which is // very slow. Get matches for "help" instead. if (find_help_tags(*pat == NUL ? "help" : pat, - num_file, file, false) == OK) { - cleanup_help_tags(*num_file, *file); + numMatches, matches, false) == OK) { + cleanup_help_tags(*numMatches, *matches); return OK; } return FAIL; } if (xp->xp_context == EXPAND_SHELLCMD) { - *file = NULL; - expand_shellcmd(pat, num_file, file, flags); + expand_shellcmd(pat, matches, numMatches, flags); return OK; } if (xp->xp_context == EXPAND_OLD_SETTING) { - ExpandOldSetting(num_file, file); + ExpandOldSetting(numMatches, matches); return OK; } if (xp->xp_context == EXPAND_BUFFERS) { - return ExpandBufnames(pat, num_file, file, options); + return ExpandBufnames(pat, numMatches, matches, options); } if (xp->xp_context == EXPAND_DIFF_BUFFERS) { - return ExpandBufnames(pat, num_file, file, options | BUF_DIFF_FILTER); + return ExpandBufnames(pat, numMatches, matches, options | BUF_DIFF_FILTER); } if (xp->xp_context == EXPAND_TAGS || xp->xp_context == EXPAND_TAGS_LISTFILES) { - return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file); + return expand_tags(xp->xp_context == EXPAND_TAGS, pat, numMatches, matches); } if (xp->xp_context == EXPAND_COLORS) { char *directories[] = { "colors", NULL }; - return ExpandRTDir(pat, DIP_START + DIP_OPT + DIP_LUA, num_file, file, directories); + return ExpandRTDir(pat, DIP_START + DIP_OPT + DIP_LUA, numMatches, matches, directories); } if (xp->xp_context == EXPAND_COMPILER) { char *directories[] = { "compiler", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + return ExpandRTDir(pat, DIP_LUA, numMatches, matches, directories); } if (xp->xp_context == EXPAND_OWNSYNTAX) { char *directories[] = { "syntax", NULL }; - return ExpandRTDir(pat, 0, num_file, file, directories); + return ExpandRTDir(pat, 0, numMatches, matches, directories); } if (xp->xp_context == EXPAND_FILETYPE) { char *directories[] = { "syntax", "indent", "ftplugin", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + return ExpandRTDir(pat, DIP_LUA, numMatches, matches, directories); } if (xp->xp_context == EXPAND_USER_LIST) { - return ExpandUserList(xp, num_file, file); + return ExpandUserList(xp, matches, numMatches); } if (xp->xp_context == EXPAND_USER_LUA) { - return ExpandUserLua(xp, num_file, file); + return ExpandUserLua(xp, numMatches, matches); } if (xp->xp_context == EXPAND_PACKADD) { - return ExpandPackAddDir(pat, num_file, file); + return ExpandPackAddDir(pat, numMatches, matches); } // When expanding a function name starting with s:, match the <SNR>nr_ @@ -2468,7 +2661,7 @@ static int ExpandFromContext(expand_T *xp, char *pat, int *num_file, char ***fil if (xp->xp_context == EXPAND_LUA) { ILOG("PAT %s", pat); - return nlua_expand_pat(xp, pat, num_file, file); + return nlua_expand_pat(xp, pat, numMatches, matches); } regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0); @@ -2477,17 +2670,17 @@ static int ExpandFromContext(expand_T *xp, char *pat, int *num_file, char ***fil } // set ignore-case according to p_ic, p_scs and pat - regmatch.rm_ic = ignorecase((char_u *)pat); + regmatch.rm_ic = ignorecase(pat); if (xp->xp_context == EXPAND_SETTINGS || xp->xp_context == EXPAND_BOOL_SETTINGS) { - ret = ExpandSettings(xp, ®match, num_file, file); + ret = ExpandSettings(xp, ®match, numMatches, matches); } else if (xp->xp_context == EXPAND_MAPPINGS) { - ret = ExpandMappings(®match, num_file, file); + ret = ExpandMappings(®match, numMatches, matches); } else if (xp->xp_context == EXPAND_USER_DEFINED) { - ret = ExpandUserDefined(xp, ®match, num_file, file); + ret = ExpandUserDefined(xp, ®match, matches, numMatches); } else { - ret = ExpandOther(xp, ®match, num_file, file); + ret = ExpandOther(xp, ®match, matches, numMatches); } vim_regfree(regmatch.regprog); @@ -2503,7 +2696,7 @@ static int ExpandFromContext(expand_T *xp, char *pat, int *num_file, char ***fil /// program. Matching strings are copied into an array, which is returned. /// /// @param func returns a string from the list -static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file, +static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, char ***matches, int *numMatches, CompleteListItemGetter func, int escaped) { int i; @@ -2527,8 +2720,8 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha return; } assert(count < INT_MAX); - *num_file = (int)count; - *file = xmalloc(count * sizeof(char_u *)); + *numMatches = (int)count; + *matches = xmalloc(count * sizeof(char *)); // copy the matching names into allocated memory count = 0; @@ -2542,11 +2735,11 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha } if (vim_regexec(regmatch, str, (colnr_T)0)) { if (escaped) { - str = (char *)vim_strsave_escaped((char_u *)str, (char_u *)" \t\\."); + str = vim_strsave_escaped(str, " \t\\."); } else { str = xstrdup(str); } - (*file)[count++] = str; + (*matches)[count++] = str; if (func == get_menu_names) { // Test for separator added by get_menu_names(). str += strlen(str) - 1; @@ -2563,9 +2756,9 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha || xp->xp_context == EXPAND_FUNCTIONS || xp->xp_context == EXPAND_USER_FUNC) { // <SNR> functions should be sorted to the end. - qsort((void *)(*file), (size_t)(*num_file), sizeof(char *), sort_func_compare); + qsort((void *)(*matches), (size_t)(*numMatches), sizeof(char *), sort_func_compare); } else { - sort_strings(*file, *num_file); + sort_strings(*matches, *numMatches); } } @@ -2574,15 +2767,53 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha reset_expand_highlight(); } +/// Expand shell command matches in one directory of $PATH. +static void expand_shellcmd_onedir(char *buf, char *s, size_t l, char *pat, char ***matches, + int *numMatches, int flags, hashtab_T *ht, garray_T *gap) +{ + xstrlcpy(buf, s, l + 1); + add_pathsep(buf); + l = strlen(buf); + xstrlcpy(buf + l, pat, MAXPATHL - l); + + // Expand matches in one directory of $PATH. + int ret = expand_wildcards(1, &buf, numMatches, matches, flags); + if (ret != OK) { + return; + } + + ga_grow(gap, *numMatches); + + for (int i = 0; i < *numMatches; i++) { + char *name = (*matches)[i]; + + if (strlen(name) > l) { + // Check if this name was already found. + hash_T hash = hash_hash((char_u *)name + l); + hashitem_T *hi = + hash_lookup(ht, (const char *)(name + l), strlen(name + l), hash); + if (HASHITEM_EMPTY(hi)) { + // Remove the path that was prepended. + STRMOVE(name, name + l); + ((char **)gap->ga_data)[gap->ga_len++] = name; + hash_add_item(ht, hi, (char_u *)name, hash); + name = NULL; + } + } + xfree(name); + } + xfree(*matches); +} + /// Complete a shell command. /// -/// @param filepat is a pattern to match with command names. -/// @param[out] num_file is pointer to number of matches. -/// @param[out] file is pointer to array of pointers to matches. -/// *file will either be set to NULL or point to -/// allocated memory. -/// @param flagsarg is a combination of EW_* flags. -static void expand_shellcmd(char *filepat, int *num_file, char ***file, int flagsarg) +/// @param filepat is a pattern to match with command names. +/// @param[out] matches is pointer to array of pointers to matches. +/// *matches will either be set to NULL or point to +/// allocated memory. +/// @param[out] numMatches is pointer to number of matches. +/// @param flagsarg is a combination of EW_* flags. +static void expand_shellcmd(char *filepat, char ***matches, int *numMatches, int flagsarg) FUNC_ATTR_NONNULL_ALL { char *pat; @@ -2593,7 +2824,6 @@ static void expand_shellcmd(char *filepat, int *num_file, char ***file, int flag size_t l; char *s, *e; int flags = flagsarg; - int ret; bool did_curdir = false; // for ":set path=" and ":set tags=" halve backslashes for escaped space @@ -2653,44 +2883,13 @@ static void expand_shellcmd(char *filepat, int *num_file, char ***file, int flag if (l > MAXPATHL - 5) { break; } - xstrlcpy(buf, s, l + 1); - add_pathsep(buf); - l = strlen(buf); - xstrlcpy(buf + l, pat, MAXPATHL - l); - - // Expand matches in one directory of $PATH. - ret = expand_wildcards(1, &buf, num_file, file, flags); - if (ret == OK) { - ga_grow(&ga, *num_file); - { - for (i = 0; i < *num_file; i++) { - char *name = (*file)[i]; - - if (strlen(name) > l) { - // Check if this name was already found. - hash_T hash = hash_hash((char_u *)name + l); - hashitem_T *hi = - hash_lookup(&found_ht, (const char *)(name + l), - strlen(name + l), hash); - if (HASHITEM_EMPTY(hi)) { - // Remove the path that was prepended. - STRMOVE(name, name + l); - ((char **)ga.ga_data)[ga.ga_len++] = name; - hash_add_item(&found_ht, hi, (char_u *)name, hash); - name = NULL; - } - } - xfree(name); - } - xfree(*file); - } - } + expand_shellcmd_onedir(buf, s, l, pat, matches, numMatches, flags, &found_ht, &ga); if (*e != NUL) { e++; } } - *file = ga.ga_data; - *num_file = ga.ga_len; + *matches = ga.ga_data; + *numMatches = ga.ga_len; xfree(buf); xfree(pat); @@ -2702,8 +2901,7 @@ static void expand_shellcmd(char *filepat, int *num_file, char ***file, int flag /// Call "user_expand_func()" to invoke a user defined Vim script function and /// return the result (either a string, a List or NULL). -static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T *xp, int *num_file, - char ***file) +static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T *xp) FUNC_ATTR_NONNULL_ALL { CmdlineInfo *const ccline = get_cmdline_info(); @@ -2715,8 +2913,6 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL) { return NULL; } - *num_file = 0; - *file = NULL; if (ccline->cmdbuff != NULL) { keep = ccline->cmdbuff[ccline->cmdlen]; @@ -2734,7 +2930,7 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T current_sctx = xp->xp_script_ctx; - void *const ret = user_expand_func((char_u *)xp->xp_arg, 3, args); + void *const ret = user_expand_func(xp->xp_arg, 3, args); current_sctx = save_current_sctx; if (ccline->cmdbuff != NULL) { @@ -2746,13 +2942,14 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T } /// Expand names with a function defined by the user. -static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file) +static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, char ***matches, int *numMatches) { char *e; garray_T ga; - char *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file, - file); + *matches = NULL; + *numMatches = 0; + char *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp); if (retstr == NULL) { return FAIL; @@ -2778,16 +2975,17 @@ static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, } } xfree(retstr); - *file = ga.ga_data; - *num_file = ga.ga_len; + *matches = ga.ga_data; + *numMatches = ga.ga_len; return OK; } /// Expand names with a list returned by a function defined by the user. -static int ExpandUserList(expand_T *xp, int *num_file, char ***file) +static int ExpandUserList(expand_T *xp, char ***matches, int *numMatches) { - list_T *const retlist = call_user_expand_func((user_expand_func_T)call_func_retlist, xp, num_file, - file); + *matches = NULL; + *numMatches = 0; + list_T *const retlist = call_user_expand_func((user_expand_func_T)call_func_retlist, xp); if (retlist == NULL) { return FAIL; } @@ -2805,8 +3003,8 @@ static int ExpandUserList(expand_T *xp, int *num_file, char ***file) }); tv_list_unref(retlist); - *file = ga.ga_data; - *num_file = ga.ga_len; + *matches = ga.ga_data; + *numMatches = ga.ga_len; return OK; } @@ -2859,10 +3057,10 @@ void globpath(char *path, char *file, garray_T *ga, int expand_options) char **p; int num_p = 0; - (void)ExpandFromContext(&xpc, buf, &num_p, &p, + (void)ExpandFromContext(&xpc, buf, &p, &num_p, WILD_SILENT | expand_options); if (num_p > 0) { - ExpandEscape(&xpc, (char_u *)buf, num_p, p, WILD_SILENT | expand_options); + ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT | expand_options); // Concatenate new results to previous ones. ga_grow(ga, num_p); @@ -2914,145 +3112,158 @@ static void cmdline_del(CmdlineInfo *cclp, int from) cclp->cmdpos = from; } -/// Handle a key pressed when wild menu is displayed -int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) +/// Handle a key pressed when the wild menu for the menu names +/// (EXPAND_MENUNAMES) is displayed. +static int wildmenu_process_key_menunames(CmdlineInfo *cclp, int key, expand_T *xp) { - int c = key; - - // Special translations for 'wildmenu' - if (xp->xp_context == EXPAND_MENUNAMES) { - // Hitting <Down> after "emenu Name.": complete submenu - if (c == K_DOWN && cclp->cmdpos > 0 - && cclp->cmdbuff[cclp->cmdpos - 1] == '.') { - c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - } else if (c == K_UP) { - // Hitting <Up>: Remove one submenu name in front of the - // cursor - int found = false; - - int j = (int)(xp->xp_pattern - cclp->cmdbuff); - int i = 0; - while (--j > 0) { - // check for start of menu name - if (cclp->cmdbuff[j] == ' ' - && cclp->cmdbuff[j - 1] != '\\') { + // Hitting <Down> after "emenu Name.": complete submenu + if (key == K_DOWN && cclp->cmdpos > 0 + && cclp->cmdbuff[cclp->cmdpos - 1] == '.') { + key = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } else if (key == K_UP) { + // Hitting <Up>: Remove one submenu name in front of the + // cursor + int found = false; + + int j = (int)(xp->xp_pattern - cclp->cmdbuff); + int i = 0; + while (--j > 0) { + // check for start of menu name + if (cclp->cmdbuff[j] == ' ' + && cclp->cmdbuff[j - 1] != '\\') { + i = j + 1; + break; + } + // check for start of submenu name + if (cclp->cmdbuff[j] == '.' + && cclp->cmdbuff[j - 1] != '\\') { + if (found) { i = j + 1; break; - } - - // check for start of submenu name - if (cclp->cmdbuff[j] == '.' - && cclp->cmdbuff[j - 1] != '\\') { - if (found) { - i = j + 1; - break; - } else { - found = true; - } + } else { + found = true; } } - if (i > 0) { - cmdline_del(cclp, i); - } - c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - xp->xp_context = EXPAND_NOTHING; } + if (i > 0) { + cmdline_del(cclp, i); + } + key = (int)p_wc; + KeyTyped = true; // in case the key was mapped + xp->xp_context = EXPAND_NOTHING; } - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_DIRECTORIES - || xp->xp_context == EXPAND_SHELLCMD) { - char upseg[5]; - - upseg[0] = PATHSEP; - upseg[1] = '.'; - upseg[2] = '.'; - upseg[3] = PATHSEP; - upseg[4] = NUL; - - if (c == K_DOWN - && cclp->cmdpos > 0 - && cclp->cmdbuff[cclp->cmdpos - 1] == PATHSEP - && (cclp->cmdpos < 3 - || cclp->cmdbuff[cclp->cmdpos - 2] != '.' - || cclp->cmdbuff[cclp->cmdpos - 3] != '.')) { - // go down a directory - c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - } else if (strncmp(xp->xp_pattern, upseg + 1, 3) == 0 - && c == K_DOWN) { - // If in a direct ancestor, strip off one ../ to go down - int found = false; - - int j = cclp->cmdpos; - int i = (int)(xp->xp_pattern - cclp->cmdbuff); - while (--j > i) { - j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); - if (vim_ispathsep(cclp->cmdbuff[j])) { - found = true; - break; - } - } - if (found - && cclp->cmdbuff[j - 1] == '.' - && cclp->cmdbuff[j - 2] == '.' - && (vim_ispathsep(cclp->cmdbuff[j - 3]) || j == i + 2)) { - cmdline_del(cclp, j - 2); - c = (int)p_wc; - KeyTyped = true; // in case the key was mapped + + return key; +} + +/// Handle a key pressed when the wild menu for file names (EXPAND_FILES) or +/// directory names (EXPAND_DIRECTORIES) or shell command names +/// (EXPAND_SHELLCMD) is displayed. +static int wildmenu_process_key_filenames(CmdlineInfo *cclp, int key, expand_T *xp) +{ + char upseg[5]; + upseg[0] = PATHSEP; + upseg[1] = '.'; + upseg[2] = '.'; + upseg[3] = PATHSEP; + upseg[4] = NUL; + + if (key == K_DOWN + && cclp->cmdpos > 0 + && cclp->cmdbuff[cclp->cmdpos - 1] == PATHSEP + && (cclp->cmdpos < 3 + || cclp->cmdbuff[cclp->cmdpos - 2] != '.' + || cclp->cmdbuff[cclp->cmdpos - 3] != '.')) { + // go down a directory + key = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } else if (strncmp(xp->xp_pattern, upseg + 1, 3) == 0 && key == K_DOWN) { + // If in a direct ancestor, strip off one ../ to go down + int found = false; + + int j = cclp->cmdpos; + int i = (int)(xp->xp_pattern - cclp->cmdbuff); + while (--j > i) { + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + if (vim_ispathsep(cclp->cmdbuff[j])) { + found = true; + break; } - } else if (c == K_UP) { - // go up a directory - int found = false; - - int j = cclp->cmdpos - 1; - int i = (int)(xp->xp_pattern - cclp->cmdbuff); - while (--j > i) { - j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); - if (vim_ispathsep(cclp->cmdbuff[j]) + } + if (found + && cclp->cmdbuff[j - 1] == '.' + && cclp->cmdbuff[j - 2] == '.' + && (vim_ispathsep(cclp->cmdbuff[j - 3]) || j == i + 2)) { + cmdline_del(cclp, j - 2); + key = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } + } else if (key == K_UP) { + // go up a directory + int found = false; + + int j = cclp->cmdpos - 1; + int i = (int)(xp->xp_pattern - cclp->cmdbuff); + while (--j > i) { + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + if (vim_ispathsep(cclp->cmdbuff[j]) #ifdef BACKSLASH_IN_FILENAME - && vim_strchr((const char_u *)" *?[{`$%#", cclp->cmdbuff[j + 1]) - == NULL + && vim_strchr(" *?[{`$%#", (uint8_t)cclp->cmdbuff[j + 1]) == NULL #endif - ) { - if (found) { - i = j + 1; - break; - } else { - found = true; - } + ) { + if (found) { + i = j + 1; + break; + } else { + found = true; } } + } - if (!found) { - j = i; - } else if (strncmp(cclp->cmdbuff + j, upseg, 4) == 0) { - j += 4; - } else if (strncmp(cclp->cmdbuff + j, upseg + 1, 3) == 0 - && j == i) { - j += 3; - } else { - j = 0; - } - - if (j > 0) { - // TODO(tarruda): this is only for DOS/Unix systems - need to put in - // machine-specific stuff here and in upseg init - cmdline_del(cclp, j); - put_on_cmdline((char_u *)upseg + 1, 3, false); - } else if (cclp->cmdpos > i) { - cmdline_del(cclp, i); - } + if (!found) { + j = i; + } else if (strncmp(cclp->cmdbuff + j, upseg, 4) == 0) { + j += 4; + } else if (strncmp(cclp->cmdbuff + j, upseg + 1, 3) == 0 + && j == i) { + j += 3; + } else { + j = 0; + } - // Now complete in the new directory. Set KeyTyped in case the - // Up key came from a mapping. - c = (int)p_wc; - KeyTyped = true; + if (j > 0) { + // TODO(tarruda): this is only for DOS/Unix systems - need to put in + // machine-specific stuff here and in upseg init + cmdline_del(cclp, j); + put_on_cmdline(upseg + 1, 3, false); + } else if (cclp->cmdpos > i) { + cmdline_del(cclp, i); } + + // Now complete in the new directory. Set KeyTyped in case the + // Up key came from a mapping. + key = (int)p_wc; + KeyTyped = true; } - return c; + return key; +} + +/// Handle a key pressed when wild menu is displayed +int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) +{ + // Special translations for 'wildmenu' + if (xp->xp_context == EXPAND_MENUNAMES) { + return wildmenu_process_key_menunames(cclp, key, xp); + } + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_DIRECTORIES + || xp->xp_context == EXPAND_SHELLCMD) { + return wildmenu_process_key_filenames(cclp, key, xp); + } + + return key; } /// Free expanded names when finished walking through the matches diff --git a/src/nvim/cmdexpand.h b/src/nvim/cmdexpand.h index cdd6192086..810e289f7c 100644 --- a/src/nvim/cmdexpand.h +++ b/src/nvim/cmdexpand.h @@ -19,8 +19,8 @@ enum { WILD_ALL_KEEP = 8, WILD_CANCEL = 9, WILD_APPLY = 10, - // WILD_PAGEUP = 11, not ported yet - // WILD_PAGEDOWN = 12, not ported yet + WILD_PAGEUP = 11, + WILD_PAGEDOWN = 12, WILD_PUM_WANT = 13, }; diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c index 0d56319891..b1dbc68ea3 100644 --- a/src/nvim/cursor.c +++ b/src/nvim/cursor.c @@ -115,7 +115,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a col = wcol; if ((addspaces || finetune) && !VIsual_active) { - curwin->w_curswant = linetabsize((char_u *)line) + one_more; + curwin->w_curswant = linetabsize(line) + one_more; if (curwin->w_curswant > 0) { curwin->w_curswant--; } @@ -129,7 +129,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a && curwin->w_width_inner != 0 && wcol >= (colnr_T)width && width > 0) { - csize = linetabsize((char_u *)line); + csize = linetabsize(line); if (csize > 0) { csize--; } @@ -178,11 +178,11 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a int correct = wcol - col; size_t newline_size; STRICT_ADD(idx, correct, &newline_size, size_t); - char_u *newline = xmallocz(newline_size); + char *newline = xmallocz(newline_size); memcpy(newline, line, (size_t)idx); memset(newline + idx, ' ', (size_t)correct); - ml_replace(pos->lnum, (char *)newline, false); + ml_replace(pos->lnum, newline, false); inserted_bytes(pos->lnum, (colnr_T)idx, 0, correct); idx += correct; col = wcol; @@ -190,7 +190,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a // Break a tab int linelen = (int)strlen(line); int correct = wcol - col - csize + 1; // negative!! - char_u *newline; + char *newline; if (-correct > csize) { return FAIL; @@ -208,7 +208,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a STRICT_SUB(n, 1, &n, size_t); memcpy(newline + idx + csize, line + idx + 1, n); - ml_replace(pos->lnum, (char *)newline, false); + ml_replace(pos->lnum, newline, false); inserted_bytes(pos->lnum, idx, 1, csize); idx += (csize - 1 + correct); col += correct; diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 601d4f0f29..45f00cb41e 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -1171,7 +1171,7 @@ static int diff_file(diffio_T *dio) tmp_orig, tmp_new); append_redir(cmd, len, p_srr, tmp_diff); block_autocmds(); // Avoid ShellCmdPost stuff - (void)call_shell((char_u *)cmd, + (void)call_shell(cmd, kShellOptFilter | kShellOptSilent | kShellOptDoOut, NULL); unblock_autocmds(); @@ -1255,7 +1255,7 @@ void ex_diffpatch(exarg_T *eap) vim_snprintf(buf, buflen, "patch -o %s %s < %s", tmp_new, tmp_orig, esc_name); block_autocmds(); // Avoid ShellCmdPost stuff - (void)call_shell((char_u *)buf, kShellOptFilter, NULL); + (void)call_shell(buf, kShellOptFilter, NULL); unblock_autocmds(); } diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c index 744520149f..33038dfb9f 100644 --- a/src/nvim/digraph.c +++ b/src/nvim/digraph.c @@ -1656,8 +1656,8 @@ static void registerdigraph(int char1, int char2, int n) bool check_digraph_chars_valid(int char1, int char2) { if (char2 == 0) { - char_u msg[MB_MAXBYTES + 1]; - msg[utf_char2bytes(char1, (char *)msg)] = NUL; + char msg[MB_MAXBYTES + 1]; + msg[utf_char2bytes(char1, msg)] = NUL; semsg(_(e_digraph_must_be_just_two_characters_str), msg); return false; } @@ -2133,7 +2133,7 @@ void ex_loadkeymap(exarg_T *eap) vim_snprintf(buf, sizeof(buf), "<buffer> %s %s", ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].from, ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].to); - (void)do_map(MAPTYPE_MAP, (char_u *)buf, MODE_LANGMAP, false); + (void)do_map(MAPTYPE_MAP, buf, MODE_LANGMAP, false); } p_cpo = save_cpo; @@ -2170,7 +2170,7 @@ static void keymap_unload(void) for (int i = 0; i < curbuf->b_kmap_ga.ga_len; i++) { vim_snprintf(buf, sizeof(buf), "<buffer> %s", kp[i].from); - (void)do_map(MAPTYPE_UNMAP, (char_u *)buf, MODE_LANGMAP, false); + (void)do_map(MAPTYPE_UNMAP, buf, MODE_LANGMAP, false); } keymap_ga_clear(&curbuf->b_kmap_ga); diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index b1cdfe209b..8fc1a4b029 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -403,8 +403,8 @@ static int get_sign_attrs(buf_T *buf, linenr_T lnum, SignTextAttrs *sattrs, int /// /// @param[out] stcp Status column attributes static void get_statuscol_str(win_T *wp, linenr_T lnum, int row, int startrow, int filler_lines, - int cul_attr, int sign_num_attr, SignTextAttrs *sattrs, - foldinfo_T foldinfo, char_u *extra, statuscol_T *stcp) + int cul_attr, int sign_num_attr, int sign_cul_attr, char_u *extra, + foldinfo_T foldinfo, SignTextAttrs *sattrs, statuscol_T *stcp) { long relnum = 0; bool wrapped = row != startrow + filler_lines; @@ -417,7 +417,7 @@ static void get_statuscol_str(win_T *wp, linenr_T lnum, int row, int startrow, i : get_line_number_attr(wp, lnum, row, startrow, filler_lines); if (compute_foldcolumn(wp, 0)) { - size_t n = fill_foldcolumn((char_u *)stcp->fold_text, wp, foldinfo, lnum); + size_t n = fill_foldcolumn(stcp->fold_text, wp, foldinfo, lnum); stcp->fold_text[n] = NUL; stcp->fold_attr = win_hl_attr(wp, use_cul ? HLF_CLF : HLF_FC); } @@ -427,7 +427,8 @@ static void get_statuscol_str(win_T *wp, linenr_T lnum, int row, int startrow, i for (; i < wp->w_scwidth; i++) { SignTextAttrs *sattr = wrapped ? NULL : sign_get_attr(i, sattrs, wp->w_scwidth); stcp->sign_text[i] = sattr && sattr->text ? sattr->text : " "; - stcp->sign_attr[i] = use_cul && cul_attr ? cul_attr : sattr ? sattr->hl_attr_id : 0; + stcp->sign_attr[i] = sattr ? (use_cul && sign_cul_attr ? sign_cul_attr : sattr->hl_attr_id) + : win_hl_attr(wp, use_cul ? HLF_CLS : HLF_SC); } stcp->sign_text[i] = NULL; @@ -615,16 +616,15 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, int c_extra = NUL; // extra chars, all the same int c_final = NUL; // final char, mandatory if set int extra_attr = 0; // attributes when n_extra != 0 - static char_u *at_end_str = (char_u *)""; // used for p_extra when displaying - // curwin->w_p_lcs_chars.eol at - // end-of-line + static char *at_end_str = ""; // used for p_extra when displaying curwin->w_p_lcs_chars.eol + // at end-of-line int lcs_eol_one = wp->w_p_lcs_chars.eol; // 'eol' until it's been used int lcs_prec_todo = wp->w_p_lcs_chars.prec; // 'prec' until it's been used bool has_fold = foldinfo.fi_level != 0 && foldinfo.fi_lines > 0; // saved "extra" items for when draw_state becomes WL_LINE (again) int saved_n_extra = 0; - char_u *saved_p_extra = NULL; + char *saved_p_extra = NULL; int saved_c_extra = 0; int saved_c_final = 0; int saved_char_attr = 0; @@ -698,7 +698,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, bool has_decor = false; // this buffer has decoration int win_col_offset = 0; // offset for window columns - char_u buf_fold[FOLD_TEXT_LEN]; // Hold value returned by get_foldtext + char buf_fold[FOLD_TEXT_LEN]; // Hold value returned by get_foldtext bool area_active = false; @@ -1239,7 +1239,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // already be in use. xfree(p_extra_free); p_extra_free = xmalloc(MAX_MCO * (size_t)fdc + 1); - n_extra = (int)fill_foldcolumn((char_u *)p_extra_free, wp, foldinfo, lnum); + n_extra = (int)fill_foldcolumn(p_extra_free, wp, foldinfo, lnum); p_extra_free[n_extra] = NUL; p_extra = p_extra_free; c_extra = NUL; @@ -1298,10 +1298,10 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, } if (wp->w_p_rl) { // reverse line numbers // like rl_mirror(), but keep the space at the end - char_u *p2 = (char_u *)skipwhite((char *)extra); - p2 = (char_u *)skiptowhite((char *)p2) - 1; - for (char_u *p1 = (char_u *)skipwhite((char *)extra); p1 < p2; p1++, p2--) { - const char_u t = *p1; + char *p2 = skipwhite((char *)extra); + p2 = skiptowhite(p2) - 1; + for (char *p1 = skipwhite((char *)extra); p1 < p2; p1++, p2--) { + const char t = *p1; *p1 = *p2; *p2 = t; } @@ -1327,8 +1327,8 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // Draw the 'statuscolumn' if option is set. if (statuscol.draw) { if (statuscol.textp == NULL) { - get_statuscol_str(wp, lnum, row, startrow, filler_lines, cul_attr, - sign_num_attr, sattrs, foldinfo, extra, &statuscol); + get_statuscol_str(wp, lnum, row, startrow, filler_lines, cul_attr, sign_num_attr, + sign_cul_attr, extra, foldinfo, sattrs, &statuscol); if (wp->w_redr_statuscol) { return 0; } @@ -1366,7 +1366,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, c_extra = ' '; c_final = NUL; n_extra = - get_breakindent_win(wp, (char_u *)ml_get_buf(wp->w_buffer, lnum, false)); + get_breakindent_win(wp, ml_get_buf(wp->w_buffer, lnum, false)); if (row == startrow) { n_extra -= win_col_off2(wp); if (n_extra < 0) { @@ -1424,7 +1424,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (wp->w_skipcol == 0 || !wp->w_p_wrap) { need_showbreak = false; } - vcol_sbr = vcol + mb_charlen((char_u *)sbr); + vcol_sbr = vcol + mb_charlen(sbr); // Correct end of highlighted area for 'showbreak', // required when 'linebreak' is also set. if (tocol == vcol) { @@ -1451,7 +1451,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, n_extra = saved_n_extra; c_extra = saved_c_extra; c_final = saved_c_final; - p_extra = (char *)saved_p_extra; + p_extra = saved_p_extra; char_attr = saved_char_attr; } else { char_attr = 0; @@ -1493,10 +1493,10 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, linenr_T lnume = lnum + foldinfo.fi_lines - 1; memset(buf_fold, ' ', FOLD_TEXT_LEN); - p_extra = get_foldtext(wp, lnum, lnume, foldinfo, (char *)buf_fold); + p_extra = get_foldtext(wp, lnum, lnume, foldinfo, buf_fold); n_extra = (int)strlen(p_extra); - if (p_extra != (char *)buf_fold) { + if (p_extra != buf_fold) { xfree(p_extra_free); p_extra_free = p_extra; } @@ -1960,7 +1960,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // We have just drawn the showbreak value, no need to add // space for it again. if (vcol == vcol_sbr) { - n_extra -= mb_charlen(get_showbreak_value(wp)); + n_extra -= mb_charlen((char *)get_showbreak_value(wp)); if (n_extra < 0) { n_extra = 0; } @@ -2061,7 +2061,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // Only adjust the tab_len, when at the first column after the // showbreak value was drawn. if (*sbr != NUL && vcol == vcol_sbr && wp->w_p_wrap) { - vcol_adjusted = vcol - mb_charlen(sbr); + vcol_adjusted = vcol - mb_charlen((char *)sbr); } // tab amount depends on current column tab_len = tabstop_padding((colnr_T)vcol_adjusted, @@ -2071,7 +2071,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (!wp->w_p_lbr || !wp->w_p_list) { n_extra = tab_len; } else { - char_u *p; + char *p; int i; int saved_nextra = n_extra; @@ -2100,7 +2100,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, memset(p, ' ', (size_t)len); p[len] = NUL; xfree(p_extra_free); - p_extra_free = (char *)p; + p_extra_free = p; for (i = 0; i < tab_len; i++) { if (*p == NUL) { tab_len = i; @@ -2112,7 +2112,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (wp->w_p_lcs_chars.tab3 && i == tab_len - 1) { lcs = wp->w_p_lcs_chars.tab3; } - p += utf_char2bytes(lcs, (char *)p); + p += utf_char2bytes(lcs, p); n_extra += utf_char2len(lcs) - (saved_nextra > 0 ? 1 : 0); } p_extra = p_extra_free; @@ -2186,7 +2186,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, && tocol != MAXCOL && vcol < tocol) { n_extra = 0; } else { - p_extra = (char *)at_end_str; + p_extra = at_end_str; n_extra = 1; c_extra = NUL; c_final = NUL; @@ -2214,17 +2214,17 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, c_extra = NUL; c_final = NUL; if (wp->w_p_lbr) { - char_u *p; + char *p; c = (uint8_t)(*p_extra); p = xmalloc((size_t)n_extra + 1); memset(p, ' ', (size_t)n_extra); - strncpy((char *)p, // NOLINT(runtime/printf) + strncpy(p, // NOLINT(runtime/printf) p_extra + 1, (size_t)strlen(p_extra) - 1); p[n_extra] = NUL; xfree(p_extra_free); - p_extra_free = p_extra = (char *)p; + p_extra_free = p_extra = p; } else { n_extra = byte2cells(c) - 1; c = (uint8_t)(*p_extra++); @@ -2739,7 +2739,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, || *ptr != NUL || filler_todo > 0 || (wp->w_p_list && wp->w_p_lcs_chars.eol != NUL - && p_extra != (char *)at_end_str) + && p_extra != at_end_str) || (n_extra != 0 && (c_extra != NUL || *p_extra != NUL)))) { bool wrap = wp->w_p_wrap // Wrapping enabled. @@ -2809,7 +2809,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // reset the drawing state for the start of a wrapped line draw_state = WL_START; saved_n_extra = n_extra; - saved_p_extra = (char_u *)p_extra; + saved_p_extra = p_extra; saved_c_extra = c_extra; saved_c_final = c_final; saved_char_attr = char_attr; diff --git a/src/nvim/edit.c b/src/nvim/edit.c index f3dea5f612..36a8674730 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -195,7 +195,7 @@ static void insert_enter(InsertState *s) } } - Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr()); + Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr()); Insstart_blank_vcol = MAXCOL; if (!did_ai) { @@ -1442,7 +1442,7 @@ void edit_putchar(int c, bool highlight) // save the character to be able to put it back if (pc_status == PC_STATUS_UNSET) { - grid_getbytes(&curwin->w_grid, pc_row, pc_col, pc_bytes, &pc_attr); + grid_getbytes(&curwin->w_grid, pc_row, pc_col, (char *)pc_bytes, &pc_attr); pc_status = PC_STATUS_SET; } grid_putchar(&curwin->w_grid, c, pc_row, pc_col, attr); @@ -2261,7 +2261,7 @@ int stop_arrow(void) // right, except when nothing was inserted yet. update_Insstart_orig = false; } - Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr()); + Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr()); if (u_save_cursor() == OK) { arrow_used = false; @@ -3166,7 +3166,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) // search back for the start of a word. line = get_cursor_line_ptr(); for (s = line + curwin->w_cursor.col; s > line; s = n) { - n = (char *)mb_prevptr((char_u *)line, (char_u *)s); + n = mb_prevptr(line, s); if (!vim_iswordp(n)) { break; } @@ -4003,7 +4003,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) // Delete up to starting point, start of line or previous word. int prev_cclass = 0; - int cclass = mb_get_class((char_u *)get_cursor_pos_ptr()); + int cclass = mb_get_class(get_cursor_pos_ptr()); do { if (!revins_on) { // put cursor on char to be deleted dec_cursor(); @@ -4011,7 +4011,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) cc = gchar_cursor(); // look multi-byte character class prev_cclass = cclass; - cclass = mb_get_class((char_u *)get_cursor_pos_ptr()); + cclass = mb_get_class(get_cursor_pos_ptr()); if (mode == BACKSPACE_WORD && !ascii_isspace(cc)) { // start of word? mode = BACKSPACE_WORD_NOT_SPACE; temp = vim_iswordc(cc); diff --git a/src/nvim/eval.c b/src/nvim/eval.c index de6f150304..f9825496a5 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -2213,7 +2213,7 @@ static int eval_func(char **const arg, char *const name, const int name_len, typ // If "s" is the name of a variable of type VAR_FUNC // use its contents. partial_T *partial; - s = (char *)deref_func_name((const char *)s, &len, &partial, !evaluate); + s = deref_func_name((const char *)s, &len, &partial, !evaluate); // Need to make a copy, in case evaluating the arguments makes // the name invalid. @@ -2226,7 +2226,7 @@ static int eval_func(char **const arg, char *const name, const int name_len, typ funcexe.fe_evaluate = evaluate; funcexe.fe_partial = partial; funcexe.fe_basetv = basetv; - int ret = get_func_tv((char_u *)s, len, rettv, arg, &funcexe); + int ret = get_func_tv(s, len, rettv, arg, &funcexe); xfree(s); @@ -3221,7 +3221,7 @@ static int call_func_rettv(char **const arg, typval_T *const rettv, const bool e funcexe.fe_partial = pt; funcexe.fe_selfdict = selfdict; funcexe.fe_basetv = basetv; - const int ret = get_func_tv((char_u *)funcname, is_lua ? (int)(*arg - funcname) : -1, rettv, + const int ret = get_func_tv(funcname, is_lua ? (int)(*arg - funcname) : -1, rettv, arg, &funcexe); // Clear the funcref afterwards, so that deleting it while @@ -5050,7 +5050,7 @@ void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref) if (tv_list_len(list) == 0) { arg_idx = 0; } else if (tv_list_len(list) > MAX_FUNC_ARGS) { - emsg_funcname((char *)e_toomanyarg, (char_u *)s); + emsg_funcname((char *)e_toomanyarg, s); xfree(name); goto theend; } @@ -6098,7 +6098,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret } int len; if (charcol) { - len = mb_charlen((char_u *)ml_get(pos.lnum)); + len = mb_charlen(ml_get(pos.lnum)); } else { len = (int)strlen(ml_get(pos.lnum)); } @@ -6184,7 +6184,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret } else { pos.lnum = curwin->w_cursor.lnum; if (charcol) { - pos.col = (colnr_T)mb_charlen((char_u *)get_cursor_line_ptr()); + pos.col = (colnr_T)mb_charlen(get_cursor_line_ptr()); } else { pos.col = (colnr_T)strlen(get_cursor_line_ptr()); } @@ -7675,8 +7675,7 @@ int store_session_globals(FILE *fd) && var_flavour((char *)this_var->di_key) == VAR_FLAVOUR_SESSION) { // Escape special characters with a backslash. Turn a LF and // CR into \n and \r. - char *const p = (char *)vim_strsave_escaped((const char_u *)tv_get_string(&this_var->di_tv), - (const char_u *)"\\\"\n\r"); + char *const p = (char *)vim_strsave_escaped(tv_get_string(&this_var->di_tv), "\\\"\n\r"); for (char *t = p; *t != NUL; t++) { if (*t == '\n') { *t = 'n'; @@ -7817,8 +7816,8 @@ repeat: } // FullName_save() is slow, don't use it when not needed. - if (*p != NUL || !vim_isAbsName((char_u *)(*fnamep))) { - *fnamep = FullName_save((*fnamep), *p != NUL); + if (*p != NUL || !vim_isAbsName(*fnamep)) { + *fnamep = FullName_save(*fnamep, *p != NUL); xfree(*bufp); // free any allocated file name *bufp = *fnamep; if (*fnamep == NULL) { diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index a87698a9f9..d6b9ca20fc 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -1522,9 +1522,8 @@ static void f_escape(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { char buf[NUMBUFLEN]; - rettv->vval.v_string = (char *)vim_strsave_escaped((const char_u *)tv_get_string(&argvars[0]), - (const char_u *)tv_get_string_buf(&argvars[1], - buf)); + rettv->vval.v_string = vim_strsave_escaped(tv_get_string(&argvars[0]), + tv_get_string_buf(&argvars[1], buf)); rettv->v_type = VAR_STRING; } @@ -2245,7 +2244,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) const char *const what = tv_get_string(&argvars[1]); if (strcmp(what, "func") == 0 || strcmp(what, "name") == 0) { - const char *name = (const char *)partial_name(pt); + const char *name = partial_name(pt); rettv->v_type = (*what == 'f' ? VAR_FUNC : VAR_STRING); assert(name != NULL); if (rettv->v_type == VAR_FUNC) { @@ -2253,7 +2252,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } if (*what == 'n' && pt->pt_name == NULL && pt->pt_func != NULL) { // use <SNR> instead of the byte code - name = (const char *)printable_func_name(pt->pt_func); + name = printable_func_name(pt->pt_func); } rettv->vval.v_string = xstrdup(name); } else if (strcmp(what, "dict") == 0) { @@ -4963,7 +4962,7 @@ static void f_pathshorten(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) rettv->vval.v_string = NULL; } else { rettv->vval.v_string = xstrdup(p); - shorten_dir_len((char_u *)rettv->vval.v_string, trim_len); + shorten_dir_len(rettv->vval.v_string, trim_len); } } @@ -5966,7 +5965,7 @@ static void f_resolve(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) # endif #endif - simplify_filename((char_u *)rettv->vval.v_string); + simplify_filename(rettv->vval.v_string); } /// "reverse({list})" function @@ -7410,7 +7409,7 @@ static void f_simplify(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { const char *const p = tv_get_string(&argvars[0]); rettv->vval.v_string = xstrdup(p); - simplify_filename((char_u *)rettv->vval.v_string); // Simplify in place. + simplify_filename(rettv->vval.v_string); // Simplify in place. rettv->v_type = VAR_STRING; } diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index 1de268a9d8..7c61a2f990 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -326,10 +326,12 @@ void tv_list_free_list(list_T *const l) void tv_list_free(list_T *const l) FUNC_ATTR_NONNULL_ALL { - if (!tv_in_free_unref_items) { - tv_list_free_contents(l); - tv_list_free_list(l); + if (tv_in_free_unref_items) { + return; } + + tv_list_free_contents(l); + tv_list_free_list(l); } /// Unreference a list diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h index 8ff7f7f43a..1ee3b5bf69 100644 --- a/src/nvim/eval/typval.h +++ b/src/nvim/eval/typval.h @@ -434,7 +434,7 @@ extern bool tv_in_free_unref_items; /// @param li Name of the variable with current listitem_T entry. /// @param code Cycle body. #define TV_LIST_ITER(l, li, code) \ - _TV_LIST_ITER_MOD( , l, li, code) + _TV_LIST_ITER_MOD( , l, li, code) // NOLINT(whitespace/parens) /// Iterate over a list /// diff --git a/src/nvim/eval/typval_defs.h b/src/nvim/eval/typval_defs.h index f025f21cf7..939e5d0810 100644 --- a/src/nvim/eval/typval_defs.h +++ b/src/nvim/eval/typval_defs.h @@ -206,7 +206,7 @@ typedef struct { struct { \ typval_T di_tv; /* Structure that holds scope dictionary itself. */ \ uint8_t di_flags; /* Flags. */ \ - char_u di_key[__VA_ARGS__]; /* Key value. */ \ + char_u di_key[__VA_ARGS__]; /* Key value. */ /* NOLINT(runtime/arrays)*/ \ } /// Structure to hold a scope dictionary diff --git a/src/nvim/eval/typval_encode.c.h b/src/nvim/eval/typval_encode.c.h index ff4f92e40b..6c931d3f88 100644 --- a/src/nvim/eval/typval_encode.c.h +++ b/src/nvim/eval/typval_encode.c.h @@ -266,7 +266,7 @@ static inline int _TYPVAL_ENCODE_CHECK_SELF_REFERENCE( const MPConvStack *const mpstack, const int copyID, const MPConvStackValType conv_type, const char *const objname) -REAL_FATTR_NONNULL_ARG(2, 3, 4, 7) REAL_FATTR_WARN_UNUSED_RESULT + REAL_FATTR_NONNULL_ARG(2, 3, 4, 7) REAL_FATTR_WARN_UNUSED_RESULT REAL_FATTR_ALWAYS_INLINE; /// Function for checking whether container references itself @@ -301,7 +301,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( MPConvStack *const mpstack, MPConvStackVal *const cur_mpsv, typval_T *const tv, const int copyID, const char *const objname) -REAL_FATTR_NONNULL_ARG(2, 4, 6) REAL_FATTR_WARN_UNUSED_RESULT; + REAL_FATTR_NONNULL_ARG(2, 4, 6) REAL_FATTR_WARN_UNUSED_RESULT; /// Convert single value /// @@ -358,7 +358,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( .pt = tv->vval.v_partial, }, }, - })); + })); break; } case VAR_LIST: { @@ -381,7 +381,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( .li = tv_list_first(tv->vval.v_list), }, }, - })); + })); TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START(tv, _mp_last(*mpstack)); break; } @@ -459,8 +459,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( const listitem_T *const highest_bits_li = ( TV_LIST_ITEM_NEXT(val_list, sign_li)); if (TV_LIST_ITEM_TV(highest_bits_li)->v_type != VAR_NUMBER - || ((highest_bits - = TV_LIST_ITEM_TV(highest_bits_li)->vval.v_number) + || ((highest_bits = TV_LIST_ITEM_TV(highest_bits_li)->vval.v_number) < 0)) { goto _convert_one_value_regular_dict; } @@ -536,7 +535,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( .li = tv_list_first(val_di->di_tv.vval.v_list), }, }, - })); + })); break; } case kMPMap: { @@ -571,7 +570,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( .li = tv_list_first(val_list), }, }, - })); + })); break; } case kMPExt: { @@ -581,8 +580,7 @@ static int _TYPVAL_ENCODE_CONVERT_ONE_VALUE( || tv_list_len((val_list = val_di->di_tv.vval.v_list)) != 2 || (TV_LIST_ITEM_TV(tv_list_first(val_list))->v_type != VAR_NUMBER) - || ((type - = TV_LIST_ITEM_TV(tv_list_first(val_list))->vval.v_number) + || ((type = TV_LIST_ITEM_TV(tv_list_first(val_list))->vval.v_number) > INT8_MAX) || type < INT8_MIN || (TV_LIST_ITEM_TV(tv_list_last(val_list))->v_type @@ -622,7 +620,7 @@ _convert_one_value_regular_dict: {} .todo = tv->vval.v_dict->dv_hashtab.ht_used, }, }, - })); + })); TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(tv, tv->vval.v_dict, _mp_last(*mpstack)); break; @@ -640,7 +638,7 @@ typval_encode_stop_converting_one_item: TYPVAL_ENCODE_SCOPE int _TYPVAL_ENCODE_ENCODE( TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME, typval_T *const tv, const char *const objname) -REAL_FATTR_NONNULL_ARG(2, 3) REAL_FATTR_WARN_UNUSED_RESULT; + REAL_FATTR_NONNULL_ARG(2, 3) REAL_FATTR_WARN_UNUSED_RESULT; /// Convert the whole typval /// @@ -758,7 +756,7 @@ typval_encode_stop_converting_one_item: .todo = (size_t)pt->pt_argc, }, }, - })); + })); } break; case kMPConvPartialSelf: { @@ -797,7 +795,7 @@ typval_encode_stop_converting_one_item: .todo = dict->dv_hashtab.ht_used, }, }, - })); + })); TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(NULL, pt->pt_dict, _mp_last(mpstack)); } else { diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 9078050067..c70d56cd25 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -93,10 +93,10 @@ static int get_function_args(char **argp, char_u endchar, garray_T *newargs, int int i; if (newargs != NULL) { - ga_init(newargs, (int)sizeof(char_u *), 3); + ga_init(newargs, (int)sizeof(char *), 3); } if (default_args != NULL) { - ga_init(default_args, (int)sizeof(char_u *), 3); + ga_init(default_args, (int)sizeof(char *), 3); } if (varargs != NULL) { @@ -312,7 +312,7 @@ int get_lambda_tv(char **arg, typval_T *rettv, bool evaluate) fp = xcalloc(1, offsetof(ufunc_T, uf_name) + strlen(name) + 1); pt = xcalloc(1, sizeof(partial_T)); - ga_init(&newlines, (int)sizeof(char_u *), 1); + ga_init(&newlines, (int)sizeof(char *), 1); ga_grow(&newlines, 1); // Add "return " before the expression. @@ -330,7 +330,7 @@ int get_lambda_tv(char **arg, typval_T *rettv, bool evaluate) set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); fp->uf_args = newargs; - ga_init(&fp->uf_def_args, (int)sizeof(char_u *), 1); + ga_init(&fp->uf_def_args, (int)sizeof(char *), 1); fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; @@ -383,7 +383,7 @@ errret: /// was not found. /// /// @return name of the function. -char_u *deref_func_name(const char *name, int *lenp, partial_T **const partialp, bool no_autoload) +char *deref_func_name(const char *name, int *lenp, partial_T **const partialp, bool no_autoload) FUNC_ATTR_NONNULL_ARG(1, 2) { if (partialp != NULL) { @@ -394,10 +394,10 @@ char_u *deref_func_name(const char *name, int *lenp, partial_T **const partialp, if (v != NULL && v->di_tv.v_type == VAR_FUNC) { if (v->di_tv.vval.v_string == NULL) { // just in case *lenp = 0; - return (char_u *)""; + return ""; } *lenp = (int)strlen(v->di_tv.vval.v_string); - return (char_u *)v->di_tv.vval.v_string; + return v->di_tv.vval.v_string; } if (v != NULL && v->di_tv.v_type == VAR_PARTIAL) { @@ -405,31 +405,31 @@ char_u *deref_func_name(const char *name, int *lenp, partial_T **const partialp, if (pt == NULL) { // just in case *lenp = 0; - return (char_u *)""; + return ""; } if (partialp != NULL) { *partialp = pt; } char *s = partial_name(pt); *lenp = (int)strlen(s); - return (char_u *)s; + return s; } - return (char_u *)name; + return (char *)name; } /// Give an error message with a function name. Handle <SNR> things. /// /// @param ermsg must be passed without translation (use N_() instead of _()). /// @param name function name -void emsg_funcname(char *ermsg, const char_u *name) +void emsg_funcname(char *ermsg, const char *name) { - char_u *p; + char *p; - if (*name == K_SPECIAL) { - p = (char_u *)concat_str("<SNR>", (char *)name + 3); + if ((uint8_t)(*name) == K_SPECIAL) { + p = concat_str("<SNR>", name + 3); } else { - p = (char_u *)name; + p = (char *)name; } semsg(_(ermsg), p); @@ -447,7 +447,7 @@ void emsg_funcname(char *ermsg, const char_u *name) /// @param funcexe various values /// /// @return OK or FAIL. -int get_func_tv(const char_u *name, int len, typval_T *rettv, char **arg, funcexe_T *funcexe) +int get_func_tv(const char *name, int len, typval_T *rettv, char **arg, funcexe_T *funcexe) { char *argp; int ret = OK; @@ -491,7 +491,7 @@ int get_func_tv(const char_u *name, int len, typval_T *rettv, char **arg, funcex ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } } - ret = call_func((char *)name, len, rettv, argcount, argvars, funcexe); + ret = call_func(name, len, rettv, argcount, argvars, funcexe); funcargs.ga_len -= i; } else if (!aborting()) { @@ -593,7 +593,7 @@ ufunc_T *find_func(const char_u *name) /// Copy the function name of "fp" to buffer "buf". /// "buf" must be able to hold the function name plus three bytes. /// Takes care of script-local function names. -static void cat_func_name(char_u *buf, ufunc_T *fp) +static void cat_func_name(char *buf, ufunc_T *fp) { if ((uint8_t)fp->uf_name[0] == K_SPECIAL) { STRCPY(buf, "<SNR>"); @@ -845,7 +845,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett int fixvar_idx = 0; // index in fixvar[] int ai; bool islambda = false; - char_u numbuf[NUMBUFLEN]; + char numbuf[NUMBUFLEN]; char *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; @@ -984,8 +984,8 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett break; } // "..." argument a:1, a:2, etc. - snprintf((char *)numbuf, sizeof(numbuf), "%d", ai + 1); - name = (char *)numbuf; + snprintf(numbuf, sizeof(numbuf), "%d", ai + 1); + name = numbuf; } if (fixvar_idx < FIXVAR_CNT && strlen(name) <= VAR_SHORT_LEN) { v = (dictitem_T *)&fc->fixvar[fixvar_idx++]; @@ -1439,28 +1439,25 @@ static void user_func_error(int error, const char_u *name) { switch (error) { case FCERR_UNKNOWN: - emsg_funcname(N_("E117: Unknown function: %s"), name); + emsg_funcname(N_("E117: Unknown function: %s"), (char *)name); break; case FCERR_NOTMETHOD: - emsg_funcname(N_("E276: Cannot use function as a method: %s"), name); + emsg_funcname(N_("E276: Cannot use function as a method: %s"), (char *)name); break; case FCERR_DELETED: - emsg_funcname(N_("E933: Function was deleted: %s"), name); + emsg_funcname(N_("E933: Function was deleted: %s"), (char *)name); break; case FCERR_TOOMANY: - emsg_funcname(_(e_toomanyarg), name); + emsg_funcname(_(e_toomanyarg), (char *)name); break; case FCERR_TOOFEW: - emsg_funcname(N_("E119: Not enough arguments for function: %s"), - name); + emsg_funcname(N_("E119: Not enough arguments for function: %s"), (char *)name); break; case FCERR_SCRIPT: - emsg_funcname(N_("E120: Using <SID> not in a script context: %s"), - name); + emsg_funcname(N_("E120: Using <SID> not in a script context: %s"), (char *)name); break; case FCERR_DICT: - emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), - name); + emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), (char *)name); break; } } @@ -1527,7 +1524,7 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t // Make a copy of the name, if it comes from a funcref variable it could // be changed or deleted in the called function. name = xstrnsave(funcname, (size_t)len); - fname = fname_trans_sid(name, (char *)fname_buf, &tofree, &error); + fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) { @@ -1652,9 +1649,9 @@ theend: return ret; } -char_u *printable_func_name(ufunc_T *fp) +char *printable_func_name(ufunc_T *fp) { - return fp->uf_name_exp != NULL ? fp->uf_name_exp : (char_u *)fp->uf_name; + return fp->uf_name_exp != NULL ? (char *)fp->uf_name_exp : fp->uf_name; } /// List the head of the function: "name(arg1, arg2)". @@ -1730,8 +1727,8 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa FUNC_ATTR_NONNULL_ARG(1) { char *name = NULL; - const char_u *start; - const char_u *end; + const char *start; + const char *end; int lead; int len; lval_T lv; @@ -1739,7 +1736,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa if (fdp != NULL) { CLEAR_POINTER(fdp); } - start = (char_u *)(*pp); + start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). @@ -1752,14 +1749,14 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". - lead = eval_fname_script((const char *)start); + lead = eval_fname_script(start); if (lead > 2) { start += lead; } // Note that TFN_ flags use the same values as GLV_ flags. - end = (char_u *)get_lval((char *)start, NULL, &lv, false, skip, flags | GLV_READ_ONLY, - lead > 2 ? 0 : FNE_CHECK_START); + end = get_lval((char *)start, NULL, &lv, false, skip, flags | GLV_READ_ONLY, + lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) { emsg(_("E129: Function name required")); @@ -1783,7 +1780,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; - fdp->fd_newkey = (char_u *)lv.ll_newkey; + fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } @@ -1793,7 +1790,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { if (is_luafunc(lv.ll_tv->vval.v_partial) && *end == '.') { - len = check_luafunc_name((const char *)end + 1, true); + len = check_luafunc_name(end + 1, true); if (len == 0) { semsg(e_invexpr2, "v:lua"); goto theend; @@ -1830,15 +1827,14 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)strlen(lv.ll_exp_name); - name = (char *)deref_func_name(lv.ll_exp_name, &len, partial, - flags & TFN_NO_AUTOLOAD); + name = deref_func_name(lv.ll_exp_name, &len, partial, + flags & TFN_NO_AUTOLOAD); if ((const char *)name == lv.ll_exp_name) { name = NULL; } } else if (!(flags & TFN_NO_DEREF)) { - len = (int)(end - (char_u *)(*pp)); - name = (char *)deref_func_name((const char *)(*pp), &len, partial, - flags & TFN_NO_AUTOLOAD); + len = (int)(end - *pp); + name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD); if (name == *pp) { name = NULL; } @@ -1873,7 +1869,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa lv.ll_name += 2; lv.ll_name_len -= 2; } - len = (int)((const char *)end - lv.ll_name); + len = (int)(end - lv.ll_name); } size_t sid_buf_len = 0; @@ -1904,7 +1900,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { - char_u *cp = xmemrchr(lv.ll_name, ':', lv.ll_name_len); + char *cp = xmemrchr(lv.ll_name, ':', lv.ll_name_len); if (cp != NULL && cp < end) { semsg(_("E884: Function name cannot contain a colon: %s"), start); @@ -2162,7 +2158,7 @@ void ex_function(exarg_T *eap) msg_puts(eap->forceit ? "endfunction" : " endfunction"); } } else { - emsg_funcname(N_("E123: Undefined function: %s"), (char_u *)name); + emsg_funcname(N_("E123: Undefined function: %s"), name); } } goto ret_free; @@ -2182,8 +2178,8 @@ void ex_function(exarg_T *eap) } p = skipwhite(p + 1); - ga_init(&newargs, (int)sizeof(char_u *), 3); - ga_init(&newlines, (int)sizeof(char_u *), 3); + ga_init(&newargs, (int)sizeof(char *), 3); + ga_init(&newlines, (int)sizeof(char *), 3); if (!eap->skip) { // Check the name of the function. Unless it's a dictionary function @@ -2191,7 +2187,7 @@ void ex_function(exarg_T *eap) if (name != NULL) { arg = name; } else { - arg = (char *)fudi.fd_newkey; + arg = fudi.fd_newkey; } if (arg != NULL && (fudi.fd_di == NULL || !tv_is_func(fudi.fd_di->di_tv))) { int j = ((uint8_t)(*arg) == K_SPECIAL) ? 3 : 0; @@ -2199,7 +2195,7 @@ void ex_function(exarg_T *eap) j++; } if (arg[j] != NUL) { - emsg_funcname((char *)e_invarg2, (char_u *)arg); + emsg_funcname((char *)e_invarg2, arg); } } // Disallow using the g: dict. @@ -2235,7 +2231,7 @@ void ex_function(exarg_T *eap) p += 7; if (current_funccal == NULL) { emsg_funcname(N_("E932: Closure function should not be at top level: %s"), - name == NULL ? (char_u *)"" : (char_u *)name); + name == NULL ? "" : name); goto erret; } } else { @@ -2260,7 +2256,7 @@ void ex_function(exarg_T *eap) if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) { emsg(_(e_funcdict)); } else if (name != NULL && find_func((char_u *)name) != NULL) { - emsg_funcname(e_funcexts, (char_u *)name); + emsg_funcname(e_funcexts, name); } } @@ -2509,8 +2505,7 @@ void ex_function(exarg_T *eap) if (fudi.fd_dict == NULL) { v = find_var((const char *)name, strlen(name), &ht, false); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { - emsg_funcname(N_("E707: Function name conflicts with variable: %s"), - (char_u *)name); + emsg_funcname(N_("E707: Function name conflicts with variable: %s"), name); goto erret; } @@ -2521,12 +2516,11 @@ void ex_function(exarg_T *eap) if (!eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) { - emsg_funcname(e_funcexts, (char_u *)name); + emsg_funcname(e_funcexts, name); goto erret; } if (fp->uf_calls > 0) { - emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), - (char_u *)name); + emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), name); goto erret; } if (fp->uf_refcount > 1) { @@ -2577,13 +2571,13 @@ void ex_function(exarg_T *eap) if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; - char_u *scriptname; + char *scriptname; // Check that the autoload name matches the script name. int j = FAIL; if (SOURCING_NAME != NULL) { - scriptname = (char_u *)autoload_name((const char *)name, strlen(name)); - p = vim_strchr((char *)scriptname, '/'); + scriptname = autoload_name(name, strlen(name)); + p = vim_strchr(scriptname, '/'); plen = (int)strlen(p); slen = (int)strlen(SOURCING_NAME); if (slen > plen && path_fnamecmp(p, SOURCING_NAME + slen - plen) == 0) { @@ -2706,7 +2700,7 @@ bool translated_function_exists(const char *name) /// @return true if it exists, false otherwise. bool function_exists(const char *const name, bool no_deref) { - const char_u *nm = (const char_u *)name; + const char *nm = name; bool n = false; int flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; @@ -2714,7 +2708,7 @@ bool function_exists(const char *const name, bool no_deref) flag |= TFN_NO_DEREF; } char *const p = (char *)trans_function_name((char **)&nm, false, flag, NULL, NULL); - nm = (char_u *)skipwhite((char *)nm); + nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". @@ -2758,7 +2752,7 @@ char *get_user_func_name(expand_T *xp, int idx) return (char *)fp->uf_name; // Prevent overflow. } - cat_func_name((char_u *)IObuff, fp); + cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC) { STRCAT(IObuff, "("); if (!fp->uf_varargs && GA_EMPTY(&fp->uf_args)) { @@ -2774,12 +2768,12 @@ char *get_user_func_name(expand_T *xp, int idx) void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; - char_u *p; + char *p; char_u *name; funcdict_T fudi; - p = (char_u *)eap->arg; - name = trans_function_name((char **)&p, eap->skip, 0, &fudi, NULL); + p = eap->arg; + name = trans_function_name(&p, eap->skip, 0, &fudi, NULL); xfree(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) { @@ -2787,12 +2781,12 @@ void ex_delfunction(exarg_T *eap) } return; } - if (!ends_excmd(*skipwhite((char *)p))) { + if (!ends_excmd(*skipwhite(p))) { xfree(name); semsg(_(e_trailing_arg), p); return; } - eap->nextcmd = check_nextcmd((char *)p); + eap->nextcmd = check_nextcmd(p); if (eap->nextcmd != NULL) { *p = NUL; } @@ -3043,7 +3037,7 @@ void ex_call(exarg_T *eap) // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)strlen(tofree); - name = (char *)deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, false); + name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, false); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. @@ -3077,7 +3071,7 @@ void ex_call(exarg_T *eap) funcexe.fe_evaluate = true; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; - if (get_func_tv((char_u *)name, -1, &rettv, &arg, &funcexe) == FAIL) { + if (get_func_tv(name, -1, &rettv, &arg, &funcexe) == FAIL) { failed = true; break; } @@ -3309,7 +3303,7 @@ void make_partial(dict_T *const selfdict, typval_T *const rettv) ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. - fname = fname_trans_sid(fname, (char *)fname_buf, &tofree, &error); + fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func((char_u *)fname); xfree(tofree); } @@ -3655,7 +3649,7 @@ bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) } if (fp_in == NULL) { - fname = fname_trans_sid((char *)name, (char *)fname_buf, &tofree, &error); + fname = fname_trans_sid((char *)name, fname_buf, &tofree, &error); fp = find_func((char_u *)fname); } if (fp != NULL) { diff --git a/src/nvim/eval/userfunc.h b/src/nvim/eval/userfunc.h index 1255f86103..c8583f232c 100644 --- a/src/nvim/eval/userfunc.h +++ b/src/nvim/eval/userfunc.h @@ -36,7 +36,7 @@ struct funccal_entry; /// Structure used by trans_function_name() typedef struct { dict_T *fd_dict; ///< Dictionary used. - char_u *fd_newkey; ///< New key in "dict" in allocated memory. + char *fd_newkey; ///< New key in "dict" in allocated memory. dictitem_T *fd_di; ///< Dictionary item used. } funcdict_T; diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index 62138221e6..206df03381 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -864,7 +864,7 @@ static int do_unlet_var(lval_T *lp, char *name_end, exarg_T *eap, int deep FUNC_ int cc; if (lp->ll_tv == NULL) { - cc = (char_u)(*name_end); + cc = (uint8_t)(*name_end); *name_end = NUL; // Environment variable, normal name or expanded name. @@ -1112,7 +1112,7 @@ int get_var_tv(const char *name, int len, typval_T *rettv, dictitem_T **dip, boo /// NULL when it doesn't exist. /// /// @see tv_get_string() for how long the pointer remains valid. -char_u *get_var_value(const char *const name) +char *get_var_value(const char *const name) { dictitem_T *v; @@ -1120,7 +1120,7 @@ char_u *get_var_value(const char *const name) if (v == NULL) { return NULL; } - return (char_u *)tv_get_string(&v->di_tv); + return (char *)tv_get_string(&v->di_tv); } /// Clean up a list of internal variables. diff --git a/src/nvim/eval/window.c b/src/nvim/eval/window.c index 50b25378e4..4bcbc13534 100644 --- a/src/nvim/eval/window.c +++ b/src/nvim/eval/window.c @@ -766,7 +766,7 @@ void f_winnr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// "winrestcmd()" function void f_winrestcmd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - char_u buf[50]; + char buf[50]; garray_T ga; ga_init(&ga, (int)sizeof(char), 70); @@ -775,12 +775,12 @@ void f_winrestcmd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) for (int i = 0; i < 2; i++) { int winnr = 1; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { - snprintf((char *)buf, sizeof(buf), "%dresize %d|", winnr, + snprintf(buf, sizeof(buf), "%dresize %d|", winnr, wp->w_height); - ga_concat(&ga, (char *)buf); - snprintf((char *)buf, sizeof(buf), "vert %dresize %d|", winnr, + ga_concat(&ga, buf); + snprintf(buf, sizeof(buf), "vert %dresize %d|", winnr, wp->w_width); - ga_concat(&ga, (char *)buf); + ga_concat(&ga, buf); winnr++; } } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index f6e5d5c665..c2af0e6986 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -347,7 +347,7 @@ static int linelen(int *has_tab) char save = *last; *last = NUL; // Get line length. - len = linetabsize((char_u *)line); + len = linetabsize(line); // Check for embedded TAB. if (has_tab != NULL) { *has_tab = vim_strchr(first, TAB) != NULL; @@ -1025,7 +1025,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out // If % or # appears in the command, it must have been escaped. // Reescape them, so that redoing them does not substitute them by the // buffername. - char *cmd = (char *)vim_strsave_escaped((char_u *)prevcmd, (char_u *)"%#"); + char *cmd = vim_strsave_escaped(prevcmd, "%#"); AppendToRedobuffLit(cmd, -1); xfree(cmd); @@ -1179,7 +1179,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b read_linecount = curbuf->b_ml.ml_line_count; // Pass on the kShellOptDoOut flag when the output is being redirected. - call_shell((char_u *)cmd_buf, (ShellOpts)(kShellOptFilter | shell_flags), NULL); + call_shell(cmd_buf, (ShellOpts)(kShellOptFilter | shell_flags), NULL); xfree(cmd_buf); did_check_timestamps = false; @@ -1324,7 +1324,7 @@ void do_shell(char *cmd, int flags) // This ui_cursor_goto is required for when the '\n' resulted in a "delete line // 1" command to the terminal. ui_cursor_goto(msg_row, msg_col); - (void)call_shell((char_u *)cmd, (ShellOpts)flags, NULL); + (void)call_shell(cmd, (ShellOpts)flags, NULL); msg_didout = true; did_check_timestamps = false; need_check_timestamps = true; @@ -1367,12 +1367,12 @@ char *make_filter_cmd(char *cmd, char *itmp, char *otmp) { bool is_fish_shell = #if defined(UNIX) - strncmp((char *)invocation_path_tail((char_u *)p_sh, NULL), "fish", 4) == 0; + strncmp((char *)invocation_path_tail(p_sh, NULL), "fish", 4) == 0; #else false; #endif - bool is_pwsh = strncmp((char *)invocation_path_tail((char_u *)p_sh, NULL), "pwsh", 4) == 0 - || strncmp((char *)invocation_path_tail((char_u *)p_sh, NULL), "powershell", + bool is_pwsh = strncmp((char *)invocation_path_tail(p_sh, NULL), "pwsh", 4) == 0 + || strncmp((char *)invocation_path_tail(p_sh, NULL), "powershell", 10) == 0; size_t len = strlen(cmd) + 1; // At least enough space for cmd + NULL. @@ -1382,7 +1382,7 @@ char *make_filter_cmd(char *cmd, char *itmp, char *otmp) : 0; if (itmp != NULL) { - len += is_pwsh ? strlen(itmp) + sizeof("& { Get-Content " " | & " " }") - 1 + len += is_pwsh ? strlen(itmp) + sizeof("& { Get-Content " " | & " " }") - 1 + 6 // +6: #20530 : strlen(itmp) + sizeof(" { " " < " " } ") - 1; } if (otmp != NULL) { diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c index 7020747cf6..d08823bc30 100644 --- a/src/nvim/ex_cmds2.c +++ b/src/nvim/ex_cmds2.c @@ -721,7 +721,7 @@ void ex_compiler(exarg_T *eap) // plugin will then skip the settings. Afterwards set // "b:current_compiler" and restore "current_compiler". // Explicitly prepend "g:" to make it work in a function. - old_cur_comp = (char *)get_var_value("g:current_compiler"); + old_cur_comp = get_var_value("g:current_compiler"); if (old_cur_comp != NULL) { old_cur_comp = xstrdup(old_cur_comp); } @@ -743,7 +743,7 @@ void ex_compiler(exarg_T *eap) do_cmdline_cmd(":delcommand CompilerSet"); // Set "b:current_compiler" from "current_compiler". - p = (char *)get_var_value("g:current_compiler"); + p = get_var_value("g:current_compiler"); if (p != NULL) { set_internal_string_var("b:current_compiler", p); } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index e847f74289..e11dd0a2f6 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -3802,7 +3802,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) for (l = repl; *l; l++) { if (vim_strchr((char *)ESCAPE_CHARS, *l) != NULL) { - l = (char *)vim_strsave_escaped((char_u *)repl, ESCAPE_CHARS); + l = vim_strsave_escaped(repl, (char *)ESCAPE_CHARS); xfree(repl); repl = l; break; @@ -3817,7 +3817,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) && strpbrk(repl, "!") != NULL) { char *l; - l = (char *)vim_strsave_escaped((char_u *)repl, (char_u *)"!"); + l = vim_strsave_escaped(repl, "!"); xfree(repl); repl = l; } @@ -4965,8 +4965,8 @@ void ex_splitview(exarg_T *eap) } if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind) { - fname = (char *)find_file_in_path((char_u *)eap->arg, strlen(eap->arg), - FNAME_MESS, true, (char_u *)curbuf->b_ffname); + fname = (char *)find_file_in_path(eap->arg, strlen(eap->arg), + FNAME_MESS, true, curbuf->b_ffname); if (fname == NULL) { goto theend; } @@ -5158,15 +5158,15 @@ static void ex_resize(exarg_T *eap) /// ":find [+command] <file>" command. static void ex_find(exarg_T *eap) { - char *fname = (char *)find_file_in_path((char_u *)eap->arg, strlen(eap->arg), - FNAME_MESS, true, (char_u *)curbuf->b_ffname); + char *fname = (char *)find_file_in_path(eap->arg, strlen(eap->arg), + FNAME_MESS, true, curbuf->b_ffname); if (eap->addr_count > 0) { // Repeat finding the file "count" times. This matters when it // appears several times in the path. linenr_T count = eap->line2; while (fname != NULL && --count > 0) { xfree(fname); - fname = (char *)find_file_in_path(NULL, 0, FNAME_MESS, false, (char_u *)curbuf->b_ffname); + fname = (char *)find_file_in_path(NULL, 0, FNAME_MESS, false, curbuf->b_ffname); } } @@ -6042,7 +6042,7 @@ static void ex_redir(exarg_T *eap) return; } - redir_fd = open_exfile((char_u *)fname, eap->forceit, mode); + redir_fd = open_exfile(fname, eap->forceit, mode); xfree(fname); } else if (*arg == '@') { // redirect to a register a-z (resp. A-Z for appending) @@ -6215,22 +6215,22 @@ int vim_mkdir_emsg(const char *const name, const int prot) /// @param mode "w" for create new file or "a" for append /// /// @return file descriptor, or NULL on failure. -FILE *open_exfile(char_u *fname, int forceit, char *mode) +FILE *open_exfile(char *fname, int forceit, char *mode) { #ifdef UNIX // with Unix it is possible to open a directory - if (os_isdir((char *)fname)) { + if (os_isdir(fname)) { semsg(_(e_isadir2), fname); return NULL; } #endif - if (!forceit && *mode != 'a' && os_path_exists((char *)fname)) { + if (!forceit && *mode != 'a' && os_path_exists(fname)) { semsg(_("E189: \"%s\" exists (add ! to override)"), fname); return NULL; } FILE *fd; - if ((fd = os_fopen((char *)fname, mode)) == NULL) { + if ((fd = os_fopen(fname, mode)) == NULL) { semsg(_("E190: Cannot open \"%s\" for writing"), fname); } @@ -6387,7 +6387,7 @@ static void ex_normal(exarg_T *eap) check_cursor_moved(curwin); } - exec_normal_cmd((char_u *)(arg != NULL ? arg : eap->arg), + exec_normal_cmd((arg != NULL ? arg : eap->arg), eap->forceit ? REMAP_NONE : REMAP_YES, false); } while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int); } @@ -6451,10 +6451,10 @@ static void ex_stopinsert(exarg_T *eap) /// Execute normal mode command "cmd". /// "remap" can be REMAP_NONE or REMAP_YES. -void exec_normal_cmd(char_u *cmd, int remap, bool silent) +void exec_normal_cmd(char *cmd, int remap, bool silent) { // Stuff the argument into the typeahead buffer. - ins_typebuf((char *)cmd, remap, 0, true, silent); + ins_typebuf(cmd, remap, 0, true, silent); exec_normal(false); } @@ -6859,7 +6859,7 @@ char_u *eval_vars(char_u *src, const char_u *srcstart, size_t *usedlen, linenr_T *errormsg = _("E495: no autocommand file name to substitute for \"<afile>\""); return NULL; } - result = (char *)path_try_shorten_fname((char_u *)result); + result = path_try_shorten_fname(result); break; case SPEC_ABUF: // buffer number for autocommand @@ -7263,7 +7263,7 @@ static void ex_terminal(exarg_T *eap) char ex_cmd[1024]; if (*eap->arg != NUL) { // Run {cmd} in 'shell'. - char *name = (char *)vim_strsave_escaped((char_u *)eap->arg, (char_u *)"\"\\"); + char *name = vim_strsave_escaped(eap->arg, "\"\\"); snprintf(ex_cmd, sizeof(ex_cmd), ":enew%s | call termopen(\"%s\")", eap->forceit ? "!" : "", name); diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 93c5d24c0d..62586598bf 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -1225,6 +1225,8 @@ static int command_line_execute(VimState *state, int key) } if (cmdline_pum_active() || s->did_wild_list) { + // Ctrl-Y: Accept the current selection and close the popup menu. + // Ctrl-E: cancel the cmdline popup menu and return the original text. if (s->c == Ctrl_E || s->c == Ctrl_Y) { const int wild_type = (s->c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY; (void)nextwild(&s->xpc, wild_type, WILD_NO_BEEP, s->firstc != '@'); @@ -1232,10 +1234,20 @@ static int command_line_execute(VimState *state, int key) } } + // The wildmenu is cleared if the pressed key is not used for + // navigating the wild menu (i.e. the key is not 'wildchar' or + // 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L). + // If the popup menu is displayed, then PageDown and PageUp keys are + // also used to navigate the menu. + bool end_wildmenu = (!(s->c == p_wc && KeyTyped) && s->c != p_wcm && s->c != Ctrl_Z + && s->c != Ctrl_N && s->c != Ctrl_P && s->c != Ctrl_A + && s->c != Ctrl_L); + end_wildmenu = end_wildmenu && (!cmdline_pum_active() + || (s->c != K_PAGEDOWN && s->c != K_PAGEUP + && s->c != K_KPAGEDOWN && s->c != K_KPAGEUP)); + // free expanded names when finished walking through matches - if (!(s->c == p_wc && KeyTyped) && s->c != p_wcm && s->c != Ctrl_Z - && s->c != Ctrl_N && s->c != Ctrl_P && s->c != Ctrl_A - && s->c != Ctrl_L) { + if (end_wildmenu) { command_line_end_wildmenu(s); } @@ -1466,27 +1478,27 @@ static int command_line_erase_chars(CommandLineState *s) } if (ccline.cmdpos > 0) { - char_u *p; + char *p; int j = ccline.cmdpos; - p = mb_prevptr((char_u *)ccline.cmdbuff, (char_u *)ccline.cmdbuff + j); + p = mb_prevptr(ccline.cmdbuff, ccline.cmdbuff + j); if (s->c == Ctrl_W) { - while (p > (char_u *)ccline.cmdbuff && ascii_isspace(*p)) { - p = mb_prevptr((char_u *)ccline.cmdbuff, p); + while (p > ccline.cmdbuff && ascii_isspace(*p)) { + p = mb_prevptr(ccline.cmdbuff, p); } int i = mb_get_class(p); - while (p > (char_u *)ccline.cmdbuff && mb_get_class(p) == i) { - p = mb_prevptr((char_u *)ccline.cmdbuff, p); + while (p > ccline.cmdbuff && mb_get_class(p) == i) { + p = mb_prevptr(ccline.cmdbuff, p); } if (mb_get_class(p) != i) { - p += utfc_ptr2len((char *)p); + p += utfc_ptr2len(p); } } - ccline.cmdpos = (int)(p - (char_u *)ccline.cmdbuff); + ccline.cmdpos = (int)(p - ccline.cmdbuff); ccline.cmdlen -= j - ccline.cmdpos; int i = ccline.cmdpos; @@ -1998,8 +2010,8 @@ static int command_line_handle_key(CommandLineState *s) case Ctrl_N: // next match case Ctrl_P: // previous match if (s->xpc.xp_numfiles > 0) { - if (nextwild(&s->xpc, (s->c == Ctrl_P) ? WILD_PREV : WILD_NEXT, - 0, s->firstc != '@') == FAIL) { + const int wild_type = (s->c == Ctrl_P) ? WILD_PREV : WILD_NEXT; + if (nextwild(&s->xpc, wild_type, 0, s->firstc != '@') == FAIL) { break; } return command_line_not_changed(s); @@ -2014,13 +2026,26 @@ static int command_line_handle_key(CommandLineState *s) case K_KPAGEUP: case K_PAGEDOWN: case K_KPAGEDOWN: - switch (command_line_browse_history(s)) { - case CMDLINE_CHANGED: - return command_line_changed(s); - case GOTO_NORMAL_MODE: - return 0; - default: + if (cmdline_pum_active() + && (s->c == K_PAGEUP || s->c == K_PAGEDOWN + || s->c == K_KPAGEUP || s->c == K_KPAGEDOWN)) { + // If the popup menu is displayed, then PageUp and PageDown + // are used to scroll the menu. + const int wild_type = + (s->c == K_PAGEDOWN || s->c == K_KPAGEDOWN) ? WILD_PAGEDOWN : WILD_PAGEUP; + if (nextwild(&s->xpc, wild_type, 0, s->firstc != '@') == FAIL) { + break; + } return command_line_not_changed(s); + } else { + switch (command_line_browse_history(s)) { + case CMDLINE_CHANGED: + return command_line_changed(s); + case GOTO_NORMAL_MODE: + return 0; + default: + return command_line_not_changed(s); + } } case Ctrl_G: // next match @@ -2097,11 +2122,11 @@ static int command_line_handle_key(CommandLineState *s) // put the character in the command line if (IS_SPECIAL(s->c) || mod_mask != 0) { - put_on_cmdline(get_special_key_name(s->c, mod_mask), -1, true); + put_on_cmdline((char *)get_special_key_name(s->c, mod_mask), -1, true); } else { int j = utf_char2bytes(s->c, IObuff); IObuff[j] = NUL; // exclude composing chars - put_on_cmdline((char_u *)IObuff, j, true); + put_on_cmdline(IObuff, j, true); } return command_line_changed(s); } @@ -3509,14 +3534,14 @@ void unputcmdline(void) // part will be redrawn, otherwise it will not. If this function is called // twice in a row, then 'redraw' should be false and redrawcmd() should be // called afterwards. -void put_on_cmdline(char_u *str, int len, int redraw) +void put_on_cmdline(char *str, int len, int redraw) { int i; int m; int c; if (len < 0) { - len = (int)strlen((char *)str); + len = (int)strlen(str); } realloc_cmdbuff(ccline.cmdlen + len + 1); @@ -3529,7 +3554,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) } else { // Count nr of characters in the new string. m = 0; - for (i = 0; i < len; i += utfc_ptr2len((char *)str + i)) { + for (i = 0; i < len; i += utfc_ptr2len(str + i)) { m++; } // Count nr of bytes in cmdline that are overwritten by these @@ -3725,7 +3750,7 @@ void cmdline_paste_str(char_u *s, int literally) int c, cv; if (literally) { - put_on_cmdline(s, -1, true); + put_on_cmdline((char *)s, -1, true); } else { while (*s != NUL) { cv = *s; @@ -3964,18 +3989,16 @@ char *vim_strsave_fnameescape(const char *const fname, const int what) char *p = (char *)vim_strsave_escaped((const char_u *)fname, (const char_u *)buf); #else -# define PATH_ESC_CHARS ((char_u *)" \t\n*?[{`$\\%#'\"|!<") -# define SHELL_ESC_CHARS ((char_u *)" \t\n*?[{`$\\%#'\"|!<>();&") -# define BUFFER_ESC_CHARS ((char_u *)" \t\n*?[`$\\%#'\"|!<") - char *p = - (char *)vim_strsave_escaped((const char_u *)fname, - what == VSE_SHELL ? SHELL_ESC_CHARS - : what == VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS); +# define PATH_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<" +# define SHELL_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<>();&" +# define BUFFER_ESC_CHARS " \t\n*?[`$\\%#'\"|!<" + char *p = vim_strsave_escaped(fname, + what == VSE_SHELL ? SHELL_ESC_CHARS : what == + VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS); if (what == VSE_SHELL && csh_like_shell()) { // For csh and similar shells need to put two backslashes before '!'. // One is taken by Vim, one by the shell. - char *s = (char *)vim_strsave_escaped((const char_u *)p, - (const char_u *)"!"); + char *s = vim_strsave_escaped(p, "!"); xfree(p); p = s; } @@ -4002,7 +4025,7 @@ void escape_fname(char **pp) /// For each file name in files[num_files]: /// If 'orig_pat' starts with "~/", replace the home directory with "~". -void tilde_replace(char_u *orig_pat, int num_files, char **files) +void tilde_replace(char *orig_pat, int num_files, char **files) { char *p; diff --git a/src/nvim/ex_session.c b/src/nvim/ex_session.c index 48d52fa5f9..cae9c18309 100644 --- a/src/nvim/ex_session.c +++ b/src/nvim/ex_session.c @@ -964,7 +964,7 @@ void ex_mkrc(exarg_T *eap) vim_mkdir_emsg((const char *)p_vdir, 0755); } - fd = open_exfile((char_u *)fname, eap->forceit, WRITEBIN); + fd = open_exfile(fname, eap->forceit, WRITEBIN); if (fd != NULL) { if (eap->cmdidx == CMD_mkview) { flagp = &vop_flags; diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index 5c5839cb08..d0280b3571 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -288,7 +288,7 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i && rel_fname != NULL) { size_t len = (size_t)(path_tail(rel_fname) - rel_fname); - if (!vim_isAbsName((char_u *)rel_fname) && len + 1 < MAXPATHL) { + if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) { // Make the start dir an absolute path name. xstrlcpy(ff_expand_buffer, rel_fname, len + 1); search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, false); @@ -298,7 +298,7 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i if (*++path != NUL) { path++; } - } else if (*path == NUL || !vim_isAbsName((char_u *)path)) { + } else if (*path == NUL || !vim_isAbsName(path)) { #ifdef BACKSLASH_IN_FILENAME // "c:dir" needs "c:" to be expanded, otherwise use current dir if (*path != NUL && path[1] == ':') { @@ -347,7 +347,7 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i } size_t dircount = 1; - search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(char_u *)); + search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(char *)); do { char *helper; @@ -355,7 +355,7 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i helper = walker; ptr = xrealloc(search_ctx->ffsc_stopdirs_v, - (dircount + 1) * sizeof(char_u *)); + (dircount + 1) * sizeof(char *)); search_ctx->ffsc_stopdirs_v = ptr; walker = vim_strchr(walker, ';'); if (walker) { @@ -447,11 +447,11 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i add_pathsep(ff_expand_buffer); { size_t eb_len = strlen(ff_expand_buffer); - char_u *buf = xmalloc(eb_len + strlen(search_ctx->ffsc_fix_path) + 1); + char *buf = xmalloc(eb_len + strlen(search_ctx->ffsc_fix_path) + 1); STRCPY(buf, ff_expand_buffer); STRCPY(buf + eb_len, search_ctx->ffsc_fix_path); - if (os_isdir((char *)buf)) { + if (os_isdir(buf)) { STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path); add_pathsep(ff_expand_buffer); } else { @@ -504,9 +504,9 @@ error_return: } /// @return the stopdir string. Check that ';' is not escaped. -char_u *vim_findfile_stopdir(char_u *buf) +char_u *vim_findfile_stopdir(char *buf) { - char_u *r_ptr = buf; + char_u *r_ptr = (char_u *)buf; while (*r_ptr != NUL && *r_ptr != ';') { if (r_ptr[0] == '\\' && r_ptr[1] == ';') { @@ -555,7 +555,7 @@ char_u *vim_findfile(void *search_ctx_arg) { char *file_path; char *rest_of_wildcards; - char_u *path_end = NULL; + char *path_end = NULL; ff_stack_T *stackp = NULL; size_t len; char *p; @@ -574,7 +574,7 @@ char_u *vim_findfile(void *search_ctx_arg) // store the end of the start dir -- needed for upward search if (search_ctx->ffsc_start_dir != NULL) { - path_end = (char_u *)&search_ctx->ffsc_start_dir[strlen(search_ctx->ffsc_start_dir)]; + path_end = &search_ctx->ffsc_start_dir[strlen(search_ctx->ffsc_start_dir)]; } // upward search loop @@ -654,7 +654,7 @@ char_u *vim_findfile(void *search_ctx_arg) dirptrs[1] = NULL; // if we have a start dir copy it in - if (!vim_isAbsName((char_u *)stackp->ffs_fix_path) + if (!vim_isAbsName(stackp->ffs_fix_path) && search_ctx->ffsc_start_dir) { if (strlen(search_ctx->ffsc_start_dir) + 1 >= MAXPATHL) { ff_free_stack_element(stackp); @@ -813,7 +813,7 @@ char_u *vim_findfile(void *search_ctx_arg) ff_push(search_ctx, stackp); if (!path_with_url(file_path)) { - simplify_filename((char_u *)file_path); + simplify_filename(file_path); } if (os_dirname(ff_expand_buffer, MAXPATHL) == OK) { p = path_shorten_fname(file_path, ff_expand_buffer); @@ -886,16 +886,16 @@ char_u *vim_findfile(void *search_ctx_arg) // is the last starting directory in the stop list? if (ff_path_in_stoplist(search_ctx->ffsc_start_dir, - (int)(path_end - (char_u *)search_ctx->ffsc_start_dir), + (int)(path_end - search_ctx->ffsc_start_dir), search_ctx->ffsc_stopdirs_v) == true) { break; } // cut of last dir - while (path_end > (char_u *)search_ctx->ffsc_start_dir && vim_ispathsep(*path_end)) { + while (path_end > search_ctx->ffsc_start_dir && vim_ispathsep(*path_end)) { path_end--; } - while (path_end > (char_u *)search_ctx->ffsc_start_dir && !vim_ispathsep(path_end[-1])) { + while (path_end > search_ctx->ffsc_start_dir && !vim_ispathsep(path_end[-1])) { path_end--; } *path_end = 0; @@ -1025,7 +1025,7 @@ static ff_visited_list_hdr_T *ff_get_visited_list(char *filename, /// - char by char comparison is OK /// - the only differences are in the counters behind a '**', so /// '**\20' is equal to '**\24' -static bool ff_wc_equal(char_u *s1, char_u *s2) +static bool ff_wc_equal(char *s1, char *s2) { int i, j; int c1 = NUL; @@ -1042,8 +1042,8 @@ static bool ff_wc_equal(char_u *s1, char_u *s2) } for (i = 0, j = 0; s1[i] != NUL && s2[j] != NUL;) { - c1 = utf_ptr2char((char *)s1 + i); - c2 = utf_ptr2char((char *)s2 + j); + c1 = utf_ptr2char(s1 + i); + c2 = utf_ptr2char(s2 + j); if ((p_fic ? mb_tolower(c1) != mb_tolower(c2) : c1 != c2) && (prev1 != '*' || prev2 != '*')) { @@ -1052,8 +1052,8 @@ static bool ff_wc_equal(char_u *s1, char_u *s2) prev2 = prev1; prev1 = c1; - i += utfc_ptr2len((char *)s1 + i); - j += utfc_ptr2len((char *)s2 + j); + i += utfc_ptr2len(s1 + i); + j += utfc_ptr2len(s2 + j); } return s1[i] == s2[j]; } @@ -1086,7 +1086,7 @@ static int ff_check_visited(ff_visited_T **visited_list, char *fname, char *wc_p || (!url && vp->file_id_valid && os_fileid_equal(&(vp->file_id), &file_id))) { // are the wildcard parts equal - if (ff_wc_equal((char_u *)vp->ffv_wc_path, (char_u *)wc_path)) { + if (ff_wc_equal(vp->ffv_wc_path, wc_path)) { // already visited return FAIL; } @@ -1287,13 +1287,13 @@ static int ff_path_in_stoplist(char *path, int path_len, char **stopdirs_v) /// @param rel_fname file name searching relative to /// /// @return an allocated string for the file name. NULL for error. -char_u *find_file_in_path(char_u *ptr, size_t len, int options, int first, char_u *rel_fname) +char_u *find_file_in_path(char *ptr, size_t len, int options, int first, char *rel_fname) { - return (char_u *)find_file_in_path_option((char *)ptr, len, options, first, + return (char_u *)find_file_in_path_option(ptr, len, options, first, (*curbuf->b_p_path == NUL ? (char *)p_path : curbuf->b_p_path), - FINDFILE_BOTH, (char *)rel_fname, curbuf->b_p_sua); + FINDFILE_BOTH, rel_fname, curbuf->b_p_sua); } static char *ff_file_to_find = NULL; @@ -1379,7 +1379,7 @@ char *find_file_in_path_option(char *ptr, size_t len, int options, int first, ch || (ff_file_to_find[1] == '.' && (ff_file_to_find[2] == NUL || vim_ispathsep(ff_file_to_find[2]))))); - if (vim_isAbsName((char_u *)ff_file_to_find) + if (vim_isAbsName(ff_file_to_find) // "..", "../path", "." and "./path": don't use the path_option || rel_to_curdir #if defined(MSWIN) @@ -1453,7 +1453,7 @@ char *find_file_in_path_option(char *ptr, size_t len, int options, int first, ch did_findfile_init = false; } else { - char_u *r_ptr; + char *r_ptr; if (dir == NULL || *dir == NUL) { // We searched all paths of the option, now we can free the search context. @@ -1469,9 +1469,9 @@ char *find_file_in_path_option(char *ptr, size_t len, int options, int first, ch copy_option_part(&dir, buf, MAXPATHL, " ,"); // get the stopdir string - r_ptr = vim_findfile_stopdir((char_u *)buf); + r_ptr = (char *)vim_findfile_stopdir(buf); fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find, - (char *)r_ptr, 100, false, find_what, + r_ptr, 100, false, find_what, fdip_search_ctx, false, rel_fname); if (fdip_search_ctx != NULL) { did_findfile_init = true; diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index fb45157d9c..0ee547d124 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -488,7 +488,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, } } if (!silent) { - if (dir_of_file_exists((char_u *)fname)) { + if (dir_of_file_exists(fname)) { filemess(curbuf, sfname, new_file_message(), 0); } else { filemess(curbuf, sfname, _("[New DIRECTORY]"), 0); diff --git a/src/nvim/globals.h b/src/nvim/globals.h index bb7c519b7c..aa8dbf6331 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -419,7 +419,7 @@ EXTERN win_T *prevwin INIT(= NULL); // previous window // -V:FOR_ALL_WINDOWS_IN_TAB:501 #define FOR_ALL_WINDOWS_IN_TAB(wp, tp) \ for (win_T *wp = ((tp) == curtab) \ - ? firstwin : (tp)->tp_firstwin; wp != NULL; wp = wp->w_next) + ? firstwin : (tp)->tp_firstwin; wp != NULL; wp = wp->w_next) EXTERN win_T *curwin; // currently active window diff --git a/src/nvim/grid.c b/src/nvim/grid.c index 87b232eec3..4702e224c6 100644 --- a/src/nvim/grid.c +++ b/src/nvim/grid.c @@ -140,7 +140,7 @@ void grid_putchar(ScreenGrid *grid, int c, int row, int col, int attr) /// get a single character directly from grid.chars into "bytes[]". /// Also return its attribute in *attrp; -void grid_getbytes(ScreenGrid *grid, int row, int col, char_u *bytes, int *attrp) +void grid_getbytes(ScreenGrid *grid, int row, int col, char *bytes, int *attrp) { size_t off; @@ -150,7 +150,7 @@ void grid_getbytes(ScreenGrid *grid, int row, int col, char_u *bytes, int *attrp if (grid->chars != NULL && row < grid->rows && col < grid->cols) { off = grid->line_offset[row] + (size_t)col; *attrp = grid->attrs[off]; - schar_copy((char *)bytes, grid->chars[off]); + schar_copy(bytes, grid->chars[off]); } } diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index 59ffff40a6..404835c4a9 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -601,7 +601,7 @@ void init_highlight(bool both, bool reset) // Try finding the color scheme file. Used when a color file was loaded // and 'background' or 't_Co' is changed. - char *p = (char *)get_var_value("g:colors_name"); + char *p = get_var_value("g:colors_name"); if (p != NULL) { // Value of g:colors_name could be freed in load_colors() and make // p invalid, so copy it. diff --git a/src/nvim/indent.c b/src/nvim/indent.c index 7d3b1f4a3f..be1dfb77cf 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -798,7 +798,7 @@ bool briopt_check(win_T *wp) // Return appropriate space number for breakindent, taking influencing // parameters into account. Window must be specified, since it is not // necessarily always the current one. -int get_breakindent_win(win_T *wp, char_u *line) +int get_breakindent_win(win_T *wp, char *line) FUNC_ATTR_NONNULL_ALL { static int prev_indent = 0; // Cached indent value. @@ -820,17 +820,17 @@ int get_breakindent_win(win_T *wp, char_u *line) // - 'tabstop' changed // - 'briopt_list changed' changed or // - 'formatlistpattern' changed - if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts + if (prev_line != (char_u *)line || prev_ts != wp->w_buffer->b_p_ts || prev_tick != buf_get_changedtick(wp->w_buffer) || prev_listopt != wp->w_briopt_list || (prev_flp == NULL || (strcmp(prev_flp, get_flp_value(wp->w_buffer)) != 0)) || prev_vts != wp->w_buffer->b_p_vts_array) { - prev_line = line; + prev_line = (char_u *)line; prev_ts = wp->w_buffer->b_p_ts; prev_tick = buf_get_changedtick(wp->w_buffer); prev_vts = wp->w_buffer->b_p_vts_array; if (wp->w_briopt_vcol == 0) { - prev_indent = get_indent_str_vtab((char *)line, + prev_indent = get_indent_str_vtab(line, wp->w_buffer->b_p_ts, wp->w_buffer->b_p_vts_array, wp->w_p_list); @@ -846,7 +846,7 @@ int get_breakindent_win(win_T *wp, char_u *line) }; if (regmatch.regprog != NULL) { regmatch.rm_ic = false; - if (vim_regexec(®match, (char *)line, 0)) { + if (vim_regexec(®match, line, 0)) { if (wp->w_briopt_list > 0) { prev_list += wp->w_briopt_list; } else { @@ -1396,11 +1396,13 @@ void fixthisline(IndentGetter get_the_indent) { int amount = get_the_indent(); - if (amount >= 0) { - change_indent(INDENT_SET, amount, false, 0, true); - if (linewhite(curwin->w_cursor.lnum)) { - did_ai = true; // delete the indent if the line stays empty - } + if (amount < 0) { + return; + } + + change_indent(INDENT_SET, amount, false, 0, true); + if (linewhite(curwin->w_cursor.lnum)) { + did_ai = true; // delete the indent if the line stays empty } } diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index f2ee299211..fa8e78f624 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -169,7 +169,7 @@ typedef struct { pos_T first_match_pos; ///< first match position pos_T last_match_pos; ///< last match position bool found_all; ///< found all matches of a certain type. - char_u *dict; ///< dictionary file to search + char *dict; ///< dictionary file to search int dict_f; ///< "dict" is an exact file name or not } ins_compl_next_state_T; @@ -588,8 +588,8 @@ bool ins_compl_accept_char(int c) /// Get the completed text by inferring the case of the originally typed text. /// If the result is in allocated memory "tofree" is set to it. -static char_u *ins_compl_infercase_gettext(const char_u *str, int char_len, int compl_char_len, - int min_len, char **tofree) +static char *ins_compl_infercase_gettext(const char *str, int char_len, int compl_char_len, + int min_len, char **tofree) { bool has_lower = false; bool was_letter = false; @@ -597,7 +597,7 @@ static char_u *ins_compl_infercase_gettext(const char_u *str, int char_len, int // Allocate wide character array for the completion and fill it. int *const wca = xmalloc((size_t)char_len * sizeof(*wca)); { - const char_u *p = str; + const char_u *p = (char_u *)str; for (int i = 0; i < char_len; i++) { wca[i] = mb_ptr2char_adv(&p); } @@ -683,7 +683,7 @@ static char_u *ins_compl_infercase_gettext(const char_u *str, int char_len, int } *p = NUL; - return (char_u *)IObuff; + return IObuff; } /// This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the @@ -692,11 +692,11 @@ static char_u *ins_compl_infercase_gettext(const char_u *str, int char_len, int /// the rest of the word to be in -- webb /// /// @param[in] cont_s_ipos next ^X<> will set initial_pos -int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, Direction dir, +int ins_compl_add_infercase(char *str_arg, int len, bool icase, char *fname, Direction dir, bool cont_s_ipos) FUNC_ATTR_NONNULL_ARG(1) { - char_u *str = str_arg; + char *str = str_arg; int char_len; // count multi-byte characters int compl_char_len; int flags = 0; @@ -707,7 +707,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, // Find actual length of completion. { - const char_u *p = str; + const char *p = str; char_len = 0; while (*p != NUL) { MB_PTR_ADV(p); @@ -717,7 +717,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, // Find actual length of original text. { - const char_u *p = (char_u *)compl_orig_text; + const char *p = compl_orig_text; compl_char_len = 0; while (*p != NUL) { MB_PTR_ADV(p); @@ -738,7 +738,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, flags |= CP_ICASE; } - int res = ins_compl_add((char *)str, len, (char *)fname, NULL, false, NULL, dir, flags, false); + int res = ins_compl_add(str, len, fname, NULL, false, NULL, dir, flags, false); xfree(tofree); return res; } @@ -908,7 +908,7 @@ static bool ins_compl_equal(compl_T *match, char *str, size_t len) /// Reduce the longest common string for match "match". static void ins_compl_longest_match(compl_T *match) { - char_u *p, *s; + char *p, *s; int c1, c2; int had_match; @@ -932,11 +932,11 @@ static void ins_compl_longest_match(compl_T *match) } // Reduce the text if this match differs from compl_leader. - p = (char_u *)compl_leader; - s = (char_u *)match->cp_str; + p = compl_leader; + s = match->cp_str; while (*p != NUL) { - c1 = utf_ptr2char((char *)p); - c2 = utf_ptr2char((char *)s); + c1 = utf_ptr2char(p); + c2 = utf_ptr2char(s); if ((match->cp_flags & CP_ICASE) ? (mb_tolower(c1) != mb_tolower(c2)) @@ -1193,16 +1193,16 @@ static int ins_compl_build_pum(void) } if (compl->cp_text[CPT_ABBR] != NULL) { - compl_match_array[i].pum_text = (char_u *)compl->cp_text[CPT_ABBR]; + compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR]; } else { - compl_match_array[i].pum_text = (char_u *)compl->cp_str; + compl_match_array[i].pum_text = compl->cp_str; } - compl_match_array[i].pum_kind = (char_u *)compl->cp_text[CPT_KIND]; - compl_match_array[i].pum_info = (char_u *)compl->cp_text[CPT_INFO]; + compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND]; + compl_match_array[i].pum_info = compl->cp_text[CPT_INFO]; if (compl->cp_text[CPT_MENU] != NULL) { - compl_match_array[i++].pum_extra = (char_u *)compl->cp_text[CPT_MENU]; + compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU]; } else { - compl_match_array[i++].pum_extra = (char_u *)compl->cp_fname; + compl_match_array[i++].pum_extra = compl->cp_fname; } } @@ -1256,8 +1256,8 @@ void ins_compl_show_pum(void) } else { // popup menu already exists, only need to find the current item. for (int i = 0; i < compl_match_arraysize; i++) { - if (compl_match_array[i].pum_text == (char_u *)compl_shown_match->cp_str - || compl_match_array[i].pum_text == (char_u *)compl_shown_match->cp_text[CPT_ABBR]) { + if (compl_match_array[i].pum_text == compl_shown_match->cp_str + || compl_match_array[i].pum_text == compl_shown_match->cp_text[CPT_ABBR]) { cur = i; break; } @@ -1293,10 +1293,10 @@ void ins_compl_show_pum(void) /// /// @param flags DICT_FIRST and/or DICT_EXACT /// @param thesaurus Thesaurus completion -static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, int thesaurus) +static void ins_compl_dictionaries(char *dict_start, char *pat, int flags, int thesaurus) { - char *dict = (char *)dict_start; - char_u *ptr; + char *dict = dict_start; + char *ptr; char *buf; regmatch_T regmatch; char **files; @@ -1327,16 +1327,16 @@ static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, i // to only match at the start of a line. Otherwise just match the // pattern. Also need to double backslashes. if (ctrl_x_mode_line_or_eval()) { - char *pat_esc = (char *)vim_strsave_escaped(pat, (char_u *)"\\"); + char *pat_esc = vim_strsave_escaped(pat, "\\"); size_t len = strlen(pat_esc) + 10; ptr = xmalloc(len); - vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc); - regmatch.regprog = vim_regcomp((char *)ptr, RE_MAGIC); + vim_snprintf(ptr, len, "^\\s*\\zs\\V%s", pat_esc); + regmatch.regprog = vim_regcomp(ptr, RE_MAGIC); xfree(pat_esc); xfree(ptr); } else { - regmatch.regprog = vim_regcomp((char *)pat, magic_isset() ? RE_MAGIC : 0); + regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0); if (regmatch.regprog == NULL) { goto theend; } @@ -1371,10 +1371,10 @@ static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, i } else { ptr = pat; } - spell_dump_compl((char *)ptr, regmatch.rm_ic, &dir, 0); + spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0); } else if (count > 0) { // avoid warning for using "files" uninit ins_compl_files(count, files, thesaurus, flags, - ®match, (char_u *)buf, &dir); + ®match, buf, &dir); if (flags != DICT_EXACT) { FreeWild(count, files); } @@ -1394,21 +1394,20 @@ theend: /// skipping the word at 'skip_word'. /// /// @return OK on success. -static int thesaurus_add_words_in_line(char *fname, char_u **buf_arg, int dir, - const char_u *skip_word) +static int thesaurus_add_words_in_line(char *fname, char **buf_arg, int dir, const char *skip_word) { int status = OK; // Add the other matches on the line - char *ptr = (char *)(*buf_arg); + char *ptr = *buf_arg; while (!got_int) { // Find start of the next word. Skip white // space and punctuation. - ptr = (char *)find_word_start((char_u *)ptr); + ptr = find_word_start(ptr); if (*ptr == NUL || *ptr == NL) { break; } - char_u *wstart = (char_u *)ptr; + char *wstart = ptr; // Find end of the word. // Japanese words may have characters in @@ -1425,25 +1424,25 @@ static int thesaurus_add_words_in_line(char *fname, char_u **buf_arg, int dir, // Add the word. Skip the regexp match. if (wstart != skip_word) { - status = ins_compl_add_infercase(wstart, (int)(ptr - (char *)wstart), p_ic, - (char_u *)fname, dir, false); + status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic, + fname, dir, false); if (status == FAIL) { break; } } } - *buf_arg = (char_u *)ptr; + *buf_arg = ptr; return status; } /// Process "count" dictionary/thesaurus "files" and add the text matching /// "regmatch". static void ins_compl_files(int count, char **files, int thesaurus, int flags, regmatch_T *regmatch, - char_u *buf, Direction *dir) + char *buf, Direction *dir) FUNC_ATTR_NONNULL_ARG(2, 7) { - char_u *ptr; + char *ptr; int i; FILE *fp; int add_r; @@ -1463,23 +1462,22 @@ static void ins_compl_files(int count, char **files, int thesaurus, int flags, r // Read dictionary file line by line. // Check each line for a match. - while (!got_int && !compl_interrupted && !vim_fgets((char *)buf, LSIZE, fp)) { + while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp)) { ptr = buf; - while (vim_regexec(regmatch, (char *)buf, (colnr_T)(ptr - buf))) { - ptr = (char_u *)regmatch->startp[0]; + while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf))) { + ptr = regmatch->startp[0]; if (ctrl_x_mode_line_or_eval()) { - ptr = (char_u *)find_line_end((char *)ptr); + ptr = find_line_end(ptr); } else { ptr = find_word_end(ptr); } - add_r = ins_compl_add_infercase((char_u *)regmatch->startp[0], - (int)(ptr - (char_u *)regmatch->startp[0]), - p_ic, (char_u *)files[i], *dir, false); + add_r = ins_compl_add_infercase(regmatch->startp[0], + (int)(ptr - regmatch->startp[0]), + p_ic, files[i], *dir, false); if (thesaurus) { // For a thesaurus, add all the words in the line ptr = buf; - add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir, - (char_u *)regmatch->startp[0]); + add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir, regmatch->startp[0]); } if (add_r == OK) { // if dir was BACKWARD then honor it just once @@ -1502,24 +1500,24 @@ static void ins_compl_files(int count, char **files, int thesaurus, int flags, r /// Find the start of the next word. /// Returns a pointer to the first char of the word. Also stops at a NUL. -char_u *find_word_start(char_u *ptr) +char *find_word_start(char *ptr) FUNC_ATTR_PURE { while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1) { - ptr += utfc_ptr2len((char *)ptr); + ptr += utfc_ptr2len(ptr); } return ptr; } /// Find the end of the word. Assumes it starts inside a word. /// Returns a pointer to just after the word. -char_u *find_word_end(char_u *ptr) +char *find_word_end(char *ptr) FUNC_ATTR_PURE { const int start_class = mb_get_class(ptr); if (start_class > 1) { while (*ptr != NUL) { - ptr += utfc_ptr2len((char *)ptr); + ptr += utfc_ptr2len(ptr); if (mb_get_class(ptr) != start_class) { break; } @@ -1975,9 +1973,9 @@ static bool ins_compl_stop(const int c, const int prev_mode, bool retval) // of the original text that has changed. // When using the longest match, edited the match or used // CTRL-E then don't use the current match. - char_u *ptr; + char *ptr; if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) { - ptr = (char_u *)compl_curr_match->cp_str; + ptr = compl_curr_match->cp_str; } else { ptr = NULL; } @@ -2182,24 +2180,24 @@ bool ins_compl_prep(int c) /// Fix the redo buffer for the completion leader replacing some of the typed /// text. This inserts backspaces and appends the changed text. /// "ptr" is the known leader text or NUL. -static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) +static void ins_compl_fixRedoBufForLeader(char *ptr_arg) { int len; - char_u *p; - char_u *ptr = ptr_arg; + char *p; + char *ptr = ptr_arg; if (ptr == NULL) { if (compl_leader != NULL) { - ptr = (char_u *)compl_leader; + ptr = compl_leader; } else { return; // nothing to do } } if (compl_orig_text != NULL) { - p = (char_u *)compl_orig_text; + p = compl_orig_text; for (len = 0; p[len] != NUL && p[len] == ptr[len]; len++) {} if (len > 0) { - len -= utf_head_off((char *)p, (char *)p + len); + len -= utf_head_off(p, p + len); } for (p += len; *p != NUL; MB_PTR_ADV(p)) { AppendCharToRedobuff(K_BS); @@ -2207,7 +2205,7 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) } else { len = 0; } - AppendToRedobuffLit((char *)ptr + len, -1); + AppendToRedobuffLit(ptr + len, -1); } /// Loops through the list of windows, loaded-buffers or non-loaded-buffers @@ -2328,17 +2326,17 @@ bool set_ref_in_insexpand_funcs(int copyID) } /// Get the user-defined completion function name for completion "type" -static char_u *get_complete_funcname(int type) +static char *get_complete_funcname(int type) { switch (type) { case CTRL_X_FUNCTION: - return (char_u *)curbuf->b_p_cfu; + return curbuf->b_p_cfu; case CTRL_X_OMNI: - return (char_u *)curbuf->b_p_ofu; + return curbuf->b_p_ofu; case CTRL_X_THESAURUS: - return *curbuf->b_p_tsrfu == NUL ? (char_u *)p_tsrfu : (char_u *)curbuf->b_p_tsrfu; + return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu; default: - return (char_u *)""; + return ""; } } @@ -2359,11 +2357,11 @@ static Callback *get_insert_callback(int type) /// 'thesaurusfunc', and get matches in "matches". /// /// @param type either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS -static void expand_by_function(int type, char_u *base) +static void expand_by_function(int type, char *base) { list_T *matchlist = NULL; dict_T *matchdict = NULL; - char_u *funcname; + char *funcname; pos_T pos; typval_T rettv; const int save_State = State; @@ -2380,7 +2378,7 @@ static void expand_by_function(int type, char_u *base) args[1].v_type = VAR_STRING; args[2].v_type = VAR_UNKNOWN; args[0].vval.v_number = 0; - args[1].vval.v_string = base != NULL ? (char *)base : ""; + args[1].vval.v_string = base != NULL ? base : ""; pos = curwin->w_cursor; // Lock the text to avoid weird things from happening. Also disallow @@ -2636,12 +2634,12 @@ void f_complete_check(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } /// Return Insert completion mode name string -static char_u *ins_compl_mode(void) +static char *ins_compl_mode(void) { if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started) { - return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT]; + return ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT]; } - return (char_u *)""; + return ""; } /// Assign the sequence number to all the completion matches which don't have @@ -2730,8 +2728,7 @@ static void get_complete_info(list_T *what_list, dict_T *retdict) int ret = OK; if (what_flag & CI_WHAT_MODE) { - ret = tv_dict_add_str(retdict, S_LEN("mode"), - (char *)ins_compl_mode()); + ret = tv_dict_add_str(retdict, S_LEN("mode"), ins_compl_mode()); } if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE)) { @@ -2875,7 +2872,7 @@ static int process_next_cpt_value(ins_compl_next_state_T *st, int *compl_type_ar goto done; } compl_type = CTRL_X_DICTIONARY; - st->dict = (char_u *)st->ins_buf->b_fname; + st->dict = st->ins_buf->b_fname; st->dict_f = DICT_EXACT; } if (!shortmess(SHM_COMPLETIONSCAN)) { @@ -2900,7 +2897,7 @@ static int process_next_cpt_value(ins_compl_next_state_T *st, int *compl_type_ar compl_type = CTRL_X_THESAURUS; } if (*++st->e_cpt != ',' && *st->e_cpt != NUL) { - st->dict = (char_u *)st->e_cpt; + st->dict = st->e_cpt; st->dict_f = DICT_FIRST; } } else if (*st->e_cpt == 'i') { @@ -2946,17 +2943,17 @@ static void get_next_include_file_completion(int compl_type) /// Get the next set of words matching "compl_pattern" in dictionary or /// thesaurus files. -static void get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f) +static void get_next_dict_tsr_completion(int compl_type, char *dict, int dict_f) { if (thesaurus_func_complete(compl_type)) { - expand_by_function(compl_type, (char_u *)compl_pattern); + expand_by_function(compl_type, compl_pattern); } else { ins_compl_dictionaries(dict != NULL ? dict : (compl_type == CTRL_X_THESAURUS - ? (*curbuf->b_p_tsr == NUL ? p_tsr : (char_u *)curbuf->b_p_tsr) + ? (*curbuf->b_p_tsr == NUL ? (char *)p_tsr : curbuf->b_p_tsr) : (*curbuf->b_p_dict == - NUL ? (char_u *)p_dict : (char_u *)curbuf->b_p_dict)), - (char_u *)compl_pattern, + NUL ? p_dict : curbuf->b_p_dict)), + compl_pattern, dict != NULL ? dict_f : 0, compl_type == CTRL_X_THESAURUS); } @@ -2967,7 +2964,7 @@ static void get_next_tag_completion(void) { // set p_ic according to p_ic, p_scs and pat for find_tags(). const int save_p_ic = p_ic; - p_ic = ignorecase((char_u *)compl_pattern); + p_ic = ignorecase(compl_pattern); // Find up to TAG_MANY matches. Avoids that an enormous number // of matches is found when compl_pattern is empty @@ -2995,7 +2992,7 @@ static void get_next_filename_completion(void) } // May change home directory back to "~". - tilde_replace((char_u *)compl_pattern, num_matches, matches); + tilde_replace(compl_pattern, num_matches, matches); #ifdef BACKSLASH_IN_FILENAME if (curbuf->b_p_csl[0] != NUL) { for (int i = 0; i < num_matches; i++) { @@ -3030,7 +3027,7 @@ static void get_next_cmdline_completion(void) static void get_next_spell_completion(linenr_T lnum) { char **matches; - int num_matches = expand_spelling(lnum, (char_u *)compl_pattern, &matches); + int num_matches = expand_spelling(lnum, compl_pattern, &matches); if (num_matches > 0) { ins_compl_add_matches(num_matches, matches, p_ic); } else { @@ -3044,8 +3041,8 @@ static void get_next_spell_completion(linenr_T lnum) /// @param cur_match_pos current match position /// @param match_len /// @param cont_s_ipos next ^X<> will set initial_pos -static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_pos, int *match_len, - bool *cont_s_ipos) +static char *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_pos, int *match_len, + bool *cont_s_ipos) { *match_len = 0; char *ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, false) + cur_match_pos->col; @@ -3071,10 +3068,10 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p return NULL; } // Find start of next word. - tmp_ptr = (char *)find_word_start((char_u *)tmp_ptr); + tmp_ptr = find_word_start(tmp_ptr); } // Find end of this word. - tmp_ptr = (char *)find_word_end((char_u *)tmp_ptr); + tmp_ptr = find_word_end(tmp_ptr); len = (int)(tmp_ptr - ptr); if (compl_status_adding() && len == compl_length) { @@ -3086,9 +3083,9 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, false); tmp_ptr = ptr = skipwhite(ptr); // Find start of next word. - tmp_ptr = (char *)find_word_start((char_u *)tmp_ptr); + tmp_ptr = find_word_start(tmp_ptr); // Find end of next word. - tmp_ptr = (char *)find_word_end((char_u *)tmp_ptr); + tmp_ptr = find_word_end(tmp_ptr); if (tmp_ptr > ptr) { if (*ptr != ')' && IObuff[len - 1] != TAB) { if (IObuff[len - 1] != ' ') { @@ -3120,7 +3117,7 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p } *match_len = len; - return (char_u *)ptr; + return ptr; } /// Get the next set of words matching "compl_pattern" for default completion(s) @@ -3207,13 +3204,13 @@ static int get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_ continue; } int len; - char_u *ptr = ins_comp_get_next_word_or_line(st->ins_buf, st->cur_match_pos, - &len, &cont_s_ipos); + char *ptr = ins_comp_get_next_word_or_line(st->ins_buf, st->cur_match_pos, + &len, &cont_s_ipos); if (ptr == NULL) { continue; } if (ins_compl_add_infercase(ptr, len, p_ic, - st->ins_buf == curbuf ? NULL : (char_u *)st->ins_buf->b_sfname, + st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname, 0, cont_s_ipos) != NOTDONE) { found_new_match = OK; break; @@ -3260,7 +3257,7 @@ static bool get_next_completion_match(int type, ins_compl_next_state_T *st, pos_ case CTRL_X_FUNCTION: case CTRL_X_OMNI: - expand_by_function(type, (char_u *)compl_pattern); + expand_by_function(type, compl_pattern); break; case CTRL_X_SPELL: @@ -3832,17 +3829,17 @@ static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col) char *prefix = "\\<"; // we need up to 2 extra chars for the prefix - compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col, compl_length) + 2); + compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, compl_length) + 2); if (!vim_iswordp(line + compl_col) || (compl_col > 0 - && (vim_iswordp((char *)mb_prevptr((char_u *)line, (char_u *)line + compl_col))))) { + && (vim_iswordp(mb_prevptr(line, line + compl_col))))) { prefix = ""; } STRCPY(compl_pattern, prefix); - (void)quote_meta((char_u *)compl_pattern + strlen(prefix), - (char_u *)line + compl_col, compl_length); + (void)quote_meta(compl_pattern + strlen(prefix), + line + compl_col, compl_length); } else if (--startcol < 0 - || !vim_iswordp((char *)mb_prevptr((char_u *)line, (char_u *)line + startcol + 1))) { + || !vim_iswordp(mb_prevptr(line, line + startcol + 1))) { // Match any word of at least two chars compl_pattern = xstrdup("\\<\\k\\k"); compl_col += curs_col; @@ -3851,10 +3848,10 @@ static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col) // Search the point of change class of multibyte character // or not a word single byte character backward. startcol -= utf_head_off(line, line + startcol); - int base_class = mb_get_class((char_u *)line + startcol); + int base_class = mb_get_class(line + startcol); while (--startcol >= 0) { int head_off = utf_head_off(line, line + startcol); - if (base_class != mb_get_class((char_u *)line + startcol - head_off)) { + if (base_class != mb_get_class(line + startcol - head_off)) { break; } startcol -= head_off; @@ -3867,13 +3864,12 @@ static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col) // xmalloc(7) is enough -- Acevedo compl_pattern = xmalloc(7); STRCPY(compl_pattern, "\\<"); - (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, 1); + (void)quote_meta(compl_pattern + 2, line + compl_col, 1); STRCAT(compl_pattern, "\\k"); } else { - compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col, - compl_length) + 2); + compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, compl_length) + 2); STRCPY(compl_pattern, "\\<"); - (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, compl_length); + (void)quote_meta(compl_pattern + 2, line + compl_col, compl_length); } } @@ -3901,17 +3897,17 @@ static int get_wholeline_compl_info(char *line, colnr_T curs_col) /// Get the pattern, column and length for filename completion. /// Sets the global variables: compl_col, compl_length and compl_pattern. -static int get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col) +static int get_filename_compl_info(char *line, int startcol, colnr_T curs_col) { // Go back to just before the first filename character. if (startcol > 0) { - char_u *p = line + startcol; + char *p = line + startcol; MB_PTR_BACK(line, p); - while (p > line && vim_isfilec(utf_ptr2char((char *)p))) { + while (p > line && vim_isfilec(utf_ptr2char(p))) { MB_PTR_BACK(line, p); } - if (p == line && vim_isfilec(utf_ptr2char((char *)p))) { + if (p == line && vim_isfilec(utf_ptr2char(p))) { startcol = 0; } else { startcol = (int)(p - line) + 1; @@ -3920,7 +3916,7 @@ static int get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col) compl_col += startcol; compl_length = (int)curs_col - startcol; - compl_pattern = addstar((char *)line + compl_col, (size_t)compl_length, EXPAND_FILES); + compl_pattern = addstar(line + compl_col, (size_t)compl_length, EXPAND_FILES); return OK; } @@ -3930,7 +3926,7 @@ static int get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col) static int get_cmdline_compl_info(char *line, colnr_T curs_col) { compl_pattern = xstrnsave(line, (size_t)curs_col); - set_cmd_context(&compl_xp, (char_u *)compl_pattern, (int)strlen(compl_pattern), curs_col, false); + set_cmd_context(&compl_xp, compl_pattern, (int)strlen(compl_pattern), curs_col, false); if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL || compl_xp.xp_context == EXPAND_NOTHING) { // No completion possible, use an empty pattern to get a @@ -3955,7 +3951,7 @@ static int get_userdefined_compl_info(colnr_T curs_col) const int save_State = State; // Call 'completefunc' or 'omnifunc' and get pattern length as a string - char_u *funcname = get_complete_funcname(ctrl_x_mode); + char *funcname = get_complete_funcname(ctrl_x_mode); if (*funcname == NUL) { semsg(_(e_notset), ctrl_x_mode_function() ? "completefunc" : "omnifunc"); return FAIL; @@ -4053,18 +4049,18 @@ static int get_spell_compl_info(int startcol, colnr_T curs_col) /// become invalid and needs to be fetched again. /// /// @return OK on success. -static int compl_get_info(char_u *line, int startcol, colnr_T curs_col, bool *line_invalid) +static int compl_get_info(char *line, int startcol, colnr_T curs_col, bool *line_invalid) { if (ctrl_x_mode_normal() || ((ctrl_x_mode & CTRL_X_WANT_IDENT) && !thesaurus_func_complete(ctrl_x_mode))) { - return get_normal_compl_info((char *)line, startcol, curs_col); + return get_normal_compl_info(line, startcol, curs_col); } else if (ctrl_x_mode_line_or_eval()) { - return get_wholeline_compl_info((char *)line, curs_col); + return get_wholeline_compl_info(line, curs_col); } else if (ctrl_x_mode_files()) { return get_filename_compl_info(line, startcol, curs_col); } else if (ctrl_x_mode == CTRL_X_CMDLINE) { - return get_cmdline_compl_info((char *)line, curs_col); + return get_cmdline_compl_info(line, curs_col); } else if (ctrl_x_mode_function() || ctrl_x_mode_omni() || thesaurus_func_complete(ctrl_x_mode)) { if (get_userdefined_compl_info(curs_col) == FAIL) { @@ -4092,7 +4088,7 @@ static int compl_get_info(char_u *line, int startcol, colnr_T curs_col, bool *li /// the same line as the cursor then fix it (the line has been split because it /// was longer than 'tw'). if SOL is set then skip the previous pattern, a word /// at the beginning of the line has been inserted, we'll look for that. -static void ins_compl_continue_search(char_u *line) +static void ins_compl_continue_search(char *line) { // it is a continued search compl_cont_status &= ~CONT_INTRPT; // remove INTRPT @@ -4104,7 +4100,7 @@ static void ins_compl_continue_search(char_u *line) // first non_blank in the line, if it is not a wordchar // include it to get a better pattern, but then we don't // want the "\\<" prefix, check it below. - compl_col = (colnr_T)getwhitecols((char *)line); + compl_col = (colnr_T)getwhitecols(line); compl_startpos.col = compl_col; compl_startpos.lnum = curwin->w_cursor.lnum; compl_cont_status &= ~CONT_SOL; // clear SOL if present @@ -4114,9 +4110,7 @@ static void ins_compl_continue_search(char_u *line) // mode but first we need to redefine compl_startpos if (compl_cont_status & CONT_S_IPOS) { compl_cont_status |= CONT_SOL; - compl_startpos.col = (colnr_T)((char_u *)skipwhite((char *)line - + compl_length - + compl_startpos.col) - line); + compl_startpos.col = (colnr_T)(skipwhite(line + compl_length + compl_startpos.col) - line); } compl_col = compl_startpos.col; } @@ -4163,7 +4157,7 @@ static int ins_compl_start(void) && compl_cont_mode == ctrl_x_mode) { // this same ctrl-x_mode was interrupted previously. Continue the // completion. - ins_compl_continue_search((char_u *)line); + ins_compl_continue_search(line); } else { compl_cont_status &= CONT_LOCAL; } @@ -4183,7 +4177,7 @@ static int ins_compl_start(void) // Work out completion pattern and original text -- webb bool line_invalid = false; - if (compl_get_info((char_u *)line, startcol, curs_col, &line_invalid) == FAIL) { + if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL) { if (ctrl_x_mode_function() || ctrl_x_mode_omni() || thesaurus_func_complete(ctrl_x_mode)) { // restore did_ai, so that adding comment leader works @@ -4282,18 +4276,18 @@ static void ins_compl_show_statusmsg(void) if (compl_curr_match->cp_number != -1) { // Space for 10 text chars. + 2x10-digit no.s = 31. // Translations may need more than twice that. - static char_u match_ref[81]; + static char match_ref[81]; if (compl_matches > 0) { - vim_snprintf((char *)match_ref, sizeof(match_ref), + vim_snprintf(match_ref, sizeof(match_ref), _("match %d of %d"), compl_curr_match->cp_number, compl_matches); } else { - vim_snprintf((char *)match_ref, sizeof(match_ref), + vim_snprintf(match_ref, sizeof(match_ref), _("match %d"), compl_curr_match->cp_number); } - edit_submode_extra = (char *)match_ref; + edit_submode_extra = match_ref; edit_submode_highl = HLF_R; if (dollar_vcol >= 0) { curs_columns(curwin, false); @@ -4417,7 +4411,7 @@ static void show_pum(int prev_w_wrow, int prev_w_leftcol) // If dest is not NULL the chars. are copied there quoting (with // a backslash) the metachars, and dest would be NUL terminated. // Returns the length (needed) of dest -static unsigned quote_meta(char_u *dest, char_u *src, int len) +static unsigned quote_meta(char *dest, char *src, int len) { unsigned m = (unsigned)len + 1; // one extra for the NUL @@ -4452,7 +4446,7 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) *dest++ = *src; } // Copy remaining bytes of a multibyte character. - const int mb_len = utfc_ptr2len((char *)src) - 1; + const int mb_len = utfc_ptr2len(src) - 1; if (mb_len > 0 && len >= mb_len) { for (int i = 0; i < mb_len; i++) { len--; diff --git a/src/nvim/keycodes.c b/src/nvim/keycodes.c index 71086a76e5..a4228fcc7e 100644 --- a/src/nvim/keycodes.c +++ b/src/nvim/keycodes.c @@ -403,22 +403,24 @@ int name_to_mod_mask(int c) int simplify_key(const int key, int *modifiers) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { - if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT)) { - // TAB is a special case. - if (key == TAB && (*modifiers & MOD_MASK_SHIFT)) { - *modifiers &= ~MOD_MASK_SHIFT; - return K_S_TAB; - } - const int key0 = KEY2TERMCAP0(key); - const int key1 = KEY2TERMCAP1(key); - for (int i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE) { - if (key0 == modifier_keys_table[i + 3] - && key1 == modifier_keys_table[i + 4] - && (*modifiers & modifier_keys_table[i])) { - *modifiers &= ~modifier_keys_table[i]; - return TERMCAP2KEY(modifier_keys_table[i + 1], - modifier_keys_table[i + 2]); - } + if (!(*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))) { + return key; + } + + // TAB is a special case. + if (key == TAB && (*modifiers & MOD_MASK_SHIFT)) { + *modifiers &= ~MOD_MASK_SHIFT; + return K_S_TAB; + } + const int key0 = KEY2TERMCAP0(key); + const int key1 = KEY2TERMCAP1(key); + for (int i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE) { + if (key0 == modifier_keys_table[i + 3] + && key1 == modifier_keys_table[i + 4] + && (*modifiers & modifier_keys_table[i])) { + *modifiers &= ~modifier_keys_table[i]; + return TERMCAP2KEY(modifier_keys_table[i + 1], + modifier_keys_table[i + 2]); } } return key; @@ -960,10 +962,10 @@ char *replace_termcodes(const char *const from, const size_t from_len, char **co // If "mapleader" or "maplocalleader" isn't set use a backslash. if (end - src >= 7 && STRNICMP(src, "<Leader>", 8) == 0) { len = 8; - p = (char *)get_var_value("g:mapleader"); + p = get_var_value("g:mapleader"); } else if (end - src >= 12 && STRNICMP(src, "<LocalLeader>", 13) == 0) { len = 13; - p = (char *)get_var_value("g:maplocalleader"); + p = get_var_value("g:maplocalleader"); } else { len = 0; p = NULL; diff --git a/src/nvim/lib/ringbuf.h b/src/nvim/lib/ringbuf.h index 4fd110a531..907018a06e 100644 --- a/src/nvim/lib/ringbuf.h +++ b/src/nvim/lib/ringbuf.h @@ -25,14 +25,9 @@ #define _RINGBUF_LENGTH(rb) \ ((rb)->first == NULL ? 0 \ - : ((rb)->next == (rb)->first) ? (size_t)((rb)->buf_end - (rb)->buf) + 1 \ - : ((rb)->next > \ - (rb)->first) ? (size_t)((rb)->next - \ - (rb)->first) \ - : (size_t)((rb)-> \ - next - (rb)->buf + \ - (rb)->buf_end - \ - (rb)->first + 1)) + : ((rb)->next == (rb)->first) ? (size_t)((rb)->buf_end - (rb)->buf) + 1 \ + : ((rb)->next > (rb)->first) ? (size_t)((rb)->next - (rb)->first) \ + : (size_t)((rb)->next - (rb)->buf + (rb)->buf_end - (rb)->first + 1)) #define _RINGBUF_NEXT(rb, var) \ ((var) == (rb)->buf_end ? (rb)->buf : (var) + 1) diff --git a/src/nvim/locale.c b/src/nvim/locale.c index c07420be1d..6322271073 100644 --- a/src/nvim/locale.c +++ b/src/nvim/locale.c @@ -290,8 +290,7 @@ static char **find_locales(void) // Find all available locales by running command "locale -a". If this // doesn't work we won't have completion. - char *locale_a = (char *)get_cmd_output((char_u *)"locale -a", NULL, - kShellOptSilent, NULL); + char *locale_a = get_cmd_output("locale -a", NULL, kShellOptSilent, NULL); if (locale_a == NULL) { return NULL; } @@ -318,23 +317,26 @@ static char **find_locales(void) static void init_locales(void) { # ifndef MSWIN - if (!did_init_locales) { - did_init_locales = true; - locales = find_locales(); + if (did_init_locales) { + return; } + + did_init_locales = true; + locales = find_locales(); # endif } # if defined(EXITFREE) void free_locales(void) { - int i; - if (locales != NULL) { - for (i = 0; locales[i] != NULL; i++) { - xfree(locales[i]); - } - XFREE_CLEAR(locales); + if (locales == NULL) { + return; + } + + for (int i = 0; locales[i] != NULL; i++) { + xfree(locales[i]); } + XFREE_CLEAR(locales); } # endif diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 813f86eeee..dac96790d7 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -176,7 +176,7 @@ int nlua_str_utfindex(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL } size_t codepoints = 0, codeunits = 0; - mb_utflen((const char_u *)s1, (size_t)idx, &codepoints, &codeunits); + mb_utflen(s1, (size_t)idx, &codepoints, &codeunits); lua_pushinteger(lstate, (long)codepoints); lua_pushinteger(lstate, (long)codeunits); diff --git a/src/nvim/main.c b/src/nvim/main.c index 048fdd4052..6f14a00949 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -242,10 +242,10 @@ int main(int argc, char **argv) argv0 = argv[0]; - char_u *fname = NULL; // file name from command line + char *fname = NULL; // file name from command line mparm_T params; // various parameters passed between // main() and other functions. - char_u *cwd = NULL; // current working dir on startup + char *cwd = NULL; // current working dir on startup time_init(); // Many variables are in `params` so that we can pass them around easily. @@ -279,15 +279,6 @@ int main(int argc, char **argv) // argument list "global_alist". command_line_scan(¶ms); -#ifndef MSWIN - int tty_fd = params.input_isatty - ? STDIN_FILENO - : (params.output_isatty - ? STDOUT_FILENO - : (params.err_isatty ? STDERR_FILENO : -1)); - pty_process_save_termios(tty_fd); -#endif - nlua_init(argv, argc, params.lua_arg0); TIME_MSG("init lua interpreter"); @@ -560,7 +551,7 @@ int main(int argc, char **argv) // Need to jump to the tag before executing the '-c command'. // Makes "vim -c '/return' -t main" work. - handle_tag((char_u *)params.tagname); + handle_tag(params.tagname); // Execute any "+", "-c" and "-S" arguments. if (params.n_commands > 0) { @@ -1215,7 +1206,7 @@ static void command_line_scan(mparm_T *parmp) break; case 'w': // "-w{number}" set window height // "-w {scriptout}" write to script - if (ascii_isdigit(((char_u *)argv[0])[argv_idx])) { + if (ascii_isdigit((argv[0])[argv_idx])) { n = get_number_arg(argv[0], &argv_idx, 10); set_option_value_give_err("window", n, NULL, 0); break; @@ -1356,7 +1347,7 @@ scripterror: case 'w': // "-w {nr}" 'window' value // "-w {scriptout}" append to script file - if (ascii_isdigit(*((char_u *)argv[0]))) { + if (ascii_isdigit(*(argv[0]))) { argv_idx = 0; n = get_number_arg(argv[0], &argv_idx, 10); set_option_value_give_err("window", n, NULL, 0); @@ -1489,9 +1480,9 @@ static void init_path(const char *exename) } /// Get filename from command line, if any. -static char_u *get_fname(mparm_T *parmp, char_u *cwd) +static char *get_fname(mparm_T *parmp, char *cwd) { - return (char_u *)alist_name(&GARGLIST[0]); + return alist_name(&GARGLIST[0]); } // Decide about window layout for diff mode after reading vimrc. @@ -1525,7 +1516,7 @@ static void handle_quickfix(mparm_T *paramp) // Need to jump to the tag before executing the '-c command'. // Makes "vim -c '/return' -t main" work. -static void handle_tag(char_u *tagname) +static void handle_tag(char *tagname) { if (tagname != NULL) { swap_exists_did_quit = false; @@ -1713,7 +1704,7 @@ static void create_windows(mparm_T *parmp) /// If opened more than one window, start editing files in the other /// windows. make_windows() has already opened the windows. -static void edit_buffers(mparm_T *parmp, char_u *cwd) +static void edit_buffers(mparm_T *parmp, char *cwd) { int arg_idx; // index in argument list int i; @@ -1734,7 +1725,7 @@ static void edit_buffers(mparm_T *parmp, char_u *cwd) arg_idx = 1; for (i = 1; i < parmp->window_count; i++) { if (cwd != NULL) { - os_chdir((char *)cwd); + os_chdir(cwd); } // When w_arg_idx is -1 remove the window (see create_windows()). if (curwin->w_arg_idx == -1) { @@ -1837,17 +1828,19 @@ static void exe_pre_commands(mparm_T *parmp) int cnt = parmp->n_pre_commands; int i; - if (cnt > 0) { - curwin->w_cursor.lnum = 0; // just in case.. - estack_push(ETYPE_ARGS, _("pre-vimrc command line"), 0); - current_sctx.sc_sid = SID_CMDARG; - for (i = 0; i < cnt; i++) { - do_cmdline_cmd(cmds[i]); - } - estack_pop(); - current_sctx.sc_sid = 0; - TIME_MSG("--cmd commands"); + if (cnt <= 0) { + return; } + + curwin->w_cursor.lnum = 0; // just in case.. + estack_push(ETYPE_ARGS, _("pre-vimrc command line"), 0); + current_sctx.sc_sid = SID_CMDARG; + for (i = 0; i < cnt; i++) { + do_cmdline_cmd(cmds[i]); + } + estack_pop(); + current_sctx.sc_sid = 0; + TIME_MSG("--cmd commands"); } // Execute "+", "-c" and "-S" arguments. @@ -1953,13 +1946,13 @@ static bool do_user_initialization(void) return do_exrc; } - char_u *init_lua_path = (char_u *)stdpaths_user_conf_subpath("init.lua"); - char_u *user_vimrc = (char_u *)stdpaths_user_conf_subpath("init.vim"); + char *init_lua_path = stdpaths_user_conf_subpath("init.lua"); + char *user_vimrc = stdpaths_user_conf_subpath("init.vim"); // init.lua - if (os_path_exists((char *)init_lua_path) - && do_source((char *)init_lua_path, true, DOSO_VIMRC)) { - if (os_path_exists((char *)user_vimrc)) { + if (os_path_exists(init_lua_path) + && do_source(init_lua_path, true, DOSO_VIMRC)) { + if (os_path_exists(user_vimrc)) { semsg(_("E5422: Conflicting configs: \"%s\" \"%s\""), init_lua_path, user_vimrc); } @@ -1972,10 +1965,10 @@ static bool do_user_initialization(void) xfree(init_lua_path); // init.vim - if (do_source((char *)user_vimrc, true, DOSO_VIMRC) != FAIL) { + if (do_source(user_vimrc, true, DOSO_VIMRC) != FAIL) { do_exrc = p_exrc; if (do_exrc) { - do_exrc = (path_full_compare(VIMRC_FILE, (char *)user_vimrc, false, true) != kEqualFiles); + do_exrc = (path_full_compare(VIMRC_FILE, user_vimrc, false, true) != kEqualFiles); } xfree(user_vimrc); return do_exrc; @@ -2088,19 +2081,20 @@ static int execute_env(char *env) FUNC_ATTR_NONNULL_ALL { const char *initstr = os_getenv(env); - if (initstr != NULL) { - estack_push(ETYPE_ENV, env, 0); - const sctx_T save_current_sctx = current_sctx; - current_sctx.sc_sid = SID_ENV; - current_sctx.sc_seq = 0; - current_sctx.sc_lnum = 0; - do_cmdline_cmd((char *)initstr); - - estack_pop(); - current_sctx = save_current_sctx; - return OK; - } - return FAIL; + if (initstr == NULL) { + return FAIL; + } + + estack_push(ETYPE_ENV, env, 0); + const sctx_T save_current_sctx = current_sctx; + current_sctx.sc_sid = SID_ENV; + current_sctx.sc_seq = 0; + current_sctx.sc_lnum = 0; + do_cmdline_cmd((char *)initstr); + + estack_pop(); + current_sctx = save_current_sctx; + return OK; } /// Prints the following then exits: diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 757855c350..04a0107fe8 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -297,10 +297,10 @@ static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len if (rhs_lua == LUA_NOREF) { mapargs->orig_rhs_len = orig_rhs_len; - mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char_u)); + mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char)); xstrlcpy(mapargs->orig_rhs, orig_rhs, mapargs->orig_rhs_len + 1); if (STRICMP(orig_rhs, "<nop>") == 0) { // "<Nop>" means nothing - mapargs->rhs = xcalloc(1, sizeof(char_u)); // single NUL-char + mapargs->rhs = xcalloc(1, sizeof(char)); // single NUL-char mapargs->rhs_len = 0; mapargs->rhs_is_noop = true; } else { @@ -316,7 +316,7 @@ static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len } else { char tmp_buf[64]; // orig_rhs is not used for Lua mappings, but still needs to be a string. - mapargs->orig_rhs = xcalloc(1, sizeof(char_u)); + mapargs->orig_rhs = xcalloc(1, sizeof(char)); mapargs->orig_rhs_len = 0; // stores <lua>ref_no<cr> in map_str mapargs->rhs_len = (size_t)vim_snprintf(S_LEN(tmp_buf), "%c%c%c%d\r", K_SPECIAL, @@ -344,53 +344,53 @@ static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len /// @param[out] mapargs MapArguments struct holding all extracted argument /// values. /// @return 0 on success, 1 if invalid arguments are detected. -static int str_to_mapargs(const char_u *strargs, bool is_unmap, MapArguments *mapargs) +static int str_to_mapargs(const char *strargs, bool is_unmap, MapArguments *mapargs) { - const char *to_parse = (char *)strargs; - to_parse = skipwhite((char *)to_parse); + const char *to_parse = strargs; + to_parse = skipwhite(to_parse); CLEAR_POINTER(mapargs); // Accept <buffer>, <nowait>, <silent>, <expr>, <script>, and <unique> in // any order. while (true) { if (strncmp(to_parse, "<buffer>", 8) == 0) { - to_parse = skipwhite((char *)to_parse + 8); + to_parse = skipwhite(to_parse + 8); mapargs->buffer = true; continue; } if (strncmp(to_parse, "<nowait>", 8) == 0) { - to_parse = skipwhite((char *)to_parse + 8); + to_parse = skipwhite(to_parse + 8); mapargs->nowait = true; continue; } if (strncmp(to_parse, "<silent>", 8) == 0) { - to_parse = skipwhite((char *)to_parse + 8); + to_parse = skipwhite(to_parse + 8); mapargs->silent = true; continue; } // Ignore obsolete "<special>" modifier. if (strncmp(to_parse, "<special>", 9) == 0) { - to_parse = skipwhite((char *)to_parse + 9); + to_parse = skipwhite(to_parse + 9); continue; } if (strncmp(to_parse, "<script>", 8) == 0) { - to_parse = skipwhite((char *)to_parse + 8); + to_parse = skipwhite(to_parse + 8); mapargs->script = true; continue; } if (strncmp(to_parse, "<expr>", 6) == 0) { - to_parse = skipwhite((char *)to_parse + 6); + to_parse = skipwhite(to_parse + 6); mapargs->expr = true; continue; } if (strncmp(to_parse, "<unique>", 8) == 0) { - to_parse = skipwhite((char *)to_parse + 8); + to_parse = skipwhite(to_parse + 8); mapargs->unique = true; continue; } @@ -407,7 +407,7 @@ static int str_to_mapargs(const char_u *strargs, bool is_unmap, MapArguments *ma // // With :unmap, literal white space is included in the {lhs}; there is no // separate {rhs}. - const char *lhs_end = (char *)to_parse; + const char *lhs_end = to_parse; bool do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL); while (*lhs_end && (is_unmap || !ascii_iswhite(*lhs_end))) { if ((lhs_end[0] == Ctrl_V || (do_backslash && lhs_end[0] == '\\')) @@ -912,7 +912,7 @@ theend: /// - 4 for out of mem (deprecated, WON'T HAPPEN) /// - 5 for entry not unique /// -int do_map(int maptype, char_u *arg, int mode, bool is_abbrev) +int do_map(int maptype, char *arg, int mode, bool is_abbrev) { MapArguments parsed_args; int result = str_to_mapargs(arg, maptype == MAPTYPE_UNMAP, &parsed_args); @@ -1067,9 +1067,9 @@ bool map_to_exists(const char *const str, const char *const modechars, const boo int retval; char *buf = NULL; - const char_u *const rhs = (char_u *)replace_termcodes(str, strlen(str), - &buf, REPTERM_DO_LT, - NULL, CPO_TO_CPO_FLAGS); + const char *const rhs = replace_termcodes(str, strlen(str), + &buf, REPTERM_DO_LT, + NULL, CPO_TO_CPO_FLAGS); #define MAPMODE(mode, modechars, chr, modeflags) \ do { \ @@ -1087,7 +1087,7 @@ bool map_to_exists(const char *const str, const char *const modechars, const boo MAPMODE(mode, modechars, 'c', MODE_CMDLINE); #undef MAPMODE - retval = map_to_exists_mode((char *)rhs, mode, abbr); + retval = map_to_exists_mode(rhs, mode, abbr); xfree(buf); return retval; @@ -1344,7 +1344,7 @@ int ExpandMappings(regmatch_T *regmatch, int *num_file, char ***file) } if (round == 1) { - *file = xmalloc((size_t)count * sizeof(char_u *)); + *file = xmalloc((size_t)count * sizeof(char *)); } } // for (round) @@ -1418,25 +1418,25 @@ bool check_abbr(int c, char *ptr, int col, int mincol) { bool vim_abbr; - char_u *p = mb_prevptr((char_u *)ptr, (char_u *)ptr + col); - if (!vim_iswordp((char *)p)) { + char *p = mb_prevptr(ptr, ptr + col); + if (!vim_iswordp(p)) { vim_abbr = true; // Vim added abbr. } else { vim_abbr = false; // vi compatible abbr. - if (p > (char_u *)ptr) { - is_id = vim_iswordp((char *)mb_prevptr((char_u *)ptr, p)); + if (p > ptr) { + is_id = vim_iswordp(mb_prevptr(ptr, p)); } } clen = 1; - while (p > (char_u *)ptr + mincol) { - p = mb_prevptr((char_u *)ptr, p); - if (ascii_isspace(*p) || (!vim_abbr && is_id != vim_iswordp((char *)p))) { - p += utfc_ptr2len((char *)p); + while (p > ptr + mincol) { + p = mb_prevptr(ptr, p); + if (ascii_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p))) { + p += utfc_ptr2len(p); break; } clen++; } - scol = (int)(p - (char_u *)ptr); + scol = (int)(p - ptr); } if (scol < mincol) { @@ -1623,8 +1623,8 @@ char *eval_map_expr(mapblock_T *mp, int c) int makemap(FILE *fd, buf_T *buf) { mapblock_T *mp; - char_u c1, c2, c3; - char_u *p; + char c1, c2, c3; + char *p; char *cmd; int abbr; int hash; @@ -1662,8 +1662,8 @@ int makemap(FILE *fd, buf_T *buf) if (mp->m_luaref != LUA_NOREF) { continue; } - for (p = (char_u *)mp->m_str; *p != NUL; p++) { - if (p[0] == K_SPECIAL && p[1] == KS_EXTRA + for (p = mp->m_str; *p != NUL; p++) { + if ((uint8_t)p[0] == K_SPECIAL && (uint8_t)p[1] == KS_EXTRA && p[2] == KE_SNR) { break; } @@ -2107,13 +2107,12 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) const int flags = REPTERM_FROM_PART | REPTERM_DO_LT; const int mode = get_map_mode((char **)&which, 0); - char_u *keys_simplified - = (char_u *)replace_termcodes(keys, strlen(keys), &keys_buf, flags, &did_simplify, - CPO_TO_CPO_FLAGS); + char *keys_simplified = replace_termcodes(keys, strlen(keys), &keys_buf, flags, &did_simplify, + CPO_TO_CPO_FLAGS); mapblock_T *mp = NULL; int buffer_local; LuaRef rhs_lua; - char *rhs = check_map((char *)keys_simplified, mode, exact, false, abbr, &mp, &buffer_local, + char *rhs = check_map(keys_simplified, mode, exact, false, abbr, &mp, &buffer_local, &rhs_lua); if (did_simplify) { // When the lhs is being simplified the not-simplified keys are @@ -2140,7 +2139,7 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) // Return a dictionary. if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF)) { Dictionary dict = mapblock_fill_dict(mp, - did_simplify ? (char *)keys_simplified : NULL, + did_simplify ? keys_simplified : NULL, buffer_local, true); (void)object_to_vim(DICTIONARY_OBJ(dict), rettv, NULL); api_free_dictionary(dict); @@ -2350,14 +2349,14 @@ void langmap_init(void) /// changed at any time! void langmap_set(void) { - char_u *p; - char_u *p2; + char *p; + char *p2; int from, to; ga_clear(&langmap_mapga); // clear the previous map first langmap_init(); // back to one-to-one map - for (p = (char_u *)p_langmap; p[0] != NUL;) { + for (p = p_langmap; p[0] != NUL;) { for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';'; MB_PTR_ADV(p2)) { if (p2[0] == '\\' && p2[1] != NUL) { @@ -2377,7 +2376,7 @@ void langmap_set(void) if (p[0] == '\\' && p[1] != NUL) { p++; } - from = utf_ptr2char((char *)p); + from = utf_ptr2char(p); to = NUL; if (p2 == NULL) { MB_PTR_ADV(p); @@ -2385,14 +2384,14 @@ void langmap_set(void) if (p[0] == '\\') { p++; } - to = utf_ptr2char((char *)p); + to = utf_ptr2char(p); } } else { if (p2[0] != ',') { if (p2[0] == '\\') { p2++; } - to = utf_ptr2char((char *)p2); + to = utf_ptr2char(p2); } } if (to == NUL) { @@ -2416,8 +2415,7 @@ void langmap_set(void) p = p2; if (p[0] != NUL) { if (p[0] != ',') { - semsg(_("E358: 'langmap': Extra characters after semicolon: %s"), - p); + semsg(_("E358: 'langmap': Extra characters after semicolon: %s"), p); return; } p++; @@ -2437,7 +2435,7 @@ static void do_exmap(exarg_T *eap, int isabbrev) switch (do_map((*cmdp == 'n') ? MAPTYPE_NOREMAP : (*cmdp == 'u') ? MAPTYPE_UNMAP : MAPTYPE_MAP, - (char_u *)eap->arg, mode, isabbrev)) { + eap->arg, mode, isabbrev)) { case 1: emsg(_(e_invarg)); break; diff --git a/src/nvim/mark.c b/src/nvim/mark.c index b057f8d0e4..b98935e93d 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -653,29 +653,31 @@ fmark_T *getnextmark(pos_T *startpos, int dir, int begin_line) // until the mark is used to avoid a long startup delay. static void fname2fnum(xfmark_T *fm) { - if (fm->fname != NULL) { - // First expand "~/" in the file name to the home directory. - // Don't expand the whole name, it may contain other '~' chars. + if (fm->fname == NULL) { + return; + } + + // First expand "~/" in the file name to the home directory. + // Don't expand the whole name, it may contain other '~' chars. #ifdef BACKSLASH_IN_FILENAME - if (fm->fname[0] == '~' && (fm->fname[1] == '/' || fm->fname[1] == '\\')) { + if (fm->fname[0] == '~' && (fm->fname[1] == '/' || fm->fname[1] == '\\')) { #else - if (fm->fname[0] == '~' && (fm->fname[1] == '/')) { + if (fm->fname[0] == '~' && (fm->fname[1] == '/')) { #endif - expand_env("~/", NameBuff, MAXPATHL); - int len = (int)strlen(NameBuff); - xstrlcpy(NameBuff + len, fm->fname + 2, (size_t)(MAXPATHL - len)); - } else { - xstrlcpy(NameBuff, fm->fname, MAXPATHL); - } + expand_env("~/", NameBuff, MAXPATHL); + int len = (int)strlen(NameBuff); + xstrlcpy(NameBuff + len, fm->fname + 2, (size_t)(MAXPATHL - len)); + } else { + xstrlcpy(NameBuff, fm->fname, MAXPATHL); + } - // Try to shorten the file name. - os_dirname(IObuff, IOSIZE); - char *p = path_shorten_fname(NameBuff, IObuff); + // Try to shorten the file name. + os_dirname(IObuff, IOSIZE); + char *p = path_shorten_fname(NameBuff, IObuff); - // buflist_new() will call fmarks_check_names() - (void)buflist_new(NameBuff, p, (linenr_T)1, 0); - } + // buflist_new() will call fmarks_check_names() + (void)buflist_new(NameBuff, p, (linenr_T)1, 0); } // Check all file marks for a name that matches the file name in buf. @@ -833,7 +835,7 @@ void ex_marks(exarg_T *eap) } for (i = 0; i < NGLOBALMARKS; i++) { if (namedfm[i].fmark.fnum != 0) { - name = (char *)fm_getname(&namedfm[i].fmark, 15); + name = fm_getname(&namedfm[i].fmark, 15); } else { name = namedfm[i].fname; } @@ -915,7 +917,7 @@ static void show_one_mark(int c, char *arg, pos_T *p, char *name_arg, int curren // ":delmarks[!] [marks]" void ex_delmarks(exarg_T *eap) { - char_u *p; + char *p; int from, to; int i; int lower; @@ -931,14 +933,14 @@ void ex_delmarks(exarg_T *eap) emsg(_(e_argreq)); } else { // clear specified marks only - for (p = (char_u *)eap->arg; *p != NUL; p++) { + for (p = eap->arg; *p != NUL; p++) { lower = ASCII_ISLOWER(*p); digit = ascii_isdigit(*p); if (lower || digit || ASCII_ISUPPER(*p)) { if (p[1] == '-') { // clear range of marks - from = *p; - to = p[2]; + from = (uint8_t)(*p); + to = (uint8_t)p[2]; if (!(lower ? ASCII_ISLOWER(p[2]) : (digit ? ascii_isdigit(p[2]) : ASCII_ISUPPER(p[2]))) @@ -949,7 +951,7 @@ void ex_delmarks(exarg_T *eap) p += 2; } else { // clear one lower case mark - from = to = *p; + from = to = (uint8_t)(*p); } for (i = from; i <= to; i++) { @@ -1004,7 +1006,7 @@ void ex_jumps(exarg_T *eap) msg_puts_title(_("\n jump line col file/text")); for (i = 0; i < curwin->w_jumplistlen && !got_int; i++) { if (curwin->w_jumplist[i].fmark.mark.lnum != 0) { - name = (char *)fm_getname(&curwin->w_jumplist[i].fmark, 16); + name = fm_getname(&curwin->w_jumplist[i].fmark, 16); // Make sure to output the current indicator, even when on an wiped // out buffer. ":filter" may still skip it. diff --git a/src/nvim/match.c b/src/nvim/match.c index 10b12abd24..6663dfd7ec 100644 --- a/src/nvim/match.c +++ b/src/nvim/match.c @@ -461,16 +461,16 @@ static void next_search_hl(win_T *win, match_T *search_hl, match_T *shl, linenr_ } else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL || (shl->rm.endpos[0].lnum == 0 && shl->rm.endpos[0].col <= shl->rm.startpos[0].col)) { - char_u *ml; + char *ml; matchcol = shl->rm.startpos[0].col; - ml = (char_u *)ml_get_buf(shl->buf, lnum, false) + matchcol; + ml = ml_get_buf(shl->buf, lnum, false) + matchcol; if (*ml == NUL) { matchcol++; shl->lnum = 0; break; } - matchcol += utfc_ptr2len((char *)ml); + matchcol += utfc_ptr2len(ml); } else { matchcol = shl->rm.endpos[0].col; } @@ -880,12 +880,14 @@ static int matchadd_dict_arg(typval_T *tv, const char **conceal_char, win_T **wi *conceal_char = tv_get_string(&di->di_tv); } - if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("window"))) != NULL) { - *win = find_win_by_nr_or_id(&di->di_tv); - if (*win == NULL) { - emsg(_(e_invalwindow)); - return FAIL; - } + if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("window"))) == NULL) { + return OK; + } + + *win = find_win_by_nr_or_id(&di->di_tv); + if (*win == NULL) { + emsg(_(e_invalwindow)); + return FAIL; } return OK; diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index e1a870071c..93ac0fccfa 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -424,10 +424,10 @@ void remove_bom(char_u *s) // 1 for punctuation // 2 for an (ASCII) word character // >2 for other word characters -int mb_get_class(const char_u *p) +int mb_get_class(const char *p) FUNC_ATTR_PURE { - return mb_get_class_tab((char *)p, curbuf->b_chartab); + return mb_get_class_tab(p, curbuf->b_chartab); } int mb_get_class_tab(const char *p, const uint64_t *const chartab) @@ -1456,16 +1456,16 @@ int utf16_to_utf8(const wchar_t *utf16, int utf16len, char **utf8) /// @param len maximum length (an earlier NUL terminates) /// @param[out] codepoints incremented with UTF-32 code point size /// @param[out] codeunits incremented with UTF-16 code unit size -void mb_utflen(const char_u *s, size_t len, size_t *codepoints, size_t *codeunits) +void mb_utflen(const char *s, size_t len, size_t *codepoints, size_t *codeunits) FUNC_ATTR_NONNULL_ALL { size_t count = 0, extra = 0; size_t clen; for (size_t i = 0; i < len; i += clen) { - clen = (size_t)utf_ptr2len_len(s + i, (int)(len - i)); + clen = (size_t)utf_ptr2len_len((char_u *)s + i, (int)(len - i)); // NB: gets the byte value of invalid sequence bytes. // we only care whether the char fits in the BMP or not - int c = (clen > 1) ? utf_ptr2char((char *)s + i) : s[i]; + int c = (clen > 1) ? utf_ptr2char(s + i) : (uint8_t)s[i]; count++; if (c > 0xFFFF) { extra++; @@ -2012,7 +2012,7 @@ void mb_check_adjust_col(void *win_) /// @param line start of the string /// /// @return a pointer to the character before "*p", if there is one. -char_u *mb_prevptr(char_u *line, char_u *p) +char *mb_prevptr(char *line, char *p) { if (p > line) { MB_PTR_BACK(line, p); @@ -2022,9 +2022,9 @@ char_u *mb_prevptr(char_u *line, char_u *p) /// Return the character length of "str". Each multi-byte character (with /// following composing characters) counts as one. -int mb_charlen(const char_u *str) +int mb_charlen(const char *str) { - const char_u *p = str; + const char_u *p = (char_u *)str; int count; if (p == NULL) { @@ -2801,5 +2801,5 @@ void f_charclass(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) || argvars[0].vval.v_string == NULL) { return; } - rettv->vval.v_number = mb_get_class((const char_u *)argvars[0].vval.v_string); + rettv->vval.v_number = mb_get_class(argvars[0].vval.v_string); } diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c index f88e51bd83..61d7893948 100644 --- a/src/nvim/memfile.c +++ b/src/nvim/memfile.c @@ -759,7 +759,7 @@ void mf_free_fnames(memfile_T *mfp) void mf_set_fnames(memfile_T *mfp, char *fname) { mfp->mf_fname = fname; - mfp->mf_ffname = (char_u *)FullName_save(mfp->mf_fname, false); + mfp->mf_ffname = FullName_save(mfp->mf_fname, false); } /// Make name of memfile's swapfile a full path. @@ -767,11 +767,13 @@ void mf_set_fnames(memfile_T *mfp, char *fname) /// Used before doing a :cd void mf_fullname(memfile_T *mfp) { - if (mfp != NULL && mfp->mf_fname != NULL && mfp->mf_ffname != NULL) { - xfree(mfp->mf_fname); - mfp->mf_fname = (char *)mfp->mf_ffname; - mfp->mf_ffname = NULL; + if (mfp == NULL || mfp->mf_fname == NULL || mfp->mf_ffname == NULL) { + return; } + + xfree(mfp->mf_fname); + mfp->mf_fname = mfp->mf_ffname; + mfp->mf_ffname = NULL; } /// Return true if there are any translations pending for memfile. diff --git a/src/nvim/memfile_defs.h b/src/nvim/memfile_defs.h index d1e8fd0fb4..53152c28f8 100644 --- a/src/nvim/memfile_defs.h +++ b/src/nvim/memfile_defs.h @@ -89,7 +89,7 @@ typedef struct mf_blocknr_trans_item { /// A memory file. typedef struct memfile { char *mf_fname; /// name of the file - char_u *mf_ffname; /// idem, full path + char *mf_ffname; /// idem, full path int mf_fd; /// file descriptor bhdr_T *mf_free_first; /// first block header in free list bhdr_T *mf_used_first; /// mru block header in used list diff --git a/src/nvim/memline.c b/src/nvim/memline.c index 33223f6d1e..eee3b9d517 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -675,7 +675,7 @@ static void set_b0_fname(ZERO_BL *b0p, buf_T *buf) /// not set. static void set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf) { - if (same_directory((char_u *)buf->b_ml.ml_mfp->mf_fname, (char_u *)buf->b_ffname)) { + if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname)) { b0p->b0_flags |= B0_SAME_DIR; } else { b0p->b0_flags = (char)(b0p->b0_flags & ~B0_SAME_DIR); @@ -1349,7 +1349,7 @@ int recover_names(char_u *fname, int list, int nr, char **fname_out) msg_puts(". "); msg_puts((const char *)path_tail(files[i])); msg_putchar('\n'); - (void)swapfile_info((char_u *)files[i]); + (void)swapfile_info(files[i]); } } else { msg_puts(_(" -- none --\n")); @@ -1377,17 +1377,19 @@ char *make_percent_swname(const char *dir, const char *name) { char *d = NULL; char *f = fix_fname(name != NULL ? name : ""); - if (f != NULL) { - char *s = xstrdup(f); - for (d = s; *d != NUL; MB_PTR_ADV(d)) { - if (vim_ispathsep(*d)) { - *d = '%'; - } + if (f == NULL) { + return NULL; + } + + char *s = xstrdup(f); + for (d = s; *d != NUL; MB_PTR_ADV(d)) { + if (vim_ispathsep(*d)) { + *d = '%'; } - d = concat_fnames(dir, s, true); - xfree(s); - xfree(f); } + d = concat_fnames(dir, s, true); + xfree(s); + xfree(f); return d; } @@ -1434,7 +1436,7 @@ void get_b0_dict(const char *fname, dict_T *d) /// Give information about an existing swap file. /// /// @return timestamp (0 when unknown). -static time_t swapfile_info(char_u *fname) +static time_t swapfile_info(char *fname) { assert(fname != NULL); int fd; @@ -1446,7 +1448,7 @@ static time_t swapfile_info(char_u *fname) // print the swap file date FileInfo file_info; - if (os_fileinfo((char *)fname, &file_info)) { + if (os_fileinfo(fname, &file_info)) { #ifdef UNIX // print name of owner of the file if (os_get_uname((uv_uid_t)file_info.stat.st_uid, uname, B0_UNAME_SIZE) == OK) { @@ -1465,7 +1467,7 @@ static time_t swapfile_info(char_u *fname) } // print the original file name - fd = os_open((char *)fname, O_RDONLY, 0); + fd = os_open(fname, O_RDONLY, 0); if (fd >= 0) { if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) { if (strncmp(b0.b0_version, "VIM 3.0", 7) == 0) { @@ -2317,7 +2319,7 @@ void ml_add_deleted_len_buf(buf_T *buf, char *ptr, ssize_t len) curbuf->deleted_bytes += (size_t)len + 1; curbuf->deleted_bytes2 += (size_t)len + 1; if (curbuf->update_need_codepoints) { - mb_utflen((char_u *)ptr, (size_t)len, &curbuf->deleted_codepoints, + mb_utflen(ptr, (size_t)len, &curbuf->deleted_codepoints, &curbuf->deleted_codeunits); curbuf->deleted_codepoints++; // NL char curbuf->deleted_codeunits++; @@ -2641,7 +2643,7 @@ static void ml_flush_line(buf_T *buf) DATA_BL *dp = hp->bh_data; int idx = lnum - buf->b_ml.ml_locked_low; int start = ((dp->db_index[idx]) & DB_INDEX_MASK); - char_u *old_line = (char_u *)dp + start; + char *old_line = (char *)dp + start; int old_len; if (idx == 0) { // line is last in block old_len = (int)dp->db_txt_end - start; @@ -3047,13 +3049,13 @@ char *makeswapname(char *fname, char *ffname, buf_T *buf, char *dir_name) } // Prepend a '.' to the swap file name for the current directory. - char_u *r = (char_u *)modname(fname_res, ".swp", - dir_name[0] == '.' && dir_name[1] == NUL); + char *r = modname(fname_res, ".swp", + dir_name[0] == '.' && dir_name[1] == NUL); if (r == NULL) { // out of memory return NULL; } - s = get_file_in_dir((char *)r, dir_name); + s = get_file_in_dir(r, dir_name); xfree(r); return s; } @@ -3100,14 +3102,14 @@ char *get_file_in_dir(char *fname, char *dname) /// /// @param buf buffer being edited /// @param fname swap file name -static void attention_message(buf_T *buf, char_u *fname) +static void attention_message(buf_T *buf, char *fname) { assert(buf->b_fname != NULL); no_wait_return++; (void)emsg(_("E325: ATTENTION")); msg_puts(_("\nFound a swap file by the name \"")); - msg_home_replace((char *)fname); + msg_home_replace(fname); msg_puts("\"\n"); const time_t swap_mtime = swapfile_info(fname); msg_puts(_("While opening file \"")); @@ -3136,7 +3138,7 @@ static void attention_message(buf_T *buf, char_u *fname) msg_outtrans(buf->b_fname); msg_puts(_("\"\n to recover the changes (see \":help recovery\").\n")); msg_puts(_(" If you did this already, delete the swap file \"")); - msg_outtrans((char *)fname); + msg_outtrans(fname); msg_puts(_("\"\n to avoid this message.\n")); cmdline_row = msg_row; no_wait_return--; @@ -3152,9 +3154,9 @@ static void attention_message(buf_T *buf, char_u *fname) /// 4: delete it /// 5: quit /// 6: abort -static int do_swapexists(buf_T *buf, char_u *fname) +static int do_swapexists(buf_T *buf, char *fname) { - set_vim_var_string(VV_SWAPNAME, (char *)fname, -1); + set_vim_var_string(VV_SWAPNAME, fname, -1); set_vim_var_string(VV_SWAPCHOICE, NULL, -1); // Trigger SwapExists autocommands with <afile> set to the file being @@ -3266,7 +3268,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ if (b0.b0_flags & B0_SAME_DIR) { if (path_fnamecmp(path_tail(buf->b_ffname), path_tail((char *)b0.b0_fname)) != 0 - || !same_directory((char_u *)fname, (char_u *)buf->b_ffname)) { + || !same_directory(fname, buf->b_ffname)) { // Symlinks may point to the same file even // when the name differs, need to check the // inode too. @@ -3311,12 +3313,12 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ if (choice == 0 && swap_exists_action != SEA_NONE && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf)) { - choice = do_swapexists(buf, (char_u *)fname); + choice = do_swapexists(buf, fname); } if (choice == 0) { // Show info about the existing swap file. - attention_message(buf, (char_u *)fname); + attention_message(buf, fname); // We don't want a 'q' typed at the more-prompt // interrupt loading a file. diff --git a/src/nvim/menu.c b/src/nvim/menu.c index ac73510266..0fa45ac24a 100644 --- a/src/nvim/menu.c +++ b/src/nvim/menu.c @@ -1338,7 +1338,7 @@ static char *menu_text(const char *str, int *mnemonic, char **actext) break; } if (mnemonic != NULL && p[1] != '&') { - *mnemonic = (char_u)p[1]; + *mnemonic = (uint8_t)p[1]; } STRMOVE(p, p + 1); p = p + 1; @@ -1449,9 +1449,11 @@ void show_popupmenu(void) } // Only show a popup when it is defined and has entries - if (menu != NULL && menu->children != NULL) { - pum_show_popupmenu(menu); + if (menu == NULL || menu->children == NULL) { + return; } + + pum_show_popupmenu(menu); } /// Execute "menu". Use by ":emenu" and the window toolbar. @@ -1531,7 +1533,7 @@ void execute_menu(const exarg_T *eap, vimmenu_T *menu, int mode_idx) ex_normal_busy++; if (save_current_state(&save_state)) { - exec_normal_cmd((char_u *)menu->strings[idx], menu->noremap[idx], + exec_normal_cmd(menu->strings[idx], menu->noremap[idx], menu->silent[idx]); } restore_current_state(&save_state); diff --git a/src/nvim/message.c b/src/nvim/message.c index e9d66ea184..de4acd601f 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -919,9 +919,11 @@ char *msg_trunc_attr(char *s, bool force, int attr) /// @note: May change the message by replacing a character with '<'. char *msg_may_trunc(bool force, char *s) { - int room; + if (ui_has(kUIMessages)) { + return s; + } - room = (Rows - cmdline_row - 1) * Columns + sc_col - 1; + int room = (Rows - cmdline_row - 1) * Columns + sc_col - 1; if ((force || (shortmess(SHM_TRUNC) && !exmode_active)) && (int)strlen(s) - room > 0) { int size = vim_strsize(s); diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index ee8c553cd5..b7d15fe9af 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -58,13 +58,13 @@ static int orig_topfill = 0; /// 1: punctuation groups /// 2: normal word character /// >2: multi-byte word character. -static int get_mouse_class(char_u *p) +static int get_mouse_class(char *p) { - if (MB_BYTE2LEN(p[0]) > 1) { + if (MB_BYTE2LEN((uint8_t)p[0]) > 1) { return mb_get_class(p); } - const int c = *p; + const int c = (uint8_t)(*p); if (c == ' ' || c == '\t') { return 0; } @@ -90,12 +90,12 @@ static void find_start_of_word(pos_T *pos) int col; line = (char_u *)ml_get(pos->lnum); - cclass = get_mouse_class(line + pos->col); + cclass = get_mouse_class((char *)line + pos->col); while (pos->col > 0) { col = pos->col - 1; col -= utf_head_off((char *)line, (char *)line + col); - if (get_mouse_class(line + col) != cclass) { + if (get_mouse_class((char *)line + col) != cclass) { break; } pos->col = col; @@ -115,10 +115,10 @@ static void find_end_of_word(pos_T *pos) pos->col--; pos->col -= utf_head_off((char *)line, (char *)line + pos->col); } - cclass = get_mouse_class(line + pos->col); + cclass = get_mouse_class((char *)line + pos->col); while (line[pos->col] != NUL) { col = pos->col + utfc_ptr2len((char *)line + pos->col); - if (get_mouse_class(line + col) != cclass) { + if (get_mouse_class((char *)line + col) != cclass) { if (*p_sel == 'e') { pos->col = col; } @@ -1110,7 +1110,7 @@ retnomove: ? wp->w_winbar_height != 0 : false; - on_statuscol = (grid == (col < win_col_off(wp))) + on_statuscol = !on_status_line && !on_winbar && col < win_col_off(wp) ? *wp->w_p_stc != NUL : false; diff --git a/src/nvim/move.c b/src/nvim/move.c index 0d2a38b041..dc2f4b4844 100644 --- a/src/nvim/move.c +++ b/src/nvim/move.c @@ -379,12 +379,19 @@ static bool check_top_offset(void) return false; } +/// Update w_curswant. +void update_curswant_force(void) +{ + validate_virtcol(); + curwin->w_curswant = curwin->w_virtcol; + curwin->w_set_curswant = false; +} + +/// Update w_curswant if w_set_curswant is set. void update_curswant(void) { if (curwin->w_set_curswant) { - validate_virtcol(); - curwin->w_curswant = curwin->w_virtcol; - curwin->w_set_curswant = false; + update_curswant_force(); } } @@ -599,50 +606,59 @@ void validate_virtcol(void) void validate_virtcol_win(win_T *wp) { check_cursor_moved(wp); - if (!(wp->w_valid & VALID_VIRTCOL)) { - getvvcol(wp, &wp->w_cursor, NULL, &(wp->w_virtcol), NULL); - redraw_for_cursorcolumn(wp); - wp->w_valid |= VALID_VIRTCOL; + + if (wp->w_valid & VALID_VIRTCOL) { + return; } + + getvvcol(wp, &wp->w_cursor, NULL, &(wp->w_virtcol), NULL); + redraw_for_cursorcolumn(wp); + wp->w_valid |= VALID_VIRTCOL; } // Validate curwin->w_cline_height only. void validate_cheight(void) { check_cursor_moved(curwin); - if (!(curwin->w_valid & VALID_CHEIGHT)) { - curwin->w_cline_height = plines_win_full(curwin, curwin->w_cursor.lnum, - NULL, &curwin->w_cline_folded, - true); - curwin->w_valid |= VALID_CHEIGHT; + + if (curwin->w_valid & VALID_CHEIGHT) { + return; } + + curwin->w_cline_height = plines_win_full(curwin, curwin->w_cursor.lnum, + NULL, &curwin->w_cline_folded, + true); + curwin->w_valid |= VALID_CHEIGHT; } // Validate w_wcol and w_virtcol only. void validate_cursor_col(void) { validate_virtcol(); - if (!(curwin->w_valid & VALID_WCOL)) { - colnr_T col = curwin->w_virtcol; - colnr_T off = curwin_col_off(); - col += off; - int width = curwin->w_width_inner - off + curwin_col_off2(); - - // long line wrapping, adjust curwin->w_wrow - if (curwin->w_p_wrap && col >= (colnr_T)curwin->w_width_inner - && width > 0) { - // use same formula as what is used in curs_columns() - col -= ((col - curwin->w_width_inner) / width + 1) * width; - } - if (col > (int)curwin->w_leftcol) { - col -= curwin->w_leftcol; - } else { - col = 0; - } - curwin->w_wcol = col; - curwin->w_valid |= VALID_WCOL; + if (curwin->w_valid & VALID_WCOL) { + return; + } + + colnr_T col = curwin->w_virtcol; + colnr_T off = curwin_col_off(); + col += off; + int width = curwin->w_width_inner - off + curwin_col_off2(); + + // long line wrapping, adjust curwin->w_wrow + if (curwin->w_p_wrap && col >= (colnr_T)curwin->w_width_inner + && width > 0) { + // use same formula as what is used in curs_columns() + col -= ((col - curwin->w_width_inner) / width + 1) * width; } + if (col > (int)curwin->w_leftcol) { + col -= curwin->w_leftcol; + } else { + col = 0; + } + curwin->w_wcol = col; + + curwin->w_valid |= VALID_WCOL; } // Compute offset of a window, occupied by absolute or relative line number, diff --git a/src/nvim/msgpack_rpc/helpers.c b/src/nvim/msgpack_rpc/helpers.c index 609fef37d0..5f0f03dd69 100644 --- a/src/nvim/msgpack_rpc/helpers.c +++ b/src/nvim/msgpack_rpc/helpers.c @@ -39,6 +39,8 @@ typedef struct { size_t idx; } MPToAPIObjectStackItem; +// uncrustify:off + /// Convert type used by msgpack parser to Nvim API type. /// /// @param[in] obj Msgpack value to convert. @@ -118,7 +120,7 @@ bool msgpack_rpc_to_object(const msgpack_object *const obj, Object *const arg) .mobj = &cur.mobj->via.array.ptr[idx], .aobj = &cur.aobj->data.array.items[idx], .container = false, - })); + })); } } else { *cur.aobj = ARRAY_OBJ(((Array) { @@ -127,7 +129,7 @@ bool msgpack_rpc_to_object(const msgpack_object *const obj, Object *const arg) .items = (size > 0 ? xcalloc(size, sizeof(*cur.aobj->data.array.items)) : NULL), - })); + })); cur.container = true; kv_last(stack) = cur; } @@ -171,7 +173,7 @@ bool msgpack_rpc_to_object(const msgpack_object *const obj, Object *const arg) .mobj = &cur.mobj->via.map.ptr[idx].val, .aobj = &cur.aobj->data.dictionary.items[idx].value, .container = false, - })); + })); } } } else { @@ -181,7 +183,7 @@ bool msgpack_rpc_to_object(const msgpack_object *const obj, Object *const arg) .items = (size > 0 ? xcalloc(size, sizeof(*cur.aobj->data.dictionary.items)) : NULL), - })); + })); cur.container = true; kv_last(stack) = cur; } @@ -371,7 +373,7 @@ void msgpack_rpc_from_object(const Object result, msgpack_packer *const res) kvi_push(stack, ((APIToMPObjectStackItem) { .aobj = &cur.aobj->data.array.items[idx], .container = false, - })); + })); } } else { msgpack_pack_array(res, size); @@ -389,12 +391,11 @@ void msgpack_rpc_from_object(const Object result, msgpack_packer *const res) const size_t idx = cur.idx; cur.idx++; kv_last(stack) = cur; - msgpack_rpc_from_string(cur.aobj->data.dictionary.items[idx].key, - res); + msgpack_rpc_from_string(cur.aobj->data.dictionary.items[idx].key, res); kvi_push(stack, ((APIToMPObjectStackItem) { .aobj = &cur.aobj->data.dictionary.items[idx].value, .container = false, - })); + })); } } else { msgpack_pack_map(res, size); @@ -411,6 +412,8 @@ void msgpack_rpc_from_object(const Object result, msgpack_packer *const res) kvi_destroy(stack); } +// uncrustify:on + void msgpack_rpc_from_array(Array result, msgpack_packer *res) FUNC_ATTR_NONNULL_ARG(2) { diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 6da71a9354..8f4240c062 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -1577,7 +1577,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text // if i == 0: try to find an identifier // if i == 1: try to find any non-white text - char_u *ptr = (char_u *)ml_get_buf(wp->w_buffer, lnum, false); + char *ptr = ml_get_buf(wp->w_buffer, lnum, false); for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; i++) { // 1. skip to start of identifier/text col = startcol; @@ -1590,7 +1590,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text if (this_class != 0 && (i == 1 || this_class != 1)) { break; } - col += utfc_ptr2len((char *)ptr + col); + col += utfc_ptr2len(ptr + col); } // When starting on a ']' count it, so that we include the '['. @@ -1601,12 +1601,12 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text // // Remember class of character under cursor. if ((find_type & FIND_EVAL) && ptr[col] == ']') { - this_class = mb_get_class((char_u *)"a"); + this_class = mb_get_class("a"); } else { this_class = mb_get_class(ptr + col); } while (col > 0 && this_class != 0) { - prevcol = col - 1 - utf_head_off((char *)ptr, (char *)ptr + col - 1); + prevcol = col - 1 - utf_head_off(ptr, ptr + col - 1); prev_class = mb_get_class(ptr + prevcol); if (this_class != prev_class && (i == 0 @@ -1614,7 +1614,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text || (find_type & FIND_IDENT)) && (!(find_type & FIND_EVAL) || prevcol == 0 - || !find_is_eval_item(ptr + prevcol, &prevcol, &bn, BACKWARD))) { + || !find_is_eval_item((char_u *)ptr + prevcol, &prevcol, &bn, BACKWARD))) { break; } col = prevcol; @@ -1640,7 +1640,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text return 0; } ptr += col; - *text = (char *)ptr; + *text = ptr; if (textcol != NULL) { *textcol = col; } @@ -1657,8 +1657,8 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text : mb_get_class(ptr + col) != 0) || ((find_type & FIND_EVAL) && col <= (int)startcol - && find_is_eval_item(ptr + col, &col, &bn, FORWARD)))) { - col += utfc_ptr2len((char *)ptr + col); + && find_is_eval_item((char_u *)ptr + col, &col, &bn, FORWARD)))) { + col += utfc_ptr2len(ptr + col); } assert(col >= 0); @@ -1783,7 +1783,7 @@ void may_clear_cmdline(void) } // Routines for displaying a partly typed command -static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; // For push_showcmd() +static char old_showcmd_buf[SHOWCMD_BUFLEN]; // For push_showcmd() static bool showcmd_is_clear = true; static bool showcmd_visual = false; @@ -1827,20 +1827,20 @@ void clear_showcmd(void) } else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum) { snprintf(showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64, (int64_t)lines); } else { - char_u *s, *e; + char *s, *e; int l; int bytes = 0; int chars = 0; if (cursor_bot) { - s = (char_u *)ml_get_pos(&VIsual); - e = (char_u *)get_cursor_pos_ptr(); + s = ml_get_pos(&VIsual); + e = get_cursor_pos_ptr(); } else { - s = (char_u *)get_cursor_pos_ptr(); - e = (char_u *)ml_get_pos(&VIsual); + s = get_cursor_pos_ptr(); + e = ml_get_pos(&VIsual); } while ((*p_sel != 'e') ? s <= e : s < e) { - l = utfc_ptr2len((char *)s); + l = utfc_ptr2len(s); if (l == 0) { bytes++; chars++; @@ -2269,7 +2269,7 @@ static bool is_ident(const char_u *line, int offset) /// @return fail when not found. bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_arg) { - char_u *pat; + char *pat; pos_T old_pos; pos_T par_pos; pos_T found_pos; @@ -2285,7 +2285,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ // Put "\V" before the pattern to avoid that the special meaning of "." // and "~" causes trouble. assert(len <= INT_MAX); - sprintf((char *)pat, vim_iswordp((char *)ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s", // NOLINT(runtime/printf) + sprintf(pat, vim_iswordp((char *)ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s", // NOLINT(runtime/printf) (int)len, ptr); old_pos = curwin->w_cursor; save_p_ws = p_ws; @@ -2313,7 +2313,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ clearpos(&found_pos); for (;;) { t = searchit(curwin, curbuf, &curwin->w_cursor, NULL, FORWARD, - pat, 1L, searchflags, RE_LAST, NULL); + (char_u *)pat, 1L, searchflags, RE_LAST, NULL); if (curwin->w_cursor.lnum >= old_pos.lnum) { t = false; // match after start is failure too } @@ -2401,7 +2401,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ /// @return true if able to move cursor, false otherwise. static bool nv_screengo(oparg_T *oap, int dir, long dist) { - int linelen = linetabsize((char_u *)get_cursor_line_ptr()); + int linelen = linetabsize(get_cursor_line_ptr()); bool retval = true; bool atend = false; int n; @@ -2472,7 +2472,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) } curwin->w_cursor.lnum--; - linelen = linetabsize((char_u *)get_cursor_line_ptr()); + linelen = linetabsize(get_cursor_line_ptr()); if (linelen > width1) { int w = (((linelen - width1 - 1) / width2) + 1) * width2; assert(curwin->w_curswant <= INT_MAX - w); @@ -2508,7 +2508,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) if (curwin->w_curswant >= width1) { curwin->w_curswant -= width2; } - linelen = linetabsize((char_u *)get_cursor_line_ptr()); + linelen = linetabsize(get_cursor_line_ptr()); } } } @@ -3549,7 +3549,7 @@ static void nv_ident(cmdarg_T *cap) // Execute the command. if (cmdchar == '*' || cmdchar == '#') { if (!g_cmd - && vim_iswordp((char *)mb_prevptr((char_u *)get_cursor_line_ptr(), (char_u *)ptr))) { + && vim_iswordp(mb_prevptr(get_cursor_line_ptr(), ptr))) { STRCAT(buf, "\\>"); } @@ -3645,7 +3645,9 @@ static void nv_scroll(cmdarg_T *cap) && curwin->w_cursor.lnum > curwin->w_topline; n--) { (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); - curwin->w_cursor.lnum--; + if (curwin->w_cursor.lnum > curwin->w_topline) { + curwin->w_cursor.lnum--; + } } } else { curwin->w_cursor.lnum -= (linenr_T)cap->count1 - 1; @@ -3815,10 +3817,10 @@ static void nv_left(cmdarg_T *cap) // Don't adjust op_end now, otherwise it won't work. if ((cap->oap->op_type == OP_DELETE || cap->oap->op_type == OP_CHANGE) && !LINEEMPTY(curwin->w_cursor.lnum)) { - char_u *cp = (char_u *)get_cursor_pos_ptr(); + char *cp = get_cursor_pos_ptr(); if (*cp != NUL) { - curwin->w_cursor.col += utfc_ptr2len((char *)cp); + curwin->w_cursor.col += utfc_ptr2len(cp); } cap->retval |= CA_NO_ADJ_OP_END; } @@ -3890,7 +3892,7 @@ static void nv_down(cmdarg_T *cap) /// Grab the file name under the cursor and edit it. static void nv_gotofile(cmdarg_T *cap) { - char_u *ptr; + char *ptr; linenr_T lnum = -1; if (check_text_locked(cap->oap)) { @@ -3901,7 +3903,7 @@ static void nv_gotofile(cmdarg_T *cap) return; } - ptr = grab_file_name(cap->count1, &lnum); + ptr = (char *)grab_file_name(cap->count1, &lnum); if (ptr != NULL) { // do autowrite if necessary @@ -3909,7 +3911,7 @@ static void nv_gotofile(cmdarg_T *cap) (void)autowrite(curbuf, false); } setpcmark(); - if (do_ecmd(0, (char *)ptr, NULL, NULL, ECMD_LAST, + if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST, buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK && cap->nchar == 'F' && lnum >= 0) { curwin->w_cursor.lnum = lnum; @@ -4528,7 +4530,7 @@ static void nv_replace(cmdarg_T *cap) // Abort if not enough characters to replace. ptr = get_cursor_pos_ptr(); if (strlen(ptr) < (unsigned)cap->count1 - || (mb_charlen((char_u *)ptr) < cap->count1)) { + || (mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } @@ -5011,10 +5013,12 @@ static void nv_visual(cmdarg_T *cap) VIsual_mode = resel_VIsual_mode; if (VIsual_mode == 'v') { if (resel_VIsual_line_count <= 1) { - validate_virtcol(); + update_curswant_force(); assert(cap->count0 >= INT_MIN && cap->count0 <= INT_MAX); - curwin->w_curswant = (curwin->w_virtcol - + resel_VIsual_vcol * (int)cap->count0 - 1); + curwin->w_curswant += resel_VIsual_vcol * (int)cap->count0; + if (*p_sel != 'e') { + curwin->w_curswant--; + } } else { curwin->w_curswant = resel_VIsual_vcol; } @@ -5024,10 +5028,9 @@ static void nv_visual(cmdarg_T *cap) curwin->w_curswant = MAXCOL; coladvance(MAXCOL); } else if (VIsual_mode == Ctrl_V) { - validate_virtcol(); + update_curswant_force(); assert(cap->count0 >= INT_MIN && cap->count0 <= INT_MAX); - curwin->w_curswant = (curwin->w_virtcol - + resel_VIsual_vcol * (int)cap->count0 - 1); + curwin->w_curswant += resel_VIsual_vcol * (int)cap->count0 - 1; coladvance(curwin->w_curswant); } else { curwin->w_set_curswant = true; @@ -5238,7 +5241,7 @@ static void nv_g_underscore_cmd(cmdarg_T *cap) return; } - char_u *ptr = (char_u *)get_cursor_line_ptr(); + char *ptr = get_cursor_line_ptr(); // In Visual mode we may end up after the line. if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) { @@ -5276,9 +5279,7 @@ static void nv_g_dollar_cmd(cmdarg_T *cap) coladvance((colnr_T)i); // Make sure we stick in this column. - validate_virtcol(); - curwin->w_curswant = curwin->w_virtcol; - curwin->w_set_curswant = false; + update_curswant_force(); if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { // Check for landing on a character that got split at // the end of the line. We do not want to advance to @@ -5309,9 +5310,7 @@ static void nv_g_dollar_cmd(cmdarg_T *cap) } // Make sure we stick in this column. - validate_virtcol(); - curwin->w_curswant = curwin->w_virtcol; - curwin->w_set_curswant = false; + update_curswant_force(); } } @@ -5449,7 +5448,7 @@ static void nv_g_cmd(cmdarg_T *cap) case 'M': oap->motion_type = kMTCharWise; oap->inclusive = false; - i = linetabsize((char_u *)get_cursor_line_ptr()); + i = linetabsize(get_cursor_line_ptr()); if (cap->count0 > 0 && cap->count0 <= 100) { coladvance((colnr_T)(i * cap->count0 / 100)); } else { @@ -6230,7 +6229,7 @@ static void nv_object(cmdarg_T *cap) { bool flag; bool include; - char_u *mps_save; + char *mps_save; if (cap->cmdchar == 'i') { include = false; // "ix" = inner object: exclude white space @@ -6238,7 +6237,7 @@ static void nv_object(cmdarg_T *cap) include = true; // "ax" = an object: include white space } // Make sure (), [], {} and <> are in 'matchpairs' - mps_save = (char_u *)curbuf->b_p_mps; + mps_save = curbuf->b_p_mps; curbuf->b_p_mps = "(:),{:},[:],<:>"; switch (cap->nchar) { @@ -6293,7 +6292,7 @@ static void nv_object(cmdarg_T *cap) break; } - curbuf->b_p_mps = (char *)mps_save; + curbuf->b_p_mps = mps_save; if (!flag) { clearopbeep(cap->oap); } diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 03ce345b78..34432c58db 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -1109,12 +1109,12 @@ int do_execreg(int regname, int colon, int addcr, int silent) // don't keep the cmdline containing @: XFREE_CLEAR(new_last_cmdline); // Escape all control characters with a CTRL-V - p = (char *)vim_strsave_escaped_ext((char_u *)last_cmdline, - (char_u *)"\001\002\003\004\005\006\007" - "\010\011\012\013\014\015\016\017" - "\020\021\022\023\024\025\026\027" - "\030\031\032\033\034\035\036\037", - Ctrl_V, false); + p = vim_strsave_escaped_ext(last_cmdline, + "\001\002\003\004\005\006\007" + "\010\011\012\013\014\015\016\017" + "\020\021\022\023\024\025\026\027" + "\030\031\032\033\034\035\036\037", + Ctrl_V, false); // When in Visual mode "'<,'>" will be prepended to the command. // Remove it when it's already there. if (VIsual_active && strncmp(p, "'<,'>", 5) == 0) { @@ -5492,7 +5492,7 @@ void cursor_pos_info(dict_T *dict) validate_virtcol(); col_print((char *)buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); - col_print((char *)buf2, sizeof(buf2), (int)strlen(p), linetabsize((char_u *)p)); + col_print((char *)buf2, sizeof(buf2), (int)strlen(p), linetabsize(p)); if (char_count_cursor == byte_count_cursor && char_count == byte_count) { diff --git a/src/nvim/option.c b/src/nvim/option.c index fe905a5a05..02c770e608 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -608,7 +608,7 @@ void set_init_3(void) : !(options[idx_sp].flags & P_WAS_SET); size_t len = 0; - char *p = (char *)invocation_path_tail((char_u *)p_sh, &len); + char *p = (char *)invocation_path_tail(p_sh, &len); p = xstrnsave(p, len); { @@ -741,7 +741,7 @@ static int do_set_string(int opt_idx, int opt_flags, char **argp, int nextchar, char *varp = varp_arg; char *save_arg = NULL; char *s = NULL; - char_u *oldval = NULL; // previous value if *varp + char *oldval = NULL; // previous value if *varp char *origval = NULL; char_u *origval_l = NULL; char_u *origval_g = NULL; @@ -760,7 +760,7 @@ static int do_set_string(int opt_idx, int opt_flags, char **argp, int nextchar, } // The old value is kept until we are sure that the new value is valid. - oldval = *(char_u **)varp; + oldval = *(char **)varp; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0) { origval_l = *(char_u **)get_varp_scope(&(options[opt_idx]), OPT_LOCAL); @@ -778,7 +778,7 @@ static int do_set_string(int opt_idx, int opt_flags, char **argp, int nextchar, if (((int)options[opt_idx].indir & PV_BOTH) && (opt_flags & OPT_LOCAL)) { origval = *(char **)get_varp(&options[opt_idx]); } else { - origval = (char *)oldval; + origval = oldval; } char *newval; @@ -827,16 +827,16 @@ static int do_set_string(int opt_idx, int opt_flags, char **argp, int nextchar, break; } xfree(oldval); - if ((char_u *)origval == oldval) { + if (origval == oldval) { origval = *(char **)varp; } - if (origval_l == oldval) { + if (origval_l == (char_u *)oldval) { origval_l = *(char_u **)varp; } - if (origval_g == oldval) { + if (origval_g == (char_u *)oldval) { origval_g = *(char_u **)varp; } - oldval = *(char_u **)varp; + oldval = *(char **)varp; } else if (varp == (char *)&p_ww && ascii_isdigit(*arg)) { // Convert 'whichwrap' number to string, for backwards compatibility // with Vim 3.0. @@ -1045,7 +1045,7 @@ static int do_set_string(int opt_idx, int opt_flags, char **argp, int nextchar, // Handle side effects, and set the global value for ":set" on local // options. Note: when setting 'syntax' or 'filetype' autocommands may // be triggered that can cause havoc. - *errmsg = did_set_string_option(opt_idx, (char **)varp, (char *)oldval, + *errmsg = did_set_string_option(opt_idx, (char **)varp, oldval, errbuf, errbuflen, opt_flags, value_checked); @@ -4783,7 +4783,7 @@ void ExpandOldSetting(int *num_file, char ***file) // A backslash is required before some characters. This is the reverse of // what happens in do_set(). - char_u *buf = vim_strsave_escaped((char_u *)var, escape_chars); + char_u *buf = (char_u *)vim_strsave_escaped(var, (char *)escape_chars); #ifdef BACKSLASH_IN_FILENAME // For MS-Windows et al. we don't double backslashes at the start and diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index 56fdb6de84..3ffab71f22 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -263,8 +263,7 @@ enum { /// Represented by 'a' flag. #define SHM_ALL_ABBREVIATIONS ((char[]) { \ SHM_RO, SHM_MOD, SHM_FILE, SHM_LAST, SHM_TEXT, SHM_LINES, SHM_NEW, SHM_WRI, \ - 0, \ - }) + 0 }) // characters for p_go: #define GO_ASEL 'a' // autoselect @@ -359,8 +358,7 @@ enum { STL_SHOWCMD, STL_FOLDCOL, STL_SIGNCOL, STL_VIM_EXPR, STL_SEPARATE, \ STL_TRUNCMARK, STL_USER_HL, STL_HIGHLIGHT, STL_TABPAGENR, STL_TABCLOSENR, \ STL_CLICK_FUNC, STL_TABPAGENR, STL_TABCLOSENR, STL_CLICK_FUNC, \ - 0, \ - }) + 0, }) // flags used for parsed 'wildmode' #define WIM_FULL 0x01 diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index ef9b9c5958..e1db7a8ef7 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -543,7 +543,7 @@ void free_homedir(void) /// @see {expand_env} char *expand_env_save(char *src) { - return (char *)expand_env_save_opt((char_u *)src, false); + return (char *)expand_env_save_opt(src, false); } /// Similar to expand_env_save() but when "one" is `true` handle the string as @@ -551,10 +551,10 @@ char *expand_env_save(char *src) /// @param src String containing environment variables to expand /// @param one Should treat as only one file name /// @see {expand_env} -char_u *expand_env_save_opt(char_u *src, bool one) +char_u *expand_env_save_opt(char *src, bool one) { char_u *p = xmalloc(MAXPATHL); - expand_env_esc((char *)src, (char *)p, MAXPATHL, false, one, NULL); + expand_env_esc(src, (char *)p, MAXPATHL, false, one, NULL); return p; } @@ -711,7 +711,7 @@ void expand_env_esc(char *restrict srcp, char *restrict dst, int dstlen, bool es // If "var" contains white space, escape it with a backslash. // Required for ":e ~/tt" when $HOME includes a space. if (esc && var != NULL && strpbrk(var, " \t") != NULL) { - char *p = (char *)vim_strsave_escaped((char_u *)var, (char_u *)" \t"); + char *p = vim_strsave_escaped(var, " \t"); if (mustfree) { xfree(var); diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c index b8ade07038..e0449d468a 100644 --- a/src/nvim/os/fs.c +++ b/src/nvim/os/fs.c @@ -995,7 +995,7 @@ int os_mkdir_recurse(const char *const dir, int32_t mode, char **const failed_di int os_file_mkdir(char *fname, int32_t mode) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { - if (!dir_of_file_exists((char_u *)fname)) { + if (!dir_of_file_exists(fname)) { char *tail = path_tail_with_sep(fname); char *last_char = tail + strlen(tail) - 1; if (vim_ispathsep(*last_char)) { diff --git a/src/nvim/os/pty_process_unix.c b/src/nvim/os/pty_process_unix.c index cd2150a6a6..2413f0339b 100644 --- a/src/nvim/os/pty_process_unix.c +++ b/src/nvim/os/pty_process_unix.c @@ -160,39 +160,13 @@ static pid_t forkpty(int *amaster, char *name, struct termios *termp, struct win #endif -/// termios saved at startup (for TUI) or initialized by pty_process_spawn(). -static struct termios termios_default; - -/// Saves the termios properties associated with `tty_fd`. -/// -/// @param tty_fd TTY file descriptor, or -1 if not in a terminal. -void pty_process_save_termios(int tty_fd) -{ - if (embedded_mode) { - // TODO(bfredl): currently we cannot use the state of the host terminal in - // the server. when the TUI process launches the server, the state has already - // changed. we would need to serialize termios_default in the TUI process and - // transmit it. Altough, just always using the clean slate of init_termios() might - // be preferrable anyway. - return; - } - if (tty_fd == -1) { - return; - } - int rv = tcgetattr(tty_fd, &termios_default); - if (rv != 0) { - ELOG("tcgetattr failed (tty_fd=%d): %s", tty_fd, strerror(errno)); - } else { - DLOG("tty_fd=%d", tty_fd); - } -} - /// @returns zero on success, or negative error code int pty_process_spawn(PtyProcess *ptyproc) FUNC_ATTR_NONNULL_ALL { + // termios initialized at first use + static struct termios termios_default; if (!termios_default.c_cflag) { - // TODO(jkeyes): We could pass NULL to forkpty() instead ... init_termios(&termios_default); } diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index d647780847..8177f06c64 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -65,7 +65,7 @@ typedef struct { static void save_patterns(int num_pat, char **pat, int *num_file, char ***file) { - *file = xmalloc((size_t)num_pat * sizeof(char_u *)); + *file = xmalloc((size_t)num_pat * sizeof(char *)); for (int i = 0; i < num_pat; i++) { char *s = xstrdup(pat[i]); // Be compatible with expand_filename(): halve the number of @@ -122,7 +122,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in size_t len; char *p; bool dir; - char_u *extra_shell_arg = NULL; + char *extra_shell_arg = NULL; ShellOpts shellopts = kShellOptExpand | kShellOptSilent; int j; char *tempname; @@ -144,7 +144,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in bool is_fish_shell = #if defined(UNIX) - strncmp((char *)invocation_path_tail((char_u *)p_sh, NULL), "fish", 4) == 0; + strncmp((char *)invocation_path_tail(p_sh, NULL), "fish", 4) == 0; #else false; #endif @@ -337,17 +337,17 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in // the argument list, otherwise zsh gives an error message and doesn't // expand any other pattern. if (shell_style == STYLE_PRINT) { - extra_shell_arg = (char_u *)"-G"; // Use zsh NULL_GLOB option + extra_shell_arg = "-G"; // Use zsh NULL_GLOB option // If we use -f then shell variables set in .cshrc won't get expanded. // vi can do it, so we will too, but it is only necessary if there is a "$" // in one of the patterns, otherwise we can still use the fast option. } else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat)) { - extra_shell_arg = (char_u *)"-f"; // Use csh fast option + extra_shell_arg = "-f"; // Use csh fast option } // execute the shell command - i = call_shell((char_u *)command, shellopts, extra_shell_arg); + i = call_shell(command, shellopts, extra_shell_arg); // When running in the background, give it some time to create the temp // file, but don't wait for it to finish. @@ -488,7 +488,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in goto notfound; } *num_file = i; - *file = xmalloc(sizeof(char_u *) * (size_t)i); + *file = xmalloc(sizeof(char *) * (size_t)i); // Isolate the individual file names. p = buffer; @@ -570,18 +570,18 @@ notfound: char **shell_build_argv(const char *cmd, const char *extra_args) FUNC_ATTR_NONNULL_RET { - size_t argc = tokenize((char_u *)p_sh, NULL) + (cmd ? tokenize(p_shcf, NULL) : 0); + size_t argc = tokenize(p_sh, NULL) + (cmd ? tokenize((char *)p_shcf, NULL) : 0); char **rv = xmalloc((argc + 4) * sizeof(*rv)); // Split 'shell' - size_t i = tokenize((char_u *)p_sh, rv); + size_t i = tokenize(p_sh, rv); if (extra_args) { rv[i++] = xstrdup(extra_args); // Push a copy of `extra_args` } if (cmd) { - i += tokenize(p_shcf, rv + i); // Split 'shellcmdflag' + i += tokenize((char *)p_shcf, rv + i); // Split 'shellcmdflag' rv[i++] = shell_xescape_xquote(cmd); // Copy (and escape) `cmd`. } @@ -653,7 +653,7 @@ char *shell_argv_to_str(char **const argv) /// @param extra_args Extra arguments to the shell, or NULL. /// /// @return shell command exit code -int os_call_shell(char_u *cmd, ShellOpts opts, char_u *extra_args) +int os_call_shell(char *cmd, ShellOpts opts, char *extra_args) { DynamicBuffer input = DYNAMIC_BUFFER_INIT; char *output = NULL, **output_ptr = NULL; @@ -682,7 +682,7 @@ int os_call_shell(char_u *cmd, ShellOpts opts, char_u *extra_args) } size_t nread; - int exitcode = do_os_system(shell_build_argv((char *)cmd, (char *)extra_args), + int exitcode = do_os_system(shell_build_argv(cmd, extra_args), input.data, input.len, output_ptr, &nread, emsg_silent, forward_output); xfree(input.data); @@ -708,14 +708,14 @@ int os_call_shell(char_u *cmd, ShellOpts opts, char_u *extra_args) /// Invalidates cached tags. /// /// @return shell command exit code -int call_shell(char_u *cmd, ShellOpts opts, char_u *extra_shell_arg) +int call_shell(char *cmd, ShellOpts opts, char *extra_shell_arg) { int retval; proftime_T wait_time; if (p_verbose > 3) { verbose_enter(); - smsg(_("Executing command: \"%s\""), cmd == NULL ? p_sh : (char *)cmd); + smsg(_("Executing command: \"%s\""), cmd == NULL ? p_sh : cmd); msg_putchar('\n'); verbose_leave(); } @@ -752,23 +752,23 @@ int call_shell(char_u *cmd, ShellOpts opts, char_u *extra_shell_arg) /// @param ret_len length of the stdout /// /// @return an allocated string, or NULL for error. -char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret_len) +char *get_cmd_output(char *cmd, char *infile, ShellOpts flags, size_t *ret_len) { - char_u *buffer = NULL; + char *buffer = NULL; if (check_secure()) { return NULL; } // get a name for the temp file - char_u *tempname = (char_u *)vim_tempname(); + char *tempname = vim_tempname(); if (tempname == NULL) { emsg(_(e_notmp)); return NULL; } // Add the redirection stuff - char_u *command = (char_u *)make_filter_cmd((char *)cmd, (char *)infile, (char *)tempname); + char *command = make_filter_cmd(cmd, infile, tempname); // Call the shell to execute the command (errors are ignored). // Don't check timestamps here. @@ -779,7 +779,7 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret xfree(command); // read the names from the file into memory - FILE *fd = os_fopen((char *)tempname, READBIN); + FILE *fd = os_fopen(tempname, READBIN); if (fd == NULL) { semsg(_(e_notopen), tempname); @@ -791,9 +791,9 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret fseek(fd, 0L, SEEK_SET); buffer = xmalloc(len + 1); - size_t i = fread((char *)buffer, 1, len, fd); + size_t i = fread(buffer, 1, len, fd); fclose(fd); - os_remove((char *)tempname); + os_remove(tempname); if (i != len) { semsg(_(e_notread), tempname); XFREE_CLEAR(buffer); @@ -1165,14 +1165,14 @@ static void out_data_cb(Stream *stream, RBuffer *buf, size_t count, void *data, /// @param argv The vector that will be filled with copies of the parsed /// words. It can be NULL if the caller only needs to count words. /// @return The number of words parsed. -static size_t tokenize(const char_u *const str, char **const argv) +static size_t tokenize(const char *const str, char **const argv) FUNC_ATTR_NONNULL_ARG(1) { size_t argc = 0; - const char *p = (const char *)str; + const char *p = str; while (*p != NUL) { - const size_t len = word_length((const char_u *)p); + const size_t len = word_length(p); if (argv != NULL) { // Fill the slot @@ -1190,9 +1190,9 @@ static size_t tokenize(const char_u *const str, char **const argv) /// /// @param str A pointer to the first character of the word /// @return The offset from `str` at which the word ends. -static size_t word_length(const char_u *str) +static size_t word_length(const char *str) { - const char_u *p = str; + const char *p = str; bool inquote = false; size_t length = 0; @@ -1223,10 +1223,10 @@ static void read_input(DynamicBuffer *buf) { size_t written = 0, l = 0, len = 0; linenr_T lnum = curbuf->b_op_start.lnum; - char_u *lp = (char_u *)ml_get(lnum); + char *lp = ml_get(lnum); for (;;) { - l = strlen((char *)lp + written); + l = strlen(lp + written); if (l == 0) { len = 0; } else if (lp[written] == NL) { @@ -1235,7 +1235,7 @@ static void read_input(DynamicBuffer *buf) dynamic_buffer_ensure(buf, buf->len + len); buf->data[buf->len++] = NUL; } else { - char_u *s = (char_u *)vim_strchr((char *)lp + written, NL); + char *s = vim_strchr(lp + written, NL); len = s == NULL ? l : (size_t)(s - (lp + written)); dynamic_buffer_ensure(buf, buf->len + len); memcpy(buf->data + buf->len, lp + written, len); @@ -1255,7 +1255,7 @@ static void read_input(DynamicBuffer *buf) if (lnum > curbuf->b_op_end.lnum) { break; } - lp = (char_u *)ml_get(lnum); + lp = ml_get(lnum); written = 0; } else if (len > 0) { written += len; @@ -1332,7 +1332,7 @@ static char *shell_xescape_xquote(const char *cmd) const char *ecmd = cmd; if (*p_sxe != NUL && strcmp(p_sxq, "(") == 0) { - ecmd = (char *)vim_strsave_escaped_ext((char_u *)cmd, p_sxe, '^', false); + ecmd = vim_strsave_escaped_ext(cmd, (char *)p_sxe, '^', false); } size_t ncmd_size = strlen(ecmd) + strlen(p_sxq) * 2 + 1; char *ncmd = xmalloc(ncmd_size); diff --git a/src/nvim/path.c b/src/nvim/path.c index e4c75f67a8..9350335e54 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -154,11 +154,11 @@ char *path_tail_with_sep(char *fname) /// @post if `len` is not null, stores the length of the executable name. /// /// @return The position of the last path separator + 1. -const char_u *invocation_path_tail(const char_u *invocation, size_t *len) +const char_u *invocation_path_tail(const char *invocation, size_t *len) FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1) { - const char_u *tail = (char_u *)get_past_head((char *)invocation); - const char_u *p = tail; + const char *tail = get_past_head(invocation); + const char *p = tail; while (*p != NUL && *p != ' ') { bool was_sep = vim_ispathsep_nocolon(*p); MB_PTR_ADV(p); @@ -171,7 +171,7 @@ const char_u *invocation_path_tail(const char_u *invocation, size_t *len) *len = (size_t)(p - tail); } - return tail; + return (char_u *)tail; } /// Get the next path component of a path name. @@ -279,13 +279,13 @@ int vim_ispathlistsep(int c) /// "trim_len" specifies how many characters to keep for each directory. /// Must be 1 or more. /// It's done in-place. -void shorten_dir_len(char_u *str, int trim_len) +void shorten_dir_len(char *str, int trim_len) { - char_u *tail = (char_u *)path_tail((char *)str); - char_u *d = str; + char *tail = path_tail(str); + char *d = str; bool skip = false; int dirchunk_len = 0; - for (char_u *s = str;; s++) { + for (char *s = str;; s++) { if (s >= tail) { // copy the whole tail *d++ = *s; if (*s == NUL) { @@ -305,7 +305,7 @@ void shorten_dir_len(char_u *str, int trim_len) skip = true; } } - int l = utfc_ptr2len((char *)s); + int l = utfc_ptr2len(s); while (--l > 0) { *d++ = *++s; } @@ -317,21 +317,21 @@ void shorten_dir_len(char_u *str, int trim_len) /// It's done in-place. void shorten_dir(char *str) { - shorten_dir_len((char_u *)str, 1); + shorten_dir_len(str, 1); } /// Return true if the directory of "fname" exists, false otherwise. /// Also returns true if there is no directory name. /// "fname" must be writable!. -bool dir_of_file_exists(char_u *fname) +bool dir_of_file_exists(char *fname) { - char *p = path_tail_with_sep((char *)fname); - if ((char_u *)p == fname) { + char *p = path_tail_with_sep(fname); + if (p == fname) { return true; } char c = *p; *p = NUL; - bool retval = os_isdir((char *)fname); + bool retval = os_isdir(fname); *p = c; return retval; } @@ -553,7 +553,7 @@ static int pstrcmp(const void *a, const void *b) /// @param p The path to expand. /// @returns Unix: True if it contains one of *?[{. /// @returns Windows: True if it contains one of *?[. -bool path_has_exp_wildcard(const char_u *p) +bool path_has_exp_wildcard(const char *p) FUNC_ATTR_NONNULL_ALL { for (; *p != NUL; MB_PTR_ADV(p)) { @@ -567,7 +567,7 @@ bool path_has_exp_wildcard(const char_u *p) #else const char *wildcards = "*?["; // Windows. #endif - if (vim_strchr(wildcards, *p) != NULL) { + if (vim_strchr(wildcards, (uint8_t)(*p)) != NULL) { return true; } } @@ -585,10 +585,10 @@ bool path_has_exp_wildcard(const char_u *p) /// - EW_NOERROR: Silence error messages. /// - EW_NOTWILD: Add matches literally. /// @returns the number of matches found. -static size_t path_expand(garray_T *gap, const char_u *path, int flags) +static size_t path_expand(garray_T *gap, const char *path, int flags) FUNC_ATTR_NONNULL_ALL { - return do_path_expand(gap, (char *)path, 0, flags, false); + return do_path_expand(gap, path, 0, flags, false); } static const char *scandir_next_with_dots(Directory *dir) @@ -751,7 +751,7 @@ static size_t do_path_expand(garray_T *gap, const char *path, size_t wildoff, in } STRCPY(buf + len, path_end); - if (path_has_exp_wildcard((char_u *)path_end)) { // handle more wildcards + if (path_has_exp_wildcard(path_end)) { // handle more wildcards // need to expand another component of the path // remove backslashes for the remaining components only (void)do_path_expand(gap, buf, len + 1, flags, false); @@ -790,7 +790,7 @@ static size_t do_path_expand(garray_T *gap, const char *path, size_t wildoff, in // Moves "*psep" back to the previous path separator in "path". // Returns FAIL is "*psep" ends up at the beginning of "path". -static int find_previous_pathsep(char_u *path, char_u **psep) +static int find_previous_pathsep(char *path, char **psep) { // skip the current separator if (*psep > path && vim_ispathsep(**psep)) { @@ -854,8 +854,8 @@ static void expand_path_option(char *curdir, garray_T *gap) if (curbuf->b_ffname == NULL) { continue; } - char_u *p = (char_u *)path_tail(curbuf->b_ffname); - size_t len = (size_t)(p - (char_u *)curbuf->b_ffname); + char *p = path_tail(curbuf->b_ffname); + size_t len = (size_t)(p - curbuf->b_ffname); if (len + strlen(buf) >= MAXPATHL) { continue; } @@ -865,7 +865,7 @@ static void expand_path_option(char *curdir, garray_T *gap) STRMOVE(buf + len, buf + 2); } memmove(buf, curbuf->b_ffname, len); - simplify_filename((char_u *)buf); + simplify_filename(buf); } else if (buf[0] == NUL) { STRCPY(buf, curdir); // relative to current directory } else if (path_with_url(buf)) { @@ -879,7 +879,7 @@ static void expand_path_option(char *curdir, garray_T *gap) STRMOVE(buf + len + 1, buf); STRCPY(buf, curdir); buf[len] = (char_u)PATHSEP; - simplify_filename((char_u *)buf); + simplify_filename(buf); } GA_APPEND(char *, gap, xstrdup(buf)); @@ -940,7 +940,7 @@ static void uniquefy_paths(garray_T *gap, char *pattern) char *short_name; ga_remove_duplicate_strings(gap); - ga_init(&path_ga, (int)sizeof(char_u *), 1); + ga_init(&path_ga, (int)sizeof(char *), 1); // We need to prepend a '*' at the beginning of file_pattern so that the // regex matches anywhere in the path. FIXME: is this valid for all @@ -967,7 +967,7 @@ static void uniquefy_paths(garray_T *gap, char *pattern) os_dirname(curdir, MAXPATHL); expand_path_option(curdir, &path_ga); - in_curdir = xcalloc((size_t)gap->ga_len, sizeof(char_u *)); + in_curdir = xcalloc((size_t)gap->ga_len, sizeof(char *)); for (int i = 0; i < gap->ga_len && !got_int; i++) { char *path = fnames[i]; @@ -1000,7 +1000,7 @@ static void uniquefy_paths(garray_T *gap, char *pattern) // Here all files can be reached without path, so get shortest // unique path. We start at the end of the path. */ pathsep_p = path + len - 1; - while (find_previous_pathsep((char_u *)path, (char_u **)&pathsep_p)) { + while (find_previous_pathsep(path, &pathsep_p)) { if (vim_regexec(®match, pathsep_p + 1, (colnr_T)0) && is_unique(pathsep_p + 1, gap, i) && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff) { @@ -1117,11 +1117,11 @@ static int expand_in_path(garray_T *const gap, char *const pattern, const int fl { garray_T path_ga; - char_u *const curdir = xmalloc(MAXPATHL); - os_dirname((char *)curdir, MAXPATHL); + char *const curdir = xmalloc(MAXPATHL); + os_dirname(curdir, MAXPATHL); - ga_init(&path_ga, (int)sizeof(char_u *), 1); - expand_path_option((char *)curdir, &path_ga); + ga_init(&path_ga, (int)sizeof(char *), 1); + expand_path_option(curdir, &path_ga); xfree(curdir); if (GA_EMPTY(&path_ga)) { return 0; @@ -1241,7 +1241,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i recursive = true; // The matching file names are stored in a growarray. Init it empty. - ga_init(&ga, (int)sizeof(char_u *), 30); + ga_init(&ga, (int)sizeof(char *), 30); for (int i = 0; i < num_pat && !got_int; i++) { add_pat = -1; @@ -1259,7 +1259,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i } else { // First expand environment variables, "~/" and "~user/". if ((has_env_var((char_u *)p) && !(flags & EW_NOTENV)) || *p == '~') { - p = (char *)expand_env_save_opt((char_u *)p, true); + p = (char *)expand_env_save_opt(p, true); if (p == NULL) { p = pat[i]; } else { @@ -1284,7 +1284,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i // there is no match, and EW_NOTFOUND is given, add the pattern. // Otherwise: Add the file name if it exists or when EW_NOTFOUND is // given. - if (path_has_exp_wildcard((char_u *)p) || (flags & EW_ICASE)) { + if (path_has_exp_wildcard(p) || (flags & EW_ICASE)) { if ((flags & EW_PATH) && !path_is_absolute((char_u *)p) && !(p[0] == '.' @@ -1298,7 +1298,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i recursive = true; did_expand_in_path = true; } else { - size_t tmp_add_pat = path_expand(&ga, (char_u *)p, flags); + size_t tmp_add_pat = path_expand(&ga, p, flags); assert(tmp_add_pat <= INT_MAX); add_pat = (int)tmp_add_pat; } @@ -1372,8 +1372,7 @@ static int expand_backtick(garray_T *gap, char *pat, int flags) if (*cmd == '=') { // `={expr}`: Expand expression buffer = eval_to_string(cmd + 1, &p, true); } else { - buffer = (char *)get_cmd_output((char_u *)cmd, NULL, (flags & EW_SILENT) ? kShellOptSilent : 0, - NULL); + buffer = get_cmd_output(cmd, NULL, (flags & EW_SILENT) ? kShellOptSilent : 0, NULL); } xfree(cmd); if (buffer == NULL) { @@ -1495,10 +1494,10 @@ void addfile(garray_T *gap, char *f, int flags) // its simplest form by stripping out unneeded components, if any. The // resulting file name is simplified in place and will either be the same // length as that supplied, or shorter. -void simplify_filename(char_u *filename) +void simplify_filename(char *filename) { int components = 0; - char_u *p, *tail, *start; + char *p, *tail, *start; bool stripping_disabled = false; bool relative = true; @@ -1521,7 +1520,7 @@ void simplify_filename(char_u *filename) // At this point "p" is pointing to the char following a single "/" // or "p" is at the "start" of the (absolute or relative) path name. if (vim_ispathsep(*p)) { - STRMOVE(p, (char *)p + 1); // remove duplicate "/" + STRMOVE(p, p + 1); // remove duplicate "/" } else if (p[0] == '.' && (vim_ispathsep(p[1]) || p[1] == NUL)) { if (p == start && relative) { @@ -1539,7 +1538,7 @@ void simplify_filename(char_u *filename) } else if (p > start) { p--; // strip preceding path separator } - STRMOVE(p, (char *)tail); + STRMOVE(p, tail); } } else if (p[0] == '.' && p[1] == '.' && (vim_ispathsep(p[2]) || p[2] == NUL)) { @@ -1551,7 +1550,7 @@ void simplify_filename(char_u *filename) if (components > 0) { // strip one preceding component bool do_strip = false; - char_u saved_char; + char saved_char; // Don't strip for an erroneous file name. if (!stripping_disabled) { @@ -1561,14 +1560,14 @@ void simplify_filename(char_u *filename) saved_char = p[-1]; p[-1] = NUL; FileInfo file_info; - if (!os_fileinfo_link((char *)filename, &file_info)) { + if (!os_fileinfo_link(filename, &file_info)) { do_strip = true; } p[-1] = saved_char; p--; // Skip back to after previous '/'. - while (p > start && !after_pathsep((char *)start, (char *)p)) { + while (p > start && !after_pathsep(start, p)) { MB_PTR_BACK(start, p); } @@ -1585,7 +1584,7 @@ void simplify_filename(char_u *filename) // components. saved_char = *tail; *tail = NUL; - if (os_fileinfo((char *)filename, &file_info)) { + if (os_fileinfo(filename, &file_info)) { do_strip = true; } else { stripping_disabled = true; @@ -1605,7 +1604,7 @@ void simplify_filename(char_u *filename) } else { saved_char = *p; *p = NUL; - os_fileinfo((char *)filename, &new_file_info); + os_fileinfo(filename, &new_file_info); *p = saved_char; } @@ -1638,23 +1637,23 @@ void simplify_filename(char_u *filename) if (p > start && tail[-1] == '.') { p--; } - STRMOVE(p, (char *)tail); // strip previous component + STRMOVE(p, tail); // strip previous component } components--; } } else if (p == start && !relative) { // leading "/.." or "/../" - STRMOVE(p, (char *)tail); // strip ".." or "../" + STRMOVE(p, tail); // strip ".." or "../" } else { if (p == start + 2 && p[-2] == '.') { // leading "./../" - STRMOVE(p - 2, (char *)p); // strip leading "./" + STRMOVE(p - 2, p); // strip leading "./" tail -= 2; } p = tail; // skip to char after ".." or "../" } } else { components++; // Simple path component. - p = (char_u *)path_next_component((const char *)p); + p = (char *)path_next_component(p); } } while (*p != NUL); } @@ -1690,8 +1689,8 @@ char *find_file_name_in_path(char *ptr, size_t len, int options, long count, cha } if (options & FNAME_EXP) { - file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, true, - (char_u *)rel_fname); + file_name = (char *)find_file_in_path(ptr, len, options & ~FNAME_MESS, true, + rel_fname); // If the file could not be found in a normal way, try applying // 'includeexpr' (unless done already). @@ -1701,8 +1700,8 @@ char *find_file_name_in_path(char *ptr, size_t len, int options, long count, cha if (tofree != NULL) { ptr = tofree; len = strlen(ptr); - file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, - true, (char_u *)rel_fname); + file_name = (char *)find_file_in_path(ptr, len, options & ~FNAME_MESS, + true, rel_fname); } } if (file_name == NULL && (options & FNAME_MESS)) { @@ -1717,7 +1716,7 @@ char *find_file_name_in_path(char *ptr, size_t len, int options, long count, cha while (file_name != NULL && --count > 0) { xfree(file_name); file_name = - (char *)find_file_in_path((char_u *)ptr, len, options, false, (char_u *)rel_fname); + (char *)find_file_in_path(ptr, len, options, false, rel_fname); } } else { file_name = xstrnsave(ptr, len); @@ -1798,9 +1797,9 @@ bool path_with_extension(const char *path, const char *extension) } /// Return true if "name" is a full (absolute) path name or URL. -bool vim_isAbsName(char_u *name) +bool vim_isAbsName(char *name) { - return path_with_url((char *)name) != 0 || path_is_absolute(name); + return path_with_url(name) != 0 || path_is_absolute((char_u *)name); } /// Save absolute file name to "buf[len]". @@ -1945,7 +1944,7 @@ int after_pathsep(const char *b, const char *p) /// Return true if file names "f1" and "f2" are in the same directory. /// "f1" may be a short name, "f2" must be a full path. -bool same_directory(char_u *f1, char_u *f2) +bool same_directory(char *f1, char *f2) { char ffname[MAXPATHL]; char *t1; @@ -1956,11 +1955,11 @@ bool same_directory(char_u *f1, char_u *f2) return false; } - (void)vim_FullName((char *)f1, (char *)ffname, MAXPATHL, false); + (void)vim_FullName(f1, (char *)ffname, MAXPATHL, false); t1 = path_tail_with_sep(ffname); - t2 = path_tail_with_sep((char *)f2); - return t1 - ffname == (char_u *)t2 - f2 - && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0; + t2 = path_tail_with_sep(f2); + return t1 - ffname == t2 - f2 + && pathcmp((char *)ffname, f2, (int)(t1 - ffname)) == 0; } // Compare path "p[]" to "q[]". @@ -2044,13 +2043,13 @@ int pathcmp(const char *p, const char *q, int maxlen) /// - Pointer into `full_path` if shortened. /// - `full_path` unchanged if no shorter name is possible. /// - NULL if `full_path` is NULL. -char_u *path_try_shorten_fname(char_u *full_path) +char *path_try_shorten_fname(char *full_path) { - char_u *dirname = xmalloc(MAXPATHL); - char_u *p = full_path; + char *dirname = xmalloc(MAXPATHL); + char *p = full_path; - if (os_dirname((char *)dirname, MAXPATHL) == OK) { - p = (char_u *)path_shorten_fname((char *)full_path, (char *)dirname); + if (os_dirname(dirname, MAXPATHL) == OK) { + p = path_shorten_fname(full_path, dirname); if (p == NULL || *p == NUL) { p = full_path; } @@ -2086,7 +2085,7 @@ char *path_shorten_fname(char *full_path, char *dir_name) return NULL; } - char_u *p = (char_u *)full_path + len; + char *p = full_path + len; // If *p is not pointing to a path separator, this means that full_path's // last directory name is longer than *dir_name's last directory, so they @@ -2095,7 +2094,7 @@ char *path_shorten_fname(char *full_path, char *dir_name) return NULL; } - return (char *)p + 1; + return p + 1; } /// Invoke expand_wildcards() for one pattern @@ -2174,7 +2173,7 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int { int retval; int i, j; - char_u *p; + char *p; int non_suf_match; // number without matching suffix retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags); @@ -2215,11 +2214,11 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int for (i = 0; i < *num_files; i++) { if (!match_suffix((*files)[i])) { // Move the name without matching suffix to the front of the list. - p = (char_u *)(*files)[i]; + p = (*files)[i]; for (j = i; j > non_suf_match; j--) { (*files)[j] = (*files)[j - 1]; } - (*files)[non_suf_match++] = (char *)p; + (*files)[non_suf_match++] = p; } } } @@ -2241,8 +2240,8 @@ int match_suffix(char *fname) size_t fnamelen = strlen(fname); size_t setsuflen = 0; - for (char_u *setsuf = p_su; *setsuf;) { - setsuflen = copy_option_part((char **)&setsuf, (char *)suf_buf, MAXSUFLEN, ".,"); + for (char *setsuf = (char *)p_su; *setsuf;) { + setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,"); if (setsuflen == 0) { char *tail = path_tail(fname); diff --git a/src/nvim/path.h b/src/nvim/path.h index 37a0883c7f..c8d192dffe 100644 --- a/src/nvim/path.h +++ b/src/nvim/path.h @@ -39,4 +39,4 @@ typedef enum file_comparison { #ifdef INCLUDE_GENERATED_DECLARATIONS # include "path.h.generated.h" #endif -#endif +#endif // NVIM_PATH_H diff --git a/src/nvim/plines.c b/src/nvim/plines.c index 20a6855a16..e4d1ddf8d8 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -108,7 +108,7 @@ int plines_win_nofold(win_T *wp, linenr_T lnum) if (*s == NUL) { // empty line return 1; } - col = win_linetabsize(wp, lnum, (char_u *)s, MAXCOL); + col = win_linetabsize(wp, lnum, s, MAXCOL); // If list mode is on, then the '$' at the end of the line may take up one // extra column. @@ -146,12 +146,12 @@ int plines_win_col(win_T *wp, linenr_T lnum, long column) return lines + 1; } - char_u *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false); + char *line = ml_get_buf(wp->w_buffer, lnum, false); colnr_T col = 0; chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line); + init_chartabsize_arg(&cts, wp, lnum, 0, line, line); while (*cts.cts_ptr != NUL && --column >= 0) { cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); MB_PTR_ADV(cts.cts_ptr); @@ -244,9 +244,9 @@ int win_chartabsize(win_T *wp, char *p, colnr_T col) /// @param s /// /// @return Number of characters the string will take on the screen. -int linetabsize(char_u *s) +int linetabsize(char *s) { - return linetabsize_col(0, (char *)s); + return linetabsize_col(0, s); } /// Like linetabsize(), but "s" starts at column "startcol". @@ -273,11 +273,11 @@ int linetabsize_col(int startcol, char *s) /// @param len /// /// @return Number of characters the string will take on the screen. -unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char_u *line, colnr_T len) +unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char *line, colnr_T len) { chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line); - for (; *cts.cts_ptr != NUL && (len == MAXCOL || cts.cts_ptr < (char *)line + len); + init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + for (; *cts.cts_ptr != NUL && (len == MAXCOL || cts.cts_ptr < line + len); MB_PTR_ADV(cts.cts_ptr)) { cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); } @@ -354,7 +354,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) { win_T *wp = cts->cts_win; char *line = cts->cts_line; // start of the line - char_u *s = (char_u *)cts->cts_ptr; + char *s = cts->cts_ptr; colnr_T vcol = cts->cts_vcol; colnr_T col2; @@ -363,7 +363,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) int added; int mb_added = 0; int numberextra; - char_u *ps; + char *ps; int n; cts->cts_cur_text_width = 0; @@ -374,16 +374,16 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) if (wp->w_p_wrap) { return win_nolbr_chartabsize(cts, headp); } - return win_chartabsize(wp, (char *)s, vcol); + return win_chartabsize(wp, s, vcol); } // First get normal size, without 'linebreak' or virtual text - int size = win_chartabsize(wp, (char *)s, vcol); + int size = win_chartabsize(wp, s, vcol); if (cts->cts_has_virt_text) { // TODO(bfredl): inline virtual text } - int c = *s; + int c = (uint8_t)(*s); if (*s == TAB) { col_adj = size - 1; } @@ -392,7 +392,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) // needs a break here if (wp->w_p_lbr && vim_isbreak(c) - && !vim_isbreak((int)s[1]) + && !vim_isbreak((uint8_t)s[1]) && wp->w_p_wrap && (wp->w_width_inner != 0)) { // Count all characters from first non-blank after a blank up to next @@ -413,14 +413,14 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) for (;;) { ps = s; MB_PTR_ADV(s); - c = *s; + c = (uint8_t)(*s); if (!(c != NUL - && (vim_isbreak(c) || col2 == vcol || !vim_isbreak((int)(*ps))))) { + && (vim_isbreak(c) || col2 == vcol || !vim_isbreak((uint8_t)(*ps))))) { break; } - col2 += win_chartabsize(wp, (char *)s, col2); + col2 += win_chartabsize(wp, s, col2); if (col2 >= colmax) { // doesn't fit size = colmax - vcol + col_adj; @@ -428,7 +428,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) } } } else if ((size == 2) - && (MB_BYTE2LEN(*s) > 1) + && (MB_BYTE2LEN((uint8_t)(*s)) > 1) && wp->w_p_wrap && in_win_border(wp, vcol)) { // Count the ">" in the last column. @@ -456,7 +456,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) vcol %= numberextra; } if (*sbr != NUL) { - sbrlen = (colnr_T)mb_charlen((char_u *)sbr); + sbrlen = (colnr_T)mb_charlen(sbr); if (vcol >= sbrlen) { vcol -= sbrlen; } @@ -492,7 +492,7 @@ int win_lbr_chartabsize(chartabsize_T *cts, int *headp) } if (wp->w_p_bri) { - added += get_breakindent_win(wp, (char_u *)line); + added += get_breakindent_win(wp, line); } size += added; diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index 12e868f327..14ee71d50a 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -78,19 +78,19 @@ static void pum_compute_size(void) for (int i = 0; i < pum_size; i++) { int w; if (pum_array[i].pum_text != NULL) { - w = vim_strsize((char *)pum_array[i].pum_text); + w = vim_strsize(pum_array[i].pum_text); if (pum_base_width < w) { pum_base_width = w; } } if (pum_array[i].pum_kind != NULL) { - w = vim_strsize((char *)pum_array[i].pum_kind) + 1; + w = vim_strsize(pum_array[i].pum_kind) + 1; if (pum_kind_width < w) { pum_kind_width = w; } } if (pum_array[i].pum_extra != NULL) { - w = vim_strsize((char *)pum_array[i].pum_extra) + 1; + w = vim_strsize(pum_array[i].pum_extra) + 1; if (pum_extra_width < w) { pum_extra_width = w; } @@ -167,10 +167,10 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, i Array arr = arena_array(&arena, (size_t)size); for (int i = 0; i < size; i++) { Array item = arena_array(&arena, 4); - ADD_C(item, STRING_OBJ(cstr_as_string((char *)array[i].pum_text))); - ADD_C(item, STRING_OBJ(cstr_as_string((char *)array[i].pum_kind))); - ADD_C(item, STRING_OBJ(cstr_as_string((char *)array[i].pum_extra))); - ADD_C(item, STRING_OBJ(cstr_as_string((char *)array[i].pum_info))); + ADD_C(item, STRING_OBJ(cstr_as_string(array[i].pum_text))); + ADD_C(item, STRING_OBJ(cstr_as_string(array[i].pum_kind))); + ADD_C(item, STRING_OBJ(cstr_as_string(array[i].pum_extra))); + ADD_C(item, STRING_OBJ(cstr_as_string(array[i].pum_info))); ADD_C(arr, ARRAY_OBJ(item)); } ui_call_popupmenu_show(arr, selected, pum_win_row, cursor_col, @@ -408,8 +408,8 @@ void pum_redraw(void) int attr; int i; int idx; - char_u *s; - char_u *p = NULL; + char *s; + char *p = NULL; int totwidth, width, w; int thumb_pos = 0; int thumb_height = 1; @@ -518,24 +518,24 @@ void pum_redraw(void) if (s == NULL) { s = p; } - w = ptr2cells((char *)p); + w = ptr2cells(p); if ((*p == NUL) || (*p == TAB) || (totwidth + w > pum_width)) { // Display the text that fits or comes before a Tab. // First convert it to printable characters. - char_u *st; - char_u saved = *p; + char *st; + char saved = *p; if (saved != NUL) { *p = NUL; } - st = (char_u *)transstr((const char *)s, true); + st = transstr(s, true); if (saved != NUL) { *p = saved; } if (pum_rl) { - char *rt = reverse_text((char *)st); + char *rt = reverse_text(st); char *rt_start = rt; int size = vim_strsize(rt); @@ -559,7 +559,7 @@ void pum_redraw(void) grid_col -= width; } else { // use grid_puts_len() to truncate the text - grid_puts(&pum_grid, (char *)st, row, grid_col, attr); + grid_puts(&pum_grid, st, row, grid_col, attr); xfree(st); grid_col += width; } @@ -762,17 +762,17 @@ static bool pum_set_selected(int n, int repeat) } if (res == OK) { - char_u *p, *e; + char *p, *e; linenr_T lnum = 0; for (p = pum_array[pum_selected].pum_info; *p != NUL;) { - e = (char_u *)vim_strchr((char *)p, '\n'); + e = vim_strchr(p, '\n'); if (e == NULL) { - ml_append(lnum++, (char *)p, 0, false); + ml_append(lnum++, p, 0, false); break; } *e = NUL; - ml_append(lnum++, (char *)p, (int)(e - p + 1), false); + ml_append(lnum++, p, (int)(e - p + 1), false); *e = '\n'; p = e + 1; } @@ -1061,7 +1061,7 @@ void pum_show_popupmenu(vimmenu_T *menu) } if (s != NULL) { s = xstrdup(s); - array[idx++].pum_text = (char_u *)s; + array[idx++].pum_text = s; } } diff --git a/src/nvim/popupmenu.h b/src/nvim/popupmenu.h index 2190c560b7..08b791c509 100644 --- a/src/nvim/popupmenu.h +++ b/src/nvim/popupmenu.h @@ -10,10 +10,10 @@ /// Used for popup menu items. typedef struct { - char_u *pum_text; // main menu text - char_u *pum_kind; // extra kind text (may be truncated) - char_u *pum_extra; // extra menu text (may be truncated) - char_u *pum_info; // extra info + char *pum_text; // main menu text + char *pum_kind; // extra kind text (may be truncated) + char *pum_extra; // extra menu text (may be truncated) + char *pum_info; // extra info } pumitem_T; EXTERN ScreenGrid pum_grid INIT(= SCREEN_GRID_INIT); diff --git a/src/nvim/profile.c b/src/nvim/profile.c index 4acd8b3621..acbaf09a6e 100644 --- a/src/nvim/profile.c +++ b/src/nvim/profile.c @@ -299,7 +299,7 @@ void ex_profile(exarg_T *eap) if (len == 5 && strncmp(eap->arg, "start", 5) == 0 && *e != NUL) { xfree(profile_fname); - profile_fname = (char *)expand_env_save_opt((char_u *)e, true); + profile_fname = (char *)expand_env_save_opt(e, true); do_profiling = PROF_YES; profile_set_wait(profile_zero()); set_vim_var_nr(VV_PROFILING, 1L); @@ -354,7 +354,6 @@ char *get_profile_name(expand_T *xp, int idx) switch (pexpand_what) { case PEXP_SUBCMD: return pexpand_cmds[idx]; - // case PEXP_FUNC: TODO default: return NULL; } @@ -368,18 +367,22 @@ void set_context_in_profile_cmd(expand_T *xp, const char *arg) pexpand_what = PEXP_SUBCMD; xp->xp_pattern = (char *)arg; - char_u *const end_subcmd = (char_u *)skiptowhite(arg); + char *const end_subcmd = skiptowhite(arg); if (*end_subcmd == NUL) { return; } - if ((const char *)end_subcmd - arg == 5 && strncmp(arg, "start", 5) == 0) { + if ((end_subcmd - arg == 5 && strncmp(arg, "start", 5) == 0) + || (end_subcmd - arg == 4 && strncmp(arg, "file", 4) == 0)) { xp->xp_context = EXPAND_FILES; - xp->xp_pattern = skipwhite((char *)end_subcmd); + xp->xp_pattern = skipwhite(end_subcmd); + return; + } else if (end_subcmd - arg == 4 && strncmp(arg, "func", 4) == 0) { + xp->xp_context = EXPAND_USER_FUNC; + xp->xp_pattern = skipwhite(end_subcmd); return; } - // TODO(tarruda): expand function names after "func" xp->xp_context = EXPAND_NOTHING; } diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 7d7bf9d8ba..c895ac16f1 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -814,7 +814,7 @@ retry: } // Convert a line if it contains a non-ASCII character - if (state->vc.vc_type != CONV_NONE && has_non_ascii((char_u *)state->linebuf)) { + if (state->vc.vc_type != CONV_NONE && has_non_ascii(state->linebuf)) { char *line = string_convert(&state->vc, state->linebuf, &state->linelen); if (line != NULL) { if (state->linelen < IOSIZE) { @@ -2075,7 +2075,7 @@ static int qf_get_fnum(qf_list_T *qfl, char *directory, char *fname) } slash_adjust(fname); #endif - if (directory != NULL && !vim_isAbsName((char_u *)fname)) { + if (directory != NULL && !vim_isAbsName(fname)) { ptr = concat_fnames(directory, fname, true); // Here we check if the file really exists. // This should normally be true, but if make works without @@ -2128,7 +2128,7 @@ static char *qf_push_dir(char *dirbuf, struct dir_stack_T **stackptr, bool is_fi *stackptr = ds_new; // store directory on the stack - if (vim_isAbsName((char_u *)dirbuf) + if (vim_isAbsName(dirbuf) || (*stackptr)->next == NULL || is_file_stack) { (*stackptr)->dirname = xstrdup(dirbuf); @@ -5374,7 +5374,7 @@ static int vgr_process_files(win_T *wp, qf_info_T *qi, vgr_args_T *cmd_args, boo time_t seconds = (time_t)0; for (int fi = 0; fi < cmd_args->fcount && !got_int && cmd_args->tomatch > 0; fi++) { - char *fname = (char *)path_try_shorten_fname((char_u *)cmd_args->fnames[fi]); + char *fname = path_try_shorten_fname(cmd_args->fnames[fi]); if (time(NULL) > seconds) { // Display the file name every second or so, show the user we are // working on it. diff --git a/src/nvim/rbuffer.c b/src/nvim/rbuffer.c index dde6e32306..1088dd3778 100644 --- a/src/nvim/rbuffer.c +++ b/src/nvim/rbuffer.c @@ -165,7 +165,8 @@ void rbuffer_consumed_compact(RBuffer *buf, size_t count) assert(buf->read_ptr <= buf->write_ptr); rbuffer_consumed(buf, count); if (buf->read_ptr > buf->start_ptr) { - assert((size_t)(buf->read_ptr - buf->write_ptr) == buf->size); + assert((size_t)(buf->write_ptr - buf->read_ptr) == buf->size + || buf->write_ptr == buf->start_ptr); memmove(buf->start_ptr, buf->read_ptr, buf->size); buf->read_ptr = buf->start_ptr; buf->write_ptr = buf->read_ptr + buf->size; diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index 9bc9d86374..e396e54ced 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -1150,7 +1150,7 @@ static bool reg_match_visual(void) rex.line = reg_getline(rex.lnum); rex.input = rex.line + col; - unsigned int cols_u = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, rex.line, col); + unsigned int cols_u = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, (char *)rex.line, col); assert(cols_u <= MAXCOL); colnr_T cols = (colnr_T)cols_u; if (cols < start || cols > end - (*p_sel == 'e')) { @@ -1837,7 +1837,7 @@ static int vim_regsub_both(char *source, typval_T *expr, char *dest, int destlen } if (had_backslash && (flags & REGSUB_BACKSLASH)) { // Backslashes will be consumed, need to double them. - s = (char *)vim_strsave_escaped((char_u *)eval_result[nested], (char_u *)"\\"); + s = vim_strsave_escaped(eval_result[nested], "\\"); xfree(eval_result[nested]); eval_result[nested] = s; } diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c index 810b35a77d..f930d872b6 100644 --- a/src/nvim/regexp_bt.c +++ b/src/nvim/regexp_bt.c @@ -3703,7 +3703,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) if (!re_num_cmp(win_linetabsize(rex.reg_win == NULL ? curwin : rex.reg_win, rex.reg_firstlnum + rex.lnum, - rex.line, + (char *)rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan)) { status = RA_NOMATCH; diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index bd872235ad..6e7ff31c03 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -1735,7 +1735,7 @@ static void nfa_emit_equi_class(int c) case 0x1ef5: case 0x1ef7: case 0x1ef9: - EMIT2('y') EMIT2(y_acute) EMIT2(y_diaeresis) + EMIT2('y') EMIT2(y_acute) EMIT2(y_diaeresis) // NOLINT(whitespace/cast) EMIT2(0x177) EMIT2(0x1b4) EMIT2(0x233) EMIT2(0x24f) EMIT2(0x1e8f) EMIT2(0x1e99) EMIT2(0x1ef3) EMIT2(0x1ef5) EMIT2(0x1ef7) EMIT2(0x1ef9) @@ -5236,7 +5236,7 @@ static regsubs_T *addstate_here(nfa_list_T *l, nfa_state_T *state, regsubs_T *su sizeof(nfa_thread_T) * (size_t)count); } } - --l->n; + l->n--; *ip = listidx - 1; return r; @@ -6841,7 +6841,7 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, regsubs_T *subm result = col > t->state->val * ts; } if (!result) { - uintmax_t lts = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, rex.line, col); + uintmax_t lts = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, (char *)rex.line, col); assert(t->state->val >= 0); result = nfa_re_num_cmp((uintmax_t)t->state->val, op, lts + 1); } diff --git a/src/nvim/screen.c b/src/nvim/screen.c index afdb04ebd8..b18bf7ed6a 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -189,7 +189,7 @@ int compute_foldcolumn(win_T *wp, int col) /// /// Assume monocell characters /// @return number of chars added to \param p -size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_T lnum) +size_t fill_foldcolumn(char *p, win_T *wp, foldinfo_T foldinfo, linenr_T lnum) { int i = 0; int level; @@ -223,7 +223,7 @@ size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_T lnum) symbol = '>'; } - len = utf_char2bytes(symbol, (char *)&p[char_counter]); + len = utf_char2bytes(symbol, &p[char_counter]); char_counter += (size_t)len; if (first_level + i >= level) { i++; @@ -237,7 +237,7 @@ size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_T lnum) char_counter -= (size_t)len; memset(&p[char_counter], ' ', (size_t)len); } - len = utf_char2bytes(wp->w_p_fcs_chars.foldclosed, (char *)&p[char_counter]); + len = utf_char2bytes(wp->w_p_fcs_chars.foldclosed, &p[char_counter]); char_counter += (size_t)len; } @@ -817,7 +817,7 @@ int number_width(win_T *wp) /// Returns 0 for invalid hex or invalid UTF-8 byte. static int get_encoded_char_adv(const char_u **p) { - const char_u *s = *p; + const char *s = (const char *)(*p); if (s[0] == '\\' && (s[1] == 'x' || s[1] == 'u' || s[1] == 'U')) { int64_t num = 0; @@ -834,7 +834,7 @@ static int get_encoded_char_adv(const char_u **p) } // TODO(bfredl): use schar_T representation and utfc_ptr2len - int clen = utf_ptr2len((const char *)s); + int clen = utf_ptr2len(s); int c = mb_cptr2char_adv(p); if (clen == 1 && c > 127) { // Invalid UTF-8 byte return 0; @@ -850,8 +850,8 @@ static int get_encoded_char_adv(const char_u **p) /// @return error message, NULL if it's OK. char *set_chars_option(win_T *wp, char **varp, bool apply) { - const char_u *last_multispace = NULL; // Last occurrence of "multispace:" - const char_u *last_lmultispace = NULL; // Last occurrence of "leadmultispace:" + const char *last_multispace = NULL; // Last occurrence of "multispace:" + const char *last_lmultispace = NULL; // Last occurrence of "leadmultispace:" int multispace_len = 0; // Length of lcs-multispace string int lead_multispace_len = 0; // Length of lcs-leadmultispace string const bool is_listchars = (varp == &p_lcs || varp == &wp->w_p_lcs); @@ -898,18 +898,18 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) struct chars_tab *tab; int entries; - const char_u *value = (char_u *)(*varp); + const char *value = *varp; if (is_listchars) { tab = lcs_tab; entries = ARRAY_SIZE(lcs_tab); if (varp == &wp->w_p_lcs && wp->w_p_lcs[0] == NUL) { - value = (char_u *)p_lcs; // local value is empty, use the global value + value = p_lcs; // local value is empty, use the global value } } else { tab = fcs_tab; entries = ARRAY_SIZE(fcs_tab); if (varp == &wp->w_p_fcs && wp->w_p_fcs[0] == NUL) { - value = (char_u *)p_fcs; // local value is empty, use the global value + value = p_fcs; // local value is empty, use the global value } } @@ -944,7 +944,7 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) } } } - const char *p = (char *)value; + const char *p = value; while (*p) { int i; for (i = 0; i < entries; i++) { @@ -999,7 +999,7 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) const char_u *s = (char_u *)p + len + 1; if (round == 0) { // Get length of lcs-multispace string in the first round - last_multispace = (char_u *)p; + last_multispace = p; multispace_len = 0; while (*s != NUL && *s != ',') { int c1 = get_encoded_char_adv(&s); @@ -1017,7 +1017,7 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) int multispace_pos = 0; while (*s != NUL && *s != ',') { int c1 = get_encoded_char_adv(&s); - if (p == (char *)last_multispace) { + if (p == last_multispace) { wp->w_p_lcs_chars.multispace[multispace_pos++] = c1; } } @@ -1030,7 +1030,7 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) const char_u *s = (char_u *)p + len2 + 1; if (round == 0) { // get length of lcs-leadmultispace string in first round - last_lmultispace = (char_u *)p; + last_lmultispace = p; lead_multispace_len = 0; while (*s != NUL && *s != ',') { int c1 = get_encoded_char_adv(&s); @@ -1048,7 +1048,7 @@ char *set_chars_option(win_T *wp, char **varp, bool apply) int multispace_pos = 0; while (*s != NUL && *s != ',') { int c1 = get_encoded_char_adv(&s); - if (p == (char *)last_lmultispace) { + if (p == last_lmultispace) { wp->w_p_lcs_chars.leadmultispace[multispace_pos++] = c1; } } diff --git a/src/nvim/search.c b/src/nvim/search.c index 4cfbab8dba..871d2f9a0a 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -114,7 +114,7 @@ static char *mr_pattern = NULL; // been searched already. typedef struct SearchedFile { FILE *fp; // File pointer - char_u *name; // Full name of file + char *name; // Full name of file linenr_T lnum; // Line we were up to in file int matched; // Found a match in this file } SearchedFile; @@ -189,7 +189,7 @@ int search_regcomp(char_u *pat, char_u **used_pat, int pat_save, int pat_use, in } } - regmatch->rmm_ic = ignorecase(pat); + regmatch->rmm_ic = ignorecase((char *)pat); regmatch->rmm_maxcol = 0; regmatch->regprog = vim_regcomp((char *)pat, magic ? RE_MAGIC : 0); if (regmatch->regprog == NULL) { @@ -353,19 +353,19 @@ char_u *last_search_pattern(void) /// Return true when case should be ignored for search pattern "pat". /// Uses the 'ignorecase' and 'smartcase' options. -int ignorecase(char_u *pat) +int ignorecase(char *pat) { return ignorecase_opt(pat, p_ic, p_scs); } /// As ignorecase() put pass the "ic" and "scs" flags. -int ignorecase_opt(char_u *pat, int ic_in, int scs) +int ignorecase_opt(char *pat, int ic_in, int scs) { int ic = ic_in; if (ic && !no_smartcase && scs && !(ctrl_x_mode_not_default() && curbuf->b_p_inf)) { - ic = !pat_has_uppercase(pat); + ic = !pat_has_uppercase((char_u *)pat); } no_smartcase = false; @@ -376,17 +376,17 @@ int ignorecase_opt(char_u *pat, int ic_in, int scs) bool pat_has_uppercase(char_u *pat) FUNC_ATTR_NONNULL_ALL { - char_u *p = pat; + char *p = (char *)pat; magic_T magic_val = MAGIC_ON; // get the magicness of the pattern (void)skip_regexp_ex((char *)pat, NUL, magic_isset(), NULL, NULL, &magic_val); while (*p != NUL) { - const int l = utfc_ptr2len((char *)p); + const int l = utfc_ptr2len(p); if (l > 1) { - if (mb_isupper(utf_ptr2char((char *)p))) { + if (mb_isupper(utf_ptr2char(p))) { return true; } p += l; @@ -406,7 +406,7 @@ bool pat_has_uppercase(char_u *pat) } else { p++; } - } else if (mb_isupper(*p)) { + } else if (mb_isupper((uint8_t)(*p))) { return true; } else { p++; @@ -1028,7 +1028,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char *pat, long count, i long c; char *dircp; char *strcopy = NULL; - char_u *ps; + char *ps; char *msgbuf = NULL; size_t len; bool has_offset = false; @@ -1102,9 +1102,9 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char *pat, long count, i if (pat != NULL && *pat != NUL) { // look for (new) offset // Find end of regular expression. // If there is a matching '/' or '?', toss it. - ps = (char_u *)strcopy; + ps = strcopy; p = skip_regexp_ex(pat, search_delim, magic_isset(), &strcopy, NULL, NULL); - if (strcopy != (char *)ps) { + if (strcopy != ps) { // made a copy of "pat" to change "\?" to "?" searchcmdlen += (int)(strlen(pat) - strlen(strcopy)); pat = strcopy; @@ -1603,16 +1603,16 @@ pos_T *findmatch(oparg_T *oap, int initc) // Update "*prevcol" to the column of the previous character, unless "prevcol" // is NULL. // Handles multibyte string correctly. -static bool check_prevcol(char_u *linep, int col, int ch, int *prevcol) +static bool check_prevcol(char *linep, int col, int ch, int *prevcol) { col--; if (col > 0) { - col -= utf_head_off((char *)linep, (char *)linep + col); + col -= utf_head_off(linep, linep + col); } if (prevcol) { *prevcol = col; } - return col >= 0 && linep[col] == ch; + return col >= 0 && (uint8_t)linep[col] == ch; } /// Raw string start is found at linep[startpos.col - 1]. @@ -1839,7 +1839,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // Set "match_escaped" if there are an odd number of // backslashes. - for (col = pos.col; check_prevcol((char_u *)linep, col, '\\', &col);) { + for (col = pos.col; check_prevcol(linep, col, '\\', &col);) { bslcnt++; } match_escaped = (bslcnt & 1); @@ -2192,8 +2192,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) if (curbuf->b_p_lisp && vim_strchr("(){}[]", c) != NULL && pos.col > 1 - && check_prevcol((char_u *)linep, pos.col, '\\', NULL) - && check_prevcol((char_u *)linep, pos.col - 1, '#', NULL)) { + && check_prevcol(linep, pos.col, '\\', NULL) + && check_prevcol(linep, pos.col - 1, '#', NULL)) { break; } @@ -2204,7 +2204,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) int col, bslcnt = 0; if (!cpo_bsl) { - for (col = pos.col; check_prevcol((char_u *)linep, col, '\\', &col);) { + for (col = pos.col; check_prevcol(linep, col, '\\', &col);) { bslcnt++; } } @@ -2298,19 +2298,19 @@ void showmatch(int c) long save_siso; int save_state; colnr_T save_dollar_vcol; - char_u *p; + char *p; // Only show match for chars in the 'matchpairs' option. // 'matchpairs' is "x:y,x:y" - for (p = (char_u *)curbuf->b_p_mps; *p != NUL; p++) { - if (utf_ptr2char((char *)p) == c && (curwin->w_p_rl ^ p_ri)) { + for (p = curbuf->b_p_mps; *p != NUL; p++) { + if (utf_ptr2char(p) == c && (curwin->w_p_rl ^ p_ri)) { break; } - p += utfc_ptr2len((char *)p) + 1; - if (utf_ptr2char((char *)p) == c && !(curwin->w_p_rl ^ p_ri)) { + p += utfc_ptr2len(p) + 1; + if (utf_ptr2char(p) == c && !(curwin->w_p_rl ^ p_ri)) { break; } - p += utfc_ptr2len((char *)p); + p += utfc_ptr2len(p); if (*p == NUL) { return; } @@ -2407,8 +2407,7 @@ int current_search(long count, bool forward) } // Is the pattern is zero-width?, this time, don't care about the direction - int zero_width = is_zero_width((char_u *)spats[last_idx].pat, true, &curwin->w_cursor, - FORWARD); + int zero_width = is_zero_width(spats[last_idx].pat, true, &curwin->w_cursor, FORWARD); if (zero_width == -1) { return FAIL; // pattern not found } @@ -2515,7 +2514,7 @@ int current_search(long count, bool forward) /// else from position "cur". /// "direction" is FORWARD or BACKWARD. /// Returns true, false or -1 for failure. -static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) +static int is_zero_width(char *pattern, int move, pos_T *cur, Direction direction) { regmmatch_T regmatch; int nmatched = 0; @@ -2525,10 +2524,10 @@ static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direct int flag = 0; if (pattern == NULL) { - pattern = (char_u *)spats[last_idx].pat; + pattern = spats[last_idx].pat; } - if (search_regcomp(pattern, NULL, RE_SEARCH, RE_SEARCH, + if (search_regcomp((char_u *)pattern, NULL, RE_SEARCH, RE_SEARCH, SEARCH_KEEP, ®match) == FAIL) { return -1; } @@ -2543,7 +2542,7 @@ static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direct // accept a match at the cursor position flag = SEARCH_START; } - if (searchit(curwin, curbuf, &pos, NULL, direction, pattern, 1, + if (searchit(curwin, curbuf, &pos, NULL, direction, (char_u *)pattern, 1, SEARCH_KEEP + flag, RE_SEARCH, NULL) != FAIL) { // Zero-width pattern should match somewhere, then we can check if // start and end are in the same position. @@ -2574,9 +2573,9 @@ static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direct /// return true if line 'lnum' is empty or has white chars only. int linewhite(linenr_T lnum) { - char_u *p; + char *p; - p = (char_u *)skipwhite(ml_get(lnum)); + p = skipwhite(ml_get(lnum)); return *p == NUL; } @@ -2753,7 +2752,7 @@ static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchst void f_searchcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { pos_T pos = curwin->w_cursor; - char_u *pattern = NULL; + char *pattern = NULL; int maxcount = SEARCH_STAT_DEF_MAX_COUNT; long timeout = SEARCH_STAT_DEF_TIMEOUT; bool recompute = true; @@ -2797,9 +2796,9 @@ void f_searchcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) return; } } - di = tv_dict_find(dict, (const char *)"pattern", -1); + di = tv_dict_find(dict, "pattern", -1); if (di != NULL) { - pattern = (char_u *)tv_get_string_chk(&di->di_tv); + pattern = (char *)tv_get_string_chk(&di->di_tv); if (pattern == NULL) { return; } @@ -2845,7 +2844,7 @@ void f_searchcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) goto the_end; } xfree(spats[last_idx].pat); - spats[last_idx].pat = xstrdup((char *)pattern); + spats[last_idx].pat = xstrdup(pattern); } if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) { goto the_end; // the previous pattern was never defined @@ -2944,7 +2943,7 @@ typedef struct { /// Compute a score for a fuzzy matched string. The matching character locations /// are in 'matches'. -static int fuzzy_match_compute_score(const char_u *const str, const int strSz, +static int fuzzy_match_compute_score(const char *const str, const int strSz, const uint32_t *const matches, const int numMatches) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE { @@ -2981,14 +2980,14 @@ static int fuzzy_match_compute_score(const char_u *const str, const int strSz, // Check for bonuses based on neighbor character value if (currIdx > 0) { // Camel case - const char_u *p = str; + const char *p = str; int neighbor = ' '; for (uint32_t sidx = 0; sidx < currIdx; sidx++) { - neighbor = utf_ptr2char((char *)p); + neighbor = utf_ptr2char(p); MB_PTR_ADV(p); } - const int curr = utf_ptr2char((char *)p); + const int curr = utf_ptr2char(p); if (mb_islower(neighbor) && mb_isupper(curr)) { score += CAMEL_BONUS; @@ -3010,11 +3009,10 @@ static int fuzzy_match_compute_score(const char_u *const str, const int strSz, /// Perform a recursive search for fuzzy matching 'fuzpat' in 'str'. /// @return the number of matching characters. -static int fuzzy_match_recursive(const char_u *fuzpat, const char_u *str, uint32_t strIdx, - int *const outScore, const char_u *const strBegin, - const int strLen, const uint32_t *const srcMatches, - uint32_t *const matches, const int maxMatches, int nextMatch, - int *const recursionCount) +static int fuzzy_match_recursive(const char *fuzpat, const char *str, uint32_t strIdx, + int *const outScore, const char *const strBegin, const int strLen, + const uint32_t *const srcMatches, uint32_t *const matches, + const int maxMatches, int nextMatch, int *const recursionCount) FUNC_ATTR_NONNULL_ARG(1, 2, 4, 5, 8, 11) FUNC_ATTR_WARN_UNUSED_RESULT { // Recursion params @@ -3055,7 +3053,7 @@ static int fuzzy_match_recursive(const char_u *fuzpat, const char_u *str, uint32 // Recursive call that "skips" this match uint32_t recursiveMatches[MAX_FUZZY_MATCHES]; int recursiveScore = 0; - const char_u *const next_char = str + utfc_ptr2len((char *)str); + const char *const next_char = (char *)str + utfc_ptr2len((char *)str); if (fuzzy_match_recursive(fuzpat, next_char, strIdx + 1, &recursiveScore, strBegin, strLen, matches, recursiveMatches, sizeof(recursiveMatches) / sizeof(recursiveMatches[0]), nextMatch, @@ -3115,15 +3113,15 @@ bool fuzzy_match(char_u *const str, const char_u *const pat_arg, const bool matc int *const outScore, uint32_t *const matches, const int maxMatches) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { - const int len = mb_charlen(str); + const int len = mb_charlen((char *)str); bool complete = false; int numMatches = 0; *outScore = 0; - char_u *const save_pat = (char_u *)xstrdup((char *)pat_arg); - char_u *pat = save_pat; - char_u *p = pat; + char *const save_pat = xstrdup((char *)pat_arg); + char *pat = save_pat; + char *p = pat; // Try matching each word in 'pat_arg' in 'str' while (true) { @@ -3131,12 +3129,12 @@ bool fuzzy_match(char_u *const str, const char_u *const pat_arg, const bool matc complete = true; } else { // Extract one word from the pattern (separated by space) - p = (char_u *)skipwhite((char *)p); + p = skipwhite(p); if (*p == NUL) { break; } pat = p; - while (*p != NUL && !ascii_iswhite(utf_ptr2char((char *)p))) { + while (*p != NUL && !ascii_iswhite(utf_ptr2char(p))) { MB_PTR_ADV(p); } if (*p == NUL) { // processed all the words @@ -3148,7 +3146,8 @@ bool fuzzy_match(char_u *const str, const char_u *const pat_arg, const bool matc int score = 0; int recursionCount = 0; const int matchCount - = fuzzy_match_recursive(pat, str, 0, &score, str, len, NULL, matches + numMatches, + = fuzzy_match_recursive(pat, (char *)str, 0, &score, (char *)str, len, NULL, + matches + numMatches, maxMatches - numMatches, 0, &recursionCount); if (matchCount == 0) { numMatches = 0; @@ -3193,8 +3192,8 @@ static int fuzzy_match_item_compare(const void *const s1, const void *const s2) /// for each item or use 'item_cb' Funcref function to get the string. /// If 'retmatchpos' is true, then return a list of positions where 'str' /// matches for each item. -static void fuzzy_match_in_list(list_T *const l, char_u *const str, const bool matchseq, - const char_u *const key, Callback *const item_cb, +static void fuzzy_match_in_list(list_T *const l, char *const str, const bool matchseq, + const char *const key, Callback *const item_cb, const bool retmatchpos, list_T *const fmatchlist, const long max_matches) FUNC_ATTR_NONNULL_ARG(2, 5, 7) @@ -3217,17 +3216,17 @@ static void fuzzy_match_in_list(list_T *const l, char_u *const str, const bool m break; } - char_u *itemstr = NULL; + char *itemstr = NULL; typval_T rettv; rettv.v_type = VAR_UNKNOWN; const typval_T *const tv = TV_LIST_ITEM_TV(li); if (tv->v_type == VAR_STRING) { // list of strings - itemstr = (char_u *)tv->vval.v_string; + itemstr = tv->vval.v_string; } else if (tv->v_type == VAR_DICT && (key != NULL || item_cb->type != kCallbackNone)) { // For a dict, either use the specified key to lookup the string or // use the specified callback function to get the string. if (key != NULL) { - itemstr = (char_u *)tv_dict_get_string(tv->vval.v_dict, (const char *)key, false); + itemstr = tv_dict_get_string(tv->vval.v_dict, (const char *)key, false); } else { typval_T argv[2]; @@ -3238,7 +3237,7 @@ static void fuzzy_match_in_list(list_T *const l, char_u *const str, const bool m argv[1].v_type = VAR_UNKNOWN; if (callback_call(item_cb, 1, argv, &rettv)) { if (rettv.v_type == VAR_STRING) { - itemstr = (char_u *)rettv.vval.v_string; + itemstr = rettv.vval.v_string; } } tv_dict_unref(tv->vval.v_dict); @@ -3246,7 +3245,7 @@ static void fuzzy_match_in_list(list_T *const l, char_u *const str, const bool m } int score; - if (itemstr != NULL && fuzzy_match(itemstr, str, matchseq, &score, matches, + if (itemstr != NULL && fuzzy_match((char_u *)itemstr, (char_u *)str, matchseq, &score, matches, MAX_FUZZY_MATCHES)) { items[match_count].idx = (int)match_count; items[match_count].item = li; @@ -3257,9 +3256,9 @@ static void fuzzy_match_in_list(list_T *const l, char_u *const str, const bool m if (retmatchpos) { items[match_count].lmatchpos = tv_list_alloc(kListLenMayKnow); int j = 0; - const char_u *p = str; + const char *p = (char *)str; while (*p != NUL) { - if (!ascii_iswhite(utf_ptr2char((char *)p)) || matchseq) { + if (!ascii_iswhite(utf_ptr2char(p)) || matchseq) { tv_list_append_number(items[match_count].lmatchpos, matches[j]); j++; } @@ -3344,7 +3343,7 @@ static void do_fuzzymatch(const typval_T *const argvars, typval_T *const rettv, } Callback cb = CALLBACK_NONE; - const char_u *key = NULL; + const char *key = NULL; bool matchseq = false; long max_matches = 0; if (argvars[2].v_type != VAR_UNKNOWN) { @@ -3363,7 +3362,7 @@ static void do_fuzzymatch(const typval_T *const argvars, typval_T *const rettv, semsg(_(e_invarg2), tv_get_string(&di->di_tv)); return; } - key = (const char_u *)tv_get_string(&di->di_tv); + key = tv_get_string(&di->di_tv); } else if (!tv_dict_get_callback(d, "text_cb", -1, &cb)) { semsg(_(e_invargval), "text_cb"); return; @@ -3394,7 +3393,8 @@ static void do_fuzzymatch(const typval_T *const argvars, typval_T *const rettv, tv_list_append_list(rettv->vval.v_list, tv_list_alloc(kListLenUnknown)); } - fuzzy_match_in_list(argvars[0].vval.v_list, (char_u *)tv_get_string(&argvars[1]), matchseq, key, + fuzzy_match_in_list(argvars[0].vval.v_list, + (char *)tv_get_string(&argvars[1]), matchseq, key, &cb, retmatchpos, rettv->vval.v_list, max_matches); callback_free(&cb); } @@ -3441,16 +3441,16 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool int max_path_depth = 50; long match_count = 1; - char_u *pat; - char_u *new_fname; - char_u *curr_fname = (char_u *)curbuf->b_fname; - char_u *prev_fname = NULL; + char *pat; + char *new_fname; + char *curr_fname = curbuf->b_fname; + char *prev_fname = NULL; linenr_T lnum; int depth; int depth_displayed; // For type==CHECK_PATH int old_files; int already_searched; - char_u *file_line; + char *file_line; char *line; char *p; char save_char; @@ -3480,10 +3480,10 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool size_t patlen = len + 5; pat = xmalloc(patlen); assert(len <= INT_MAX); - snprintf((char *)pat, patlen, whole ? "\\<%.*s\\>" : "%.*s", (int)len, ptr); + snprintf(pat, patlen, whole ? "\\<%.*s\\>" : "%.*s", (int)len, ptr); // ignore case according to p_ic, p_scs and pat regmatch.rm_ic = ignorecase(pat); - regmatch.regprog = vim_regcomp((char *)pat, magic_isset() ? RE_MAGIC : 0); + regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0); xfree(pat); if (regmatch.regprog == NULL) { goto fpip_end; @@ -3517,25 +3517,26 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool if (lnum > end_lnum) { // do at least one line lnum = end_lnum; } - line = get_line_and_copy(lnum, (char *)file_line); + line = get_line_and_copy(lnum, file_line); for (;;) { if (incl_regmatch.regprog != NULL && vim_regexec(&incl_regmatch, line, (colnr_T)0)) { - char_u *p_fname = (curr_fname == (char_u *)curbuf->b_fname) - ? (char_u *)curbuf->b_ffname : curr_fname; + char *p_fname = (curr_fname == curbuf->b_fname) + ? curbuf->b_ffname : curr_fname; if (inc_opt != NULL && strstr(inc_opt, "\\zs") != NULL) { // Use text from '\zs' to '\ze' (or end) of 'include'. - new_fname = (char_u *)find_file_name_in_path(incl_regmatch.startp[0], - (size_t)(incl_regmatch.endp[0] - - incl_regmatch.startp[0]), - FNAME_EXP|FNAME_INCL|FNAME_REL, - 1L, (char *)p_fname); + new_fname = find_file_name_in_path(incl_regmatch.startp[0], + (size_t)(incl_regmatch.endp[0] + - incl_regmatch.startp[0]), + FNAME_EXP|FNAME_INCL|FNAME_REL, + 1L, p_fname); } else { // Use text after match with 'include'. - new_fname = file_name_in_line((char_u *)incl_regmatch.endp[0], 0, - FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); + new_fname = (char *)file_name_in_line((char_u *)incl_regmatch.endp[0], 0, + FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, (char_u *)p_fname, + NULL); } already_searched = false; if (new_fname != NULL) { @@ -3547,14 +3548,14 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool if (i == max_path_depth) { break; } - if (path_full_compare((char *)new_fname, (char *)files[i].name, true, + if (path_full_compare(new_fname, files[i].name, true, true) & kEqualFiles) { if (type != CHECK_PATH && action == ACTION_SHOW_ALL && files[i].matched) { msg_putchar('\n'); // cursor below last one */ if (!got_int) { // don't display if 'q' typed at "--more--" // message - msg_home_replace_hl((char *)new_fname); + msg_home_replace_hl(new_fname); msg_puts(_(" (includes previously listed match)")); prev_fname = NULL; } @@ -3584,7 +3585,7 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool for (i = 0; i < depth_displayed; i++) { msg_puts(" "); } - msg_home_replace((char *)files[depth_displayed].name); + msg_home_replace(files[depth_displayed].name); msg_puts(" -->\n"); } if (!got_int) { // don't display if 'q' typed @@ -3595,7 +3596,7 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool if (new_fname != NULL) { // using "new_fname" is more reliable, e.g., when // 'includeexpr' is set. - msg_outtrans_attr((char *)new_fname, HL_ATTR(HLF_D)); + msg_outtrans_attr(new_fname, HL_ATTR(HLF_D)); } else { // Isolate the file name. // Include the surrounding "" or <> if present. @@ -3664,7 +3665,7 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool xfree(files); files = bigger; } - if ((files[depth + 1].fp = os_fopen((char *)new_fname, "r")) == NULL) { + if ((files[depth + 1].fp = os_fopen(new_fname, "r")) == NULL) { xfree(new_fname); } else { if (++depth == old_files) { @@ -3680,12 +3681,11 @@ void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool msg_hist_off = true; // reset in msg_trunc_attr() vim_snprintf(IObuff, IOSIZE, _("Scanning included file: %s"), - (char *)new_fname); + new_fname); msg_trunc_attr(IObuff, true, HL_ATTR(HLF_R)); } else if (p_verbose >= 5) { verbose_enter(); - smsg(_("Searching included file %s"), - (char *)new_fname); + smsg(_("Searching included file %s"), new_fname); verbose_leave(); } } @@ -3778,9 +3778,9 @@ search_line: if (vim_iswordp(p)) { goto exit_matched; } - p = (char *)find_word_start((char_u *)p); + p = find_word_start(p); } - p = (char *)find_word_end((char_u *)p); + p = find_word_end(p); i = (int)(p - aux); if (compl_status_adding() && i == ins_compl_len()) { @@ -3794,8 +3794,8 @@ search_line: if (lnum >= end_lnum) { goto exit_matched; } - line = get_line_and_copy(++lnum, (char *)file_line); - } else if (vim_fgets(line = (char *)file_line, + line = get_line_and_copy(++lnum, file_line); + } else if (vim_fgets(line = file_line, LSIZE, files[depth].fp)) { goto exit_matched; } @@ -3804,8 +3804,8 @@ search_line: // if depth >= 0 we'll increase files[depth].lnum far // below -- Acevedo already = aux = p = skipwhite(line); - p = (char *)find_word_start((char_u *)p); - p = (char *)find_word_end((char_u *)p); + p = find_word_start(p); + p = find_word_end(p); if (p > aux) { if (*aux != ')' && IObuff[i - 1] != TAB) { if (IObuff[i - 1] != ' ') { @@ -3835,8 +3835,8 @@ search_line: } } - const int add_r = ins_compl_add_infercase((char_u *)aux, i, p_ic, - curr_fname == (char_u *)curbuf->b_fname + const int add_r = ins_compl_add_infercase(aux, i, p_ic, + curr_fname == curbuf->b_fname ? NULL : curr_fname, dir, cont_s_ipos); if (add_r == OK) { @@ -3856,7 +3856,7 @@ search_line: } if (!got_int) { // don't display if 'q' typed // at "--more--" message - msg_home_replace_hl((char *)curr_fname); + msg_home_replace_hl(curr_fname); } prev_fname = curr_fname; } @@ -3958,13 +3958,13 @@ exit_matched: // end-of-file, close the file and continue in the file that included // it. while (depth >= 0 && !already - && vim_fgets(line = (char *)file_line, LSIZE, files[depth].fp)) { + && vim_fgets(line = file_line, LSIZE, files[depth].fp)) { fclose(files[depth].fp); old_files--; files[old_files].name = files[depth].name; files[old_files].matched = files[depth].matched; depth--; - curr_fname = (depth == -1) ? (char_u *)curbuf->b_fname + curr_fname = (depth == -1) ? curbuf->b_fname : files[depth].name; if (depth < depth_displayed) { depth_displayed = depth; @@ -3984,7 +3984,7 @@ exit_matched: if (++lnum > end_lnum) { break; } - line = get_line_and_copy(lnum, (char *)file_line); + line = get_line_and_copy(lnum, file_line); } already = NULL; } diff --git a/src/nvim/shada.c b/src/nvim/shada.c index 8c17d8d8be..754139a147 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -1341,7 +1341,7 @@ static void shada_read(ShaDaReadDef *const sd_reader, const int flags) case kSDItemBufferList: for (size_t i = 0; i < cur_entry.data.buffer_list.size; i++) { char *const sfname = - (char *)path_try_shorten_fname((char_u *)cur_entry.data.buffer_list.buffers[i].fname); + path_try_shorten_fname(cur_entry.data.buffer_list.buffers[i].fname); buf_T *const buf = buflist_new(cur_entry.data.buffer_list.buffers[i].fname, sfname, 0, BLN_LISTED); if (buf != NULL) { diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 10abd16ca7..48aed9c6de 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -2415,7 +2415,7 @@ bool spell_iswordp(const char_u *p, const win_T *wp) int c = utf_ptr2char((char *)s); if (c > 255) { - return spell_mb_isword_class(mb_get_class(s), wp); + return spell_mb_isword_class(mb_get_class((char *)s), wp); } return spelltab.st_isw[c]; } @@ -2426,7 +2426,7 @@ bool spell_iswordp_nmw(const char_u *p, win_T *wp) { int c = utf_ptr2char((char *)p); if (c > 255) { - return spell_mb_isword_class(mb_get_class(p), wp); + return spell_mb_isword_class(mb_get_class((char *)p), wp); } return spelltab.st_isw[c]; } @@ -3421,7 +3421,7 @@ static void dump_word(slang_T *slang, char *word, char *pat, Direction *dir, int } else if (((dumpflags & DUMPFLAG_ICASE) ? mb_strnicmp(p, pat, strlen(pat)) == 0 : strncmp(p, pat, strlen(pat)) == 0) - && ins_compl_add_infercase((char_u *)p, (int)strlen(p), + && ins_compl_add_infercase(p, (int)strlen(p), p_ic, NULL, *dir, false) == OK) { // if dir was BACKWARD then honor it just once *dir = FORWARD; @@ -3584,11 +3584,11 @@ void spell_expand_check_cap(colnr_T col) // Used for Insert mode completion CTRL-X ?. // Returns the number of matches. The matches are in "matchp[]", array of // allocated strings. -int expand_spelling(linenr_T lnum, char_u *pat, char ***matchp) +int expand_spelling(linenr_T lnum, char *pat, char ***matchp) { garray_T ga; - spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, true); + spell_suggest_list(&ga, (char_u *)pat, 100, spell_expand_need_cap, true); *matchp = ga.ga_data; return ga.ga_len; } diff --git a/src/nvim/spell_defs.h b/src/nvim/spell_defs.h index 265e4b2819..4d146a1706 100644 --- a/src/nvim/spell_defs.h +++ b/src/nvim/spell_defs.h @@ -218,8 +218,7 @@ typedef struct { // the "w" library function for characters above 255. #define SPELL_TOFOLD(c) ((c) >= 128 ? utf_fold(c) : (int)spelltab.st_fold[c]) -#define SPELL_TOUPPER(c) ((c) >= 128 ? mb_toupper(c) \ - : (int)spelltab.st_upper[c]) +#define SPELL_TOUPPER(c) ((c) >= 128 ? mb_toupper(c) : (int)spelltab.st_upper[c]) #define SPELL_ISUPPER(c) ((c) >= 128 ? mb_isupper(c) : spelltab.st_isu[c]) diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 5b99d0767c..e6257aeca1 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -575,7 +575,7 @@ static inline int spell_check_magic_string(FILE *const fd) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE { char buf[VIMSPELLMAGICL]; - SPELL_READ_BYTES(buf, VIMSPELLMAGICL, fd,; ); + SPELL_READ_BYTES(buf, VIMSPELLMAGICL, fd,; ); // NOLINT(whitespace/parens) if (memcmp(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0) { return SP_FORMERROR; } @@ -1054,7 +1054,7 @@ static int read_region_section(FILE *fd, slang_T *lp, int len) if (len > MAXREGIONS * 2) { return SP_FORMERROR; } - SPELL_READ_NONNUL_BYTES((char *)lp->sl_regions, (size_t)len, fd,; ); + SPELL_READ_NONNUL_BYTES((char *)lp->sl_regions, (size_t)len, fd,; ); // NOLINT(whitespace/parens) lp->sl_regions[len] = NUL; return 0; } @@ -1121,7 +1121,7 @@ static int read_prefcond_section(FILE *fd, slang_T *lp) if (n > 0) { char buf[MAXWLEN + 1]; buf[0] = '^'; // always match at one position only - SPELL_READ_NONNUL_BYTES(buf + 1, (size_t)n, fd,; ); + SPELL_READ_NONNUL_BYTES(buf + 1, (size_t)n, fd,; ); // NOLINT(whitespace/parens) buf[n + 1] = NUL; lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC | RE_STRING); } @@ -1144,7 +1144,7 @@ static int read_rep_section(FILE *fd, garray_T *gap, int16_t *first) ga_grow(gap, cnt); // <rep> : <repfromlen> <repfrom> <reptolen> <repto> - for (; gap->ga_len < cnt; ++gap->ga_len) { + for (; gap->ga_len < cnt; gap->ga_len++) { int c; ftp = &((fromto_T *)gap->ga_data)[gap->ga_len]; ftp->ft_from = (char *)read_cnt_string(fd, 1, &c); @@ -1275,7 +1275,7 @@ static int read_sal_section(FILE *fd, slang_T *slang) // convert the multi-byte strings to wide char strings smp->sm_lead_w = mb_str2wide(smp->sm_lead); - smp->sm_leadlen = mb_charlen(smp->sm_lead); + smp->sm_leadlen = mb_charlen((char *)smp->sm_lead); if (smp->sm_oneof == NULL) { smp->sm_oneof_w = NULL; } else { @@ -1664,7 +1664,7 @@ static int *mb_str2wide(char_u *s) { int i = 0; - int *res = xmalloc(((size_t)mb_charlen(s) + 1) * sizeof(int)); + int *res = xmalloc(((size_t)mb_charlen((char *)s) + 1) * sizeof(int)); for (char_u *p = s; *p != NUL;) { res[i++] = mb_ptr2char_adv((const char_u **)&p); } @@ -2478,8 +2478,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) // Don't use an affix entry with non-ASCII characters when // "spin->si_ascii" is true. - if (!spin->si_ascii || !(has_non_ascii((char_u *)aff_entry->ae_chop) - || has_non_ascii((char_u *)aff_entry->ae_add))) { + if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop) + || has_non_ascii(aff_entry->ae_add))) { aff_entry->ae_next = cur_aff->ah_first; cur_aff->ah_first = aff_entry; @@ -2875,7 +2875,7 @@ static unsigned get_affitem(int flagtype, char_u **pp) if (flagtype == AFT_NUM) { if (!ascii_isdigit(**pp)) { - ++*pp; // always advance, avoid getting stuck + (*pp)++; // always advance, avoid getting stuck return 0; } res = getdigits_int((char **)pp, true, 0); @@ -3197,7 +3197,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) } // Skip non-ASCII words when "spin->si_ascii" is true. - if (spin->si_ascii && has_non_ascii(w)) { + if (spin->si_ascii && has_non_ascii((char *)w)) { non_ascii++; xfree(pc); continue; @@ -3493,7 +3493,7 @@ static int store_aff_word(spellinfo_T *spin, char *word, char_u *afflist, afffil p = (char_u *)word; if (ae->ae_chop != NULL) { // Skip chop string. - i = mb_charlen((char_u *)ae->ae_chop); + i = mb_charlen(ae->ae_chop); for (; i > 0; i--) { MB_PTR_ADV(p); } @@ -3505,7 +3505,7 @@ static int store_aff_word(spellinfo_T *spin, char *word, char_u *afflist, afffil if (ae->ae_chop != NULL) { // Remove chop string. p = (char_u *)newword + strlen(newword); - i = mb_charlen((char_u *)ae->ae_chop); + i = mb_charlen(ae->ae_chop); for (; i > 0; i--) { MB_PTR_BACK(newword, p); } @@ -3817,7 +3817,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) } // Skip non-ASCII words when "spin->si_ascii" is true. - if (spin->si_ascii && has_non_ascii((char_u *)line)) { + if (spin->si_ascii && has_non_ascii(line)) { non_ascii++; continue; } @@ -5641,7 +5641,7 @@ void spell_add_word(char *word, int len, SpellAddType what, int idx, bool undo) // file. We may need to create the "spell" directory first. We // already checked the runtime directory is writable in // init_spellfile(). - if (!dir_of_file_exists((char_u *)fname) + if (!dir_of_file_exists(fname) && (p = (char_u *)path_tail_with_sep(fname)) != (char_u *)fname) { int c = *p; diff --git a/src/nvim/spellsuggest.c b/src/nvim/spellsuggest.c index 2768a89d6c..9db7efb03b 100644 --- a/src/nvim/spellsuggest.c +++ b/src/nvim/spellsuggest.c @@ -483,6 +483,11 @@ void spell_suggest(int count) } badlen++; end_visual_mode(); + // make sure we don't include the NUL at the end of the line + line = get_cursor_line_ptr(); + if (badlen > (int)strlen(line) - (int)curwin->w_cursor.col) { + badlen = (int)strlen(line) - (int)curwin->w_cursor.col; + } // Find the start of the badly spelled word. } else if (spell_move_to(curwin, FORWARD, true, true, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { @@ -1386,7 +1391,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char *fword, bool soun // For multi-byte chars check character length against // COMPOUNDMIN. if (slang->sl_compminlen > 0 - && mb_charlen((char_u *)tword + sp->ts_splitoff) + && mb_charlen(tword + sp->ts_splitoff) < slang->sl_compminlen) { break; } @@ -1582,7 +1587,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char *fword, bool soun && sp->ts_twordlen - sp->ts_splitoff >= slang->sl_compminlen && (slang->sl_compminlen == 0 - || mb_charlen((char_u *)tword + sp->ts_splitoff) + || mb_charlen(tword + sp->ts_splitoff) >= slang->sl_compminlen) && (slang->sl_compsylmax < MAXWLEN || sp->ts_complen + 1 - sp->ts_compsplit diff --git a/src/nvim/statusline.c b/src/nvim/statusline.c index 6857bef810..db3e3f91bf 100644 --- a/src/nvim/statusline.c +++ b/src/nvim/statusline.c @@ -944,6 +944,7 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, char *opt_n char *usefmt = fmt; const int save_must_redraw = must_redraw; const int save_redr_type = curwin->w_redr_type; + const bool save_KeyTyped = KeyTyped; // TODO(Bram): find out why using called_emsg_before makes tests fail, does it // matter? // const int called_emsg_before = called_emsg; @@ -1502,8 +1503,14 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, char *opt_n case STL_LINE: // Overload %l with v:lnum for 'statuscolumn' - num = opt_name != NULL && strcmp(opt_name, "statuscolumn") == 0 ? get_vim_var_nr(VV_LNUM) - : (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0L : (long)(wp->w_cursor.lnum); + if (opt_name != NULL && strcmp(opt_name, "statuscolumn") == 0) { + if (wp->w_p_nu) { + num = get_vim_var_nr(VV_LNUM); + } + } else { + num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0L : (long)(wp->w_cursor.lnum); + } + break; case STL_NUMLINES: @@ -1603,7 +1610,9 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, char *opt_n case STL_ROFLAG_ALT: // Overload %r with v:relnum for 'statuscolumn' if (opt_name != NULL && strcmp(opt_name, "statuscolumn") == 0) { - num = get_vim_var_nr(VV_RELNUM); + if (wp->w_p_rnu) { + num = get_vim_var_nr(VV_RELNUM); + } } else { itemisflag = true; if (wp->w_buffer->b_p_ro) { @@ -2141,5 +2150,8 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, char *opt_n set_string_option_direct(opt_name, -1, "", OPT_FREE | opt_scope, SID_ERROR); } + // A user function may reset KeyTyped, restore it. + KeyTyped = save_KeyTyped; + return width; } diff --git a/src/nvim/strings.c b/src/nvim/strings.c index a96134be8f..f0f9fbf51b 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -41,7 +41,7 @@ char *xstrnsave(const char *string, size_t len) // Same as vim_strsave(), but any characters found in esc_chars are preceded // by a backslash. -char_u *vim_strsave_escaped(const char_u *string, const char_u *esc_chars) +char *vim_strsave_escaped(const char *string, const char *esc_chars) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { return vim_strsave_escaped_ext(string, esc_chars, '\\', false); @@ -50,36 +50,36 @@ char_u *vim_strsave_escaped(const char_u *string, const char_u *esc_chars) // Same as vim_strsave_escaped(), but when "bsl" is true also escape // characters where rem_backslash() would remove the backslash. // Escape the characters with "cc". -char_u *vim_strsave_escaped_ext(const char_u *string, const char_u *esc_chars, char_u cc, bool bsl) +char *vim_strsave_escaped_ext(const char *string, const char *esc_chars, char cc, bool bsl) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { // First count the number of backslashes required. // Then allocate the memory and insert them. size_t length = 1; // count the trailing NUL - for (const char_u *p = string; *p; p++) { - const size_t l = (size_t)(utfc_ptr2len((char *)p)); + for (const char *p = string; *p; p++) { + const size_t l = (size_t)(utfc_ptr2len(p)); if (l > 1) { length += l; // count a multibyte char p += l - 1; continue; } - if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash((char *)p))) { + if (vim_strchr(esc_chars, (uint8_t)(*p)) != NULL || (bsl && rem_backslash(p))) { length++; // count a backslash } length++; // count an ordinary char } - char_u *escaped_string = xmalloc(length); - char_u *p2 = escaped_string; - for (const char_u *p = string; *p; p++) { - const size_t l = (size_t)(utfc_ptr2len((char *)p)); + char *escaped_string = xmalloc(length); + char *p2 = escaped_string; + for (const char *p = string; *p; p++) { + const size_t l = (size_t)(utfc_ptr2len(p)); if (l > 1) { memcpy(p2, p, l); p2 += l; p += l - 1; // skip multibyte char continue; } - if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash((char *)p))) { + if (vim_strchr(esc_chars, (uint8_t)(*p)) != NULL || (bsl && rem_backslash(p))) { *p2++ = cc; } *p2++ = *p; @@ -150,7 +150,7 @@ char *vim_strsave_shellescape(const char *string, bool do_special, bool do_newli FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { char *d; - char_u *escaped_string; + char *escaped_string; size_t l; int csh_like; bool fish_like; @@ -196,7 +196,7 @@ char *vim_strsave_shellescape(const char *string, bool do_special, bool do_newli // Allocate memory for the result and fill it. escaped_string = xmalloc(length); - d = (char *)escaped_string; + d = escaped_string; // add opening quote #ifdef MSWIN @@ -206,7 +206,7 @@ char *vim_strsave_shellescape(const char *string, bool do_special, bool do_newli #endif *d++ = '\''; - for (const char *p = (char *)string; *p != NUL;) { + for (const char *p = string; *p != NUL;) { #ifdef MSWIN if (!p_ssl) { if (*p == '"') { @@ -259,19 +259,19 @@ char *vim_strsave_shellescape(const char *string, bool do_special, bool do_newli *d++ = '\''; *d = NUL; - return (char *)escaped_string; + return escaped_string; } // Like vim_strsave(), but make all characters uppercase. // This uses ASCII lower-to-upper case translation, language independent. -char_u *vim_strsave_up(const char_u *string) +char *vim_strsave_up(const char *string) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { char *p1; - p1 = xstrdup((char *)string); + p1 = xstrdup(string); vim_strup((char_u *)p1); - return (char_u *)p1; + return p1; } /// Like xstrnsave(), but make all characters uppercase. @@ -452,14 +452,14 @@ void sort_strings(char **files, int count) // Return true if string "s" contains a non-ASCII character (128 or higher). // When "s" is NULL false is returned. -bool has_non_ascii(const char_u *s) +bool has_non_ascii(const char *s) FUNC_ATTR_PURE { - const char_u *p; + const char *p; if (s != NULL) { for (p = s; *p != NUL; p++) { - if (*p >= 128) { + if ((uint8_t)(*p) >= 128) { return true; } } @@ -946,18 +946,18 @@ int vim_vsnprintf_typval(char *str, size_t str_m, const char *fmt, va_list ap, t - str_arg); } if (fmt_spec == 'S') { - char_u *p1; + char *p1; size_t i; - for (i = 0, p1 = (char_u *)str_arg; *p1; p1 += utfc_ptr2len((char *)p1)) { - size_t cell = (size_t)utf_ptr2cells((char *)p1); + for (i = 0, p1 = (char *)str_arg; *p1; p1 += utfc_ptr2len(p1)) { + size_t cell = (size_t)utf_ptr2cells(p1); if (precision_specified && i + cell > precision) { break; } i += cell; } - str_arg_l = (size_t)(p1 - (char_u *)str_arg); + str_arg_l = (size_t)(p1 - str_arg); if (min_field_width != 0) { min_field_width += str_arg_l - i; } diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index 8ff93477f9..721cc7707a 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -4573,7 +4573,7 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con static int syn_scl_name2id(char *name) { // Avoid using stricmp() too much, it's slow on some systems - char *name_u = (char *)vim_strsave_up((char_u *)name); + char *name_u = vim_strsave_up(name); int i; for (i = curwin->w_s->b_syn_clusters.ga_len; --i >= 0;) { if (SYN_CLSTR(curwin->w_s)[i].scl_name_u != NULL @@ -4635,7 +4635,7 @@ static int syn_add_cluster(char *name) &curwin->w_s->b_syn_clusters); CLEAR_POINTER(scp); scp->scl_name = (char_u *)name; - scp->scl_name_u = (char *)vim_strsave_up((char_u *)name); + scp->scl_name_u = vim_strsave_up(name); scp->scl_list = NULL; if (STRICMP(name, "Spell") == 0) { @@ -5304,7 +5304,7 @@ void ex_ownsyntax(exarg_T *eap) } // Save value of b:current_syntax. - old_value = (char *)get_var_value("b:current_syntax"); + old_value = get_var_value("b:current_syntax"); if (old_value != NULL) { old_value = xstrdup(old_value); } @@ -5313,7 +5313,7 @@ void ex_ownsyntax(exarg_T *eap) apply_autocmds(EVENT_SYNTAX, eap->arg, curbuf->b_fname, true, curbuf); // Move value of b:current_syntax to w:current_syntax. - new_value = (char *)get_var_value("b:current_syntax"); + new_value = get_var_value("b:current_syntax"); if (new_value != NULL) { set_internal_string_var("w:current_syntax", new_value); } diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 825bd523bc..73aa6eb9ca 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -747,7 +747,7 @@ void do_tag(char *tag, int type, int count, int forceit, int verbose) set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); // Jump to the desired match. - i = jumpto_tag((char_u *)matches[cur_match], forceit, true); + i = jumpto_tag(matches[cur_match], forceit, true); set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); @@ -984,7 +984,7 @@ static int add_llist_tags(char *tag, int num_matches, char **matches) list_T *list; char tag_name[128 + 1]; char *fname; - char_u *cmd; + char *cmd; int i; char *p; tagptrs_T tagp; @@ -1071,7 +1071,7 @@ static int add_llist_tags(char *tag, int num_matches, char **matches) if (cmd_len > (CMDBUFFSIZE - 5)) { cmd_len = CMDBUFFSIZE - 5; } - snprintf((char *)cmd + len, (size_t)(CMDBUFFSIZE + 1 - len), + snprintf(cmd + len, (size_t)(CMDBUFFSIZE + 1 - len), "%.*s", cmd_len, cmd_start); len += cmd_len; @@ -1093,7 +1093,7 @@ static int add_llist_tags(char *tag, int num_matches, char **matches) tv_dict_add_str(dict, S_LEN("filename"), (const char *)fname); tv_dict_add_nr(dict, S_LEN("lnum"), lnum); if (lnum == 0) { - tv_dict_add_str(dict, S_LEN("pattern"), (const char *)cmd); + tv_dict_add_str(dict, S_LEN("pattern"), cmd); } } @@ -1162,12 +1162,12 @@ void do_tags(exarg_T *eap) // Compare two strings, for length "len", ignoring case the ASCII way. // return 0 for match, < 0 for smaller, > 0 for bigger // Make sure case is folded to uppercase in comparison (like for 'sort -f') -static int tag_strnicmp(char_u *s1, char_u *s2, size_t len) +static int tag_strnicmp(char *s1, char *s2, size_t len) { int i; while (len > 0) { - i = TOUPPER_ASC(*s1) - TOUPPER_ASC(*s2); + i = TOUPPER_ASC((uint8_t)(*s1)) - TOUPPER_ASC((uint8_t)(*s2)); if (i != 0) { return i; // this character different } @@ -1775,7 +1775,7 @@ static tagmatch_status_T findtags_parse_line(findtags_state_T *st, tagptrs_T *ta // Compare the current tag with the searched tag. if (margs->sortic) { - tagcmp = tag_strnicmp((char_u *)tagpp->tagname, (char_u *)st->orgpat->head, + tagcmp = tag_strnicmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen); } else { tagcmp = strncmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen); @@ -2018,7 +2018,7 @@ static void findtags_add_match(findtags_state_T *st, tagptrs_T *tagpp, findtags_ *tagpp->tagname_end = TAB; } else if (name_only) { if (st->get_searchpat) { - char_u *temp_end = (char_u *)tagpp->command; + char *temp_end = tagpp->command; if (*temp_end == '/') { while (*temp_end && *temp_end != '\r' @@ -2028,8 +2028,8 @@ static void findtags_add_match(findtags_state_T *st, tagptrs_T *tagpp, findtags_ } } - if (tagpp->command + 2 < (char *)temp_end) { - len = (size_t)(temp_end - (char_u *)tagpp->command - 2); + if (tagpp->command + 2 < temp_end) { + len = (size_t)(temp_end - tagpp->command - 2); mfp = xmalloc(len + 2); xstrlcpy(mfp, tagpp->command + 2, len + 1); } else { @@ -2358,10 +2358,10 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc p_ic = false; break; case TC_FOLLOWSCS: - p_ic = ignorecase((char_u *)pat); + p_ic = ignorecase(pat); break; case TC_SMART: - p_ic = ignorecase_opt((char_u *)pat, true, true); + p_ic = ignorecase_opt(pat, true, true); break; default: abort(); @@ -2491,7 +2491,7 @@ static void found_tagfile_cb(char *fname, void *cookie) #ifdef BACKSLASH_IN_FILENAME slash_adjust(tag_fname); #endif - simplify_filename((char_u *)tag_fname); + simplify_filename(tag_fname); GA_APPEND(char *, &tag_fnames, tag_fname); } @@ -2547,7 +2547,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) #ifdef BACKSLASH_IN_FILENAME slash_adjust(buf); #endif - simplify_filename((char_u *)buf); + simplify_filename(buf); for (int i = 0; i < tag_fnames.ga_len; i++) { if (strcmp(buf, ((char **)(tag_fnames.ga_data))[i]) == 0) { @@ -2593,7 +2593,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) buf[0] = NUL; (void)copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,"); - r_ptr = (char *)vim_findfile_stopdir((char_u *)buf); + r_ptr = (char *)vim_findfile_stopdir(buf); // move the filename one char forward and truncate the // filepath with a NUL filename = path_tail(buf); @@ -2807,7 +2807,7 @@ static char *tag_full_fname(tagptrs_T *tagp) /// @param keep_help keep help flag /// /// @return OK for success, NOTAGFILE when file not found, FAIL otherwise. -static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) +static int jumpto_tag(const char *lbuf_arg, int forceit, int keep_help) { bool save_p_ws; int save_p_scs, save_p_ic; @@ -2815,24 +2815,24 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) char *str; char *pbuf; // search pattern buffer char *pbuf_end; - char_u *tofree_fname = NULL; + char *tofree_fname = NULL; char *fname; tagptrs_T tagp; int retval = FAIL; int getfile_result = GETFILE_UNUSED; int search_options; win_T *curwin_save = NULL; - char_u *full_fname = NULL; + char *full_fname = NULL; const bool old_KeyTyped = KeyTyped; // getting the file may reset it const int l_g_do_tagpreview = g_do_tagpreview; - const size_t len = matching_line_len((char *)lbuf_arg) + 1; - char_u *lbuf = xmalloc(len); + const size_t len = matching_line_len(lbuf_arg) + 1; + char *lbuf = xmalloc(len); memmove(lbuf, lbuf_arg, len); pbuf = xmalloc(LSIZE); // parse the match line into the tagp structure - if (parse_match((char *)lbuf, &tagp) == FAIL) { + if (parse_match(lbuf, &tagp) == FAIL) { tagp.fname_end = NULL; goto erret; } @@ -2863,7 +2863,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) // Expand file name, when needed (for environment variables). // If 'tagrelative' option set, may change file name. fname = expand_tag_fname(fname, tagp.tag_fname, true); - tofree_fname = (char_u *)fname; // free() it later + tofree_fname = fname; // free() it later // Check if the file with the tag exists before abandoning the current // file. Also accept a file name for which there is a matching BufReadCmd @@ -2886,8 +2886,8 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) // entering it (autocommands) so turn the tag filename // into a fullpath if (!curwin->w_p_pvw) { - full_fname = (char_u *)FullName_save(fname, false); - fname = (char *)full_fname; + full_fname = FullName_save(fname, false); + fname = full_fname; // Make the preview window the current window. // Open a preview window when needed. @@ -3132,13 +3132,13 @@ static char *expand_tag_fname(char *fname, char *const tag_fname, const bool exp char *retval; if ((p_tr || curbuf->b_help) - && !vim_isAbsName((char_u *)fname) + && !vim_isAbsName(fname) && (p = path_tail(tag_fname)) != tag_fname) { retval = xmalloc(MAXPATHL); STRCPY(retval, tag_fname); xstrlcpy(retval + (p - tag_fname), fname, (size_t)(MAXPATHL - (p - tag_fname))); // Translate names like "src/a/../b/file.c" into "src/b/file.c". - simplify_filename((char_u *)retval); + simplify_filename(retval); } else { retval = xstrdup(fname); } diff --git a/src/nvim/testdir/check.vim b/src/nvim/testdir/check.vim index a188f7afa1..680a59006b 100644 --- a/src/nvim/testdir/check.vim +++ b/src/nvim/testdir/check.vim @@ -1,6 +1,8 @@ source shared.vim source term_util.vim +command -nargs=1 MissingFeature throw 'Skipped: ' .. <args> .. ' feature missing' + " Command to check for the presence of a feature. command -nargs=1 CheckFeature call CheckFeature(<f-args>) func CheckFeature(name) @@ -8,7 +10,7 @@ func CheckFeature(name) " throw 'Checking for non-existent feature ' .. a:name " endif if !has(a:name) - throw 'Skipped: ' .. a:name .. ' feature missing' + MissingFeature a:name endif endfunc diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index b9f32b2db9..a074263359 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -53,9 +53,13 @@ func Test_complete_list() set completeslash=backslash call feedkeys(":e Xtest\<Tab>\<C-B>\"\<CR>", 'xt') call assert_equal('"e Xtest\', @:) + call feedkeys(":e Xtest/\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest\a.', @:) set completeslash=slash call feedkeys(":e Xtest\<Tab>\<C-B>\"\<CR>", 'xt') call assert_equal('"e Xtest/', @:) + call feedkeys(":e Xtest\\\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest/a.', @:) set completeslash& endif @@ -139,6 +143,7 @@ func Test_complete_wildmenu() call assert_equal('"e Xtestfile3 Xtestfile4', @:) cd - + " test for wildmenumode() cnoremap <expr> <F2> wildmenumode() call feedkeys(":cd Xdir\<Tab>\<F2>\<C-B>\"\<CR>", 'tx') call assert_equal('"cd Xdir1/0', @:) @@ -146,14 +151,17 @@ func Test_complete_wildmenu() call assert_equal('"e Xdir1/Xdir2/1', @:) cunmap <F2> + " Test for canceling the wild menu by pressing <PageDown> or <PageUp>. + " After this pressing <Left> or <Right> should not change the selection. + call feedkeys(":sign \<Tab>\<PageDown>\<Left>\<Right>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define', @:) + call histadd('cmd', 'TestWildMenu') + call feedkeys(":sign \<Tab>\<PageUp>\<Left>\<Right>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"TestWildMenu', @:) + " cleanup %bwipe - call delete('Xdir1/Xdir2/Xtestfile4') - call delete('Xdir1/Xdir2/Xtestfile3') - call delete('Xdir1/Xtestfile2') - call delete('Xdir1/Xtestfile1') - call delete('Xdir1/Xdir2', 'd') - call delete('Xdir1', 'd') + call delete('Xdir1', 'rf') set nowildmenu endfunc @@ -1214,6 +1222,10 @@ func Test_cmdline_complete_various() call feedkeys(":e Xx\*\<Tab>\<C-B>\"\<CR>", 'xt') call assert_equal('"e Xx\*Yy', @:) call delete('Xx*Yy') + + " use a literal star + call feedkeys(":e \\*\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e \*', @:) endif call feedkeys(":py3f\<Tab>\<C-B>\"\<CR>", 'xt') @@ -2161,34 +2173,41 @@ endfunc func Test_wildmenu_dirstack() CheckUnix %bw! - call mkdir('Xdir1/dir2/dir3', 'p') + call mkdir('Xdir1/dir2/dir3/dir4', 'p') call writefile([], 'Xdir1/file1_1.txt') call writefile([], 'Xdir1/file1_2.txt') call writefile([], 'Xdir1/dir2/file2_1.txt') call writefile([], 'Xdir1/dir2/file2_2.txt') call writefile([], 'Xdir1/dir2/dir3/file3_1.txt') call writefile([], 'Xdir1/dir2/dir3/file3_2.txt') - cd Xdir1/dir2/dir3 + call writefile([], 'Xdir1/dir2/dir3/dir4/file4_1.txt') + call writefile([], 'Xdir1/dir2/dir3/dir4/file4_2.txt') set wildmenu + cd Xdir1/dir2/dir3/dir4 call feedkeys(":e \<Tab>\<C-B>\"\<CR>", 'xt') - call assert_equal('"e file3_1.txt', @:) + call assert_equal('"e file4_1.txt', @:) call feedkeys(":e \<Tab>\<Up>\<C-B>\"\<CR>", 'xt') - call assert_equal('"e ../dir3/', @:) + call assert_equal('"e ../dir4/', @:) call feedkeys(":e \<Tab>\<Up>\<Up>\<C-B>\"\<CR>", 'xt') - call assert_equal('"e ../../dir2/', @:) + call assert_equal('"e ../../dir3/', @:) + call feedkeys(":e \<Tab>\<Up>\<Up>\<Up>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../../../dir2/', @:) call feedkeys(":e \<Tab>\<Up>\<Up>\<Down>\<C-B>\"\<CR>", 'xt') - call assert_equal('"e ../../dir2/dir3/', @:) + call assert_equal('"e ../../dir3/dir4/', @:) call feedkeys(":e \<Tab>\<Up>\<Up>\<Down>\<Down>\<C-B>\"\<CR>", 'xt') - call assert_equal('"e ../../dir2/dir3/file3_1.txt', @:) - + call assert_equal('"e ../../dir3/dir4/file4_1.txt', @:) cd - + call feedkeys(":e Xdir1/\<Tab>\<Down>\<Down>\<Down>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xdir1/dir2/dir3/dir4/file4_1.txt', @:) + call delete('Xdir1', 'rf') set wildmenu& endfunc " Test for recalling newer or older cmdline from history with <Up>, <Down>, -" <S-Up>, <S-Down>, <PageUp>, <PageDown>, <C-p>, or <C-n>. +" <S-Up>, <S-Down>, <PageUp>, <PageDown>, <kPageUp>, <kPageDown>, <C-p>, or +" <C-n>. func Test_recalling_cmdline() CheckFeature cmdline_hist @@ -2196,17 +2215,18 @@ func Test_recalling_cmdline() cnoremap <Plug>(save-cmdline) <Cmd>let g:cmdlines += [getcmdline()]<CR> let histories = [ - \ {'name': 'cmd', 'enter': ':', 'exit': "\<Esc>"}, - \ {'name': 'search', 'enter': '/', 'exit': "\<Esc>"}, - \ {'name': 'expr', 'enter': ":\<C-r>=", 'exit': "\<Esc>\<Esc>"}, - \ {'name': 'input', 'enter': ":call input('')\<CR>", 'exit': "\<CR>"}, + \ #{name: 'cmd', enter: ':', exit: "\<Esc>"}, + \ #{name: 'search', enter: '/', exit: "\<Esc>"}, + \ #{name: 'expr', enter: ":\<C-r>=", exit: "\<Esc>\<Esc>"}, + \ #{name: 'input', enter: ":call input('')\<CR>", exit: "\<CR>"}, "\ TODO: {'name': 'debug', ...} \] let keypairs = [ - \ {'older': "\<Up>", 'newer': "\<Down>", 'prefixmatch': v:true}, - \ {'older': "\<S-Up>", 'newer': "\<S-Down>", 'prefixmatch': v:false}, - \ {'older': "\<PageUp>", 'newer': "\<PageDown>", 'prefixmatch': v:false}, - \ {'older': "\<C-p>", 'newer': "\<C-n>", 'prefixmatch': v:false}, + \ #{older: "\<Up>", newer: "\<Down>", prefixmatch: v:true}, + \ #{older: "\<S-Up>", newer: "\<S-Down>", prefixmatch: v:false}, + \ #{older: "\<PageUp>", newer: "\<PageDown>", prefixmatch: v:false}, + \ #{older: "\<kPageUp>", newer: "\<kPageDown>", prefixmatch: v:false}, + \ #{older: "\<C-p>", newer: "\<C-n>", prefixmatch: v:false}, \] let prefix = 'vi' for h in histories @@ -2299,39 +2319,63 @@ func Test_wildmenu_pum() set shm+=I set noruler set noshowcmd + + func CmdCompl(a, b, c) + return repeat(['aaaa'], 120) + endfunc + command -nargs=* -complete=customlist,CmdCompl Tcmd + + func MyStatusLine() abort + return 'status' + endfunc + func SetupStatusline() + set statusline=%!MyStatusLine() + set laststatus=2 + endfunc + + func MyTabLine() + return 'my tab line' + endfunc + func SetupTabline() + set statusline= + set tabline=%!MyTabLine() + set showtabline=2 + endfunc + + func DoFeedKeys() + let &wildcharm = char2nr("\t") + call feedkeys(":edit $VIMRUNTIME/\<Tab>\<Left>\<C-U>ab\<Tab>") + endfunc [CODE] call writefile(commands, 'Xtest') let buf = RunVimInTerminal('-S Xtest', #{rows: 10}) call term_sendkeys(buf, ":sign \<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_01', {}) + " going down the popup menu using <Down> call term_sendkeys(buf, "\<Down>\<Down>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_02', {}) + " going down the popup menu using <C-N> call term_sendkeys(buf, "\<C-N>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_03', {}) + " going up the popup menu using <C-P> call term_sendkeys(buf, "\<C-P>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_04', {}) + " going up the popup menu using <Up> call term_sendkeys(buf, "\<Up>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_05', {}) " pressing <C-E> should end completion and go back to the original match call term_sendkeys(buf, "\<C-E>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_06', {}) " pressing <C-Y> should select the current match and end completion call term_sendkeys(buf, "\<Tab>\<C-P>\<C-P>\<C-Y>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_07', {}) " With 'wildmode' set to 'longest,full', completing a match should display @@ -2339,31 +2383,25 @@ func Test_wildmenu_pum() call term_sendkeys(buf, ":\<C-U>set wildmode=longest,full\<CR>") call TermWait(buf) call term_sendkeys(buf, ":sign u\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_08', {}) " pressing <Tab> should display the wildmenu call term_sendkeys(buf, "\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_09', {}) " pressing <Tab> second time should select the next entry in the menu call term_sendkeys(buf, "\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_10', {}) call term_sendkeys(buf, ":\<C-U>set wildmode=full\<CR>") - " " showing popup menu in different columns in the cmdline + " showing popup menu in different columns in the cmdline call term_sendkeys(buf, ":sign define \<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_11', {}) call term_sendkeys(buf, " \<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_12', {}) call term_sendkeys(buf, " \<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_13', {}) " Directory name completion @@ -2373,95 +2411,77 @@ func Test_wildmenu_pum() call writefile([], 'Xdir/XdirA/XdirB/XfileC') call term_sendkeys(buf, "\<C-U>e Xdi\<Tab>\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_14', {}) " Pressing <Right> on a directory name should go into that directory call term_sendkeys(buf, "\<Right>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_15', {}) " Pressing <Left> on a directory name should go to the parent directory call term_sendkeys(buf, "\<Left>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_16', {}) " Pressing <C-A> when the popup menu is displayed should list all the - " matches and remove the popup menu + " matches but the popup menu should still remain call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-A>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_17', {}) " Pressing <C-D> when the popup menu is displayed should remove the popup " menu call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-D>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_18', {}) " Pressing <S-Tab> should open the popup menu with the last entry selected call term_sendkeys(buf, "\<C-U>\<CR>:sign \<S-Tab>\<C-P>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_19', {}) " Pressing <Esc> should close the popup menu and cancel the cmd line call term_sendkeys(buf, "\<C-U>\<CR>:sign \<Tab>\<Esc>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_20', {}) " Typing a character when the popup is open, should close the popup call term_sendkeys(buf, ":sign \<Tab>x") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_21', {}) " When the popup is open, entering the cmdline window should close the popup call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-F>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_22', {}) call term_sendkeys(buf, ":q\<CR>") " After the last popup menu item, <C-N> should show the original string call term_sendkeys(buf, ":sign u\<Tab>\<C-N>\<C-N>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_23', {}) " Use the popup menu for the command name call term_sendkeys(buf, "\<C-U>bu\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_24', {}) " Pressing the left arrow should remove the popup menu call term_sendkeys(buf, "\<Left>\<Left>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_25', {}) " Pressing <BS> should remove the popup menu and erase the last character call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<BS>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_26', {}) " Pressing <C-W> should remove the popup menu and erase the previous word call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-W>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_27', {}) " Pressing <C-U> should remove the popup menu and erase the entire line call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-U>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_28', {}) " Using <C-E> to cancel the popup menu and then pressing <Up> should recall " the cmdline from history call term_sendkeys(buf, "sign xyz\<Esc>:sign \<Tab>\<C-E>\<Up>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_29', {}) " Check "list" still works call term_sendkeys(buf, "\<C-U>set wildmode=longest,list\<CR>") call term_sendkeys(buf, ":cn\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_30', {}) call term_sendkeys(buf, "s") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_31', {}) " Tests a directory name contained full-width characters. @@ -2472,15 +2492,108 @@ func Test_wildmenu_pum() call term_sendkeys(buf, "\<C-U>set wildmode&\<CR>") call term_sendkeys(buf, ":\<C-U>e Xdir/あいう/\<Tab>") - call TermWait(buf) call VerifyScreenDump(buf, 'Test_wildmenu_pum_32', {}) + " Pressing <C-A> when the popup menu is displayed should list all the + " matches and pressing a key after that should remove the popup menu + call term_sendkeys(buf, "\<C-U>set wildmode=full\<CR>") + call term_sendkeys(buf, ":sign \<Tab>\<C-A>x") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_33', {}) + + " Pressing <C-A> when the popup menu is displayed should list all the + " matches and pressing <Left> after that should move the cursor + call term_sendkeys(buf, "\<C-U>abc\<Esc>") + call term_sendkeys(buf, ":sign \<Tab>\<C-A>\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_34', {}) + + " When <C-A> displays a lot of matches (screen scrolls), all the matches + " should be displayed correctly on the screen. + call term_sendkeys(buf, "\<End>\<C-U>Tcmd \<Tab>\<C-A>\<Left>\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_35', {}) + + " After using <C-A> to expand all the filename matches, pressing <Up> + " should not open the popup menu again. + call term_sendkeys(buf, "\<C-E>\<C-U>:cd Xdir/XdirA\<CR>") + call term_sendkeys(buf, ":e \<Tab>\<C-A>\<Up>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_36', {}) + call term_sendkeys(buf, "\<C-E>\<C-U>:cd -\<CR>") + + " After using <C-A> to expand all the matches, pressing <S-Tab> used to + " crash Vim + call term_sendkeys(buf, ":sign \<Tab>\<C-A>\<S-Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_37', {}) + + " After removing the pum the command line is redrawn + call term_sendkeys(buf, ":edit foo\<CR>") + call term_sendkeys(buf, ":edit bar\<CR>") + call term_sendkeys(buf, ":ls\<CR>") + call term_sendkeys(buf, ":com\<Tab> ") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_38', {}) + call term_sendkeys(buf, "\<C-U>\<CR>") + + " Esc still works to abort the command when 'statusline' is set + call term_sendkeys(buf, ":call SetupStatusline()\<CR>") + call term_sendkeys(buf, ":si\<Tab>") + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_39', {}) + + " Esc still works to abort the command when 'tabline' is set + call term_sendkeys(buf, ":call SetupTabline()\<CR>") + call term_sendkeys(buf, ":si\<Tab>") + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_40', {}) + + " popup is cleared also when 'lazyredraw' is set + call term_sendkeys(buf, ":set showtabline=1 laststatus=1 lazyredraw\<CR>") + call term_sendkeys(buf, ":call DoFeedKeys()\<CR>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_41', {}) + call term_sendkeys(buf, "\<Esc>") + + " Pressing <PageDown> should scroll the menu downward + call term_sendkeys(buf, ":sign \<Tab>\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_42', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_43', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_44', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_45', {}) + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<Down>\<Down>\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_46', {}) + + " Pressing <PageUp> should scroll the menu upward + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_47', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_48', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_49', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_50', {}) + call term_sendkeys(buf, "\<C-U>\<CR>") call StopVimInTerminal(buf) call delete('Xtest') call delete('Xdir', 'rf') endfunc +" Test for wildmenumode() with the cmdline popup menu +func Test_wildmenumode_with_pum() + set wildmenu + set wildoptions=pum + cnoremap <expr> <F2> wildmenumode() + call feedkeys(":sign \<Tab>\<F2>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define10', @:) + call feedkeys(":sign \<Tab>\<C-A>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define jump list place undefine unplace0', @:) + call feedkeys(":sign \<Tab>\<C-E>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign 0', @:) + call feedkeys(":sign \<Tab>\<C-Y>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define0', @:) + set nowildmenu wildoptions& + cunmap <F2> +endfunc + func Test_wildmenu_pum_clear_entries() CheckRunVimInTerminal @@ -2541,6 +2654,159 @@ func Test_cmdline_complete_dlist() call assert_equal("\"dlist 10 /pat/ | chistory", @:) endfunc +" Test for :breakadd argument completion +func Test_cmdline_complete_breakadd() + call feedkeys(":breakadd \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr file func here", @:) + call feedkeys(":breakadd \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr", @:) + call feedkeys(":breakadd \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr", @:) + call feedkeys(":breakadd he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here", @:) + call feedkeys(":breakadd he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here", @:) + call feedkeys(":breakadd abc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd abc", @:) + call assert_equal(['expr', 'file', 'func', 'here'], getcompletion('', 'breakpoint')) + let l = getcompletion('not', 'breakpoint') + call assert_equal([], l) + + " Test for :breakadd file [lnum] <file> + call writefile([], 'Xscript') + call feedkeys(":breakadd file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript", @:) + call feedkeys(":breakadd file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript", @:) + call feedkeys(":breakadd file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20 Xscript", @:) + call feedkeys(":breakadd file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20 Xscript", @:) + call feedkeys(":breakadd file 20x Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20x Xsc\t", @:) + call feedkeys(":breakadd file 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20\t", @:) + call feedkeys(":breakadd file 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20x\t", @:) + call feedkeys(":breakadd file Xscript \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript ", @:) + call feedkeys(":breakadd file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file X1B2C3", @:) + call delete('Xscript') + + " Test for :breakadd func [lnum] <function> + func Xbreak_func() + endfunc + call feedkeys(":breakadd func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func", @:) + call feedkeys(":breakadd func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func", @:) + call feedkeys(":breakadd func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20 Xbreak_func", @:) + call feedkeys(":breakadd func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20 Xbreak_func", @:) + call feedkeys(":breakadd func 20x Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20x Xbr\t", @:) + call feedkeys(":breakadd func 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20\t", @:) + call feedkeys(":breakadd func 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20x\t", @:) + call feedkeys(":breakadd func Xbreak_func \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func ", @:) + call feedkeys(":breakadd func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func X1B2C3", @:) + delfunc Xbreak_func + + " Test for :breakadd expr <expression> + let g:Xtest_var = 10 + call feedkeys(":breakadd expr Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var", @:) + call feedkeys(":breakadd expr Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var", @:) + call feedkeys(":breakadd expr Xtest_var \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var ", @:) + call feedkeys(":breakadd expr X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr X1B2C3", @:) + unlet g:Xtest_var + + " Test for :breakadd here + call feedkeys(":breakadd here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here Xtest", @:) + call feedkeys(":breakadd here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here Xtest", @:) + call feedkeys(":breakadd here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here ", @:) +endfunc + +" Test for :breakdel argument completion +func Test_cmdline_complete_breakdel() + call feedkeys(":breakdel \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file func here", @:) + call feedkeys(":breakdel \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file", @:) + call feedkeys(":breakdel \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file", @:) + call feedkeys(":breakdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here", @:) + call feedkeys(":breakdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here", @:) + call feedkeys(":breakdel abc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel abc", @:) + + " Test for :breakdel file [lnum] <file> + call writefile([], 'Xscript') + call feedkeys(":breakdel file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript", @:) + call feedkeys(":breakdel file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript", @:) + call feedkeys(":breakdel file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20 Xscript", @:) + call feedkeys(":breakdel file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20 Xscript", @:) + call feedkeys(":breakdel file 20x Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20x Xsc\t", @:) + call feedkeys(":breakdel file 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20\t", @:) + call feedkeys(":breakdel file 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20x\t", @:) + call feedkeys(":breakdel file Xscript \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript ", @:) + call feedkeys(":breakdel file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file X1B2C3", @:) + call delete('Xscript') + + " Test for :breakdel func [lnum] <function> + func Xbreak_func() + endfunc + call feedkeys(":breakdel func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func", @:) + call feedkeys(":breakdel func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func", @:) + call feedkeys(":breakdel func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20 Xbreak_func", @:) + call feedkeys(":breakdel func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20 Xbreak_func", @:) + call feedkeys(":breakdel func 20x Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20x Xbr\t", @:) + call feedkeys(":breakdel func 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20\t", @:) + call feedkeys(":breakdel func 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20x\t", @:) + call feedkeys(":breakdel func Xbreak_func \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func ", @:) + call feedkeys(":breakdel func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func X1B2C3", @:) + delfunc Xbreak_func + + " Test for :breakdel here + call feedkeys(":breakdel here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here Xtest", @:) + call feedkeys(":breakdel here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here Xtest", @:) + call feedkeys(":breakdel here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here ", @:) +endfunc + " this was going over the end of IObuff func Test_report_error_with_composing() let caught = 'no' diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index c17ac16a97..b065df68f7 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -91,7 +91,7 @@ let s:filename_checks = { \ 'blueprint': ['file.blp'], \ 'bsdl': ['file.bsd', 'file.bsdl'], \ 'bst': ['file.bst'], - \ 'bzl': ['file.bazel', 'file.bzl', 'WORKSPACE'], + \ 'bzl': ['file.bazel', 'file.bzl', 'WORKSPACE', 'WORKSPACE.bzlmod'], \ 'bzr': ['bzr_log.any', 'bzr_log.file'], \ 'c': ['enlightenment/file.cfg', 'file.qc', 'file.c', 'some-enlightenment/file.cfg'], \ 'cabal': ['file.cabal'], @@ -232,6 +232,7 @@ let s:filename_checks = { \ 'gnuplot': ['file.gpi', '.gnuplot'], \ 'go': ['file.go'], \ 'gomod': ['go.mod'], + \ 'gosum': ['go.sum'], \ 'gowork': ['go.work'], \ 'gp': ['file.gp', '.gprc'], \ 'gpg': ['/.gnupg/options', '/.gnupg/gpg.conf', '/usr/any/gnupg/options.skel', 'any/.gnupg/gpg.conf', 'any/.gnupg/options', 'any/usr/any/gnupg/options.skel'], @@ -525,9 +526,11 @@ let s:filename_checks = { \ 'slrnrc': ['.slrnrc'], \ 'slrnsc': ['file.score'], \ 'sm': ['sendmail.cf'], + \ 'smali': ['file.smali'], \ 'smarty': ['file.tpl'], \ 'smcl': ['file.hlp', 'file.ihlp', 'file.smcl'], \ 'smith': ['file.smt', 'file.smith'], + \ 'smithy': ['file.smithy'], \ 'sml': ['file.sml'], \ 'snobol4': ['file.sno', 'file.spt'], \ 'solidity': ['file.sol'], diff --git a/src/nvim/testdir/test_fold.vim b/src/nvim/testdir/test_fold.vim index f19e4c8253..130ad9c7e1 100644 --- a/src/nvim/testdir/test_fold.vim +++ b/src/nvim/testdir/test_fold.vim @@ -1475,4 +1475,12 @@ func Test_sort_closed_fold() bwipe! endfunc +func Test_indent_with_L_command() + " The "L" command moved the cursor to line zero, causing the text saved for + " undo to use line number -1, which caused trouble for undo later. + new + sil! norm 8R
V{zf8=Lu + bwipe! +endfunc + " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_profile.vim b/src/nvim/testdir/test_profile.vim index 4225b91bc4..9165f7bace 100644 --- a/src/nvim/testdir/test_profile.vim +++ b/src/nvim/testdir/test_profile.vim @@ -403,6 +403,47 @@ func Test_profile_completion() call feedkeys(":profile start test_prof\<C-A>\<C-B>\"\<CR>", 'tx') call assert_match('^"profile start.* test_profile\.vim', @:) + + call feedkeys(":profile file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_profile\.vim', @:) + call feedkeys(":profile file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_profile\.vim', @:) + call feedkeys(":profile file test_prof \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_prof ', @:) + call feedkeys(":profile file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file X1B2C3', @:) + + func Xprof_test() + endfunc + call feedkeys(":profile func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof_test', @:) + call feedkeys(":profile func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof_test', @:) + call feedkeys(":profile func Xprof \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof ', @:) + call feedkeys(":profile func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func X1B2C3', @:) + + call feedkeys(":profdel \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file func', @:) + call feedkeys(":profdel fu\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func', @:) + call feedkeys(":profdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel he', @:) + call feedkeys(":profdel here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel here ', @:) + call feedkeys(":profdel file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file test_profile.vim', @:) + call feedkeys(":profdel file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file X1B2C3', @:) + call feedkeys(":profdel func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func Xprof_test', @:) + call feedkeys(":profdel func Xprof_test \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func Xprof_test ', @:) + call feedkeys(":profdel func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func X1B2C3', @:) + + delfunc Xprof_test endfunc func Test_profile_errors() diff --git a/src/nvim/testdir/test_spell.vim b/src/nvim/testdir/test_spell.vim index a919156066..c840e834b9 100644 --- a/src/nvim/testdir/test_spell.vim +++ b/src/nvim/testdir/test_spell.vim @@ -531,8 +531,23 @@ func Test_spellsuggest_timeout() call assert_fails('set spellsuggest=timeout:--9', 'E474:') endfunc +func Test_spellsuggest_visual_end_of_line() + let enc_save = &encoding + " set encoding=iso8859 + + " This was reading beyond the end of the line. + norm R00000000000 + sil norm 0 + sil! norm i00000) + sil! norm i00000) + call feedkeys("\<CR>") + norm z= + + let &encoding = enc_save +endfunc + func Test_spellinfo() - throw 'skipped: Nvim does not support enc=latin1' + throw 'Skipped: Nvim does not support enc=latin1' new let runtime = substitute($VIMRUNTIME, '\\', '/', 'g') diff --git a/src/nvim/testdir/test_statusline.vim b/src/nvim/testdir/test_statusline.vim index 25ab1cf518..990c852ccd 100644 --- a/src/nvim/testdir/test_statusline.vim +++ b/src/nvim/testdir/test_statusline.vim @@ -569,22 +569,41 @@ func Test_statusline_showcmd() CheckScreendump let lines =<< trim END + func MyStatusLine() + return '%S' + endfunc + set laststatus=2 - set statusline=%S + set statusline=%!MyStatusLine() set showcmdloc=statusline call setline(1, ['a', 'b', 'c']) + set foldopen+=jump + 1,2fold + 3 END call writefile(lines, 'XTest_statusline', 'D') let buf = RunVimInTerminal('-S XTest_statusline', {'rows': 6}) - call feedkeys("\<C-V>Gl", "xt") + + call term_sendkeys(buf, "g") call VerifyScreenDump(buf, 'Test_statusline_showcmd_1', {}) - call feedkeys("\<Esc>1234", "xt") + " typing "gg" should open the fold + call term_sendkeys(buf, "g") call VerifyScreenDump(buf, 'Test_statusline_showcmd_2', {}) - call feedkeys("\<Esc>:set statusline=\<CR>:\<CR>1234", "xt") + call term_sendkeys(buf, "\<C-V>Gl") call VerifyScreenDump(buf, 'Test_statusline_showcmd_3', {}) + + call term_sendkeys(buf, "\<Esc>1234") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_4', {}) + + call term_sendkeys(buf, "\<Esc>:set statusline=\<CR>") + call term_sendkeys(buf, ":\<CR>") + call term_sendkeys(buf, "1234") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_5', {}) + + call StopVimInTerminal(buf) endfunc " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_tabline.vim b/src/nvim/testdir/test_tabline.vim index 20a9657f32..d9bef09067 100644 --- a/src/nvim/testdir/test_tabline.vim +++ b/src/nvim/testdir/test_tabline.vim @@ -167,19 +167,41 @@ func Test_tabline_showcmd() CheckScreendump let lines =<< trim END + func MyTabLine() + return '%S' + endfunc + set showtabline=2 + set tabline=%!MyTabLine() set showcmdloc=tabline call setline(1, ['a', 'b', 'c']) + set foldopen+=jump + 1,2fold + 3 END call writefile(lines, 'XTest_tabline', 'D') let buf = RunVimInTerminal('-S XTest_tabline', {'rows': 6}) - call feedkeys("\<C-V>Gl", "xt") + call term_sendkeys(buf, "g") call VerifyScreenDump(buf, 'Test_tabline_showcmd_1', {}) - call feedkeys("\<Esc>1234", "xt") + " typing "gg" should open the fold + call term_sendkeys(buf, "g") call VerifyScreenDump(buf, 'Test_tabline_showcmd_2', {}) + + call term_sendkeys(buf, "\<C-V>Gl") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_3', {}) + + call term_sendkeys(buf, "\<Esc>1234") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_4', {}) + + call term_sendkeys(buf, "\<Esc>:set tabline=\<CR>") + call term_sendkeys(buf, ":\<CR>") + call term_sendkeys(buf, "1234") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_5', {}) + + call StopVimInTerminal(buf) endfunc " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_usercommands.vim b/src/nvim/testdir/test_usercommands.vim index 3ae990e022..6910361345 100644 --- a/src/nvim/testdir/test_usercommands.vim +++ b/src/nvim/testdir/test_usercommands.vim @@ -354,6 +354,14 @@ func Test_CmdCompletion() call feedkeys(":com -complete=co\<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"com -complete=color command compiler', @:) + " try completion for unsupported argument values + call feedkeys(":com -newarg=\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"com -newarg=\t", @:) + + " command completion after the name in a user defined command + call feedkeys(":com MyCmd chist\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"com MyCmd chistory", @:) + command! DoCmd1 : command! DoCmd2 : call feedkeys(":com \<C-A>\<C-B>\"\<CR>", 'tx') @@ -365,6 +373,10 @@ func Test_CmdCompletion() call feedkeys(":delcom DoC\<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"delcom DoCmd1 DoCmd2', @:) + " try argument completion for a command without completion + call feedkeys(":DoCmd1 \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"DoCmd1 \t", @:) + delcom DoCmd1 call feedkeys(":delcom DoC\<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"delcom DoCmd2', @:) @@ -383,6 +395,21 @@ func Test_CmdCompletion() call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"DoCmd mswin xterm', @:) + " Test for file name completion + com! -nargs=1 -complete=file DoCmd : + call feedkeys(":DoCmd READM\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd README.txt', @:) + + " Test for buffer name completion + com! -nargs=1 -complete=buffer DoCmd : + let bnum = bufadd('BufForUserCmd') + call setbufvar(bnum, '&buflisted', 1) + call feedkeys(":DoCmd BufFor\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd BufForUserCmd', @:) + bwipe BufForUserCmd + call feedkeys(":DoCmd BufFor\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd BufFor', @:) + com! -nargs=* -complete=custom,CustomComplete DoCmd : call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"DoCmd January February Mars', @:) @@ -694,5 +721,30 @@ func Test_recursive_define() endwhile endfunc +" Test for using buffer-local ambiguous user-defined commands +func Test_buflocal_ambiguous_usercmd() + new + command -buffer -nargs=1 -complete=sign TestCmd1 echo "Hello" + command -buffer -nargs=1 -complete=sign TestCmd2 echo "World" + + call assert_fails("call feedkeys(':TestCmd\<CR>', 'xt')", 'E464:') + call feedkeys(":TestCmd \<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"TestCmd ', @:) + + delcommand TestCmd1 + delcommand TestCmd2 + bw! +endfunc + +" Test for using a multibyte character in a user command +func Test_multibyte_in_usercmd() + command SubJapanesePeriodToDot exe "%s/\u3002/./g" + new + call setline(1, "Hello\u3002") + SubJapanesePeriodToDot + call assert_equal('Hello.', getline(1)) + bw! + delcommand SubJapanesePeriodToDot +endfunc " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_utf8.vim b/src/nvim/testdir/test_utf8.vim index aa3b02b575..9146cf7ab3 100644 --- a/src/nvim/testdir/test_utf8.vim +++ b/src/nvim/testdir/test_utf8.vim @@ -2,6 +2,7 @@ source check.vim source view_util.vim +source screendump.vim " Visual block Insert adjusts for multi-byte char func Test_visual_block_insert() @@ -198,6 +199,22 @@ func Test_setcellwidths() call setcellwidths([]) endfunc +func Test_setcellwidths_dump() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, "\ue5ffDesktop") + END + call writefile(lines, 'XCellwidths', 'D') + let buf = RunVimInTerminal('-S XCellwidths', {'rows': 6}) + call VerifyScreenDump(buf, 'Test_setcellwidths_dump_1', {}) + + call term_sendkeys(buf, ":call setcellwidths([[0xe5ff, 0xe5ff, 2]])\<CR>") + call VerifyScreenDump(buf, 'Test_setcellwidths_dump_2', {}) + + call StopVimInTerminal(buf) +endfunc + func Test_print_overlong() " Text with more composing characters than MB_MAXBYTES. new diff --git a/src/nvim/testdir/test_visual.vim b/src/nvim/testdir/test_visual.vim index 712ea343ed..14d62089cf 100644 --- a/src/nvim/testdir/test_visual.vim +++ b/src/nvim/testdir/test_visual.vim @@ -1338,6 +1338,18 @@ func Test_visual_reselect_with_count() call delete('XvisualReselect') endfunc +func Test_visual_reselect_exclusive() + new + call setline(1, ['abcde', 'abcde']) + set selection=exclusive + normal 1G0viwd + normal 2G01vd + call assert_equal(['', ''], getline(1, 2)) + + set selection& + bwipe! +endfunc + func Test_visual_block_insert_round_off() new " The number of characters are tuned to fill a 4096 byte allocated block, diff --git a/src/nvim/testdir/test_window_cmd.vim b/src/nvim/testdir/test_window_cmd.vim index ab63506d3c..c25b1f1157 100644 --- a/src/nvim/testdir/test_window_cmd.vim +++ b/src/nvim/testdir/test_window_cmd.vim @@ -1761,6 +1761,8 @@ function Test_splitkeep_callback() call term_sendkeys(buf, ":quit\<CR>Gt") call VerifyScreenDump(buf, 'Test_splitkeep_callback_4', {}) + + call StopVimInTerminal(buf) endfunc function Test_splitkeep_fold() @@ -1791,6 +1793,8 @@ function Test_splitkeep_fold() call term_sendkeys(buf, ":wincmd k\<CR>:quit\<CR>") call VerifyScreenDump(buf, 'Test_splitkeep_fold_4', {}) + + call StopVimInTerminal(buf) endfunction function Test_splitkeep_status() @@ -1809,6 +1813,8 @@ function Test_splitkeep_status() call term_sendkeys(buf, ":call win_move_statusline(win, 1)\<CR>") call VerifyScreenDump(buf, 'Test_splitkeep_status_1', {}) + + call StopVimInTerminal(buf) endfunction function Test_new_help_window_on_error() diff --git a/src/nvim/testdir/test_writefile.vim b/src/nvim/testdir/test_writefile.vim index 6d27407f82..6019cee193 100644 --- a/src/nvim/testdir/test_writefile.vim +++ b/src/nvim/testdir/test_writefile.vim @@ -896,6 +896,9 @@ endfunc " link to the original file. The backup file should not be modified. func Test_write_backup_symlink() CheckUnix + call mkdir('Xbackup') + let save_backupdir = &backupdir + set backupdir=.,./Xbackup call writefile(['1111'], 'Xfile') silent !ln -s Xfile Xfile.bak @@ -904,11 +907,18 @@ func Test_write_backup_symlink() write call assert_equal('link', getftype('Xfile.bak')) call assert_equal('Xfile', resolve('Xfile.bak')) + " backup file should be created in the 'backup' directory + if !has('bsd') + " This check fails on FreeBSD + call assert_true(filereadable('./Xbackup/Xfile.bak')) + endif set backup& backupcopy& backupext& - close + %bw call delete('Xfile') call delete('Xfile.bak') + call delete('Xbackup', 'rf') + let &backupdir = save_backupdir endfunc " Test for ':write ++bin' and ':write ++nobin' diff --git a/src/nvim/textobject.c b/src/nvim/textobject.c index b9b4d0dfe3..ee6c39a8ba 100644 --- a/src/nvim/textobject.c +++ b/src/nvim/textobject.c @@ -237,9 +237,9 @@ bool findpar(bool *pincl, int dir, long count, int what, bool both) } /// check if the string 's' is a nroff macro that is in option 'opt' -static bool inmacro(char_u *opt, const char_u *s) +static bool inmacro(char *opt, const char *s) { - char_u *macro; + char *macro; for (macro = opt; macro[0]; macro++) { // Accept two characters in the option being equal to two characters @@ -266,14 +266,14 @@ static bool inmacro(char_u *opt, const char_u *s) /// If 'both' is true also stop at '}' bool startPS(linenr_T lnum, int para, bool both) { - char_u *s; + char *s; - s = (char_u *)ml_get(lnum); - if (*s == para || *s == '\f' || (both && *s == '}')) { + s = ml_get(lnum); + if ((uint8_t)(*s) == para || *s == '\f' || (both && *s == '}')) { return true; } - if (*s == '.' && (inmacro((char_u *)p_sections, s + 1) - || (!para && inmacro(p_para, s + 1)))) { + if (*s == '.' && (inmacro(p_sections, s + 1) + || (!para && inmacro((char *)p_para, s + 1)))) { return true; } return false; @@ -1040,8 +1040,8 @@ int current_block(oparg_T *oap, long count, bool include, int what, int other) /// @return true if the cursor is on a "<aaa>" tag. Ignore "<aaa/>". static bool in_html_tag(bool end_tag) { - char_u *line = (char_u *)get_cursor_line_ptr(); - char_u *p; + char *line = get_cursor_line_ptr(); + char *p; int c; int lc = NUL; pos_T pos; @@ -1097,8 +1097,8 @@ int current_tagblock(oparg_T *oap, long count_arg, bool include) pos_T start_pos; pos_T end_pos; pos_T old_start, old_end; - char_u *p; - char_u *cp; + char *p; + char *cp; int len; bool do_include = include; bool save_p_ws = p_ws; @@ -1165,7 +1165,7 @@ again: // Search for matching "</aaa>". First isolate the "aaa". inc_cursor(); - p = (char_u *)get_cursor_pos_ptr(); + p = get_cursor_pos_ptr(); for (cp = p; *cp != NUL && *cp != '>' && !ascii_iswhite(*cp); MB_PTR_ADV(cp)) {} @@ -1204,7 +1204,7 @@ again: } } } else { - char_u *c = (char_u *)get_cursor_pos_ptr(); + char *c = get_cursor_pos_ptr(); // Exclude the '<' of the end tag. // If the closing tag is on new line, do not decrement cursor, but make // operation exclusive, so that the linefeed will be selected @@ -1441,15 +1441,15 @@ extend: /// @param escape escape characters, can be NULL /// /// @return column number of "quotechar" or -1 when not found. -static int find_next_quote(char_u *line, int col, int quotechar, char_u *escape) +static int find_next_quote(char *line, int col, int quotechar, char *escape) { int c; for (;;) { - c = line[col]; + c = (uint8_t)line[col]; if (c == NUL) { return -1; - } else if (escape != NULL && vim_strchr((char *)escape, c)) { + } else if (escape != NULL && vim_strchr(escape, c)) { col++; if (line[col] == NUL) { return -1; @@ -1457,7 +1457,7 @@ static int find_next_quote(char_u *line, int col, int quotechar, char_u *escape) } else if (c == quotechar) { break; } - col += utfc_ptr2len((char *)line + col); + col += utfc_ptr2len(line + col); } return col; } @@ -1469,23 +1469,23 @@ static int find_next_quote(char_u *line, int col, int quotechar, char_u *escape) /// @param escape escape characters, can be NULL /// /// @return the found column or zero. -static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *escape) +static int find_prev_quote(char *line, int col_start, int quotechar, char *escape) { int n; while (col_start > 0) { col_start--; - col_start -= utf_head_off((char *)line, (char *)line + col_start); + col_start -= utf_head_off(line, line + col_start); n = 0; if (escape != NULL) { - while (col_start - n > 0 && vim_strchr((char *)escape, - line[col_start - n - 1]) != NULL) { + while (col_start - n > 0 && vim_strchr(escape, + (uint8_t)line[col_start - n - 1]) != NULL) { n++; } } if (n & 1) { col_start -= n; // uneven number of escape chars, skip it - } else if (line[col_start] == quotechar) { + } else if ((uint8_t)line[col_start] == quotechar) { break; } } @@ -1501,7 +1501,7 @@ static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *e bool current_quote(oparg_T *oap, long count, bool include, int quotechar) FUNC_ATTR_NONNULL_ALL { - char_u *line = (char_u *)get_cursor_line_ptr(); + char *line = get_cursor_line_ptr(); int col_end; int col_start = curwin->w_cursor.col; bool inclusive = false; @@ -1550,16 +1550,16 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) // quotes. if (vis_bef_curs) { inside_quotes = VIsual.col > 0 - && line[VIsual.col - 1] == quotechar + && (uint8_t)line[VIsual.col - 1] == quotechar && line[curwin->w_cursor.col] != NUL - && line[curwin->w_cursor.col + 1] == quotechar; + && (uint8_t)line[curwin->w_cursor.col + 1] == quotechar; i = VIsual.col; col_end = curwin->w_cursor.col; } else { inside_quotes = curwin->w_cursor.col > 0 - && line[curwin->w_cursor.col - 1] == quotechar + && (uint8_t)line[curwin->w_cursor.col - 1] == quotechar && line[VIsual.col] != NUL - && line[VIsual.col + 1] == quotechar; + && (uint8_t)line[VIsual.col + 1] == quotechar; i = curwin->w_cursor.col; col_end = VIsual.col; } @@ -1571,14 +1571,14 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) if (line[i] == NUL) { break; } - if (line[i++] == quotechar) { + if ((uint8_t)line[i++] == quotechar) { selected_quote = true; break; } } } - if (!vis_empty && line[col_start] == quotechar) { + if (!vis_empty && (uint8_t)line[col_start] == quotechar) { // Already selecting something and on a quote character. Find the // next quoted string. if (vis_bef_curs) { @@ -1588,7 +1588,7 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) if (col_start < 0) { goto abort_search; } - col_end = find_next_quote(line, col_start + 1, quotechar, (char_u *)curbuf->b_p_qe); + col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { // We were on a starting quote perhaps? col_end = col_start; @@ -1596,17 +1596,17 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) } } else { col_end = find_prev_quote(line, col_start, quotechar, NULL); - if (line[col_end] != quotechar) { + if ((uint8_t)line[col_end] != quotechar) { goto abort_search; } - col_start = find_prev_quote(line, col_end, quotechar, (char_u *)curbuf->b_p_qe); - if (line[col_start] != quotechar) { + col_start = find_prev_quote(line, col_end, quotechar, curbuf->b_p_qe); + if ((uint8_t)line[col_start] != quotechar) { // We were on an ending quote perhaps? col_start = col_end; col_end = curwin->w_cursor.col; } } - } else if (line[col_start] == quotechar || !vis_empty) { + } else if ((uint8_t)line[col_start] == quotechar || !vis_empty) { int first_col = col_start; if (!vis_empty) { @@ -1628,7 +1628,7 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) goto abort_search; } // Find close quote character. - col_end = find_next_quote(line, col_start + 1, quotechar, (char_u *)curbuf->b_p_qe); + col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { goto abort_search; } @@ -1641,8 +1641,8 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) } } else { // Search backward for a starting quote. - col_start = find_prev_quote(line, col_start, quotechar, (char_u *)curbuf->b_p_qe); - if (line[col_start] != quotechar) { + col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe); + if ((uint8_t)line[col_start] != quotechar) { // No quote before the cursor, look after the cursor. col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0) { @@ -1651,7 +1651,7 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) } // Find close quote character. - col_end = find_next_quote(line, col_start + 1, quotechar, (char_u *)curbuf->b_p_qe); + col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { goto abort_search; } @@ -1685,9 +1685,9 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) || (vis_bef_curs && !selected_quote && (inside_quotes - || (line[VIsual.col] != quotechar + || ((uint8_t)line[VIsual.col] != quotechar && (VIsual.col == 0 - || line[VIsual.col - 1] != quotechar))))) { + || (uint8_t)line[VIsual.col - 1] != quotechar))))) { VIsual = curwin->w_cursor; redraw_curbuf_later(UPD_INVERTED); } @@ -1715,9 +1715,9 @@ bool current_quote(oparg_T *oap, long count, bool include, int quotechar) // quote. if (inside_quotes || (!selected_quote - && line[VIsual.col] != quotechar + && (uint8_t)line[VIsual.col] != quotechar && (line[VIsual.col] == NUL - || line[VIsual.col + 1] != quotechar))) { + || (uint8_t)line[VIsual.col + 1] != quotechar))) { dec_cursor(); VIsual = curwin->w_cursor; } diff --git a/src/nvim/ui.c b/src/nvim/ui.c index 7775d98983..b25fa04c8b 100644 --- a/src/nvim/ui.c +++ b/src/nvim/ui.c @@ -292,34 +292,36 @@ void vim_beep(unsigned val) { called_vim_beep = true; - if (emsg_silent == 0 && !in_assert_fails) { - if (!((bo_flags & val) || (bo_flags & BO_ALL))) { - static int beeps = 0; - static uint64_t start_time = 0; - - // Only beep up to three times per half a second, - // otherwise a sequence of beeps would freeze Vim. - if (start_time == 0 || os_hrtime() - start_time > 500000000U) { - beeps = 0; - start_time = os_hrtime(); - } - beeps++; - if (beeps <= 3) { - if (p_vb) { - ui_call_visual_bell(); - } else { - ui_call_bell(); - } + if (emsg_silent != 0 || in_assert_fails) { + return; + } + + if (!((bo_flags & val) || (bo_flags & BO_ALL))) { + static int beeps = 0; + static uint64_t start_time = 0; + + // Only beep up to three times per half a second, + // otherwise a sequence of beeps would freeze Vim. + if (start_time == 0 || os_hrtime() - start_time > 500000000U) { + beeps = 0; + start_time = os_hrtime(); + } + beeps++; + if (beeps <= 3) { + if (p_vb) { + ui_call_visual_bell(); + } else { + ui_call_bell(); } } + } - // When 'debug' contains "beep" produce a message. If we are sourcing - // a script or executing a function give the user a hint where the beep - // comes from. - if (vim_strchr(p_debug, 'e') != NULL) { - msg_source(HL_ATTR(HLF_W)); - msg_attr(_("Beep!"), HL_ATTR(HLF_W)); - } + // When 'debug' contains "beep" produce a message. If we are sourcing + // a script or executing a function give the user a hint where the beep + // comes from. + if (vim_strchr(p_debug, 'e') != NULL) { + msg_source(HL_ATTR(HLF_W)); + msg_attr(_("Beep!"), HL_ATTR(HLF_W)); } } diff --git a/src/nvim/undo.c b/src/nvim/undo.c index c39e11f266..85e261fc39 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -573,7 +573,7 @@ int u_savecommon(buf_T *buf, linenr_T top, linenr_T bot, linenr_T newbot, int re } if (size > 0) { - uep->ue_array = xmalloc(sizeof(char_u *) * (size_t)size); + uep->ue_array = xmalloc(sizeof(char *) * (size_t)size); linenr_T lnum; long i; for (i = 0, lnum = top + 1; i < size; i++) { @@ -2322,7 +2322,7 @@ static void u_undoredo(int undo, bool do_buf_event) linenr_T lnum; for (lnum = bot - 1, i = oldsize; --i >= 0; lnum--) { // what can we do when we run out of memory? - newarray[i] = u_save_line(lnum); + newarray[i] = (char_u *)u_save_line(lnum); // remember we deleted the last line in the buffer, and a // dummy empty line will be inserted if (curbuf->b_ml.ml_line_count == 1) { @@ -2978,7 +2978,7 @@ void u_saveline(linenr_T lnum) } else { curbuf->b_u_line_colnr = 0; } - curbuf->b_u_line_ptr = (char *)u_save_line(lnum); + curbuf->b_u_line_ptr = u_save_line(lnum); } /// clear the line saved for the "U" command @@ -3009,7 +3009,7 @@ void u_undoline(void) return; } - char *oldp = (char *)u_save_line(curbuf->b_u_line_lnum); + char *oldp = u_save_line(curbuf->b_u_line_lnum); ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, true); changed_bytes(curbuf->b_u_line_lnum, 0); extmark_splice_cols(curbuf, (int)curbuf->b_u_line_lnum - 1, 0, (colnr_T)strlen(oldp), @@ -3043,9 +3043,9 @@ void u_blockfree(buf_T *buf) /// Allocate memory and copy curbuf line into it. /// /// @param lnum the line to copy -static char_u *u_save_line(linenr_T lnum) +static char *u_save_line(linenr_T lnum) { - return (char_u *)u_save_line_buf(curbuf, lnum); + return u_save_line_buf(curbuf, lnum); } /// Allocate memory and copy line into it diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index e175bd5b61..22e092781c 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -25,8 +25,10 @@ #include "nvim/keycodes.h" #include "nvim/lua/executor.h" #include "nvim/macros.h" +#include "nvim/mapping.h" #include "nvim/mbyte.h" #include "nvim/memory.h" +#include "nvim/menu.h" #include "nvim/message.h" #include "nvim/option_defs.h" #include "nvim/os/input.h" @@ -93,6 +95,7 @@ static const char *command_complete[] = { [EXPAND_TAGS_LISTFILES] = "tag_listfiles", [EXPAND_USER] = "user", [EXPAND_USER_VARS] = "var", + [EXPAND_BREAKPOINT] = "breakpoint", }; /// List of names of address types. Must be alphabetical for completion. @@ -220,6 +223,7 @@ char *find_ucmd(exarg_T *eap, char *p, int *full, expand_T *xp, int *complp) return p; } +/// Set completion context for :command const char *set_context_in_user_cmd(expand_T *xp, const char *arg_in) { const char *arg = arg_in; @@ -271,6 +275,47 @@ const char *set_context_in_user_cmd(expand_T *xp, const char *arg_in) return (const char *)skipwhite(p); } +/// Set the completion context for the argument of a user defined command. +const char *set_context_in_user_cmdarg(const char *cmd FUNC_ATTR_UNUSED, const char *arg, + uint32_t argt, int context, expand_T *xp, bool forceit) +{ + if (context == EXPAND_NOTHING) { + return NULL; + } + + if (argt & EX_XFILE) { + // EX_XFILE: file names are handled above. + xp->xp_context = context; + return NULL; + } + + if (context == EXPAND_MENUS) { + return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); + } + if (context == EXPAND_COMMANDS) { + return arg; + } + if (context == EXPAND_MAPPINGS) { + return (const char *)set_context_in_map_cmd(xp, "map", (char *)arg, forceit, false, false, + CMD_map); + } + // Find start of last argument. + const char *p = arg; + while (*p) { + if (*p == ' ') { + // argument starts after a space + arg = p + 1; + } else if (*p == '\\' && *(p + 1) != NUL) { + p++; // skip over escaped character + } + MB_PTR_ADV(p); + } + xp->xp_pattern = (char *)arg; + xp->xp_context = context; + + return NULL; +} + char *expand_user_command_name(int idx) { return get_user_commands(NULL, idx - CMD_SIZE); @@ -1608,10 +1653,10 @@ int do_ucmd(exarg_T *eap, bool preview) end = vim_strchr(start + 1, '>'); } if (buf != NULL) { - for (ksp = p; *ksp != NUL && (char_u)(*ksp) != K_SPECIAL; ksp++) {} - if ((char_u)(*ksp) == K_SPECIAL + for (ksp = p; *ksp != NUL && (uint8_t)(*ksp) != K_SPECIAL; ksp++) {} + if ((uint8_t)(*ksp) == K_SPECIAL && (start == NULL || ksp < start || end == NULL) - && ((char_u)ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)) { + && ((uint8_t)ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)) { // K_SPECIAL has been put in the buffer as K_SPECIAL // KS_SPECIAL KE_FILLER, like for mappings, but // do_cmdline() doesn't handle that, so convert it back. diff --git a/src/nvim/vim.h b/src/nvim/vim.h index c395eb438c..0ab9d96173 100644 --- a/src/nvim/vim.h +++ b/src/nvim/vim.h @@ -154,6 +154,7 @@ enum { EXPAND_MAPCLEAR, EXPAND_ARGLIST, EXPAND_DIFF_BUFFERS, + EXPAND_BREAKPOINT, EXPAND_CHECKHEALTH, EXPAND_LUA, }; diff --git a/src/nvim/window.c b/src/nvim/window.c index 37f297909a..2bcbef14b0 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -5780,6 +5780,10 @@ static void frame_setheight(frame_T *curfrp, int height) if (curfrp->fr_parent == NULL) { // topframe: can only change the command line height + // Avoid doing so with external messages. + if (ui_has(kUIMessages)) { + return; + } if (height > ROWS_AVAIL) { // If height is greater than the available space, try to create space for // the frame by reducing 'cmdheight' if possible, while making sure @@ -6115,13 +6119,13 @@ void win_setminwidth(void) /// Status line of dragwin is dragged "offset" lines down (negative is up). void win_drag_status_line(win_T *dragwin, int offset) { - // If the user explicitly set 'cmdheight' to zero, then allow for dragging - // the status line making it zero again. - if (p_ch == 0) { - p_ch_was_zero = true; + frame_T *fr = dragwin->w_frame; + + // Avoid changing command line height with external messages. + if (fr->fr_next == NULL && ui_has(kUIMessages)) { + return; } - frame_T *fr = dragwin->w_frame; frame_T *curfr = fr; if (fr != topframe) { // more than one window fr = fr->fr_parent; |