diff options
193 files changed, 5437 insertions, 5476 deletions
diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml index e1307b89d2..25f8414008 100644 --- a/.github/workflows/backport.yml +++ b/.github/workflows/backport.yml @@ -2,8 +2,13 @@ name: Backport on: pull_request_target: types: [closed, labeled] + issue_comment: + types: [created] jobs: backport: + permissions: + contents: write + pull-requests: write name: Backport Pull Request if: > github.repository_owner == 'neovim' && ( @@ -22,7 +27,7 @@ jobs: fetch-depth: 0 ref: ${{ github.event.pull_request.head.sha }} - name: Create backport PRs - uses: zeebe-io/backport-action@v0.0.6 + uses: zeebe-io/backport-action@v0.0.7 with: github_token: ${{ secrets.GITHUB_TOKEN }} github_workspace: ${{ github.workspace }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 968094a2a6..5bedafefd0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,9 @@ name: CI on: push: - branches: '**' + branches: + - 'master' + - 'release-[0-9]+.[0-9]+' pull_request: types: [opened, synchronize, reopened, ready_for_review] branches: @@ -33,11 +35,6 @@ jobs: - cc: clang runner: macos-11.0 os: osx - - flavor: functionaltest-lua - cc: gcc - runner: ubuntu-20.04 - os: linux - cmake: minimum_required runs-on: ${{ matrix.runner }} timeout-minutes: 45 if: github.event.pull_request.draft == false @@ -47,7 +44,7 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Setup commom environment variables + - name: Setup common environment variables run: ./.github/workflows/env.sh ${{ matrix.flavor }} - name: Install apt packages @@ -56,24 +53,6 @@ jobs: sudo apt-get update sudo apt-get install -y autoconf automake build-essential ccache cmake cpanminus cscope gcc-multilib gdb gettext gperf language-pack-tr libtool-bin locales ninja-build pkg-config python3 python3-pip python3-setuptools unzip valgrind xclip - - name: Install minimum required version of cmake - if: matrix.cmake == 'minimum_required' - env: - CMAKE_URL: 'https://cmake.org/files/v3.10/cmake-3.10.0-Linux-x86_64.sh' - CMAKE_VERSION: '3.10.0' - shell: bash - run: | - curl --retry 5 --silent --show-error --fail -o /tmp/cmake-installer.sh "$CMAKE_URL" - mkdir -p "$HOME/.local/bin" /opt/cmake-custom - chmod a+x /tmp/cmake-installer.sh - /tmp/cmake-installer.sh --prefix=/opt/cmake-custom --skip-license - ln -sfn /opt/cmake-custom/bin/cmake "$HOME/.local/bin/cmake" - cmake_version="$(cmake --version | head -1)" - echo "$cmake_version" | grep -qF "cmake version $CMAKE_VERSION" || { - echo "Unexpected CMake version: $cmake_version" - exit 1 - } - - name: Install new clang if: matrix.flavor == 'asan' || matrix.flavor == 'tsan' run: | @@ -138,3 +117,69 @@ jobs: run: powershell ci\build.ps1 env: CONFIGURATION: ${{ matrix.config }} + + functionaltest: + name: ${{ matrix.runner }} ${{ matrix.flavor }} (cc=${{ matrix.cc }}) + strategy: + fail-fast: false + matrix: + include: + - flavor: functionaltest-lua + cc: gcc + runner: ubuntu-20.04 + os: linux + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + env: + CC: ${{ matrix.cc }} + CI_OS_NAME: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + + - name: Setup commom environment variables + run: ./.github/workflows/env.sh ${{ matrix.flavor }} + + - name: Install apt packages + run: | + sudo apt-get update + sudo apt-get install -y autoconf automake build-essential ccache cmake cpanminus cscope gcc-multilib gdb gettext gperf language-pack-tr libtool-bin locales ninja-build pkg-config python3 python3-pip python3-setuptools unzip valgrind xclip + + - name: Install minimum required version of cmake + env: + CMAKE_URL: 'https://cmake.org/files/v3.10/cmake-3.10.0-Linux-x86_64.sh' + CMAKE_VERSION: '3.10.0' + shell: bash + run: | + curl --retry 5 --silent --show-error --fail -o /tmp/cmake-installer.sh "$CMAKE_URL" + mkdir -p "$HOME/.local/bin" /opt/cmake-custom + chmod a+x /tmp/cmake-installer.sh + /tmp/cmake-installer.sh --prefix=/opt/cmake-custom --skip-license + ln -sfn /opt/cmake-custom/bin/cmake "$HOME/.local/bin/cmake" + cmake_version="$(cmake --version | head -1)" + echo "$cmake_version" | grep -qF "cmake version $CMAKE_VERSION" || { + echo "Unexpected CMake version: $cmake_version" + exit 1 + } + + - name: Setup interpreter packages + run: | + ./ci/before_install.sh + ./ci/install.sh + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: | + ${{ env.CACHE_NVIM_DEPS_DIR }} + ~/.ccache + key: ${{ matrix.runner }}-${{ matrix.flavor }}-${{ matrix.cc }}-${{ hashFiles('cmake/*', 'third-party/**', '**/CMakeLists.txt') }}-${{ github.base_ref }} + + - name: Build third-party + run: ./ci/before_script.sh + + - name: Build and test + run: ./ci/script.sh + + - name: Cache dependencies + if: ${{ success() }} + run: ./ci/before_cache.sh diff --git a/.github/workflows/notes.md b/.github/workflows/notes.md new file mode 100644 index 0000000000..20f998ff32 --- /dev/null +++ b/.github/workflows/notes.md @@ -0,0 +1,41 @@ +``` +${NVIM_VERSION} +``` + +## Install + +### Windows + +1. Extract **nvim-win64.zip** (or **nvim-win32.zip**) +2. Run `nvim-qt.exe` + +### macOS + +1. Download **nvim-macos.tar.gz** +2. Extract: `tar xzvf nvim-macos.tar.gz` +3. Run `./nvim-osx64/bin/nvim` + +### Linux (x64) + +1. Download **nvim.appimage** +2. Run `chmod u+x nvim.appimage && ./nvim.appimage` + - If your system does not have FUSE you can [extract the appimage](https://github.com/AppImage/AppImageKit/wiki/FUSE#type-2-appimage): + ``` + ./nvim.appimage --appimage-extract + ./squashfs-root/usr/bin/nvim + ``` + +### Other + +- Install by [package manager](https://github.com/neovim/neovim/wiki/Installing-Neovim) + +## SHA256 Checksums + +``` +${SHA_LINUX_64} +${SHA_APP_IMAGE} +${SHA_APP_IMAGE_ZSYNC} +${SHA_MACOS} +${SHA_WIN_64} +${SHA_WIN_32} +``` diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c6d3eaf42b..9333449a6c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -145,10 +145,22 @@ jobs: publish: needs: [linux, appimage, macOS, windows] runs-on: ubuntu-20.04 + env: + GH_REPO: ${{ github.repository }} permissions: contents: write steps: + # Must perform checkout first, since it deletes the target directory + # before running, and would therefore delete the downloaded artifacts + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v2 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y gettext-base + - if: github.event_name == 'workflow_dispatch' run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV - if: github.event_name == 'schedule' @@ -158,16 +170,21 @@ jobs: TAG_NAME=${{ github.ref }} echo "TAG_NAME=${TAG_NAME#refs/tags/}" >> $GITHUB_ENV - if: env.TAG_NAME == 'nightly' - run: echo 'SUBJECT=Nvim development (prerelease) build' >> $GITHUB_ENV + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + (echo 'SUBJECT=Nvim development (prerelease) build'; + echo 'PRERELEASE=--prerelease') >> $GITHUB_ENV + gh release delete nightly --yes || true + git push origin :nightly || true - if: env.TAG_NAME != 'nightly' - run: echo 'SUBJECT=Nvim release build' >> $GITHUB_ENV - - if: env.TAG_NAME == 'nightly' - uses: dev-drprasad/delete-tag-and-release@v0.1.2 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - delete_release: true - tag_name: nightly + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + (echo 'SUBJECT=Nvim release build'; + echo 'PRERELEASE=') >> $GITHUB_ENV + gh release delete stable --yes || true + git push origin :stable || true # `sha256sum` outputs <sha> <path>, so we cd into each dir to drop the # containing folder from the output. - name: Generate Linux64 SHA256 checksums @@ -200,67 +217,13 @@ jobs: cd ./nvim-win64 sha256sum nvim-win64.zip > nvim-win64.zip.sha256sum echo "SHA_WIN_64=$(cat nvim-win64.zip.sha256sum)" >> $GITHUB_ENV - - uses: meeDamian/github-release@2.0 - with: - token: ${{ secrets.GITHUB_TOKEN }} - tag: ${{ env.TAG_NAME }} - name: ${{ needs.linux.outputs.release }} - prerelease: ${{ env.TAG_NAME == 'nightly' }} - commitish: ${{ github.sha }} - gzip: false - allow_override: ${{ env.TAG_NAME == 'nightly' }} - files: | - nvim-macos.tar.gz:./nvim-macos/nvim-macos.tar.gz - nvim-macos.tar.gz.sha256sum:./nvim-macos/nvim-macos.tar.gz.sha256sum - nvim-linux64.tar.gz:./nvim-linux64/nvim-linux64.tar.gz - nvim-linux64.tar.gz.sha256sum:./nvim-linux64/nvim-linux64.tar.gz.sha256sum - nvim.appimage:./appimage/nvim.appimage - nvim.appimage.sha256sum:./appimage/nvim.appimage.sha256sum - nvim.appimage.zsync:./appimage/nvim.appimage.zsync - nvim.appimage.zsync.sha256sum:./appimage/nvim.appimage.zsync.sha256sum - nvim-win32.zip:./nvim-win32/nvim-win32.zip - nvim-win32.zip.sha256sum:./nvim-win32/nvim-win32.zip.sha256sum - nvim-win64.zip:./nvim-win64/nvim-win64.zip - nvim-win64.zip.sha256sum:./nvim-win64/nvim-win64.zip.sha256sum - body: | - ${{ env.SUBJECT }} - ``` - ${{ needs.linux.outputs.version }}``` - - ## Install - - ### Windows - - 1. Extract **nvim-win64.zip** (or **nvim-win32.zip**) - 2. Run `nvim-qt.exe` - - ### macOS - - 1. Download **nvim-macos.tar.gz** - 2. Extract: `tar xzvf nvim-macos.tar.gz` - 3. Run `./nvim-osx64/bin/nvim` - - ### Linux (x64) - - 1. Download **nvim.appimage** - 2. Run `chmod u+x nvim.appimage && ./nvim.appimage` - - If your system does not have FUSE you can [extract the appimage](https://github.com/AppImage/AppImageKit/wiki/FUSE#type-2-appimage): - ``` - ./nvim.appimage --appimage-extract - ./squashfs-root/usr/bin/nvim - ``` - - ### Other - - - Install by [package manager](https://github.com/neovim/neovim/wiki/Installing-Neovim) - - ## SHA256 Checksums - - ``` - ${{ env.SHA_LINUX_64 }} - ${{ env.SHA_APP_IMAGE }} - ${{ env.SHA_APP_IMAGE_ZSYNC }} - ${{ env.SHA_MACOS }} - ${{ env.SHA_WIN_64 }} - ${{ env.SHA_WIN_32 }} - ``` + - name: Publish release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NVIM_VERSION: ${{ needs.linux.outputs.version }} + run: | + envsubst < "$GITHUB_WORKSPACE/.github/workflows/notes.md" > "$RUNNER_TEMP/notes.md" + gh release create $TAG_NAME $PRERELEASE --notes-file "$RUNNER_TEMP/notes.md" --title "$SUBJECT" --target $GITHUB_SHA nvim-macos/* nvim-linux64/* appimage/* nvim-win32/* nvim-win64/* + if [ "$TAG_NAME" != "nightly" ]; then + gh release create stable $PRERELEASE --notes-file "$RUNNER_TEMP/notes.md" --title "$SUBJECT" --target $GITHUB_SHA nvim-macos/* nvim-linux64/* appimage/* nvim-win32/* nvim-win64/* + fi diff --git a/ci/build.ps1 b/ci/build.ps1 index 8876ac31ef..a81d351bc6 100644 --- a/ci/build.ps1 +++ b/ci/build.ps1 @@ -170,6 +170,11 @@ if (-not $NoTests) { } } +# Ensure choco's cpack is not in PATH otherwise, it conflicts with CMake's +if (Test-Path -Path $env:ChocolateyInstall\bin\cpack.exe) { + Remove-Item -Path $env:ChocolateyInstall\bin\cpack.exe -Force +} + # Build artifacts cpack -G ZIP -C RelWithDebInfo if ($env:APPVEYOR_REPO_TAG_NAME -ne $null) { diff --git a/cmake/InstallHelpers.cmake b/cmake/InstallHelpers.cmake index bebc0d0d17..9d997260cd 100644 --- a/cmake/InstallHelpers.cmake +++ b/cmake/InstallHelpers.cmake @@ -154,3 +154,25 @@ function(install_helper) ${RENAME}) endif() endfunction() + +# Without CONFIGURE_DEPENDS globbing reuses cached file tree on rebuild. +# For example it will ignore new files. +# CONFIGURE_DEPENDS was introduced in 3.12 + +function(glob_wrapper outvar) + if(${CMAKE_VERSION} VERSION_LESS 3.12) + file(GLOB ${outvar} ${ARGN}) + else() + file(GLOB ${outvar} CONFIGURE_DEPENDS ${ARGN}) + endif() + set(${outvar} ${${outvar}} PARENT_SCOPE) +endfunction() + +function(globrecurse_wrapper outvar root) + if(${CMAKE_VERSION} VERSION_LESS 3.12) + file(GLOB_RECURSE ${outvar} RELATIVE ${root} ${ARGN}) + else() + file(GLOB_RECURSE ${outvar} CONFIGURE_DEPENDS RELATIVE ${root} ${ARGN}) + endif() + set(${outvar} ${${outvar}} PARENT_SCOPE) +endfunction() diff --git a/config/CMakeLists.txt b/config/CMakeLists.txt index 6b88c92cf0..581f25857b 100644 --- a/config/CMakeLists.txt +++ b/config/CMakeLists.txt @@ -12,11 +12,6 @@ check_type_size("size_t" SIZEOF_SIZE_T) check_type_size("long long" SIZEOF_LONG_LONG) check_type_size("void *" SIZEOF_VOID_PTR) -if (CMAKE_HOST_SYSTEM_VERSION MATCHES ".*-(Microsoft|microsoft-standard)") - # Windows Subsystem for Linux - set(HAVE_WSL 1) -endif() - check_symbol_exists(_NSGetEnviron crt_externs.h HAVE__NSGETENVIRON) # Headers diff --git a/config/config.h.in b/config/config.h.in index 502f84bbcf..27a28116af 100644 --- a/config/config.h.in +++ b/config/config.h.in @@ -39,7 +39,6 @@ #cmakedefine HAVE_SYS_WAIT_H #cmakedefine HAVE_TERMIOS_H #cmakedefine HAVE_WORKING_LIBINTL -#cmakedefine HAVE_WSL #cmakedefine UNIX #cmakedefine CASE_INSENSITIVE_FILENAME #cmakedefine USE_FNAME_CASE diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 4fdcfc0f33..37029874f2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -21,12 +21,12 @@ add_custom_command(OUTPUT ${GENERATED_SYN_VIM} ${FUNCS_DATA} ) -file(GLOB PACKAGES ${PROJECT_SOURCE_DIR}/runtime/pack/dist/opt/*) +glob_wrapper(PACKAGES ${PROJECT_SOURCE_DIR}/runtime/pack/dist/opt/*) set(GENERATED_PACKAGE_TAGS) foreach(PACKAGE ${PACKAGES}) get_filename_component(PACKNAME ${PACKAGE} NAME) - file(GLOB "${PACKNAME}_DOC_FILES" ${PACKAGE}/doc/*.txt) + glob_wrapper("${PACKNAME}_DOC_FILES" ${PACKAGE}/doc/*.txt) if(${PACKNAME}_DOC_FILES) file(MAKE_DIRECTORY ${GENERATED_PACKAGE_DIR}/${PACKNAME}) add_custom_command(OUTPUT "${GENERATED_PACKAGE_DIR}/${PACKNAME}/doc/tags" @@ -54,7 +54,7 @@ foreach(PACKAGE ${PACKAGES}) endif() endforeach() -file(GLOB DOCFILES ${PROJECT_SOURCE_DIR}/runtime/doc/*.txt) +glob_wrapper(DOCFILES ${PROJECT_SOURCE_DIR}/runtime/doc/*.txt) set(BUILDDOCFILES) foreach(DF ${DOCFILES}) @@ -114,9 +114,7 @@ if(NOT APPLE) DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps) endif() -file(GLOB_RECURSE RUNTIME_PROGRAMS - RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} - *.awk *.sh *.bat) +globrecurse_wrapper(RUNTIME_PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR} *.awk *.sh *.bat) foreach(PROG ${RUNTIME_PROGRAMS}) get_filename_component(BASEDIR ${PROG} PATH) @@ -124,10 +122,8 @@ foreach(PROG ${RUNTIME_PROGRAMS}) DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/nvim/runtime/${BASEDIR}) endforeach() -file(GLOB_RECURSE RUNTIME_FILES - RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} - rgb.txt - *.vim *.lua *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) +globrecurse_wrapper(RUNTIME_FILES ${CMAKE_CURRENT_SOURCE_DIR} + rgb.txt *.vim *.lua *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) foreach(F ${RUNTIME_FILES}) get_filename_component(BASEDIR ${F} PATH) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 1573bec7ac..bb8e83f84a 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1078,7 +1078,7 @@ nvim_get_keymap({mode}) *nvim_get_keymap()* Array of maparg()-like dictionaries describing mappings. The "buffer" key is always zero. -nvim_get_mark({name}) *nvim_get_mark()* +nvim_get_mark({name}, {opts}) *nvim_get_mark()* Return a tuple (row, col, buffer, buffername) representing the position of the uppercase/file named mark. See |mark-motions|. @@ -1090,6 +1090,7 @@ nvim_get_mark({name}) *nvim_get_mark()* Parameters: ~ {name} Mark name + {opts} Optional parameters. Reserved for future use. Return: ~ 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if @@ -2420,7 +2421,7 @@ nvim_buf_set_lines({buffer}, {start}, {end}, {strict_indexing}, {replacement}) {replacement} Array of lines to use as replacement *nvim_buf_set_mark()* -nvim_buf_set_mark({buffer}, {name}, {line}, {col}) +nvim_buf_set_mark({buffer}, {name}, {line}, {col}, {opts}) Sets a named mark in the given buffer, all marks are allowed file/uppercase, visual, last change, etc. See |mark-motions|. @@ -2434,6 +2435,7 @@ nvim_buf_set_mark({buffer}, {name}, {line}, {col}) {name} Mark name {line} Line number {col} Column/row number + {opts} Optional parameters. Reserved for future use. Return: ~ true if the mark was set, else false. diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt index a7ce4135af..21a34178b3 100644 --- a/runtime/doc/deprecated.txt +++ b/runtime/doc/deprecated.txt @@ -85,6 +85,9 @@ For each of the functions below, use the corresponding function in *vim.lsp.diagnostic.save()* Use |vim.diagnostic.set()| instead. *vim.lsp.diagnostic.set_loclist()* Use |vim.diagnostic.setloclist()| instead. *vim.lsp.diagnostic.set_qflist()* Use |vim.diagnostic.setqflist()| instead. + +The following have been replaced by |vim.diagnostic.open_float()|. + *vim.lsp.diagnostic.show_line_diagnostics()* *vim.lsp.diagnostic.show_position_diagnostics()* diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index 4d1e5ac997..d121dba435 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -75,6 +75,100 @@ Functions that take a severity as an optional parameter (e.g. The latter form allows users to specify a range of severities. ============================================================================== +HANDLERS *diagnostic-handlers* + +Diagnostics are shown to the user with |vim.diagnostic.show()|. The display of +diagnostics is managed through handlers. A handler is a table with a "show" +and (optionally) a "hide" function. The "show" function has the signature +> + function(namespace, bufnr, diagnostics, opts) +< +and is responsible for displaying or otherwise handling the given +diagnostics. The "hide" function takes care of "cleaning up" any actions taken +by the "show" function and has the signature +> + function(namespace, bufnr) +< +Handlers can be configured with |vim.diagnostic.config()| and added by +creating a new key in `vim.diagnostic.handlers` (see +|diagnostic-handlers-example|). + +The {opts} table passed to a handler is the full set of configuration options +(that is, it is not limited to just the options for the handler itself). The +values in the table are already resolved (i.e. if a user specifies a +function for a config option, the function has already been evaluated). + +Nvim provides these handlers by default: "virtual_text", "signs", and +"underline". + + *diagnostic-handlers-example* +The example below creates a new handler that notifies the user of diagnostics +with |vim.notify()|: > + + -- It's good practice to namespace custom handlers to avoid collisions + vim.diagnostic.handlers["my/notify"] = { + show = function(namespace, bufnr, diagnostics, opts) + -- In our example, the opts table has a "log_level" option + local level = opts["my/notify"].log_level + + local name = vim.diagnostic.get_namespace(namespace).name + local msg = string.format("%d diagnostics in buffer %d from %s", + #diagnostics, + bufnr, + name) + vim.notify(msg, level) + end, + } + + -- Users can configure the handler + vim.diagnostic.config({ + ["my/notify"] = { + log_level = vim.log.levels.INFO + } + }) +< +In this example, there is nothing to do when diagnostics are hidden, so we +omit the "hide" function. + +Existing handlers can be overriden. For example, use the following to only +show a sign for the highest severity diagnostic on a given line: > + + -- Create a custom namespace. This will aggregate signs from all other + -- namespaces and only show the one with the highest severity on a + -- given line + local ns = vim.api.nvim_create_namespace("my_namespace") + + -- Get a reference to the original signs handler + local orig_signs_handler = vim.diagnostic.handlers.signs + + -- Override the built-in signs handler + vim.diagnostic.handlers.signs = { + show = function(_, bufnr, _, opts) + -- Get all diagnostics from the whole buffer rather than just the + -- diagnostics passed to the handler + local diagnostics = vim.diagnostic.get(bufnr) + + -- Find the "worst" diagnostic per line + local max_severity_per_line = {} + for _, d in pairs(diagnostics) do + local m = max_severity_per_line[d.lnum] + if not m or d.severity < m.severity then + max_severity_per_line[d.lnum] = d + end + end + + -- Pass the filtered diagnostics (with our custom namespace) to + -- the original handler + local filtered_diagnostics = vim.tbl_values(max_severity_per_line) + orig_signs_handler.show(ns, bufnr, filtered_diagnostics, opts) + end, + hide = function(_, bufnr) + orig_signs_handler.hide(ns, bufnr) + end, + } +< + +============================================================================== HIGHLIGHTS *diagnostic-highlights* All highlights defined for diagnostics begin with `Diagnostic` followed by @@ -202,51 +296,6 @@ Example: > autocmd User DiagnosticsChanged lua vim.diagnostic.setqflist({open = false }) < ============================================================================== -CUSTOMIZATION *diagnostic-config* - -If you need more customization over the way diagnostics are displayed than the -built-in configuration options provide, you can override the display handler -explicitly. For example, use the following to only show a sign for the highest -severity diagnostic on a given line: > - - -- Disable the default signs handler - vim.diagnostic.config({signs = false}) - - -- Create a namespace. This won't be used to add any diagnostics, - -- only to display them. - local ns = vim.api.nvim_create_namespace("my_namespace") - - -- Create a reference to the original function - local orig_show = vim.diagnostic.show - - local function set_signs(bufnr) - -- Get all diagnostics from the current buffer - local diagnostics = vim.diagnostic.get(bufnr) - - -- Find the "worst" diagnostic per line - local max_severity_per_line = {} - for _, d in pairs(diagnostics) do - local m = max_severity_per_line[d.lnum] - if not m or d.severity < m.severity then - max_severity_per_line[d.lnum] = d - end - end - - -- Show the filtered diagnostics using the custom namespace. Use the - -- reference to the original function to avoid a loop. - local filtered_diagnostics = vim.tbl_values(max_severity_per_line) - orig_show(ns, bufnr, filtered_diagnostics, { - virtual_text=false, - underline=false, - signs=true - }) - end - - function vim.diagnostic.show(namespace, bufnr, ...) - orig_show(namespace, bufnr, ...) - set_signs(bufnr) - end -< ============================================================================== Lua module: vim.diagnostic *diagnostic-api* @@ -394,6 +443,15 @@ get({bufnr}, {opts}) *vim.diagnostic.get()* Return: ~ table A list of diagnostic items |diagnostic-structure|. +get_namespace({namespace}) *vim.diagnostic.get_namespace()* + Get namespace metadata. + + Parameters: ~ + {ns} number Diagnostic namespace + + Return: ~ + table Namespace metadata + get_namespaces() *vim.diagnostic.get_namespaces()* Get current diagnostic namespaces. @@ -619,7 +677,7 @@ show({namespace}, {bufnr}, {diagnostics}, {opts}) Display diagnostics for the given namespace and buffer. Parameters: ~ - {namespace} number Diagnostic namespace + {namespace} number Diagnostic namespace. {bufnr} number|nil Buffer number. Defaults to the current buffer. {diagnostics} table|nil The diagnostics to display. When diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 5549d3c180..80ac762792 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -61,6 +61,10 @@ Example config (in init.vim): > -- See `:help omnifunc` and `:help ins-completion` for more information. vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.vim.lsp.omnifunc') + -- Use LSP as the handler for formatexpr. + -- See `:help formatexpr` for more information. + vim.api.nvim_buf_set_option(0, 'formatexpr', 'v:lua.vim.lsp.formatexpr()') + -- For plugins with an `on_attach` callback, call them here. For example: -- require('completion').on_attach() end @@ -452,6 +456,22 @@ LspSignatureActiveParameter |vim.lsp.handlers.signature_help()|. ============================================================================== +EVENTS *lsp-events* + +LspProgressUpdate *LspProgressUpdate* + Upon receipt of a progress notification from the server. See + |vim.lsp.util.get_progress_messages()|. + +LspRequest *LspRequest* + After a change to the active set of pending LSP requests. See {requests} + in |vim.lsp.client|. + +Example: > + autocmd User LspProgressUpdate redrawstatus + autocmd User LspRequest redrawstatus +< + +============================================================================== Lua module: vim.lsp *lsp-core* buf_attach_client({bufnr}, {client_id}) *vim.lsp.buf_attach_client()* @@ -608,6 +628,11 @@ client() *vim.lsp.client* server. • {handlers} (table): The handlers used by the client as described in |lsp-handler|. + • {requests} (table): The current pending requests in flight + to the server. Entries are key-value pairs with the key + being the request ID while the value is a table with `type`, + `bufnr`, and `method` key-value pairs. `type` is either "pending" + for an active request, or "cancel" for a cancel request. • {config} (table): copy of the table that was passed by the user to |vim.lsp.start_client()|. • {server_capabilities} (table): Response from the server diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 877c838602..1e058874bd 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -698,15 +698,14 @@ vim.diff({a}, {b}, {opts}) *vim.diff()* ------------------------------------------------------------------------------ VIM.MPACK *lua-mpack* -The *vim.mpack* module provides packing and unpacking of lua objects to -msgpack encoded strings. |vim.NIL| and |vim.empty_dict()| are supported. +The *vim.mpack* module provides encoding and decoding of Lua objects to and +from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. -vim.mpack.pack({obj}) *vim.mpack.pack* - Packs a lua object {obj} and returns the msgpack representation as - a string +vim.mpack.encode({obj}) *vim.mpack.encode* + Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. -vim.mpack.unpack({str}) *vim.mpack.unpack* - Unpacks the msgpack encoded {str} and returns a lua object +vim.mpack.decode({str}) *vim.mpack.decode* + Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. ------------------------------------------------------------------------------ VIM *lua-builtin* diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 4cf22282a2..911d482bfd 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -24,6 +24,16 @@ local global_diagnostic_options = { severity_sort = false, } +M.handlers = setmetatable({}, { + __newindex = function(t, name, handler) + vim.validate { handler = {handler, "t" } } + rawset(t, name, handler) + if not global_diagnostic_options[name] then + global_diagnostic_options[name] = true + end + end, +}) + -- Local functions {{{ ---@private @@ -97,30 +107,8 @@ end local all_namespaces = {} ---@private -local function get_namespace(ns) - if not all_namespaces[ns] then - local name - for k, v in pairs(vim.api.nvim_get_namespaces()) do - if ns == v then - name = k - break - end - end - - assert(name, "namespace does not exist or is anonymous") - - all_namespaces[ns] = { - name = name, - sign_group = string.format("vim.diagnostic.%s", name), - opts = {} - } - end - return all_namespaces[ns] -end - ----@private local function enabled_value(option, namespace) - local ns = namespace and get_namespace(namespace) or {} + local ns = namespace and M.get_namespace(namespace) or {} if ns.opts and type(ns.opts[option]) == "table" then return ns.opts[option] end @@ -154,7 +142,7 @@ end ---@private local function get_resolved_options(opts, namespace, bufnr) - local ns = namespace and get_namespace(namespace) or {} + local ns = namespace and M.get_namespace(namespace) or {} -- Do not use tbl_deep_extend so that an empty table can be used to reset to default values local resolved = vim.tbl_extend('keep', opts or {}, ns.opts or {}, global_diagnostic_options) for k in pairs(global_diagnostic_options) do @@ -343,7 +331,7 @@ local registered_autocmds = {} ---@private local function make_augroup_key(namespace, bufnr) - local ns = get_namespace(namespace) + local ns = M.get_namespace(namespace) return string.format("DiagnosticInsertLeave:%s:%s", bufnr, ns.name) end @@ -566,7 +554,7 @@ function M.config(opts, namespace) local t if namespace then - local ns = get_namespace(namespace) + local ns = M.get_namespace(namespace) t = ns.opts else t = global_diagnostic_options @@ -633,6 +621,32 @@ function M.set(namespace, bufnr, diagnostics, opts) vim.api.nvim_command("doautocmd <nomodeline> User DiagnosticsChanged") end +--- Get namespace metadata. +--- +---@param ns number Diagnostic namespace +---@return table Namespace metadata +function M.get_namespace(namespace) + vim.validate { namespace = { namespace, 'n' } } + if not all_namespaces[namespace] then + local name + for k, v in pairs(vim.api.nvim_get_namespaces()) do + if namespace == v then + name = k + break + end + end + + assert(name, "namespace does not exist or is anonymous") + + all_namespaces[namespace] = { + name = name, + opts = {}, + user_data = {}, + } + end + return all_namespaces[namespace] +end + --- Get current diagnostic namespaces. --- ---@return table A list of active diagnostic namespaces |vim.diagnostic|. @@ -782,156 +796,167 @@ function M.goto_next(opts) ) end --- Diagnostic Setters {{{ - ---- Set signs for given diagnostics. ---- ----@param namespace number The diagnostic namespace ----@param bufnr number Buffer number ----@param diagnostics table A list of diagnostic items |diagnostic-structure|. When omitted the ---- current diagnostics in the given buffer are used. ----@param opts table Configuration table with the following keys: ---- - priority: Set the priority of the signs |sign-priority|. ----@private -function M._set_signs(namespace, bufnr, diagnostics, opts) - vim.validate { - namespace = {namespace, 'n'}, - bufnr = {bufnr, 'n'}, - diagnostics = {diagnostics, 't'}, - opts = {opts, 't', true}, - } - - bufnr = get_bufnr(bufnr) - opts = get_resolved_options({ signs = opts }, namespace, bufnr) +M.handlers.signs = { + show = function(namespace, bufnr, diagnostics, opts) + vim.validate { + namespace = {namespace, 'n'}, + bufnr = {bufnr, 'n'}, + diagnostics = {diagnostics, 't'}, + opts = {opts, 't', true}, + } - if opts.signs and opts.signs.severity then - diagnostics = filter_by_severity(opts.signs.severity, diagnostics) - end + bufnr = get_bufnr(bufnr) - local ns = get_namespace(namespace) + if opts.signs and opts.signs.severity then + diagnostics = filter_by_severity(opts.signs.severity, diagnostics) + end - define_default_signs() + define_default_signs() - -- 10 is the default sign priority when none is explicitly specified - local priority = opts.signs and opts.signs.priority or 10 - local get_priority - if opts.severity_sort then - if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then - get_priority = function(severity) - return priority + (severity - vim.diagnostic.severity.ERROR) + -- 10 is the default sign priority when none is explicitly specified + local priority = opts.signs and opts.signs.priority or 10 + local get_priority + if opts.severity_sort then + if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then + get_priority = function(severity) + return priority + (severity - vim.diagnostic.severity.ERROR) + end + else + get_priority = function(severity) + return priority + (vim.diagnostic.severity.HINT - severity) + end end else - get_priority = function(severity) - return priority + (vim.diagnostic.severity.HINT - severity) + get_priority = function() + return priority end end - else - get_priority = function() - return priority - end - end - for _, diagnostic in ipairs(diagnostics) do - vim.fn.sign_place( - 0, - ns.sign_group, - sign_highlight_map[diagnostic.severity], - bufnr, - { - priority = get_priority(diagnostic.severity), - lnum = diagnostic.lnum + 1 - } - ) - end -end - ---- Set underline for given diagnostics. ---- ----@param namespace number The diagnostic namespace ----@param bufnr number Buffer number ----@param diagnostics table A list of diagnostic items |diagnostic-structure|. When omitted the ---- current diagnostics in the given buffer are used. ----@param opts table Configuration table. Currently unused. ----@private -function M._set_underline(namespace, bufnr, diagnostics, opts) - vim.validate { - namespace = {namespace, 'n'}, - bufnr = {bufnr, 'n'}, - diagnostics = {diagnostics, 't'}, - opts = {opts, 't', true}, - } + local ns = M.get_namespace(namespace) + if not ns.user_data.sign_group then + ns.user_data.sign_group = string.format("vim.diagnostic.%s", ns.name) + end - bufnr = get_bufnr(bufnr) - opts = get_resolved_options({ underline = opts }, namespace, bufnr).underline + local sign_group = ns.user_data.sign_group + for _, diagnostic in ipairs(diagnostics) do + vim.fn.sign_place( + 0, + sign_group, + sign_highlight_map[diagnostic.severity], + bufnr, + { + priority = get_priority(diagnostic.severity), + lnum = diagnostic.lnum + 1 + } + ) + end + end, + hide = function(namespace, bufnr) + local ns = M.get_namespace(namespace) + if ns.user_data.sign_group then + vim.fn.sign_unplace(ns.user_data.sign_group, {buffer=bufnr}) + end + end, +} - if opts and opts.severity then - diagnostics = filter_by_severity(opts.severity, diagnostics) - end +M.handlers.underline = { + show = function(namespace, bufnr, diagnostics, opts) + vim.validate { + namespace = {namespace, 'n'}, + bufnr = {bufnr, 'n'}, + diagnostics = {diagnostics, 't'}, + opts = {opts, 't', true}, + } - for _, diagnostic in ipairs(diagnostics) do - local higroup = underline_highlight_map[diagnostic.severity] + bufnr = get_bufnr(bufnr) - if higroup == nil then - -- Default to error if we don't have a highlight associated - higroup = underline_highlight_map.Error + if opts.underline and opts.underline.severity then + diagnostics = filter_by_severity(opts.underline.severity, diagnostics) end - vim.highlight.range( - bufnr, - namespace, - higroup, - { diagnostic.lnum, diagnostic.col }, - { diagnostic.end_lnum, diagnostic.end_col } - ) - end -end + local ns = M.get_namespace(namespace) + if not ns.user_data.underline_ns then + ns.user_data.underline_ns = vim.api.nvim_create_namespace("") + end ---- Set virtual text for given diagnostics. ---- ----@param namespace number The diagnostic namespace ----@param bufnr number Buffer number ----@param diagnostics table A list of diagnostic items |diagnostic-structure|. When omitted the ---- current diagnostics in the given buffer are used. ----@param opts table|nil Configuration table with the following keys: ---- - prefix: (string) Prefix to display before virtual text on line. ---- - spacing: (number) Number of spaces to insert before virtual text. ---- - source: (string) Include the diagnostic source in virtual text. One of "always" or ---- "if_many". ----@private -function M._set_virtual_text(namespace, bufnr, diagnostics, opts) - vim.validate { - namespace = {namespace, 'n'}, - bufnr = {bufnr, 'n'}, - diagnostics = {diagnostics, 't'}, - opts = {opts, 't', true}, - } + local underline_ns = ns.user_data.underline_ns + for _, diagnostic in ipairs(diagnostics) do + local higroup = underline_highlight_map[diagnostic.severity] - bufnr = get_bufnr(bufnr) - opts = get_resolved_options({ virtual_text = opts }, namespace, bufnr).virtual_text + if higroup == nil then + -- Default to error if we don't have a highlight associated + higroup = underline_highlight_map.Error + end - if opts and opts.format then - diagnostics = reformat_diagnostics(opts.format, diagnostics) + vim.highlight.range( + bufnr, + underline_ns, + higroup, + { diagnostic.lnum, diagnostic.col }, + { diagnostic.end_lnum, diagnostic.end_col } + ) + end + end, + hide = function(namespace, bufnr) + local ns = M.get_namespace(namespace) + if ns.user_data.underline_ns then + vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1) + end end +} - if opts and opts.source then - diagnostics = prefix_source(opts.source, diagnostics) - end +M.handlers.virtual_text = { + show = function(namespace, bufnr, diagnostics, opts) + vim.validate { + namespace = {namespace, 'n'}, + bufnr = {bufnr, 'n'}, + diagnostics = {diagnostics, 't'}, + opts = {opts, 't', true}, + } + + bufnr = get_bufnr(bufnr) - local buffer_line_diagnostics = diagnostic_lines(diagnostics) - for line, line_diagnostics in pairs(buffer_line_diagnostics) do - if opts and opts.severity then - line_diagnostics = filter_by_severity(opts.severity, line_diagnostics) + local severity + if opts.virtual_text then + if opts.virtual_text.format then + diagnostics = reformat_diagnostics(opts.virtual_text.format, diagnostics) + end + if opts.virtual_text.source then + diagnostics = prefix_source(opts.virtual_text.source, diagnostics) + end + if opts.virtual_text.severity then + severity = opts.virtual_text.severity + end end - local virt_texts = M._get_virt_text_chunks(line_diagnostics, opts) - if virt_texts then - vim.api.nvim_buf_set_extmark(bufnr, namespace, line, 0, { - hl_mode = "combine", - virt_text = virt_texts, - }) + local ns = M.get_namespace(namespace) + if not ns.user_data.virt_text_ns then + ns.user_data.virt_text_ns = vim.api.nvim_create_namespace("") end - end -end + + local virt_text_ns = ns.user_data.virt_text_ns + local buffer_line_diagnostics = diagnostic_lines(diagnostics) + for line, line_diagnostics in pairs(buffer_line_diagnostics) do + if severity then + line_diagnostics = filter_by_severity(severity, line_diagnostics) + end + local virt_texts = M._get_virt_text_chunks(line_diagnostics, opts.virtual_text) + + if virt_texts then + vim.api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, { + hl_mode = "combine", + virt_text = virt_texts, + }) + end + end + end, + hide = function(namespace, bufnr) + local ns = M.get_namespace(namespace) + if ns.user_data.virt_text_ns then + vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1) + end + end, +} --- Get virtual text chunks to display using |nvim_buf_set_extmark()|. --- @@ -1011,19 +1036,16 @@ function M.hide(namespace, bufnr) bufnr = get_bufnr(bufnr) diagnostic_cache_extmarks[bufnr][namespace] = {} - local ns = get_namespace(namespace) - - -- clear sign group - vim.fn.sign_unplace(ns.sign_group, {buffer=bufnr}) - - -- clear virtual text namespace - vim.api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) + for _, handler in pairs(M.handlers) do + if handler.hide then + handler.hide(namespace, bufnr) + end + end end - --- Display diagnostics for the given namespace and buffer. --- ----@param namespace number Diagnostic namespace +---@param namespace number Diagnostic namespace. ---@param bufnr number|nil Buffer number. Defaults to the current buffer. ---@param diagnostics table|nil The diagnostics to display. When omitted, use the --- saved diagnostics for the given namespace and @@ -1074,16 +1096,10 @@ function M.show(namespace, bufnr, diagnostics, opts) clamp_line_numbers(bufnr, diagnostics) - if opts.underline then - M._set_underline(namespace, bufnr, diagnostics, opts.underline) - end - - if opts.virtual_text then - M._set_virtual_text(namespace, bufnr, diagnostics, opts.virtual_text) - end - - if opts.signs then - M._set_signs(namespace, bufnr, diagnostics, opts.signs) + for handler_name, handler in pairs(M.handlers) do + if handler.show and opts[handler_name] then + handler.show(namespace, bufnr, diagnostics, opts) + end end save_extmarks(namespace, bufnr) @@ -1138,6 +1154,17 @@ function M.open_float(bufnr, opts) error("Invalid value for option 'scope'") end + do + -- Resolve options with user settings from vim.diagnostic.config + -- Unlike the other decoration functions (e.g. set_virtual_text, set_signs, etc.) `open_float` + -- does not have a dedicated table for configuration options; instead, the options are mixed in + -- with its `opts` table which also includes "keyword" parameters. So we create a dedicated + -- options table that inherits missing keys from the global configuration before resolving. + local t = global_diagnostic_options.float + local float_opts = vim.tbl_extend("keep", opts, type(t) == "table" and t or {}) + opts = get_resolved_options({ float = float_opts }, nil, bufnr).float + end + local diagnostics = M.get(bufnr, opts) clamp_line_numbers(bufnr, diagnostics) @@ -1168,17 +1195,6 @@ function M.open_float(bufnr, opts) end end - do - -- Resolve options with user settings from vim.diagnostic.config - -- Unlike the other decoration functions (e.g. set_virtual_text, set_signs, etc.) `open_float` - -- does not have a dedicated table for configuration options; instead, the options are mixed in - -- with its `opts` table which also includes "keyword" parameters. So we create a dedicated - -- options table that inherits missing keys from the global configuration before resolving. - local t = global_diagnostic_options.float - local float_opts = vim.tbl_extend("keep", opts, type(t) == "table" and t or {}) - opts = get_resolved_options({ float = float_opts }, nil, bufnr).float - end - local lines = {} local highlights = {} local show_header = vim.F.if_nil(opts.show_header, true) diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 56ac1cbc66..fb4718c1bb 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -239,6 +239,7 @@ local function validate_client_config(config) on_exit = { config.on_exit, "f", true }; on_init = { config.on_init, "f", true }; settings = { config.settings, "t", true }; + commands = { config.commands, 't', true }; before_init = { config.before_init, "f", true }; offset_encoding = { config.offset_encoding, "s", true }; flags = { config.flags, "t", true }; @@ -590,6 +591,11 @@ end --- returned to the language server if requested via `workspace/configuration`. --- Keys are case-sensitive. --- +---@param commands table Table that maps string of clientside commands to user-defined functions. +--- Commands passed to start_client take precedence over the global command registry. Each key +--- must be a unique comand name, and the value is a function which is called if any LSP action +--- (code action, code lenses, ...) triggers the command. +--- ---@param init_options Values to pass in the initialization request --- as `initializationOptions`. See `initialize` in the LSP spec. --- @@ -772,8 +778,11 @@ function lsp.start_client(config) attached_buffers = {}; handlers = handlers; + commands = config.commands or {}; + + requests = {}; -- for $/progress report - messages = { name = name, messages = {}, progress = {}, status = {} } + messages = { name = name, messages = {}, progress = {}, status = {} }; } -- Store the uninitialized_clients for cleanup in case we exit before initialize finishes. @@ -906,11 +915,21 @@ function lsp.start_client(config) end -- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state changetracking.flush(client) - + bufnr = resolve_bufnr(bufnr) local _ = log.debug() and log.debug(log_prefix, "client.request", client_id, method, params, handler, bufnr) - return rpc.request(method, params, function(err, result) + local success, request_id = rpc.request(method, params, function(err, result) handler(err, result, {method=method, client_id=client_id, bufnr=bufnr, params=params}) + end, function(request_id) + client.requests[request_id] = nil + nvim_command("doautocmd <nomodeline> User LspRequest") end) + + if success then + client.requests[request_id] = { type='pending', bufnr=bufnr, method=method } + nvim_command("doautocmd <nomodeline> User LspRequest") + end + + return success, request_id end ---@private @@ -970,6 +989,11 @@ function lsp.start_client(config) ---@see |vim.lsp.client.notify()| function client.cancel_request(id) validate{id = {id, 'n'}} + local request = client.requests[id] + if request and request.type == 'pending' then + request.type = 'cancel' + nvim_command("doautocmd <nomodeline> User LspRequest") + end return rpc.notify("$/cancelRequest", { id = id }) end @@ -1238,27 +1262,30 @@ function lsp._vim_exit_handler() send_kill = true timeouts[client_id] = timeout max_timeout = math.max(timeout, max_timeout) - else - active_clients[client_id] = nil end end local poll_time = 50 local function check_clients_closed() + for client_id, timeout in pairs(timeouts) do + timeouts[client_id] = timeout - poll_time + end + for client_id, _ in pairs(active_clients) do - timeouts[client_id] = timeouts[client_id] - poll_time - if timeouts[client_id] < 0 then - active_clients[client_id] = nil + if timeouts[client_id] ~= nil and timeouts[client_id] > 0 then + return false end end - return tbl_isempty(active_clients) + return true end if send_kill then if not vim.wait(max_timeout, check_clients_closed, poll_time) then - for _, client in pairs(active_clients) do - client.stop(true) + for client_id, client in pairs(active_clients) do + if timeouts[client_id] ~= nil then + client.stop(true) + end end end end @@ -1300,7 +1327,7 @@ function lsp.buf_request(bufnr, method, params, handler) if not tbl_isempty(all_buffer_active_clients[resolve_bufnr(bufnr)] or {}) and not method_supported then vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR) vim.api.nvim_command("redraw") - return + return {}, function() end end local client_request_ids = {} @@ -1512,6 +1539,52 @@ function lsp.omnifunc(findstart, base) return -2 end +--- Provides an interface between the built-in client and a `formatexpr` function. +--- +--- Currently only supports a single client. This can be set via +--- `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` but will typically or in `on_attach` +--- via `vim.api.nvim_buf_set_option(bufnr, 'formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')`. +--- +---@param opts table options for customizing the formatting expression which takes the +--- following optional keys: +--- * timeout_ms (default 500ms). The timeout period for the formatting request. +function lsp.formatexpr(opts) + opts = opts or {} + local timeout_ms = opts.timeout_ms or 500 + + if vim.tbl_contains({'i', 'R', 'ic', 'ix'}, vim.fn.mode()) then + -- `formatexpr` is also called when exceeding `textwidth` in insert mode + -- fall back to internal formatting + return 1 + end + + local start_line = vim.v.lnum + local end_line = start_line + vim.v.count - 1 + + if start_line > 0 and end_line > 0 then + local params = { + textDocument = util.make_text_document_params(); + range = { + start = { line = start_line - 1; character = 0; }; + ["end"] = { line = end_line - 1; character = 0; }; + }; + }; + params.options = util.make_formatting_params().options + local client_results = vim.lsp.buf_request_sync(0, "textDocument/rangeFormatting", params, timeout_ms) + + -- Apply the text edits from one and only one of the clients. + for _, response in pairs(client_results) do + if response.result then + vim.lsp.util.apply_text_edits(response.result, 0) + return 0 + end + end + end + + -- do not run builtin formatter. + return 0 +end + ---Checks whether a client is stopped. --- ---@param client_id (Number) diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 245f29943e..128f0b01ad 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -480,11 +480,11 @@ local function on_code_action_results(results, ctx) end if action.command then local command = type(action.command) == 'table' and action.command or action - local fn = vim.lsp.commands[command.command] + local fn = client.commands[command.command] or vim.lsp.commands[command.command] if fn then local enriched_ctx = vim.deepcopy(ctx) enriched_ctx.client_id = client.id - fn(command, ctx) + fn(command, enriched_ctx) else M.execute_command(command) end @@ -529,6 +529,7 @@ local function on_code_action_results(results, ctx) vim.ui.select(action_tuples, { prompt = 'Code actions:', + kind = 'codeaction', format_item = function(action_tuple) local title = action_tuple[2].title:gsub('\r\n', '\\r\\n') return title:gsub('\n', '\\n') diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 63fcbe430b..9eb64c9a2e 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -31,15 +31,15 @@ local function execute_lens(lens, bufnr, client_id) local line = lens.range.start.line api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) + local client = vim.lsp.get_client_by_id(client_id) + assert(client, 'Client is required to execute lens, client_id=' .. client_id) local command = lens.command - local fn = vim.lsp.commands[command.command] + local fn = client.commands[command.command] or vim.lsp.commands[command.command] if fn then fn(command, { bufnr = bufnr, client_id = client_id }) return end -- Need to use the client that returned the lens → must not use buf_request - local client = vim.lsp.get_client_by_id(client_id) - assert(client, 'Client is required to execute lens, client_id=' .. client_id) local command_provider = client.server_capabilities.executeCommandProvider local commands = type(command_provider) == 'table' and command_provider.commands or {} if not vim.tbl_contains(commands, command.command) then diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index bea0e44aca..1e6f83c1ba 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -146,7 +146,8 @@ local _client_namespaces = {} function M.get_namespace(client_id) vim.validate { client_id = { client_id, 'n' } } if not _client_namespaces[client_id] then - local name = string.format("vim.lsp.client-%d", client_id) + local client = vim.lsp.get_client_by_id(client_id) + local name = string.format("vim.lsp.%s.%d", client and client.name or "unknown", client_id) _client_namespaces[client_id] = vim.api.nvim_create_namespace(name) end return _client_namespaces[client_id] diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index eff27807be..01d7102e8f 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -185,7 +185,7 @@ local function response_to_list(map_result, entity) title = 'Language Server'; items = map_result(result, ctx.bufnr); }) - api.nvim_command("copen") + api.nvim_command("botright copen") end end end diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index d9a684a738..bce1e9f35d 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -297,6 +297,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local message_index = 0 local message_callbacks = {} + local notify_reply_callbacks = {} local handle, pid do @@ -309,8 +310,9 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) stdout:close() stderr:close() handle:close() - -- Make sure that message_callbacks can be gc'd. + -- Make sure that message_callbacks/notify_reply_callbacks can be gc'd. message_callbacks = nil + notify_reply_callbacks = nil dispatchers.on_exit(code, signal) end local spawn_params = { @@ -375,10 +377,12 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) ---@param method (string) The invoked LSP method ---@param params (table) Parameters for the invoked LSP method ---@param callback (function) Callback to invoke + ---@param notify_reply_callback (function) Callback to invoke as soon as a request is no longer pending ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not - local function request(method, params, callback) + local function request(method, params, callback, notify_reply_callback) validate { callback = { callback, 'f' }; + notify_reply_callback = { notify_reply_callback, 'f', true }; } message_index = message_index + 1 local message_id = message_index @@ -388,8 +392,15 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) method = method; params = params; } - if result and message_callbacks then - message_callbacks[message_id] = schedule_wrap(callback) + if result then + if message_callbacks then + message_callbacks[message_id] = schedule_wrap(callback) + else + return false + end + if notify_reply_callback and notify_reply_callbacks then + notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback) + end return result, message_id else return false @@ -466,6 +477,16 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) -- We sent a number, so we expect a number. local result_id = tonumber(decoded.id) + -- Notify the user that a response was received for the request + local notify_reply_callback = notify_reply_callbacks and notify_reply_callbacks[result_id] + if notify_reply_callback then + validate { + notify_reply_callback = { notify_reply_callback, 'f' }; + } + notify_reply_callback(result_id) + notify_reply_callbacks[result_id] = nil + end + -- Do not surface RequestCancelled to users, it is RPC-internal. if decoded.error then local mute_error = false diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 7a0ac458f3..a5bf0efcb1 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -152,6 +152,7 @@ end --- Returns a zero-indexed column, since set_lines() does the conversion to --- 1-indexed local function get_line_byte_from_position(bufnr, position) + -- TODO handle offset_encoding -- LSP's line and characters are 0-indexed -- Vim's line and columns are 1-indexed local col = position.character @@ -165,7 +166,7 @@ local function get_line_byte_from_position(bufnr, position) local line = position.line local lines = api.nvim_buf_get_lines(bufnr, line, line + 1, false) if #lines > 0 then - local ok, result = pcall(vim.str_byteindex, lines[1], col) + local ok, result = pcall(vim.str_byteindex, lines[1], col, true) if ok then return result @@ -276,7 +277,8 @@ function M.apply_text_edits(text_edits, bufnr) -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't accept it so we should fix it here. local has_eol_text_edit = false local max = vim.api.nvim_buf_line_count(bufnr) - local len = vim.str_utfindex(vim.api.nvim_buf_get_lines(bufnr, -2, -1, false)[1] or '') + -- TODO handle offset_encoding + local _, len = vim.str_utfindex(vim.api.nvim_buf_get_lines(bufnr, -2, -1, false)[1] or '') text_edits = vim.tbl_map(function(text_edit) if max <= text_edit.range.start.line then text_edit.range.start.line = max - 1 @@ -1720,7 +1722,9 @@ function M.symbols_to_items(symbols, bufnr) }) if symbol.children then for _, v in ipairs(_symbols_to_items(symbol.children, _items, _bufnr)) do - vim.list_extend(_items, v) + for _, s in ipairs(v) do + table.insert(_items, s) + end end end end @@ -1788,7 +1792,9 @@ local function make_position_param() if not line then return { line = 0; character = 0; } end - col = str_utfindex(line, col) + -- TODO handle offset_encoding + local _ + _, col = str_utfindex(line, col) return { line = row; character = col; } end @@ -1838,11 +1844,14 @@ function M.make_given_range_params(start_pos, end_pos) A[1] = A[1] - 1 B[1] = B[1] - 1 -- account for encoding. + -- TODO handle offset_encoding if A[2] > 0 then - A = {A[1], M.character_offset(0, A[1], A[2])} + local _, char = M.character_offset(0, A[1], A[2]) + A = {A[1], char} end if B[2] > 0 then - B = {B[1], M.character_offset(0, B[1], B[2])} + local _, char = M.character_offset(0, B[1], B[2]) + B = {B[1], char} end -- we need to offset the end character position otherwise we loose the last -- character of the selection, as LSP end position is exclusive diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index b57b7ad4ad..6e40b6ca52 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -605,7 +605,7 @@ do function vim.validate(opt) local ok, err_msg = is_valid(opt) if not ok then - error(debug.traceback(err_msg, 2), 2) + error(err_msg, 2) end end end diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index 5eab20fc54..adc1e16759 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -9,6 +9,11 @@ local M = {} --- - format_item (function item -> text) --- Function to format an --- individual item from `items`. Defaults to `tostring`. +--- - kind (string|nil) +--- Arbitrary hint string indicating the item shape. +--- Plugins reimplementing `vim.ui.select` may wish to +--- use this to infer the structure or semantics of +--- `items`, or the context in which select() was called. ---@param on_choice function ((item|nil, idx|nil) -> ()) --- Called once the user made a choice. --- `idx` is the 1-based index of `item` within `item`. diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py index 813b79bae9..cb80bd05c6 100755 --- a/scripts/gen_vimdoc.py +++ b/scripts/gen_vimdoc.py @@ -89,7 +89,9 @@ CONFIG = { # Section ordering. 'section_order': [ 'vim.c', + 'vimscript.c', 'buffer.c', + 'extmark.c', 'window.c', 'win_config.c', 'tabpage.c', diff --git a/scripts/vim-patch.sh b/scripts/vim-patch.sh index d92480abb9..ac47f6aafd 100755 --- a/scripts/vim-patch.sh +++ b/scripts/vim-patch.sh @@ -183,7 +183,7 @@ assign_commit_details() { # Patch surgery preprocess_patch() { local file="$1" - local nvim="nvim -u NORC -i NONE --headless" + local nvim="nvim -u NONE -n -i NONE --headless" # Remove Filelist, README local na_files='Filelist\|README.*' @@ -683,7 +683,7 @@ review_commit() { msg_ok "Saved pull request diff to '${NVIM_SOURCE_DIR}/n${patch_file}'." CREATED_FILES+=("${NVIM_SOURCE_DIR}/n${patch_file}") - local nvim="nvim -u NORC -n -i NONE --headless" + local nvim="nvim -u NONE -n -i NONE --headless" 2>/dev/null $nvim --cmd 'set dir=/tmp' +'1,/^$/g/^ /-1join' +w +q "${NVIM_SOURCE_DIR}/n${patch_file}" local expected_commit_message diff --git a/src/mpack/lmpack.c b/src/mpack/lmpack.c index 24d27fd17a..87acf46592 100644 --- a/src/mpack/lmpack.c +++ b/src/mpack/lmpack.c @@ -34,7 +34,9 @@ #include "rpc.h" #define UNPACKER_META_NAME "mpack.Unpacker" +#define UNPACK_FN_NAME "decode" #define PACKER_META_NAME "mpack.Packer" +#define PACK_FN_NAME "encode" #define SESSION_META_NAME "mpack.Session" #define NIL_NAME "mpack.NIL" #define EMPTY_DICT_NAME "mpack.empty_dict" @@ -432,8 +434,8 @@ static int lmpack_unpacker_unpack_str(lua_State *L, Unpacker *unpacker, if (unpacker->unpacking) { return luaL_error(L, "Unpacker instance already working. Use another " - "Unpacker or the module's \"unpack\" function if you " - "need to unpack from the ext handler"); + "Unpacker or mpack." UNPACK_FN_NAME "() if you " + "need to " UNPACK_FN_NAME " from the ext handler"); } do { @@ -784,8 +786,8 @@ static int lmpack_packer_pack(lua_State *L) if (packer->packing) { return luaL_error(L, "Packer instance already working. Use another Packer " - "or the module's \"pack\" function if you need to " - "pack from the ext handler"); + "or mpack." PACK_FN_NAME "() if you need to " + PACK_FN_NAME " from the ext handler"); } do { @@ -1161,8 +1163,8 @@ static const luaL_reg mpack_functions[] = { {"Unpacker", lmpack_unpacker_new}, {"Packer", lmpack_packer_new}, {"Session", lmpack_session_new}, - {"unpack", lmpack_unpack}, - {"pack", lmpack_pack}, + {UNPACK_FN_NAME, lmpack_unpack}, + {PACK_FN_NAME, lmpack_pack}, {NULL, NULL} }; diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c index cbfb63581f..4076a0d220 100644 --- a/src/nvim/api/buffer.c +++ b/src/nvim/api/buffer.c @@ -1161,10 +1161,12 @@ Boolean nvim_buf_del_mark(Buffer buffer, String name, Error *err) /// @param name Mark name /// @param line Line number /// @param col Column/row number +/// @param opts Optional parameters. Reserved for future use. /// @return true if the mark was set, else false. /// @see |nvim_buf_del_mark()| /// @see |nvim_buf_get_mark()| -Boolean nvim_buf_set_mark(Buffer buffer, String name, Integer line, Integer col, Error *err) +Boolean nvim_buf_set_mark(Buffer buffer, String name, Integer line, Integer col, Dictionary opts, + Error *err) FUNC_API_SINCE(8) { bool res = false; diff --git a/src/nvim/api/deprecated.c b/src/nvim/api/deprecated.c index 815dd70a52..76b699800e 100644 --- a/src/nvim/api/deprecated.c +++ b/src/nvim/api/deprecated.c @@ -12,6 +12,7 @@ #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" +#include "nvim/api/vimscript.h" #include "nvim/extmark.h" #include "nvim/lua/executor.h" diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index e6756315c6..6f1fb15dac 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -94,7 +94,6 @@ static bool ns_initialized(uint64_t ns) } - static Array extmark_to_array(ExtmarkInfo extmark, bool id, bool add_dict) { Array rv = ARRAY_DICT_INIT; @@ -504,7 +503,7 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer } #define OPTION_TO_BOOL(target, name, val) \ - target = api_object_to_bool(opts-> name, #name, val, err); \ + target = api_object_to_bool(opts->name, #name, val, err); \ if (ERROR_SET(err)) { \ goto error; \ } diff --git a/src/nvim/api/private/converter.c b/src/nvim/api/private/converter.c new file mode 100644 index 0000000000..36da6c13a9 --- /dev/null +++ b/src/nvim/api/private/converter.c @@ -0,0 +1,348 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check +// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + +#include <assert.h> +#include <stddef.h> +#include <stdlib.h> + +#include "nvim/api/private/converter.h" +#include "nvim/api/private/defs.h" +#include "nvim/api/private/helpers.h" +#include "nvim/assert.h" +#include "nvim/eval/typval.h" + +/// Helper structure for vim_to_object +typedef struct { + kvec_withinit_t(Object, 2) stack; ///< Object stack. +} EncodedData; + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "api/private/converter.c.generated.h" +#endif + +#define TYPVAL_ENCODE_ALLOW_SPECIALS false + +#define TYPVAL_ENCODE_CONV_NIL(tv) \ + kvi_push(edata->stack, NIL) + +#define TYPVAL_ENCODE_CONV_BOOL(tv, num) \ + kvi_push(edata->stack, BOOLEAN_OBJ((Boolean)(num))) + +#define TYPVAL_ENCODE_CONV_NUMBER(tv, num) \ + kvi_push(edata->stack, INTEGER_OBJ((Integer)(num))) + +#define TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER TYPVAL_ENCODE_CONV_NUMBER + +#define TYPVAL_ENCODE_CONV_FLOAT(tv, flt) \ + kvi_push(edata->stack, FLOAT_OBJ((Float)(flt))) + +#define TYPVAL_ENCODE_CONV_STRING(tv, str, len) \ + do { \ + const size_t len_ = (size_t)(len); \ + const char *const str_ = (const char *)(str); \ + assert(len_ == 0 || str_ != NULL); \ + kvi_push(edata->stack, STRING_OBJ(cbuf_to_string((len_?str_:""), len_))); \ + } while (0) + +#define TYPVAL_ENCODE_CONV_STR_STRING TYPVAL_ENCODE_CONV_STRING + +#define TYPVAL_ENCODE_CONV_EXT_STRING(tv, str, len, type) \ + TYPVAL_ENCODE_CONV_NIL(tv) + +#define TYPVAL_ENCODE_CONV_BLOB(tv, blob, len) \ + do { \ + const size_t len_ = (size_t)(len); \ + const blob_T *const blob_ = (blob); \ + kvi_push(edata->stack, STRING_OBJ(((String) { \ + .data = len_ != 0 ? xmemdup(blob_->bv_ga.ga_data, len_) : NULL, \ + .size = len_ \ + }))); \ + } while (0) + +#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \ + do { \ + TYPVAL_ENCODE_CONV_NIL(tv); \ + goto typval_encode_stop_converting_one_item; \ + } while (0) + +#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS(tv, len) +#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF(tv, len) +#define TYPVAL_ENCODE_CONV_FUNC_END(tv) + +#define TYPVAL_ENCODE_CONV_EMPTY_LIST(tv) \ + kvi_push(edata->stack, ARRAY_OBJ(((Array) { .capacity = 0, .size = 0 }))) + +#define TYPVAL_ENCODE_CONV_EMPTY_DICT(tv, dict) \ + kvi_push(edata->stack, \ + DICTIONARY_OBJ(((Dictionary) { .capacity = 0, .size = 0 }))) + +static inline void typval_encode_list_start(EncodedData *const edata, const size_t len) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + kvi_push(edata->stack, ARRAY_OBJ(((Array) { + .capacity = len, + .size = 0, + .items = xmalloc(len * sizeof(*((Object)OBJECT_INIT).data.array.items)), + }))); +} + +#define TYPVAL_ENCODE_CONV_LIST_START(tv, len) \ + typval_encode_list_start(edata, (size_t)(len)) + +#define TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START(tv, mpsv) + +static inline void typval_encode_between_list_items(EncodedData *const edata) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + Object item = kv_pop(edata->stack); + Object *const list = &kv_last(edata->stack); + assert(list->type == kObjectTypeArray); + assert(list->data.array.size < list->data.array.capacity); + list->data.array.items[list->data.array.size++] = item; +} + +#define TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS(tv) \ + typval_encode_between_list_items(edata) + +static inline void typval_encode_list_end(EncodedData *const edata) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + typval_encode_between_list_items(edata); +#ifndef NDEBUG + const Object *const list = &kv_last(edata->stack); + assert(list->data.array.size == list->data.array.capacity); +#endif +} + +#define TYPVAL_ENCODE_CONV_LIST_END(tv) \ + typval_encode_list_end(edata) + +static inline void typval_encode_dict_start(EncodedData *const edata, const size_t len) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + kvi_push(edata->stack, DICTIONARY_OBJ(((Dictionary) { + .capacity = len, + .size = 0, + .items = xmalloc(len * sizeof(*((Object)OBJECT_INIT).data.dictionary.items)), + }))); +} + +#define TYPVAL_ENCODE_CONV_DICT_START(tv, dict, len) \ + typval_encode_dict_start(edata, (size_t)(len)) + +#define TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(tv, dict, mpsv) + +#define TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK(label, kv_pair) + +static inline void typval_encode_after_key(EncodedData *const edata) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + Object key = kv_pop(edata->stack); + Object *const dict = &kv_last(edata->stack); + assert(dict->type == kObjectTypeDictionary); + assert(dict->data.dictionary.size < dict->data.dictionary.capacity); + if (key.type == kObjectTypeString) { + dict->data.dictionary.items[dict->data.dictionary.size].key + = key.data.string; + } else { + api_free_object(key); + dict->data.dictionary.items[dict->data.dictionary.size].key + = STATIC_CSTR_TO_STRING("__INVALID_KEY__"); + } +} + +#define TYPVAL_ENCODE_CONV_DICT_AFTER_KEY(tv, dict) \ + typval_encode_after_key(edata) + +static inline void typval_encode_between_dict_items(EncodedData *const edata) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + Object val = kv_pop(edata->stack); + Object *const dict = &kv_last(edata->stack); + assert(dict->type == kObjectTypeDictionary); + assert(dict->data.dictionary.size < dict->data.dictionary.capacity); + dict->data.dictionary.items[dict->data.dictionary.size++].value = val; +} + +#define TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS(tv, dict) \ + typval_encode_between_dict_items(edata) + +static inline void typval_encode_dict_end(EncodedData *const edata) + FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL +{ + typval_encode_between_dict_items(edata); +#ifndef NDEBUG + const Object *const dict = &kv_last(edata->stack); + assert(dict->data.dictionary.size == dict->data.dictionary.capacity); +#endif +} + +#define TYPVAL_ENCODE_CONV_DICT_END(tv, dict) \ + typval_encode_dict_end(edata) + +#define TYPVAL_ENCODE_CONV_RECURSE(val, conv_type) \ + TYPVAL_ENCODE_CONV_NIL(val) + +#define TYPVAL_ENCODE_SCOPE static +#define TYPVAL_ENCODE_NAME object +#define TYPVAL_ENCODE_FIRST_ARG_TYPE EncodedData *const +#define TYPVAL_ENCODE_FIRST_ARG_NAME edata +#include "nvim/eval/typval_encode.c.h" +#undef TYPVAL_ENCODE_SCOPE +#undef TYPVAL_ENCODE_NAME +#undef TYPVAL_ENCODE_FIRST_ARG_TYPE +#undef TYPVAL_ENCODE_FIRST_ARG_NAME + +#undef TYPVAL_ENCODE_CONV_STRING +#undef TYPVAL_ENCODE_CONV_STR_STRING +#undef TYPVAL_ENCODE_CONV_EXT_STRING +#undef TYPVAL_ENCODE_CONV_BLOB +#undef TYPVAL_ENCODE_CONV_NUMBER +#undef TYPVAL_ENCODE_CONV_FLOAT +#undef TYPVAL_ENCODE_CONV_FUNC_START +#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS +#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF +#undef TYPVAL_ENCODE_CONV_FUNC_END +#undef TYPVAL_ENCODE_CONV_EMPTY_LIST +#undef TYPVAL_ENCODE_CONV_LIST_START +#undef TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START +#undef TYPVAL_ENCODE_CONV_EMPTY_DICT +#undef TYPVAL_ENCODE_CONV_NIL +#undef TYPVAL_ENCODE_CONV_BOOL +#undef TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER +#undef TYPVAL_ENCODE_CONV_DICT_START +#undef TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START +#undef TYPVAL_ENCODE_CONV_DICT_END +#undef TYPVAL_ENCODE_CONV_DICT_AFTER_KEY +#undef TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS +#undef TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK +#undef TYPVAL_ENCODE_CONV_LIST_END +#undef TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS +#undef TYPVAL_ENCODE_CONV_RECURSE +#undef TYPVAL_ENCODE_ALLOW_SPECIALS + +/// Convert a vim object to an `Object` instance, recursively expanding +/// Arrays/Dictionaries. +/// +/// @param obj The source object +/// @return The converted value +Object vim_to_object(typval_T *obj) +{ + EncodedData edata; + kvi_init(edata.stack); + const int evo_ret = encode_vim_to_object(&edata, obj, + "vim_to_object argument"); + (void)evo_ret; + assert(evo_ret == OK); + Object ret = kv_A(edata.stack, 0); + assert(kv_size(edata.stack) == 1); + kvi_destroy(edata.stack); + return ret; +} + +/// Converts from type Object to a VimL value. +/// +/// @param obj Object to convert from. +/// @param tv Conversion result is placed here. On failure member v_type is +/// set to VAR_UNKNOWN (no allocation was made for this variable). +/// returns true if conversion is successful, otherwise false. +bool object_to_vim(Object obj, typval_T *tv, Error *err) +{ + tv->v_type = VAR_UNKNOWN; + tv->v_lock = VAR_UNLOCKED; + + switch (obj.type) { + case kObjectTypeNil: + tv->v_type = VAR_SPECIAL; + tv->vval.v_special = kSpecialVarNull; + break; + + case kObjectTypeBoolean: + tv->v_type = VAR_BOOL; + tv->vval.v_bool = obj.data.boolean? kBoolVarTrue: kBoolVarFalse; + break; + + case kObjectTypeBuffer: + case kObjectTypeWindow: + case kObjectTypeTabpage: + case kObjectTypeInteger: + STATIC_ASSERT(sizeof(obj.data.integer) <= sizeof(varnumber_T), + "Integer size must be <= VimL number size"); + tv->v_type = VAR_NUMBER; + tv->vval.v_number = (varnumber_T)obj.data.integer; + break; + + case kObjectTypeFloat: + tv->v_type = VAR_FLOAT; + tv->vval.v_float = obj.data.floating; + break; + + case kObjectTypeString: + tv->v_type = VAR_STRING; + if (obj.data.string.data == NULL) { + tv->vval.v_string = NULL; + } else { + tv->vval.v_string = xmemdupz(obj.data.string.data, + obj.data.string.size); + } + break; + + case kObjectTypeArray: { + list_T *const list = tv_list_alloc((ptrdiff_t)obj.data.array.size); + + for (uint32_t i = 0; i < obj.data.array.size; i++) { + Object item = obj.data.array.items[i]; + typval_T li_tv; + + if (!object_to_vim(item, &li_tv, err)) { + tv_list_free(list); + return false; + } + + tv_list_append_owned_tv(list, li_tv); + } + tv_list_ref(list); + + tv->v_type = VAR_LIST; + tv->vval.v_list = list; + break; + } + + case kObjectTypeDictionary: { + dict_T *const dict = tv_dict_alloc(); + + for (uint32_t i = 0; i < obj.data.dictionary.size; i++) { + KeyValuePair item = obj.data.dictionary.items[i]; + String key = item.key; + + if (key.size == 0) { + api_set_error(err, kErrorTypeValidation, + "Empty dictionary keys aren't allowed"); + // cleanup + tv_dict_free(dict); + return false; + } + + dictitem_T *const di = tv_dict_item_alloc(key.data); + + if (!object_to_vim(item.value, &di->di_tv, err)) { + // cleanup + tv_dict_item_free(di); + tv_dict_free(dict); + return false; + } + + tv_dict_add(dict, di); + } + dict->dv_refcount++; + + tv->v_type = VAR_DICT; + tv->vval.v_dict = dict; + break; + } + default: + abort(); + } + + return true; +} diff --git a/src/nvim/api/private/converter.h b/src/nvim/api/private/converter.h new file mode 100644 index 0000000000..80ee640295 --- /dev/null +++ b/src/nvim/api/private/converter.h @@ -0,0 +1,11 @@ +#ifndef NVIM_API_PRIVATE_CONVERTER_H +#define NVIM_API_PRIVATE_CONVERTER_H + +#include "nvim/api/private/defs.h" +#include "nvim/eval/typval.h" + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "api/private/converter.h.generated.h" +#endif + +#endif // NVIM_API_PRIVATE_CONVERTER_H diff --git a/src/nvim/api/private/defs.h b/src/nvim/api/private/defs.h index 663d1e16b5..396fab721d 100644 --- a/src/nvim/api/private/defs.h +++ b/src/nvim/api/private/defs.h @@ -26,7 +26,7 @@ typedef enum { kErrorTypeNone = -1, kErrorTypeException, - kErrorTypeValidation + kErrorTypeValidation, } ErrorType; typedef enum { diff --git a/src/nvim/api/private/dispatch.c b/src/nvim/api/private/dispatch.c index 79af9bf176..8ab7743e01 100644 --- a/src/nvim/api/private/dispatch.c +++ b/src/nvim/api/private/dispatch.c @@ -15,6 +15,7 @@ #include "nvim/api/tabpage.h" #include "nvim/api/ui.h" #include "nvim/api/vim.h" +#include "nvim/api/vimscript.h" #include "nvim/api/win_config.h" #include "nvim/api/window.h" #include "nvim/log.h" diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c index 745681c3f8..d470def277 100644 --- a/src/nvim/api/private/helpers.c +++ b/src/nvim/api/private/helpers.c @@ -8,6 +8,7 @@ #include <stdlib.h> #include <string.h> +#include "nvim/api/private/converter.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" @@ -37,11 +38,6 @@ #include "nvim/vim.h" #include "nvim/window.h" -/// Helper structure for vim_to_object -typedef struct { - kvec_withinit_t(Object, 2) stack; ///< Object stack. -} EncodedData; - #ifdef INCLUDE_GENERATED_DECLARATIONS # include "api/private/funcs_metadata.generated.h" # include "api/private/helpers.c.generated.h" @@ -415,226 +411,6 @@ void set_option_to(uint64_t channel_id, void *to, int type, String name, Object current_sctx = save_current_sctx; } -#define TYPVAL_ENCODE_ALLOW_SPECIALS false - -#define TYPVAL_ENCODE_CONV_NIL(tv) \ - kvi_push(edata->stack, NIL) - -#define TYPVAL_ENCODE_CONV_BOOL(tv, num) \ - kvi_push(edata->stack, BOOLEAN_OBJ((Boolean)(num))) - -#define TYPVAL_ENCODE_CONV_NUMBER(tv, num) \ - kvi_push(edata->stack, INTEGER_OBJ((Integer)(num))) - -#define TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER TYPVAL_ENCODE_CONV_NUMBER - -#define TYPVAL_ENCODE_CONV_FLOAT(tv, flt) \ - kvi_push(edata->stack, FLOAT_OBJ((Float)(flt))) - -#define TYPVAL_ENCODE_CONV_STRING(tv, str, len) \ - do { \ - const size_t len_ = (size_t)(len); \ - const char *const str_ = (const char *)(str); \ - assert(len_ == 0 || str_ != NULL); \ - kvi_push(edata->stack, STRING_OBJ(cbuf_to_string((len_?str_:""), len_))); \ - } while (0) - -#define TYPVAL_ENCODE_CONV_STR_STRING TYPVAL_ENCODE_CONV_STRING - -#define TYPVAL_ENCODE_CONV_EXT_STRING(tv, str, len, type) \ - TYPVAL_ENCODE_CONV_NIL(tv) - -#define TYPVAL_ENCODE_CONV_BLOB(tv, blob, len) \ - do { \ - const size_t len_ = (size_t)(len); \ - const blob_T *const blob_ = (blob); \ - kvi_push(edata->stack, STRING_OBJ(((String) { \ - .data = len_ != 0 ? xmemdup(blob_->bv_ga.ga_data, len_) : NULL, \ - .size = len_ \ - }))); \ - } while (0) - -#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \ - do { \ - TYPVAL_ENCODE_CONV_NIL(tv); \ - goto typval_encode_stop_converting_one_item; \ - } while (0) - -#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS(tv, len) -#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF(tv, len) -#define TYPVAL_ENCODE_CONV_FUNC_END(tv) - -#define TYPVAL_ENCODE_CONV_EMPTY_LIST(tv) \ - kvi_push(edata->stack, ARRAY_OBJ(((Array) { .capacity = 0, .size = 0 }))) - -#define TYPVAL_ENCODE_CONV_EMPTY_DICT(tv, dict) \ - kvi_push(edata->stack, \ - DICTIONARY_OBJ(((Dictionary) { .capacity = 0, .size = 0 }))) - -static inline void typval_encode_list_start(EncodedData *const edata, const size_t len) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - kvi_push(edata->stack, ARRAY_OBJ(((Array) { - .capacity = len, - .size = 0, - .items = xmalloc(len * sizeof(*((Object)OBJECT_INIT).data.array.items)), - }))); -} - -#define TYPVAL_ENCODE_CONV_LIST_START(tv, len) \ - typval_encode_list_start(edata, (size_t)(len)) - -#define TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START(tv, mpsv) - -static inline void typval_encode_between_list_items(EncodedData *const edata) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - Object item = kv_pop(edata->stack); - Object *const list = &kv_last(edata->stack); - assert(list->type == kObjectTypeArray); - assert(list->data.array.size < list->data.array.capacity); - list->data.array.items[list->data.array.size++] = item; -} - -#define TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS(tv) \ - typval_encode_between_list_items(edata) - -static inline void typval_encode_list_end(EncodedData *const edata) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - typval_encode_between_list_items(edata); -#ifndef NDEBUG - const Object *const list = &kv_last(edata->stack); - assert(list->data.array.size == list->data.array.capacity); -#endif -} - -#define TYPVAL_ENCODE_CONV_LIST_END(tv) \ - typval_encode_list_end(edata) - -static inline void typval_encode_dict_start(EncodedData *const edata, const size_t len) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - kvi_push(edata->stack, DICTIONARY_OBJ(((Dictionary) { - .capacity = len, - .size = 0, - .items = xmalloc(len * sizeof( - *((Object)OBJECT_INIT).data.dictionary.items)), - }))); -} - -#define TYPVAL_ENCODE_CONV_DICT_START(tv, dict, len) \ - typval_encode_dict_start(edata, (size_t)(len)) - -#define TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(tv, dict, mpsv) - -#define TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK(label, kv_pair) - -static inline void typval_encode_after_key(EncodedData *const edata) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - Object key = kv_pop(edata->stack); - Object *const dict = &kv_last(edata->stack); - assert(dict->type == kObjectTypeDictionary); - assert(dict->data.dictionary.size < dict->data.dictionary.capacity); - if (key.type == kObjectTypeString) { - dict->data.dictionary.items[dict->data.dictionary.size].key - = key.data.string; - } else { - api_free_object(key); - dict->data.dictionary.items[dict->data.dictionary.size].key - = STATIC_CSTR_TO_STRING("__INVALID_KEY__"); - } -} - -#define TYPVAL_ENCODE_CONV_DICT_AFTER_KEY(tv, dict) \ - typval_encode_after_key(edata) - -static inline void typval_encode_between_dict_items(EncodedData *const edata) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - Object val = kv_pop(edata->stack); - Object *const dict = &kv_last(edata->stack); - assert(dict->type == kObjectTypeDictionary); - assert(dict->data.dictionary.size < dict->data.dictionary.capacity); - dict->data.dictionary.items[dict->data.dictionary.size++].value = val; -} - -#define TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS(tv, dict) \ - typval_encode_between_dict_items(edata) - -static inline void typval_encode_dict_end(EncodedData *const edata) - FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL -{ - typval_encode_between_dict_items(edata); -#ifndef NDEBUG - const Object *const dict = &kv_last(edata->stack); - assert(dict->data.dictionary.size == dict->data.dictionary.capacity); -#endif -} - -#define TYPVAL_ENCODE_CONV_DICT_END(tv, dict) \ - typval_encode_dict_end(edata) - -#define TYPVAL_ENCODE_CONV_RECURSE(val, conv_type) \ - TYPVAL_ENCODE_CONV_NIL(val) - -#define TYPVAL_ENCODE_SCOPE static -#define TYPVAL_ENCODE_NAME object -#define TYPVAL_ENCODE_FIRST_ARG_TYPE EncodedData *const -#define TYPVAL_ENCODE_FIRST_ARG_NAME edata -#include "nvim/eval/typval_encode.c.h" -#undef TYPVAL_ENCODE_SCOPE -#undef TYPVAL_ENCODE_NAME -#undef TYPVAL_ENCODE_FIRST_ARG_TYPE -#undef TYPVAL_ENCODE_FIRST_ARG_NAME - -#undef TYPVAL_ENCODE_CONV_STRING -#undef TYPVAL_ENCODE_CONV_STR_STRING -#undef TYPVAL_ENCODE_CONV_EXT_STRING -#undef TYPVAL_ENCODE_CONV_BLOB -#undef TYPVAL_ENCODE_CONV_NUMBER -#undef TYPVAL_ENCODE_CONV_FLOAT -#undef TYPVAL_ENCODE_CONV_FUNC_START -#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS -#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF -#undef TYPVAL_ENCODE_CONV_FUNC_END -#undef TYPVAL_ENCODE_CONV_EMPTY_LIST -#undef TYPVAL_ENCODE_CONV_LIST_START -#undef TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START -#undef TYPVAL_ENCODE_CONV_EMPTY_DICT -#undef TYPVAL_ENCODE_CONV_NIL -#undef TYPVAL_ENCODE_CONV_BOOL -#undef TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER -#undef TYPVAL_ENCODE_CONV_DICT_START -#undef TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START -#undef TYPVAL_ENCODE_CONV_DICT_END -#undef TYPVAL_ENCODE_CONV_DICT_AFTER_KEY -#undef TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS -#undef TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK -#undef TYPVAL_ENCODE_CONV_LIST_END -#undef TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS -#undef TYPVAL_ENCODE_CONV_RECURSE -#undef TYPVAL_ENCODE_ALLOW_SPECIALS - -/// Convert a vim object to an `Object` instance, recursively expanding -/// Arrays/Dictionaries. -/// -/// @param obj The source object -/// @return The converted value -Object vim_to_object(typval_T *obj) -{ - EncodedData edata; - kvi_init(edata.stack); - const int evo_ret = encode_vim_to_object(&edata, obj, - "vim_to_object argument"); - (void)evo_ret; - assert(evo_ret == OK); - Object ret = kv_A(edata.stack, 0); - assert(kv_size(edata.stack) == 1); - kvi_destroy(edata.stack); - return ret; -} buf_T *find_buffer_by_handle(Buffer buffer, Error *err) { @@ -831,7 +607,7 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String MapArguments parsed_args = MAP_ARGUMENTS_INIT; if (opts) { #define KEY_TO_BOOL(name) \ - parsed_args. name = api_object_to_bool(opts-> name, #name, false, err); \ + parsed_args.name = api_object_to_bool(opts->name, #name, false, err); \ if (ERROR_SET(err)) { \ goto fail_and_free; \ } @@ -966,112 +742,6 @@ bool buf_collect_lines(buf_T *buf, size_t n, int64_t start, bool replace_nl, Arr return true; } -/// Converts from type Object to a VimL value. -/// -/// @param obj Object to convert from. -/// @param tv Conversion result is placed here. On failure member v_type is -/// set to VAR_UNKNOWN (no allocation was made for this variable). -/// returns true if conversion is successful, otherwise false. -bool object_to_vim(Object obj, typval_T *tv, Error *err) -{ - tv->v_type = VAR_UNKNOWN; - tv->v_lock = VAR_UNLOCKED; - - switch (obj.type) { - case kObjectTypeNil: - tv->v_type = VAR_SPECIAL; - tv->vval.v_special = kSpecialVarNull; - break; - - case kObjectTypeBoolean: - tv->v_type = VAR_BOOL; - tv->vval.v_bool = obj.data.boolean? kBoolVarTrue: kBoolVarFalse; - break; - - case kObjectTypeBuffer: - case kObjectTypeWindow: - case kObjectTypeTabpage: - case kObjectTypeInteger: - STATIC_ASSERT(sizeof(obj.data.integer) <= sizeof(varnumber_T), - "Integer size must be <= VimL number size"); - tv->v_type = VAR_NUMBER; - tv->vval.v_number = (varnumber_T)obj.data.integer; - break; - - case kObjectTypeFloat: - tv->v_type = VAR_FLOAT; - tv->vval.v_float = obj.data.floating; - break; - - case kObjectTypeString: - tv->v_type = VAR_STRING; - if (obj.data.string.data == NULL) { - tv->vval.v_string = NULL; - } else { - tv->vval.v_string = xmemdupz(obj.data.string.data, - obj.data.string.size); - } - break; - - case kObjectTypeArray: { - list_T *const list = tv_list_alloc((ptrdiff_t)obj.data.array.size); - - for (uint32_t i = 0; i < obj.data.array.size; i++) { - Object item = obj.data.array.items[i]; - typval_T li_tv; - - if (!object_to_vim(item, &li_tv, err)) { - tv_list_free(list); - return false; - } - - tv_list_append_owned_tv(list, li_tv); - } - tv_list_ref(list); - - tv->v_type = VAR_LIST; - tv->vval.v_list = list; - break; - } - - case kObjectTypeDictionary: { - dict_T *const dict = tv_dict_alloc(); - - for (uint32_t i = 0; i < obj.data.dictionary.size; i++) { - KeyValuePair item = obj.data.dictionary.items[i]; - String key = item.key; - - if (key.size == 0) { - api_set_error(err, kErrorTypeValidation, - "Empty dictionary keys aren't allowed"); - // cleanup - tv_dict_free(dict); - return false; - } - - dictitem_T *const di = tv_dict_item_alloc(key.data); - - if (!object_to_vim(item.value, &di->di_tv, err)) { - // cleanup - tv_dict_item_free(di); - tv_dict_free(dict); - return false; - } - - tv_dict_add(dict, di); - } - dict->dv_refcount++; - - tv->v_type = VAR_DICT; - tv->vval.v_dict = dict; - break; - } - default: - abort(); - } - - return true; -} void api_free_string(String value) { diff --git a/src/nvim/api/private/helpers.h b/src/nvim/api/private/helpers.h index 08d2c8d90c..6d0aec9c90 100644 --- a/src/nvim/api/private/helpers.h +++ b/src/nvim/api/private/helpers.h @@ -1,8 +1,6 @@ #ifndef NVIM_API_PRIVATE_HELPERS_H #define NVIM_API_PRIVATE_HELPERS_H -#include <stdbool.h> - #include "nvim/api/private/defs.h" #include "nvim/decoration.h" #include "nvim/ex_eval.h" diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 7f442c8e52..2fbafb9889 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -10,6 +10,7 @@ #include "nvim/api/buffer.h" #include "nvim/api/deprecated.h" +#include "nvim/api/private/converter.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/dispatch.h" #include "nvim/api/private/helpers.h" @@ -59,84 +60,6 @@ # include "api/vim.c.generated.h" #endif -/// Executes Vimscript (multiline block of Ex-commands), like anonymous -/// |:source|. -/// -/// Unlike |nvim_command()| this function supports heredocs, script-scope (s:), -/// etc. -/// -/// On execution error: fails with VimL error, does not update v:errmsg. -/// -/// @see |execute()| -/// @see |nvim_command()| -/// -/// @param src Vimscript code -/// @param output Capture and return all (non-error, non-shell |:!|) output -/// @param[out] err Error details (Vim error), if any -/// @return Output (non-error, non-shell |:!|) if `output` is true, -/// else empty string. -String nvim_exec(String src, Boolean output, Error *err) - FUNC_API_SINCE(7) -{ - const int save_msg_silent = msg_silent; - garray_T *const save_capture_ga = capture_ga; - garray_T capture_local; - if (output) { - ga_init(&capture_local, 1, 80); - capture_ga = &capture_local; - } - - try_start(); - if (output) { - msg_silent++; - } - do_source_str(src.data, "nvim_exec()"); - if (output) { - capture_ga = save_capture_ga; - msg_silent = save_msg_silent; - } - try_end(err); - - if (ERROR_SET(err)) { - goto theend; - } - - if (output && capture_local.ga_len > 1) { - String s = (String){ - .data = capture_local.ga_data, - .size = (size_t)capture_local.ga_len, - }; - // redir usually (except :echon) prepends a newline. - if (s.data[0] == '\n') { - memmove(s.data, s.data + 1, s.size - 1); - s.data[s.size - 1] = '\0'; - s.size = s.size - 1; - } - return s; // Caller will free the memory. - } -theend: - if (output) { - ga_clear(&capture_local); - } - return (String)STRING_INIT; -} - -/// Executes an ex-command. -/// -/// On execution error: fails with VimL error, does not update v:errmsg. -/// -/// @see |nvim_exec()| -/// -/// @param command Ex-command string -/// @param[out] err Error details (Vim error), if any -void nvim_command(String command, Error *err) - FUNC_API_SINCE(1) -{ - try_start(); - do_cmdline_cmd(command.data); - try_end(err); -} - /// Gets a highlight definition by name. /// /// @param name Highlight group name @@ -477,51 +400,6 @@ String nvim_replace_termcodes(String str, Boolean from_part, Boolean do_lt, Bool return cstr_as_string(ptr); } -/// Evaluates a VimL |expression|. -/// Dictionaries and Lists are recursively expanded. -/// -/// On execution error: fails with VimL error, does not update v:errmsg. -/// -/// @param expr VimL expression string -/// @param[out] err Error details, if any -/// @return Evaluation result or expanded object -Object nvim_eval(String expr, Error *err) - FUNC_API_SINCE(1) -{ - static int recursive = 0; // recursion depth - Object rv = OBJECT_INIT; - - TRY_WRAP({ - // Initialize `force_abort` and `suppress_errthrow` at the top level. - if (!recursive) { - force_abort = false; - suppress_errthrow = false; - current_exception = NULL; - // `did_emsg` is set by emsg(), which cancels execution. - did_emsg = false; - } - recursive++; - try_start(); - - typval_T rettv; - int ok = eval0((char_u *)expr.data, &rettv, NULL, true); - - if (!try_end(err)) { - if (ok == FAIL) { - // Should never happen, try_end() should get the error. #8371 - api_set_error(err, kErrorTypeException, - "Failed to evaluate expression: '%.*s'", 256, expr.data); - } else { - rv = vim_to_object(&rettv); - } - } - - tv_clear(&rettv); - recursive--; - }); - - return rv; -} /// Execute Lua code. Parameters (if any) are available as `...` inside the /// chunk. The chunk can return a value. @@ -562,164 +440,6 @@ Object nvim_notify(String msg, Integer log_level, Dictionary opts, Error *err) return nlua_exec(STATIC_CSTR_AS_STRING("return vim.notify(...)"), args, err); } -/// Calls a VimL function. -/// -/// @param fn Function name -/// @param args Function arguments -/// @param self `self` dict, or NULL for non-dict functions -/// @param[out] err Error details, if any -/// @return Result of the function call -static Object _call_function(String fn, Array args, dict_T *self, Error *err) -{ - static int recursive = 0; // recursion depth - Object rv = OBJECT_INIT; - - if (args.size > MAX_FUNC_ARGS) { - api_set_error(err, kErrorTypeValidation, - "Function called with too many arguments"); - return rv; - } - - // Convert the arguments in args from Object to typval_T values - typval_T vim_args[MAX_FUNC_ARGS + 1]; - size_t i = 0; // also used for freeing the variables - for (; i < args.size; i++) { - if (!object_to_vim(args.items[i], &vim_args[i], err)) { - goto free_vim_args; - } - } - - TRY_WRAP({ - // Initialize `force_abort` and `suppress_errthrow` at the top level. - if (!recursive) { - force_abort = false; - suppress_errthrow = false; - current_exception = NULL; - // `did_emsg` is set by emsg(), which cancels execution. - did_emsg = false; - } - recursive++; - try_start(); - typval_T rettv; - funcexe_T funcexe = FUNCEXE_INIT; - funcexe.firstline = curwin->w_cursor.lnum; - funcexe.lastline = curwin->w_cursor.lnum; - funcexe.evaluate = true; - funcexe.selfdict = self; - // call_func() retval is deceptive, ignore it. Instead we set `msg_list` - // (see above) to capture abort-causing non-exception errors. - (void)call_func((char_u *)fn.data, (int)fn.size, &rettv, (int)args.size, - vim_args, &funcexe); - if (!try_end(err)) { - rv = vim_to_object(&rettv); - } - tv_clear(&rettv); - recursive--; - }); - -free_vim_args: - while (i > 0) { - tv_clear(&vim_args[--i]); - } - - return rv; -} - -/// Calls a VimL function with the given arguments. -/// -/// On execution error: fails with VimL error, does not update v:errmsg. -/// -/// @param fn Function to call -/// @param args Function arguments packed in an Array -/// @param[out] err Error details, if any -/// @return Result of the function call -Object nvim_call_function(String fn, Array args, Error *err) - FUNC_API_SINCE(1) -{ - return _call_function(fn, args, NULL, err); -} - -/// Calls a VimL |Dictionary-function| with the given arguments. -/// -/// On execution error: fails with VimL error, does not update v:errmsg. -/// -/// @param dict Dictionary, or String evaluating to a VimL |self| dict -/// @param fn Name of the function defined on the VimL dict -/// @param args Function arguments packed in an Array -/// @param[out] err Error details, if any -/// @return Result of the function call -Object nvim_call_dict_function(Object dict, String fn, Array args, Error *err) - FUNC_API_SINCE(4) -{ - Object rv = OBJECT_INIT; - - typval_T rettv; - bool mustfree = false; - switch (dict.type) { - case kObjectTypeString: - try_start(); - if (eval0((char_u *)dict.data.string.data, &rettv, NULL, true) == FAIL) { - api_set_error(err, kErrorTypeException, - "Failed to evaluate dict expression"); - } - if (try_end(err)) { - return rv; - } - // Evaluation of the string arg created a new dict or increased the - // refcount of a dict. Not necessary for a RPC dict. - mustfree = true; - break; - case kObjectTypeDictionary: - if (!object_to_vim(dict, &rettv, err)) { - goto end; - } - break; - default: - api_set_error(err, kErrorTypeValidation, - "dict argument type must be String or Dictionary"); - return rv; - } - dict_T *self_dict = rettv.vval.v_dict; - if (rettv.v_type != VAR_DICT || !self_dict) { - api_set_error(err, kErrorTypeValidation, "dict not found"); - goto end; - } - - if (fn.data && fn.size > 0 && dict.type != kObjectTypeDictionary) { - dictitem_T *const di = tv_dict_find(self_dict, fn.data, (ptrdiff_t)fn.size); - if (di == NULL) { - api_set_error(err, kErrorTypeValidation, "Not found: %s", fn.data); - goto end; - } - if (di->di_tv.v_type == VAR_PARTIAL) { - api_set_error(err, kErrorTypeValidation, - "partial function not supported"); - goto end; - } - if (di->di_tv.v_type != VAR_FUNC) { - api_set_error(err, kErrorTypeValidation, "Not a function: %s", fn.data); - goto end; - } - fn = (String) { - .data = (char *)di->di_tv.vval.v_string, - .size = STRLEN(di->di_tv.vval.v_string), - }; - } - - if (!fn.data || fn.size < 1) { - api_set_error(err, kErrorTypeValidation, "Invalid (empty) function name"); - goto end; - } - - rv = _call_function(fn, args, self_dict, err); -end: - if (mustfree) { - tv_clear(&rettv); - } - - return rv; -} - /// Calculates the number of display cells occupied by `text`. /// <Tab> counts as one cell. /// @@ -1990,439 +1710,6 @@ theend: return rv; } -typedef struct { - ExprASTNode **node_p; - Object *ret_node_p; -} ExprASTConvStackItem; - -/// @cond DOXYGEN_NOT_A_FUNCTION -typedef kvec_withinit_t(ExprASTConvStackItem, 16) ExprASTConvStack; -/// @endcond - -/// Parse a VimL expression. -/// -/// @param[in] expr Expression to parse. Always treated as a single line. -/// @param[in] flags Flags: -/// - "m" if multiple expressions in a row are allowed (only -/// the first one will be parsed), -/// - "E" if EOC tokens are not allowed (determines whether -/// they will stop parsing process or be recognized as an -/// operator/space, though also yielding an error). -/// - "l" when needing to start parsing with lvalues for -/// ":let" or ":for". -/// Common flag sets: -/// - "m" to parse like for ":echo". -/// - "E" to parse like for "<C-r>=". -/// - empty string for ":call". -/// - "lm" to parse for ":let". -/// @param[in] highlight If true, return value will also include "highlight" -/// key containing array of 4-tuples (arrays) (Integer, -/// Integer, Integer, String), where first three numbers -/// define the highlighted region and represent line, -/// starting column and ending column (latter exclusive: -/// one should highlight region [start_col, end_col)). -/// -/// @return -/// - AST: top-level dictionary with these keys: -/// - "error": Dictionary with error, present only if parser saw some -/// error. Contains the following keys: -/// - "message": String, error message in printf format, translated. -/// Must contain exactly one "%.*s". -/// - "arg": String, error message argument. -/// - "len": Amount of bytes successfully parsed. With flags equal to "" -/// that should be equal to the length of expr string. -/// (“Successfully parsed” here means “participated in AST -/// creation”, not “till the first error”.) -/// - "ast": AST, either nil or a dictionary with these keys: -/// - "type": node type, one of the value names from ExprASTNodeType -/// stringified without "kExprNode" prefix. -/// - "start": a pair [line, column] describing where node is "started" -/// where "line" is always 0 (will not be 0 if you will be -/// using nvim_parse_viml() on e.g. ":let", but that is not -/// present yet). Both elements are Integers. -/// - "len": “length” of the node. This and "start" are there for -/// debugging purposes primary (debugging parser and providing -/// debug information). -/// - "children": a list of nodes described in top/"ast". There always -/// is zero, one or two children, key will not be present -/// if node has no children. Maximum number of children -/// may be found in node_maxchildren array. -/// - Local values (present only for certain nodes): -/// - "scope": a single Integer, specifies scope for "Option" and -/// "PlainIdentifier" nodes. For "Option" it is one of -/// ExprOptScope values, for "PlainIdentifier" it is one of -/// ExprVarScope values. -/// - "ident": identifier (without scope, if any), present for "Option", -/// "PlainIdentifier", "PlainKey" and "Environment" nodes. -/// - "name": Integer, register name (one character) or -1. Only present -/// for "Register" nodes. -/// - "cmp_type": String, comparison type, one of the value names from -/// ExprComparisonType, stringified without "kExprCmp" -/// prefix. Only present for "Comparison" nodes. -/// - "ccs_strategy": String, case comparison strategy, one of the -/// value names from ExprCaseCompareStrategy, -/// stringified without "kCCStrategy" prefix. Only -/// present for "Comparison" nodes. -/// - "augmentation": String, augmentation type for "Assignment" nodes. -/// Is either an empty string, "Add", "Subtract" or -/// "Concat" for "=", "+=", "-=" or ".=" respectively. -/// - "invert": Boolean, true if result of comparison needs to be -/// inverted. Only present for "Comparison" nodes. -/// - "ivalue": Integer, integer value for "Integer" nodes. -/// - "fvalue": Float, floating-point value for "Float" nodes. -/// - "svalue": String, value for "SingleQuotedString" and -/// "DoubleQuotedString" nodes. -/// @param[out] err Error details, if any -Dictionary nvim_parse_expression(String expr, String flags, Boolean highlight, Error *err) - FUNC_API_SINCE(4) FUNC_API_FAST -{ - int pflags = 0; - for (size_t i = 0 ; i < flags.size ; i++) { - switch (flags.data[i]) { - case 'm': - pflags |= kExprFlagsMulti; break; - case 'E': - pflags |= kExprFlagsDisallowEOC; break; - case 'l': - pflags |= kExprFlagsParseLet; break; - case NUL: - api_set_error(err, kErrorTypeValidation, "Invalid flag: '\\0' (%u)", - (unsigned)flags.data[i]); - return (Dictionary)ARRAY_DICT_INIT; - default: - api_set_error(err, kErrorTypeValidation, "Invalid flag: '%c' (%u)", - flags.data[i], (unsigned)flags.data[i]); - return (Dictionary)ARRAY_DICT_INIT; - } - } - ParserLine parser_lines[] = { - { - .data = expr.data, - .size = expr.size, - .allocated = false, - }, - { NULL, 0, false }, - }; - ParserLine *plines_p = parser_lines; - ParserHighlight colors; - kvi_init(colors); - ParserHighlight *const colors_p = (highlight ? &colors : NULL); - ParserState pstate; - viml_parser_init(&pstate, parser_simple_get_line, &plines_p, colors_p); - ExprAST east = viml_pexpr_parse(&pstate, pflags); - - const size_t ret_size = ( - 2 // "ast", "len" - + (size_t)(east.err.msg != NULL) // "error" - + (size_t)highlight // "highlight" - + 0); - Dictionary ret = { - .items = xmalloc(ret_size * sizeof(ret.items[0])), - .size = 0, - .capacity = ret_size, - }; - ret.items[ret.size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ast"), - .value = NIL, - }; - ret.items[ret.size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("len"), - .value = INTEGER_OBJ((Integer)(pstate.pos.line == 1 - ? parser_lines[0].size - : pstate.pos.col)), - }; - if (east.err.msg != NULL) { - Dictionary err_dict = { - .items = xmalloc(2 * sizeof(err_dict.items[0])), - .size = 2, - .capacity = 2, - }; - err_dict.items[0] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("message"), - .value = STRING_OBJ(cstr_to_string(east.err.msg)), - }; - if (east.err.arg == NULL) { - err_dict.items[1] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("arg"), - .value = STRING_OBJ(STRING_INIT), - }; - } else { - err_dict.items[1] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("arg"), - .value = STRING_OBJ(((String) { - .data = xmemdupz(east.err.arg, (size_t)east.err.arg_len), - .size = (size_t)east.err.arg_len, - })), - }; - } - ret.items[ret.size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("error"), - .value = DICTIONARY_OBJ(err_dict), - }; - } - if (highlight) { - Array hl = (Array) { - .items = xmalloc(kv_size(colors) * sizeof(hl.items[0])), - .capacity = kv_size(colors), - .size = kv_size(colors), - }; - for (size_t i = 0 ; i < kv_size(colors) ; i++) { - const ParserHighlightChunk chunk = kv_A(colors, i); - Array chunk_arr = (Array) { - .items = xmalloc(4 * sizeof(chunk_arr.items[0])), - .capacity = 4, - .size = 4, - }; - chunk_arr.items[0] = INTEGER_OBJ((Integer)chunk.start.line); - chunk_arr.items[1] = INTEGER_OBJ((Integer)chunk.start.col); - chunk_arr.items[2] = INTEGER_OBJ((Integer)chunk.end_col); - chunk_arr.items[3] = STRING_OBJ(cstr_to_string(chunk.group)); - hl.items[i] = ARRAY_OBJ(chunk_arr); - } - ret.items[ret.size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("highlight"), - .value = ARRAY_OBJ(hl), - }; - } - kvi_destroy(colors); - - // Walk over the AST, freeing nodes in process. - ExprASTConvStack ast_conv_stack; - kvi_init(ast_conv_stack); - kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { - .node_p = &east.root, - .ret_node_p = &ret.items[0].value, - })); - while (kv_size(ast_conv_stack)) { - ExprASTConvStackItem cur_item = kv_last(ast_conv_stack); - ExprASTNode *const node = *cur_item.node_p; - if (node == NULL) { - assert(kv_size(ast_conv_stack) == 1); - kv_drop(ast_conv_stack, 1); - } else { - if (cur_item.ret_node_p->type == kObjectTypeNil) { - const size_t ret_node_items_size = (size_t)( - 3 // "type", "start" and "len" - + (node->children != NULL) // "children" - + (node->type == kExprNodeOption - || node->type == kExprNodePlainIdentifier) // "scope" - + (node->type == kExprNodeOption - || node->type == kExprNodePlainIdentifier - || node->type == kExprNodePlainKey - || node->type == kExprNodeEnvironment) // "ident" - + (node->type == kExprNodeRegister) // "name" - + (3 // "cmp_type", "ccs_strategy", "invert" - * (node->type == kExprNodeComparison)) - + (node->type == kExprNodeInteger) // "ivalue" - + (node->type == kExprNodeFloat) // "fvalue" - + (node->type == kExprNodeDoubleQuotedString - || node->type == kExprNodeSingleQuotedString) // "svalue" - + (node->type == kExprNodeAssignment) // "augmentation" - + 0); - Dictionary ret_node = { - .items = xmalloc(ret_node_items_size * sizeof(ret_node.items[0])), - .capacity = ret_node_items_size, - .size = 0, - }; - *cur_item.ret_node_p = DICTIONARY_OBJ(ret_node); - } - Dictionary *ret_node = &cur_item.ret_node_p->data.dictionary; - if (node->children != NULL) { - const size_t num_children = 1 + (node->children->next != NULL); - Array children_array = { - .items = xmalloc(num_children * sizeof(children_array.items[0])), - .capacity = num_children, - .size = num_children, - }; - for (size_t i = 0; i < num_children; i++) { - children_array.items[i] = NIL; - } - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("children"), - .value = ARRAY_OBJ(children_array), - }; - kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { - .node_p = &node->children, - .ret_node_p = &children_array.items[0], - })); - } else if (node->next != NULL) { - kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { - .node_p = &node->next, - .ret_node_p = cur_item.ret_node_p + 1, - })); - } else { - kv_drop(ast_conv_stack, 1); - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("type"), - .value = STRING_OBJ(cstr_to_string(east_node_type_tab[node->type])), - }; - Array start_array = { - .items = xmalloc(2 * sizeof(start_array.items[0])), - .capacity = 2, - .size = 2, - }; - start_array.items[0] = INTEGER_OBJ((Integer)node->start.line); - start_array.items[1] = INTEGER_OBJ((Integer)node->start.col); - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("start"), - .value = ARRAY_OBJ(start_array), - }; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("len"), - .value = INTEGER_OBJ((Integer)node->len), - }; - switch (node->type) { - case kExprNodeDoubleQuotedString: - case kExprNodeSingleQuotedString: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("svalue"), - .value = STRING_OBJ(((String) { - .data = node->data.str.value, - .size = node->data.str.size, - })), - }; - break; - case kExprNodeOption: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("scope"), - .value = INTEGER_OBJ(node->data.opt.scope), - }; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ident"), - .value = STRING_OBJ(((String) { - .data = xmemdupz(node->data.opt.ident, - node->data.opt.ident_len), - .size = node->data.opt.ident_len, - })), - }; - break; - case kExprNodePlainIdentifier: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("scope"), - .value = INTEGER_OBJ(node->data.var.scope), - }; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ident"), - .value = STRING_OBJ(((String) { - .data = xmemdupz(node->data.var.ident, - node->data.var.ident_len), - .size = node->data.var.ident_len, - })), - }; - break; - case kExprNodePlainKey: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ident"), - .value = STRING_OBJ(((String) { - .data = xmemdupz(node->data.var.ident, - node->data.var.ident_len), - .size = node->data.var.ident_len, - })), - }; - break; - case kExprNodeEnvironment: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ident"), - .value = STRING_OBJ(((String) { - .data = xmemdupz(node->data.env.ident, - node->data.env.ident_len), - .size = node->data.env.ident_len, - })), - }; - break; - case kExprNodeRegister: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("name"), - .value = INTEGER_OBJ(node->data.reg.name), - }; - break; - case kExprNodeComparison: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("cmp_type"), - .value = STRING_OBJ(cstr_to_string(eltkn_cmp_type_tab[node->data.cmp.type])), - }; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ccs_strategy"), - .value = STRING_OBJ(cstr_to_string(ccs_tab[node->data.cmp.ccs])), - }; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("invert"), - .value = BOOLEAN_OBJ(node->data.cmp.inv), - }; - break; - case kExprNodeFloat: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("fvalue"), - .value = FLOAT_OBJ(node->data.flt.value), - }; - break; - case kExprNodeInteger: - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("ivalue"), - .value = INTEGER_OBJ((Integer)( - node->data.num.value > API_INTEGER_MAX - ? API_INTEGER_MAX - : (Integer)node->data.num.value)), - }; - break; - case kExprNodeAssignment: { - const ExprAssignmentType asgn_type = node->data.ass.type; - ret_node->items[ret_node->size++] = (KeyValuePair) { - .key = STATIC_CSTR_TO_STRING("augmentation"), - .value = STRING_OBJ(asgn_type == kExprAsgnPlain - ? (String)STRING_INIT - : cstr_to_string(expr_asgn_type_tab[asgn_type])), - }; - break; - } - case kExprNodeMissing: - case kExprNodeOpMissing: - case kExprNodeTernary: - case kExprNodeTernaryValue: - case kExprNodeSubscript: - case kExprNodeListLiteral: - case kExprNodeUnaryPlus: - case kExprNodeBinaryPlus: - case kExprNodeNested: - case kExprNodeCall: - case kExprNodeComplexIdentifier: - case kExprNodeUnknownFigure: - case kExprNodeLambda: - case kExprNodeDictLiteral: - case kExprNodeCurlyBracesIdentifier: - case kExprNodeComma: - case kExprNodeColon: - case kExprNodeArrow: - case kExprNodeConcat: - case kExprNodeConcatOrSubscript: - case kExprNodeOr: - case kExprNodeAnd: - case kExprNodeUnaryMinus: - case kExprNodeBinaryMinus: - case kExprNodeNot: - case kExprNodeMultiplication: - case kExprNodeDivision: - case kExprNodeMod: - break; - } - assert(cur_item.ret_node_p->data.dictionary.size - == cur_item.ret_node_p->data.dictionary.capacity); - xfree(*cur_item.node_p); - *cur_item.node_p = NULL; - } - } - } - kvi_destroy(ast_conv_stack); - - assert(ret.size == ret.capacity); - // Should be a no-op actually, leaving it in case non-nodes will need to be - // freed later. - viml_pexpr_free_ast(east); - viml_parser_destroy(&pstate); - return ret; -} - - /// Writes a message to vim output or error buffer. The string is split /// and flushed after each newline. Incomplete lines are kept for writing /// later. @@ -2437,11 +1724,10 @@ static void write_msg(String message, bool to_err) #define PUSH_CHAR(i, pos, line_buf, msg) \ if (message.data[i] == NL || pos == LINE_BUFFER_SIZE - 1) { \ line_buf[pos] = NUL; \ - msg((char_u *)line_buf); \ + msg(line_buf); \ pos = 0; \ continue; \ } \ - \ line_buf[pos++] = message.data[i]; ++no_wait_return; @@ -2727,11 +2013,12 @@ Boolean nvim_del_mark(String name, Error *err) /// /// @note fails with error if a lowercase or buffer local named mark is used. /// @param name Mark name +/// @param opts Optional parameters. Reserved for future use. /// @return 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is /// not set. /// @see |nvim_buf_set_mark()| /// @see |nvim_del_mark()| -Array nvim_get_mark(String name, Error *err) +Array nvim_get_mark(String name, Dictionary opts, Error *err) FUNC_API_SINCE(8) { Array rv = ARRAY_DICT_INIT; @@ -2895,16 +2182,15 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error * int p_crb_save = ewp->w_p_crb; ewp->w_p_crb = false; - int width = build_stl_str_hl( - ewp, - (char_u *)buf, - sizeof(buf), - (char_u *)str.data, - false, - (char_u)fillchar, - maxwidth, - hltab_ptr, - NULL); + int width = build_stl_str_hl(ewp, + (char_u *)buf, + sizeof(buf), + (char_u *)str.data, + false, + (char_u)fillchar, + maxwidth, + hltab_ptr, + NULL); PUT(result, "width", INTEGER_OBJ(width)); diff --git a/src/nvim/api/vimscript.c b/src/nvim/api/vimscript.c new file mode 100644 index 0000000000..c516cedaf4 --- /dev/null +++ b/src/nvim/api/vimscript.c @@ -0,0 +1,733 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check +// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + +#include <assert.h> +#include <limits.h> +#include <stdlib.h> + +#include "nvim/api/private/converter.h" +#include "nvim/api/private/defs.h" +#include "nvim/api/private/helpers.h" +#include "nvim/api/vimscript.h" +#include "nvim/ascii.h" +#include "nvim/eval.h" +#include "nvim/eval/typval.h" +#include "nvim/eval/userfunc.h" +#include "nvim/ex_cmds2.h" +#include "nvim/viml/parser/expressions.h" +#include "nvim/viml/parser/parser.h" + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "api/vimscript.c.generated.h" +#endif + +/// Executes Vimscript (multiline block of Ex-commands), like anonymous +/// |:source|. +/// +/// Unlike |nvim_command()| this function supports heredocs, script-scope (s:), +/// etc. +/// +/// On execution error: fails with VimL error, does not update v:errmsg. +/// +/// @see |execute()| +/// @see |nvim_command()| +/// +/// @param src Vimscript code +/// @param output Capture and return all (non-error, non-shell |:!|) output +/// @param[out] err Error details (Vim error), if any +/// @return Output (non-error, non-shell |:!|) if `output` is true, +/// else empty string. +String nvim_exec(String src, Boolean output, Error *err) + FUNC_API_SINCE(7) +{ + const int save_msg_silent = msg_silent; + garray_T *const save_capture_ga = capture_ga; + garray_T capture_local; + if (output) { + ga_init(&capture_local, 1, 80); + capture_ga = &capture_local; + } + + try_start(); + if (output) { + msg_silent++; + } + do_source_str(src.data, "nvim_exec()"); + if (output) { + capture_ga = save_capture_ga; + msg_silent = save_msg_silent; + } + try_end(err); + + if (ERROR_SET(err)) { + goto theend; + } + + if (output && capture_local.ga_len > 1) { + String s = (String){ + .data = capture_local.ga_data, + .size = (size_t)capture_local.ga_len, + }; + // redir usually (except :echon) prepends a newline. + if (s.data[0] == '\n') { + memmove(s.data, s.data + 1, s.size - 1); + s.data[s.size - 1] = '\0'; + s.size = s.size - 1; + } + return s; // Caller will free the memory. + } +theend: + if (output) { + ga_clear(&capture_local); + } + return (String)STRING_INIT; +} + +/// Executes an ex-command. +/// +/// On execution error: fails with VimL error, does not update v:errmsg. +/// +/// @see |nvim_exec()| +/// +/// @param command Ex-command string +/// @param[out] err Error details (Vim error), if any +void nvim_command(String command, Error *err) + FUNC_API_SINCE(1) +{ + try_start(); + do_cmdline_cmd(command.data); + try_end(err); +} + +/// Evaluates a VimL |expression|. +/// Dictionaries and Lists are recursively expanded. +/// +/// On execution error: fails with VimL error, does not update v:errmsg. +/// +/// @param expr VimL expression string +/// @param[out] err Error details, if any +/// @return Evaluation result or expanded object +Object nvim_eval(String expr, Error *err) + FUNC_API_SINCE(1) +{ + static int recursive = 0; // recursion depth + Object rv = OBJECT_INIT; + + TRY_WRAP({ + // Initialize `force_abort` and `suppress_errthrow` at the top level. + if (!recursive) { + force_abort = false; + suppress_errthrow = false; + current_exception = NULL; + // `did_emsg` is set by emsg(), which cancels execution. + did_emsg = false; + } + recursive++; + try_start(); + + typval_T rettv; + int ok = eval0((char_u *)expr.data, &rettv, NULL, true); + + if (!try_end(err)) { + if (ok == FAIL) { + // Should never happen, try_end() should get the error. #8371 + api_set_error(err, kErrorTypeException, + "Failed to evaluate expression: '%.*s'", 256, expr.data); + } else { + rv = vim_to_object(&rettv); + } + } + + tv_clear(&rettv); + recursive--; + }); + + return rv; +} + +/// Calls a VimL function. +/// +/// @param fn Function name +/// @param args Function arguments +/// @param self `self` dict, or NULL for non-dict functions +/// @param[out] err Error details, if any +/// @return Result of the function call +static Object _call_function(String fn, Array args, dict_T *self, Error *err) +{ + static int recursive = 0; // recursion depth + Object rv = OBJECT_INIT; + + if (args.size > MAX_FUNC_ARGS) { + api_set_error(err, kErrorTypeValidation, + "Function called with too many arguments"); + return rv; + } + + // Convert the arguments in args from Object to typval_T values + typval_T vim_args[MAX_FUNC_ARGS + 1]; + size_t i = 0; // also used for freeing the variables + for (; i < args.size; i++) { + if (!object_to_vim(args.items[i], &vim_args[i], err)) { + goto free_vim_args; + } + } + + TRY_WRAP({ + // Initialize `force_abort` and `suppress_errthrow` at the top level. + if (!recursive) { + force_abort = false; + suppress_errthrow = false; + current_exception = NULL; + // `did_emsg` is set by emsg(), which cancels execution. + did_emsg = false; + } + recursive++; + try_start(); + typval_T rettv; + funcexe_T funcexe = FUNCEXE_INIT; + funcexe.firstline = curwin->w_cursor.lnum; + funcexe.lastline = curwin->w_cursor.lnum; + funcexe.evaluate = true; + funcexe.selfdict = self; + // call_func() retval is deceptive, ignore it. Instead we set `msg_list` + // (see above) to capture abort-causing non-exception errors. + (void)call_func((char_u *)fn.data, (int)fn.size, &rettv, (int)args.size, + vim_args, &funcexe); + if (!try_end(err)) { + rv = vim_to_object(&rettv); + } + tv_clear(&rettv); + recursive--; + }); + +free_vim_args: + while (i > 0) { + tv_clear(&vim_args[--i]); + } + + return rv; +} + +/// Calls a VimL function with the given arguments. +/// +/// On execution error: fails with VimL error, does not update v:errmsg. +/// +/// @param fn Function to call +/// @param args Function arguments packed in an Array +/// @param[out] err Error details, if any +/// @return Result of the function call +Object nvim_call_function(String fn, Array args, Error *err) + FUNC_API_SINCE(1) +{ + return _call_function(fn, args, NULL, err); +} + +/// Calls a VimL |Dictionary-function| with the given arguments. +/// +/// On execution error: fails with VimL error, does not update v:errmsg. +/// +/// @param dict Dictionary, or String evaluating to a VimL |self| dict +/// @param fn Name of the function defined on the VimL dict +/// @param args Function arguments packed in an Array +/// @param[out] err Error details, if any +/// @return Result of the function call +Object nvim_call_dict_function(Object dict, String fn, Array args, Error *err) + FUNC_API_SINCE(4) +{ + Object rv = OBJECT_INIT; + + typval_T rettv; + bool mustfree = false; + switch (dict.type) { + case kObjectTypeString: + try_start(); + if (eval0((char_u *)dict.data.string.data, &rettv, NULL, true) == FAIL) { + api_set_error(err, kErrorTypeException, + "Failed to evaluate dict expression"); + } + if (try_end(err)) { + return rv; + } + // Evaluation of the string arg created a new dict or increased the + // refcount of a dict. Not necessary for a RPC dict. + mustfree = true; + break; + case kObjectTypeDictionary: + if (!object_to_vim(dict, &rettv, err)) { + goto end; + } + break; + default: + api_set_error(err, kErrorTypeValidation, + "dict argument type must be String or Dictionary"); + return rv; + } + dict_T *self_dict = rettv.vval.v_dict; + if (rettv.v_type != VAR_DICT || !self_dict) { + api_set_error(err, kErrorTypeValidation, "dict not found"); + goto end; + } + + if (fn.data && fn.size > 0 && dict.type != kObjectTypeDictionary) { + dictitem_T *const di = tv_dict_find(self_dict, fn.data, (ptrdiff_t)fn.size); + if (di == NULL) { + api_set_error(err, kErrorTypeValidation, "Not found: %s", fn.data); + goto end; + } + if (di->di_tv.v_type == VAR_PARTIAL) { + api_set_error(err, kErrorTypeValidation, + "partial function not supported"); + goto end; + } + if (di->di_tv.v_type != VAR_FUNC) { + api_set_error(err, kErrorTypeValidation, "Not a function: %s", fn.data); + goto end; + } + fn = (String) { + .data = (char *)di->di_tv.vval.v_string, + .size = STRLEN(di->di_tv.vval.v_string), + }; + } + + if (!fn.data || fn.size < 1) { + api_set_error(err, kErrorTypeValidation, "Invalid (empty) function name"); + goto end; + } + + rv = _call_function(fn, args, self_dict, err); +end: + if (mustfree) { + tv_clear(&rettv); + } + + return rv; +} + +typedef struct { + ExprASTNode **node_p; + Object *ret_node_p; +} ExprASTConvStackItem; + +/// @cond DOXYGEN_NOT_A_FUNCTION +typedef kvec_withinit_t(ExprASTConvStackItem, 16) ExprASTConvStack; +/// @endcond + +/// Parse a VimL expression. +/// +/// @param[in] expr Expression to parse. Always treated as a single line. +/// @param[in] flags Flags: +/// - "m" if multiple expressions in a row are allowed (only +/// the first one will be parsed), +/// - "E" if EOC tokens are not allowed (determines whether +/// they will stop parsing process or be recognized as an +/// operator/space, though also yielding an error). +/// - "l" when needing to start parsing with lvalues for +/// ":let" or ":for". +/// Common flag sets: +/// - "m" to parse like for ":echo". +/// - "E" to parse like for "<C-r>=". +/// - empty string for ":call". +/// - "lm" to parse for ":let". +/// @param[in] highlight If true, return value will also include "highlight" +/// key containing array of 4-tuples (arrays) (Integer, +/// Integer, Integer, String), where first three numbers +/// define the highlighted region and represent line, +/// starting column and ending column (latter exclusive: +/// one should highlight region [start_col, end_col)). +/// +/// @return +/// - AST: top-level dictionary with these keys: +/// - "error": Dictionary with error, present only if parser saw some +/// error. Contains the following keys: +/// - "message": String, error message in printf format, translated. +/// Must contain exactly one "%.*s". +/// - "arg": String, error message argument. +/// - "len": Amount of bytes successfully parsed. With flags equal to "" +/// that should be equal to the length of expr string. +/// (“Successfully parsed” here means “participated in AST +/// creation”, not “till the first error”.) +/// - "ast": AST, either nil or a dictionary with these keys: +/// - "type": node type, one of the value names from ExprASTNodeType +/// stringified without "kExprNode" prefix. +/// - "start": a pair [line, column] describing where node is "started" +/// where "line" is always 0 (will not be 0 if you will be +/// using nvim_parse_viml() on e.g. ":let", but that is not +/// present yet). Both elements are Integers. +/// - "len": “length” of the node. This and "start" are there for +/// debugging purposes primary (debugging parser and providing +/// debug information). +/// - "children": a list of nodes described in top/"ast". There always +/// is zero, one or two children, key will not be present +/// if node has no children. Maximum number of children +/// may be found in node_maxchildren array. +/// - Local values (present only for certain nodes): +/// - "scope": a single Integer, specifies scope for "Option" and +/// "PlainIdentifier" nodes. For "Option" it is one of +/// ExprOptScope values, for "PlainIdentifier" it is one of +/// ExprVarScope values. +/// - "ident": identifier (without scope, if any), present for "Option", +/// "PlainIdentifier", "PlainKey" and "Environment" nodes. +/// - "name": Integer, register name (one character) or -1. Only present +/// for "Register" nodes. +/// - "cmp_type": String, comparison type, one of the value names from +/// ExprComparisonType, stringified without "kExprCmp" +/// prefix. Only present for "Comparison" nodes. +/// - "ccs_strategy": String, case comparison strategy, one of the +/// value names from ExprCaseCompareStrategy, +/// stringified without "kCCStrategy" prefix. Only +/// present for "Comparison" nodes. +/// - "augmentation": String, augmentation type for "Assignment" nodes. +/// Is either an empty string, "Add", "Subtract" or +/// "Concat" for "=", "+=", "-=" or ".=" respectively. +/// - "invert": Boolean, true if result of comparison needs to be +/// inverted. Only present for "Comparison" nodes. +/// - "ivalue": Integer, integer value for "Integer" nodes. +/// - "fvalue": Float, floating-point value for "Float" nodes. +/// - "svalue": String, value for "SingleQuotedString" and +/// "DoubleQuotedString" nodes. +/// @param[out] err Error details, if any +Dictionary nvim_parse_expression(String expr, String flags, Boolean highlight, Error *err) + FUNC_API_SINCE(4) FUNC_API_FAST +{ + int pflags = 0; + for (size_t i = 0 ; i < flags.size ; i++) { + switch (flags.data[i]) { + case 'm': + pflags |= kExprFlagsMulti; break; + case 'E': + pflags |= kExprFlagsDisallowEOC; break; + case 'l': + pflags |= kExprFlagsParseLet; break; + case NUL: + api_set_error(err, kErrorTypeValidation, "Invalid flag: '\\0' (%u)", + (unsigned)flags.data[i]); + return (Dictionary)ARRAY_DICT_INIT; + default: + api_set_error(err, kErrorTypeValidation, "Invalid flag: '%c' (%u)", + flags.data[i], (unsigned)flags.data[i]); + return (Dictionary)ARRAY_DICT_INIT; + } + } + ParserLine parser_lines[] = { + { + .data = expr.data, + .size = expr.size, + .allocated = false, + }, + { NULL, 0, false }, + }; + ParserLine *plines_p = parser_lines; + ParserHighlight colors; + kvi_init(colors); + ParserHighlight *const colors_p = (highlight ? &colors : NULL); + ParserState pstate; + viml_parser_init(&pstate, parser_simple_get_line, &plines_p, colors_p); + ExprAST east = viml_pexpr_parse(&pstate, pflags); + + const size_t ret_size = (2 // "ast", "len" + + (size_t)(east.err.msg != NULL) // "error" + + (size_t)highlight // "highlight" + + 0); + Dictionary ret = { + .items = xmalloc(ret_size * sizeof(ret.items[0])), + .size = 0, + .capacity = ret_size, + }; + ret.items[ret.size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ast"), + .value = NIL, + }; + ret.items[ret.size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("len"), + .value = INTEGER_OBJ((Integer)(pstate.pos.line == 1 + ? parser_lines[0].size + : pstate.pos.col)), + }; + if (east.err.msg != NULL) { + Dictionary err_dict = { + .items = xmalloc(2 * sizeof(err_dict.items[0])), + .size = 2, + .capacity = 2, + }; + err_dict.items[0] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("message"), + .value = STRING_OBJ(cstr_to_string(east.err.msg)), + }; + if (east.err.arg == NULL) { + err_dict.items[1] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("arg"), + .value = STRING_OBJ(STRING_INIT), + }; + } else { + err_dict.items[1] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("arg"), + .value = STRING_OBJ(((String) { + .data = xmemdupz(east.err.arg, (size_t)east.err.arg_len), + .size = (size_t)east.err.arg_len, + })), + }; + } + ret.items[ret.size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("error"), + .value = DICTIONARY_OBJ(err_dict), + }; + } + if (highlight) { + Array hl = (Array) { + .items = xmalloc(kv_size(colors) * sizeof(hl.items[0])), + .capacity = kv_size(colors), + .size = kv_size(colors), + }; + for (size_t i = 0 ; i < kv_size(colors) ; i++) { + const ParserHighlightChunk chunk = kv_A(colors, i); + Array chunk_arr = (Array) { + .items = xmalloc(4 * sizeof(chunk_arr.items[0])), + .capacity = 4, + .size = 4, + }; + chunk_arr.items[0] = INTEGER_OBJ((Integer)chunk.start.line); + chunk_arr.items[1] = INTEGER_OBJ((Integer)chunk.start.col); + chunk_arr.items[2] = INTEGER_OBJ((Integer)chunk.end_col); + chunk_arr.items[3] = STRING_OBJ(cstr_to_string(chunk.group)); + hl.items[i] = ARRAY_OBJ(chunk_arr); + } + ret.items[ret.size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("highlight"), + .value = ARRAY_OBJ(hl), + }; + } + kvi_destroy(colors); + + // Walk over the AST, freeing nodes in process. + ExprASTConvStack ast_conv_stack; + kvi_init(ast_conv_stack); + kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { + .node_p = &east.root, + .ret_node_p = &ret.items[0].value, + })); + while (kv_size(ast_conv_stack)) { + ExprASTConvStackItem cur_item = kv_last(ast_conv_stack); + ExprASTNode *const node = *cur_item.node_p; + if (node == NULL) { + assert(kv_size(ast_conv_stack) == 1); + kv_drop(ast_conv_stack, 1); + } else { + if (cur_item.ret_node_p->type == kObjectTypeNil) { + size_t items_size = (size_t)(3 // "type", "start" and "len" + + (node->children != NULL) // "children" + + (node->type == kExprNodeOption + || node->type == kExprNodePlainIdentifier) // "scope" + + (node->type == kExprNodeOption + || node->type == kExprNodePlainIdentifier + || node->type == kExprNodePlainKey + || node->type == kExprNodeEnvironment) // "ident" + + (node->type == kExprNodeRegister) // "name" + + (3 // "cmp_type", "ccs_strategy", "invert" + * (node->type == kExprNodeComparison)) + + (node->type == kExprNodeInteger) // "ivalue" + + (node->type == kExprNodeFloat) // "fvalue" + + (node->type == kExprNodeDoubleQuotedString + || node->type == kExprNodeSingleQuotedString) // "svalue" + + (node->type == kExprNodeAssignment) // "augmentation" + + 0); + Dictionary ret_node = { + .items = xmalloc(items_size * sizeof(ret_node.items[0])), + .capacity = items_size, + .size = 0, + }; + *cur_item.ret_node_p = DICTIONARY_OBJ(ret_node); + } + Dictionary *ret_node = &cur_item.ret_node_p->data.dictionary; + if (node->children != NULL) { + const size_t num_children = 1 + (node->children->next != NULL); + Array children_array = { + .items = xmalloc(num_children * sizeof(children_array.items[0])), + .capacity = num_children, + .size = num_children, + }; + for (size_t i = 0; i < num_children; i++) { + children_array.items[i] = NIL; + } + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("children"), + .value = ARRAY_OBJ(children_array), + }; + kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { + .node_p = &node->children, + .ret_node_p = &children_array.items[0], + })); + } else if (node->next != NULL) { + kvi_push(ast_conv_stack, ((ExprASTConvStackItem) { + .node_p = &node->next, + .ret_node_p = cur_item.ret_node_p + 1, + })); + } else { + kv_drop(ast_conv_stack, 1); + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("type"), + .value = STRING_OBJ(cstr_to_string(east_node_type_tab[node->type])), + }; + Array start_array = { + .items = xmalloc(2 * sizeof(start_array.items[0])), + .capacity = 2, + .size = 2, + }; + start_array.items[0] = INTEGER_OBJ((Integer)node->start.line); + start_array.items[1] = INTEGER_OBJ((Integer)node->start.col); + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("start"), + .value = ARRAY_OBJ(start_array), + }; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("len"), + .value = INTEGER_OBJ((Integer)node->len), + }; + switch (node->type) { + case kExprNodeDoubleQuotedString: + case kExprNodeSingleQuotedString: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("svalue"), + .value = STRING_OBJ(((String) { + .data = node->data.str.value, + .size = node->data.str.size, + })), + }; + break; + case kExprNodeOption: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("scope"), + .value = INTEGER_OBJ(node->data.opt.scope), + }; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ident"), + .value = STRING_OBJ(((String) { + .data = xmemdupz(node->data.opt.ident, + node->data.opt.ident_len), + .size = node->data.opt.ident_len, + })), + }; + break; + case kExprNodePlainIdentifier: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("scope"), + .value = INTEGER_OBJ(node->data.var.scope), + }; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ident"), + .value = STRING_OBJ(((String) { + .data = xmemdupz(node->data.var.ident, + node->data.var.ident_len), + .size = node->data.var.ident_len, + })), + }; + break; + case kExprNodePlainKey: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ident"), + .value = STRING_OBJ(((String) { + .data = xmemdupz(node->data.var.ident, + node->data.var.ident_len), + .size = node->data.var.ident_len, + })), + }; + break; + case kExprNodeEnvironment: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ident"), + .value = STRING_OBJ(((String) { + .data = xmemdupz(node->data.env.ident, + node->data.env.ident_len), + .size = node->data.env.ident_len, + })), + }; + break; + case kExprNodeRegister: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("name"), + .value = INTEGER_OBJ(node->data.reg.name), + }; + break; + case kExprNodeComparison: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("cmp_type"), + .value = STRING_OBJ(cstr_to_string(eltkn_cmp_type_tab[node->data.cmp.type])), + }; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ccs_strategy"), + .value = STRING_OBJ(cstr_to_string(ccs_tab[node->data.cmp.ccs])), + }; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("invert"), + .value = BOOLEAN_OBJ(node->data.cmp.inv), + }; + break; + case kExprNodeFloat: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("fvalue"), + .value = FLOAT_OBJ(node->data.flt.value), + }; + break; + case kExprNodeInteger: + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("ivalue"), + .value = INTEGER_OBJ((Integer)(node->data.num.value > API_INTEGER_MAX + ? API_INTEGER_MAX + : (Integer)node->data.num.value)), + }; + break; + case kExprNodeAssignment: { + const ExprAssignmentType asgn_type = node->data.ass.type; + ret_node->items[ret_node->size++] = (KeyValuePair) { + .key = STATIC_CSTR_TO_STRING("augmentation"), + .value = STRING_OBJ(asgn_type == kExprAsgnPlain + ? (String)STRING_INIT + : cstr_to_string(expr_asgn_type_tab[asgn_type])), + }; + break; + } + case kExprNodeMissing: + case kExprNodeOpMissing: + case kExprNodeTernary: + case kExprNodeTernaryValue: + case kExprNodeSubscript: + case kExprNodeListLiteral: + case kExprNodeUnaryPlus: + case kExprNodeBinaryPlus: + case kExprNodeNested: + case kExprNodeCall: + case kExprNodeComplexIdentifier: + case kExprNodeUnknownFigure: + case kExprNodeLambda: + case kExprNodeDictLiteral: + case kExprNodeCurlyBracesIdentifier: + case kExprNodeComma: + case kExprNodeColon: + case kExprNodeArrow: + case kExprNodeConcat: + case kExprNodeConcatOrSubscript: + case kExprNodeOr: + case kExprNodeAnd: + case kExprNodeUnaryMinus: + case kExprNodeBinaryMinus: + case kExprNodeNot: + case kExprNodeMultiplication: + case kExprNodeDivision: + case kExprNodeMod: + break; + } + assert(cur_item.ret_node_p->data.dictionary.size + == cur_item.ret_node_p->data.dictionary.capacity); + xfree(*cur_item.node_p); + *cur_item.node_p = NULL; + } + } + } + kvi_destroy(ast_conv_stack); + + assert(ret.size == ret.capacity); + // Should be a no-op actually, leaving it in case non-nodes will need to be + // freed later. + viml_pexpr_free_ast(east); + viml_parser_destroy(&pstate); + return ret; +} diff --git a/src/nvim/api/vimscript.h b/src/nvim/api/vimscript.h new file mode 100644 index 0000000000..be808b6b25 --- /dev/null +++ b/src/nvim/api/vimscript.h @@ -0,0 +1,9 @@ +#ifndef NVIM_API_VIMSCRIPT_H +#define NVIM_API_VIMSCRIPT_H + +#include "nvim/api/private/defs.h" + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "api/vimscript.h.generated.h" +#endif +#endif // NVIM_API_VIMSCRIPT_H diff --git a/src/nvim/ascii.h b/src/nvim/ascii.h index 44ed94d2fc..2cabaa43ef 100644 --- a/src/nvim/ascii.h +++ b/src/nvim/ascii.h @@ -10,7 +10,7 @@ // Definitions of various common control characters. #define CharOrd(x) ((uint8_t)(x) < 'a' \ - ? (uint8_t)(x) - 'A'\ + ? (uint8_t)(x) - 'A' \ : (uint8_t)(x) - 'a') #define CharOrdLow(x) ((uint8_t)(x) - 'a') #define CharOrdUp(x) ((uint8_t)(x) - 'A') diff --git a/src/nvim/assert.h b/src/nvim/assert.h index fc1a4be164..ad92d9a2af 100644 --- a/src/nvim/assert.h +++ b/src/nvim/assert.h @@ -70,11 +70,11 @@ # if __GNUC__ >= 6 # define STATIC_ASSERT_PRAGMA_START \ - _Pragma("GCC diagnostic push")\ + _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wpedantic\"") # else # define STATIC_ASSERT_PRAGMA_START \ - _Pragma("GCC diagnostic push")\ + _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-pedantic\"") # endif @@ -89,7 +89,7 @@ # undef STATIC_ASSERT_PRAGMA_START # define STATIC_ASSERT_PRAGMA_START \ - _Pragma("clang diagnostic push")\ + _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wc11-extensions\"") # undef STATIC_ASSERT_PRAGMA_END @@ -113,14 +113,14 @@ // These can't be used after statements in c89. #ifdef __COUNTER__ # define STATIC_ASSERT_EXPR(e, m) \ - ((enum { ASSERT_CONCAT(static_assert_, __COUNTER__) = 1/(!!(e)) }) 0) + ((enum { ASSERT_CONCAT(static_assert_, __COUNTER__) = 1/(!!(e)), }) 0) #else // This can't be used twice on the same line so ensure if using in headers // that the headers are not included twice (by wrapping in #ifndef...#endif) // Note it doesn't cause an issue when used on same line of separate modules // compiled with gcc -combine -fwhole-program. # define STATIC_ASSERT_EXPR(e, m) \ - ((enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) }) 0) + ((enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)), }) 0) #endif /// @def STRICT_ADD diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index d991b88131..2d0c0f3fd5 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -313,9 +313,9 @@ static void au_del_group(char_u *name) { int i = au_find_group(name); if (i == AUGROUP_ERROR) { // the group doesn't exist - EMSG2(_("E367: No such group: \"%s\""), name); + semsg(_("E367: No such group: \"%s\""), name); } else if (i == current_augroup) { - EMSG(_("E936: Cannot delete the current group")); + emsg(_("E936: Cannot delete the current group")); } else { event_T event; AutoPat *ap; @@ -372,7 +372,7 @@ void do_augroup(char_u *arg, int del_group) { if (del_group) { if (*arg == NUL) { - EMSG(_(e_argreq)); + emsg(_(e_argreq)); } else { au_del_group(arg); } @@ -469,7 +469,7 @@ static char_u *find_end_event(char_u *arg, int have_group) if (*arg == '*') { if (arg[1] && !ascii_iswhite(arg[1])) { - EMSG2(_("E215: Illegal character after *: %s"), arg); + semsg(_("E215: Illegal character after *: %s"), arg); return NULL; } pat = arg + 1; @@ -477,9 +477,9 @@ static char_u *find_end_event(char_u *arg, int have_group) for (pat = arg; *pat && *pat != '|' && !ascii_iswhite(*pat); pat = p) { if ((int)event_name2nr(pat, &p) >= NUM_EVENTS) { if (have_group) { - EMSG2(_("E216: No such event: %s"), pat); + semsg(_("E216: No such event: %s"), pat); } else { - EMSG2(_("E216: No such group or event: %s"), pat); + semsg(_("E216: No such group or event: %s"), pat); } return NULL; } @@ -651,7 +651,7 @@ void do_autocmd(char_u *arg_in, int forceit) // Check for "++once" flag. if (STRNCMP(cmd, "++once", 6) == 0 && ascii_iswhite(cmd[6])) { if (once) { - EMSG2(_(e_duparg2), "++once"); + semsg(_(e_duparg2), "++once"); } once = true; cmd = skipwhite(cmd + 6); @@ -660,7 +660,7 @@ void do_autocmd(char_u *arg_in, int forceit) // Check for "++nested" flag. if ((STRNCMP(cmd, "++nested", 8) == 0 && ascii_iswhite(cmd[8]))) { if (nested) { - EMSG2(_(e_duparg2), "++nested"); + semsg(_(e_duparg2), "++nested"); } nested = true; cmd = skipwhite(cmd + 8); @@ -669,7 +669,7 @@ void do_autocmd(char_u *arg_in, int forceit) // Check for the old (deprecated) "nested" flag. if (STRNCMP(cmd, "nested", 6) == 0 && ascii_iswhite(cmd[6])) { if (nested) { - EMSG2(_(e_duparg2), "nested"); + semsg(_(e_duparg2), "nested"); } nested = true; cmd = skipwhite(cmd + 6); @@ -691,7 +691,7 @@ void do_autocmd(char_u *arg_in, int forceit) // Print header when showing autocommands. if (!forceit && *cmd == NUL) { // Highlight title - MSG_PUTS_TITLE(_("\n--- Autocommands ---")); + msg_puts_title(_("\n--- Autocommands ---")); } // Loop over the events. @@ -699,7 +699,7 @@ void do_autocmd(char_u *arg_in, int forceit) last_group = AUGROUP_ERROR; // for listing the group name if (*arg == '*' || *arg == NUL || *arg == '|') { if (!forceit && *cmd != NUL) { - EMSG(_(e_cannot_define_autocommands_for_all_events)); + emsg(_(e_cannot_define_autocommands_for_all_events)); } else { for (event_T event = (event_T)0; event < NUM_EVENTS; event = (event_T)(event + 1)) { @@ -899,7 +899,7 @@ static int do_autocmd_event(event_T event, char_u *pat, bool once, int nested, c // refuse to add buffer-local ap if buffer number is invalid if (is_buflocal && (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL)) { - emsgf(_("E680: <buffer=%d>: invalid buffer number "), buflocal_nr); + semsg(_("E680: <buffer=%d>: invalid buffer number "), buflocal_nr); return FAIL; } @@ -974,7 +974,7 @@ int do_doautocmd(char_u *arg, bool do_msg, bool *did_something) group = au_get_grouparg(&arg); if (*arg == '*') { - EMSG(_("E217: Can't execute autocommands for ALL events")); + emsg(_("E217: Can't execute autocommands for ALL events")); return FAIL; } @@ -996,7 +996,7 @@ int do_doautocmd(char_u *arg, bool do_msg, bool *did_something) } if (nothing_done && do_msg) { - MSG(_("No matching autocommands")); + msg(_("No matching autocommands")); } if (did_something != NULL) { *did_something = !nothing_done; @@ -1414,7 +1414,7 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, // Allow nesting of autocommands, but restrict the depth, because it's // possible to create an endless loop. if (nesting == 10) { - EMSG(_("E218: autocommand nesting too deep")); + emsg(_("E218: autocommand nesting too deep")); goto BYPASS_AU; } diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index 37a2060021..4692f9e722 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -186,7 +186,7 @@ int open_buffer(int read_stdin, exarg_T *eap, int flags) // If there is no memfile at all, exit. // This is OK, since there are no changes to lose. if (curbuf == NULL) { - EMSG(_("E82: Cannot allocate any buffer, exiting...")); + emsg(_("E82: Cannot allocate any buffer, exiting...")); // Don't try to do any saving, with "curbuf" NULL almost nothing // will work. @@ -194,7 +194,7 @@ int open_buffer(int read_stdin, exarg_T *eap, int flags) getout(2); } - EMSG(_("E83: Cannot allocate buffer, using other one...")); + emsg(_("E83: Cannot allocate buffer, using other one...")); enter_buffer(curbuf); if (old_tw != curbuf->b_p_tw) { check_colorcolumn(curwin); @@ -439,7 +439,7 @@ bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last) // Disallow deleting the buffer when it is locked (already being closed or // halfway a command that relies on it). Unloading is allowed. if (buf->b_locked > 0 && (del_buf || wipe_buf)) { - EMSG(_("E937: Attempt to delete a buffer that is in use")); + emsg(_("E937: Attempt to delete a buffer that is in use")); return false; } @@ -466,13 +466,13 @@ bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last) if (apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, false, buf) && !bufref_valid(&bufref)) { // Autocommands deleted the buffer. - EMSG(_(e_auabort)); + emsg(_(e_auabort)); return false; } buf->b_locked--; if (abort_if_last && last_nonfloat(win)) { // Autocommands made this the only window. - EMSG(_(e_auabort)); + emsg(_(e_auabort)); return false; } @@ -483,13 +483,13 @@ bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last) if (apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname, false, buf) && !bufref_valid(&bufref)) { // Autocommands deleted the buffer. - EMSG(_(e_auabort)); + emsg(_(e_auabort)); return false; } buf->b_locked--; if (abort_if_last && last_nonfloat(win)) { // Autocommands made this the only window. - EMSG(_(e_auabort)); + emsg(_(e_auabort)); return false; } } @@ -501,7 +501,7 @@ bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last) // If the buffer was in curwin and the window has changed, go back to that // window, if it still exists. This avoids that ":edit x" triggering a // "tabnext" BufUnload autocmd leaves a window behind without a buffer. - if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { + if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { block_autocmds(); goto_tabpage_win(the_curtab, the_curwin); unblock_autocmds(); @@ -698,7 +698,7 @@ void buf_freeall(buf_T *buf, int flags) // If the buffer was in curwin and the window has changed, go back to that // window, if it still exists. This avoids that ":edit x" triggering a // "tabnext" BufUnload autocmd leaves a window behind without a buffer. - if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { + if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { block_autocmds(); goto_tabpage_win(the_curtab, the_curwin); unblock_autocmds(); @@ -918,7 +918,7 @@ void handle_swap_exists(bufref_T *old_curbuf) // User selected Recover at ATTENTION prompt. msg_scroll = true; ml_recover(false); - MSG_PUTS("\n"); // don't overwrite the last message + msg_puts("\n"); // don't overwrite the last message cmdline_row = msg_row; do_modelines(0); @@ -944,11 +944,11 @@ void handle_swap_exists(bufref_T *old_curbuf) /// @param end_bnr buffer nr or last buffer nr in a range /// /// @return error message or NULL -char_u *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int end_bnr, int forceit) +char *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int end_bnr, int forceit) { int do_current = 0; // delete current buffer? int deleted = 0; // number of buffers deleted - char_u *errormsg = NULL; // return value + char *errormsg = NULL; // return value int bnr; // buffer number char_u *p; @@ -957,7 +957,7 @@ char_u *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int e } else { if (addr_count == 2) { if (*arg) { // both range and argument is not allowed - return (char_u *)_(e_trailing); + return _(e_trailing); } bnr = start_bnr; } else { // addr_count == 1 @@ -1013,26 +1013,17 @@ char_u *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int e } else { STRCPY(IObuff, _("E517: No buffers were wiped out")); } - errormsg = IObuff; + errormsg = (char *)IObuff; } else if (deleted >= p_report) { if (command == DOBUF_UNLOAD) { - if (deleted == 1) { - MSG(_("1 buffer unloaded")); - } else { - smsg(_("%d buffers unloaded"), deleted); - } + smsg(NGETTEXT("%d buffer unloaded", "%d buffers unloaded", (unsigned long)deleted), + deleted); } else if (command == DOBUF_DEL) { - if (deleted == 1) { - MSG(_("1 buffer deleted")); - } else { - smsg(_("%d buffers deleted"), deleted); - } + smsg(NGETTEXT("%d buffer deleted", "%d buffers deleted", (unsigned long)deleted), + deleted); } else { - if (deleted == 1) { - MSG(_("1 buffer wiped out")); - } else { - smsg(_("%d buffers wiped out"), deleted); - } + smsg(NGETTEXT("%d buffer wiped out", "%d buffers wiped out", (unsigned long)deleted), + deleted); } } } @@ -1042,7 +1033,6 @@ char_u *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int e } - /* * Make the current buffer empty. * Used when it is wiped out and it's the last buffer. @@ -1053,7 +1043,7 @@ static int empty_curbuf(int close_others, int forceit, int action) buf_T *buf = curbuf; if (action == DOBUF_UNLOAD) { - EMSG(_("E90: Cannot unload last buffer")); + emsg(_("E90: Cannot unload last buffer")); return FAIL; } @@ -1126,7 +1116,7 @@ int do_buffer(int action, int start, int dir, int count, int forceit) } while (buf != curbuf && !bufIsChanged(buf)); } if (!bufIsChanged(buf)) { - EMSG(_("E84: No modified buffer found")); + emsg(_("E84: No modified buffer found")); return FAIL; } } else if (start == DOBUF_FIRST && count) { // find specified buffer number @@ -1159,7 +1149,7 @@ int do_buffer(int action, int start, int dir, int count, int forceit) } if (bp == buf) { // back where we started, didn't find anything. - EMSG(_("E85: There is no listed buffer")); + emsg(_("E85: There is no listed buffer")); return FAIL; } } @@ -1169,12 +1159,12 @@ int do_buffer(int action, int start, int dir, int count, int forceit) if (start == DOBUF_FIRST) { // don't warn when deleting if (!unload) { - EMSGN(_(e_nobufnr), count); + semsg(_(e_nobufnr), (int64_t)count); } } else if (dir == FORWARD) { - EMSG(_("E87: Cannot go beyond last buffer")); + emsg(_("E87: Cannot go beyond last buffer")); } else { - EMSG(_("E88: Cannot go before first buffer")); + emsg(_("E88: Cannot go before first buffer")); } return FAIL; } @@ -1205,9 +1195,9 @@ int do_buffer(int action, int start, int dir, int count, int forceit) return FAIL; } } else { - EMSGN(_("E89: No write since last change for buffer %" PRId64 + semsg(_("E89: No write since last change for buffer %" PRId64 " (add ! to override)"), - buf->b_fnum); + (int64_t)buf->b_fnum); return FAIL; } } @@ -1218,7 +1208,7 @@ int do_buffer(int action, int start, int dir, int count, int forceit) return FAIL; } } else { - EMSG2(_("E89: %s will be killed (add ! to override)"), + semsg(_("E89: %s will be killed (add ! to override)"), (char *)buf->b_fname); return FAIL; } @@ -1607,9 +1597,9 @@ void no_write_message(void) { if (curbuf->terminal && channel_job_running((uint64_t)curbuf->b_p_channel)) { - EMSG(_("E948: Job still running (add ! to end the job)")); + emsg(_("E948: Job still running (add ! to end the job)")); } else { - EMSG(_("E37: No write since last change (add ! to override)")); + emsg(_("E37: No write since last change (add ! to override)")); } } @@ -1618,9 +1608,9 @@ void no_write_message_nobang(const buf_T *const buf) { if (buf->terminal && channel_job_running((uint64_t)buf->b_p_channel)) { - EMSG(_("E948: Job still running")); + emsg(_("E948: Job still running")); } else { - EMSG(_("E37: No write since last change")); + emsg(_("E37: No write since last change")); } } @@ -1803,7 +1793,7 @@ buf_T *buflist_new(char_u *ffname_arg, char_u *sfname_arg, linenr_T lnum, int fl buf->b_fnum = top_file_num++; pmap_put(handle_T)(&buffer_handles, buf->b_fnum, buf); if (top_file_num < 0) { // wrap around (may cause duplicates) - EMSG(_("W14: Warning: List of file names overflow")); + emsg(_("W14: Warning: List of file names overflow")); if (emsg_silent == 0) { ui_flush(); os_delay(3001L, true); // make sure it is noticed @@ -1972,9 +1962,9 @@ int buflist_getfile(int n, linenr_T lnum, int options, int forceit) buf = buflist_findnr(n); if (buf == NULL) { if ((options & GETF_ALT) && n == 0) { - EMSG(_(e_noalt)); + emsg(_(e_noalt)); } else { - EMSGN(_("E92: Buffer %" PRId64 " not found"), n); + semsg(_("E92: Buffer %" PRId64 " not found"), (int64_t)n); } return FAIL; } @@ -2234,9 +2224,9 @@ int buflist_findpat(const char_u *pattern, const char_u *pattern_end, bool unlis } if (match == -2) { - EMSG2(_("E93: More than one match for %s"), pattern); + semsg(_("E93: More than one match for %s"), pattern); } else if (match < 0) { - EMSG2(_("E94: No matching buffer for %s"), pattern); + semsg(_("E94: No matching buffer for %s"), pattern); } return match; } @@ -2805,7 +2795,7 @@ int setfname(buf_T *buf, char_u *ffname_arg, char_u *sfname_arg, bool message) if (obuf != NULL && obuf != buf) { if (obuf->b_ml.ml_mfp != NULL) { // it's loaded, fail if (message) { - EMSG(_("E95: Buffer with this name already exists")); + emsg(_("E95: Buffer with this name already exists")); } xfree(ffname); return FAIL; @@ -2910,7 +2900,7 @@ char_u *getaltfname(bool errmsg) if (buflist_name_nr(0, &fname, &dummy) == FAIL) { if (errmsg) { - EMSG(_(e_noalt)); + emsg(_(e_noalt)); } return NULL; } @@ -3049,14 +3039,14 @@ void fileinfo(int fullname, int shorthelp, int dont_truncate) { char_u *name; int n; - char_u *p; - char_u *buffer; + char *p; + char *buffer; size_t len; buffer = xmalloc(IOSIZE); if (fullname > 1) { // 2 CTRL-G: include buffer number - vim_snprintf((char *)buffer, IOSIZE, "buf %d: ", curbuf->b_fnum); + vim_snprintf(buffer, IOSIZE, "buf %d: ", curbuf->b_fnum); p = buffer + STRLEN(buffer); } else { p = buffer; @@ -3071,12 +3061,12 @@ void fileinfo(int fullname, int shorthelp, int dont_truncate) } else { name = curbuf->b_ffname; } - home_replace(shorthelp ? curbuf : NULL, name, p, + home_replace(shorthelp ? curbuf : NULL, name, (char_u *)p, (size_t)(IOSIZE - (p - buffer)), true); } bool dontwrite = bt_dontwrite(curbuf); - vim_snprintf_add((char *)buffer, IOSIZE, "\"%s%s%s%s%s%s", + vim_snprintf_add(buffer, IOSIZE, "\"%s%s%s%s%s%s", curbufIsChanged() ? (shortmess(SHM_MOD) ? " [+]" : _(" [Modified]")) : " ", (curbuf->b_flags & BF_NOTEDITED) && !dontwrite @@ -3101,28 +3091,27 @@ void fileinfo(int fullname, int shorthelp, int dont_truncate) (long)curbuf->b_ml.ml_line_count); } if (curbuf->b_ml.ml_flags & ML_EMPTY) { - vim_snprintf_add((char *)buffer, IOSIZE, "%s", _(no_lines_msg)); + vim_snprintf_add(buffer, IOSIZE, "%s", _(no_lines_msg)); } else if (p_ru) { // Current line and column are already on the screen -- webb - if (curbuf->b_ml.ml_line_count == 1) { - vim_snprintf_add((char *)buffer, IOSIZE, _("1 line --%d%%--"), n); - } else { - vim_snprintf_add((char *)buffer, IOSIZE, _("%" PRId64 " lines --%d%%--"), - (int64_t)curbuf->b_ml.ml_line_count, n); - } + vim_snprintf_add(buffer, IOSIZE, + NGETTEXT("%" PRId64 " line --%d%%--", + "%" PRId64 " lines --%d%%--", + (unsigned long)curbuf->b_ml.ml_line_count), + (int64_t)curbuf->b_ml.ml_line_count, n); } else { - vim_snprintf_add((char *)buffer, IOSIZE, + vim_snprintf_add(buffer, IOSIZE, _("line %" PRId64 " of %" PRId64 " --%d%%-- col "), (int64_t)curwin->w_cursor.lnum, (int64_t)curbuf->b_ml.ml_line_count, n); validate_virtcol(); len = STRLEN(buffer); - col_print(buffer + len, IOSIZE - len, + col_print((char_u *)buffer + len, IOSIZE - len, (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); } - (void)append_arg_number(curwin, buffer, IOSIZE, !shortmess(SHM_FILE)); + (void)append_arg_number(curwin, (char_u *)buffer, IOSIZE, !shortmess(SHM_FILE)); if (dont_truncate) { // Temporarily set msg_scroll to avoid the message being truncated. @@ -3140,7 +3129,7 @@ void fileinfo(int fullname, int shorthelp, int dont_truncate) // before redrawing). // - When the screen was scrolled but there is no wait-return // prompt. - set_keep_msg(p, 0); + set_keep_msg((char_u *)p, 0); } } @@ -3399,7 +3388,7 @@ void free_titles(void) /// be used when printing numbers in the status line. typedef enum { kNumBaseDecimal = 10, - kNumBaseHexadecimal = 16 + kNumBaseHexadecimal = 16, } NumberBase; @@ -5172,7 +5161,6 @@ void ex_buffer_all(exarg_T *eap) } - /* * do_modelines() - process mode lines for the current file * @@ -5398,7 +5386,7 @@ bool bt_dontwrite_msg(const buf_T *const buf) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { if (bt_dontwrite(buf)) { - EMSG(_("E382: Cannot write, 'buftype' option is set")); + emsg(_("E382: Cannot write, 'buftype' option is set")); return true; } return false; diff --git a/src/nvim/buffer.h b/src/nvim/buffer.h index 0484c8550d..9e2ca999e4 100644 --- a/src/nvim/buffer.h +++ b/src/nvim/buffer.h @@ -24,7 +24,7 @@ enum getf_retvalues { GETFILE_NOT_WRITTEN = 2, // "not written" error GETFILE_SAME_FILE = 0, // success, same file GETFILE_OPEN_OTHER = -1, // success, opened another file - GETFILE_UNUSED = 8 + GETFILE_UNUSED = 8, }; // Values for buflist_new() flags diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index c0a0376088..074dde86f1 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -99,7 +99,7 @@ typedef struct { typedef struct window_S win_T; typedef struct wininfo_S wininfo_T; typedef struct frame_S frame_T; -typedef uint16_t disptick_T; // display tick type +typedef uint64_t disptick_T; // display tick type // for struct memline (it needs memfile_T) #include "nvim/memline_defs.h" @@ -147,8 +147,7 @@ struct buffheader { size_t bh_space; // space in bh_curr for appending }; -typedef struct -{ +typedef struct { buffheader_T sr_redobuff; buffheader_T sr_old_redobuff; } save_redo_T; @@ -388,7 +387,7 @@ struct stl_item { Highlight, TabPage, ClickFunc, - Trunc + Trunc, } type; }; @@ -577,8 +576,8 @@ struct file_buffer { long b_mod_xlines; // number of extra buffer lines inserted; // negative when lines were deleted wininfo_T *b_wininfo; // list of last used info for each window - int b_mod_tick_syn; // last display tick syntax was updated - int b_mod_tick_decor; // last display tick decoration providers + disptick_T b_mod_tick_syn; // last display tick syntax was updated + disptick_T b_mod_tick_decor; // last display tick decoration providers // where invoked long b_mtime; // last change time of original file @@ -1019,8 +1018,7 @@ typedef struct { #define MAXPOSMATCH 8 /// Same as lpos_T, but with additional field len. -typedef struct -{ +typedef struct { linenr_T lnum; ///< line number colnr_T col; ///< column number int len; ///< length: 0 - to the end of line @@ -1029,8 +1027,7 @@ typedef struct /// posmatch_T provides an array for storing match items for matchaddpos() /// function. typedef struct posmatch posmatch_T; -struct posmatch -{ +struct posmatch { llpos_T pos[MAXPOSMATCH]; ///< array of positions int cur; ///< internal position counter linenr_T toplnum; ///< top buffer line @@ -1111,8 +1108,7 @@ typedef struct { // Structure to store last cursor position and topline. Used by check_lnums() // and reset_lnums(). -typedef struct -{ +typedef struct { int w_topline_save; // original topline value int w_topline_corr; // corrected topline value pos_T w_cursor_save; // original cursor position diff --git a/src/nvim/change.c b/src/nvim/change.c index 2450c56838..7925c6b1ba 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -63,7 +63,7 @@ void change_warning(buf_T *buf, int col) } msg_source(HL_ATTR(HLF_W)); msg_ext_set_kind("wmsg"); - MSG_PUTS_ATTR(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST); + msg_puts_attr(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST); set_vim_var_string(VV_WARNINGMSG, _(w_readonly), -1); msg_clr_eos(); (void)msg_end(); @@ -759,7 +759,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) } // If "count" is negative the caller must be doing something wrong. if (count < 1) { - IEMSGN("E292: Invalid count for del_bytes(): %ld", count); + siemsg("E292: Invalid count for del_bytes(): %ld", (int64_t)count); return FAIL; } diff --git a/src/nvim/channel.c b/src/nvim/channel.c index 313eefd562..0eae87c1f8 100644 --- a/src/nvim/channel.c +++ b/src/nvim/channel.c @@ -1,6 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +#include "nvim/api/private/converter.h" #include "nvim/api/private/helpers.h" #include "nvim/api/ui.h" #include "nvim/channel.h" @@ -318,7 +319,7 @@ Channel *channel_job_start(char **argv, CallbackReader on_stdout, CallbackReader if (pty) { if (detach) { - EMSG2(_(e_invarg2), "terminal/pty job cannot be detached"); + semsg(_(e_invarg2), "terminal/pty job cannot be detached"); shell_free_argv(argv); if (env) { tv_dict_free(env); @@ -368,7 +369,7 @@ Channel *channel_job_start(char **argv, CallbackReader on_stdout, CallbackReader int status = process_spawn(proc, has_in, has_out, has_err); if (status) { - EMSG3(_(e_jobspawn), os_strerror(status), cmd); + semsg(_(e_jobspawn), os_strerror(status), cmd); xfree(cmd); if (proc->env) { tv_dict_free(proc->env); @@ -671,7 +672,7 @@ void channel_reader_callbacks(Channel *chan, CallbackReader *reader) tv_dict_add_list(reader->self, reader->type, strlen(reader->type), data); } else { - EMSG3(_(e_streamkey), reader->type, chan->id); + semsg(_(e_streamkey), reader->type, chan->id); } } else { channel_callback_call(chan, reader); diff --git a/src/nvim/channel.h b/src/nvim/channel.h index 8d14f465c1..81b75e2d31 100644 --- a/src/nvim/channel.h +++ b/src/nvim/channel.h @@ -17,7 +17,7 @@ typedef enum { kChannelStreamSocket, kChannelStreamStdio, kChannelStreamStderr, - kChannelStreamInternal + kChannelStreamInternal, } ChannelStreamType; typedef enum { @@ -25,7 +25,7 @@ typedef enum { kChannelPartStdout, kChannelPartStderr, kChannelPartRpc, - kChannelPartAll + kChannelPartAll, } ChannelPart; typedef enum { diff --git a/src/nvim/charset.c b/src/nvim/charset.c index d2f95ad81c..8139eae131 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -947,7 +947,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en if ((!wp->w_p_list || (wp->w_p_lcs_chars.tab1 != NUL)) && !wp->w_p_lbr && *get_showbreak_value(wp) == NUL - && !wp->w_p_bri ) { + && !wp->w_p_bri) { for (;;) { head = 0; c = *ptr; @@ -1311,7 +1311,8 @@ char_u *skiptowhite(const char_u *p) /// @param p /// /// @return Pointer to the next whitespace character. -char_u *skiptowhite_esc(char_u *p) { +char_u *skiptowhite_esc(char_u *p) +{ while (*p != ' ' && *p != '\t' && *p != NUL) { if (((*p == '\\') || (*p == Ctrl_V)) && (*(p + 1) != NUL)) { ++p; diff --git a/src/nvim/context.c b/src/nvim/context.c index 1db7938ef4..614a3ce30e 100644 --- a/src/nvim/context.c +++ b/src/nvim/context.c @@ -3,8 +3,10 @@ // Context: snapshot of the entire editor state as one big object/map +#include "nvim/api/private/converter.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" +#include "nvim/api/vimscript.h" #include "nvim/context.h" #include "nvim/eval/encode.h" #include "nvim/ex_docmd.h" @@ -314,7 +316,7 @@ static inline msgpack_sbuffer array_to_sbuf(Array array) object_to_vim(ARRAY_OBJ(array), &list_tv, &err); if (!encode_vim_list_to_buf(list_tv.vval.v_list, &sbuf.size, &sbuf.data)) { - EMSG(_("E474: Failed to convert list to msgpack string buffer")); + emsg(_("E474: Failed to convert list to msgpack string buffer")); } sbuf.alloc = sbuf.size; diff --git a/src/nvim/cursor_shape.c b/src/nvim/cursor_shape.c index 18cade1052..644bb2c324 100644 --- a/src/nvim/cursor_shape.c +++ b/src/nvim/cursor_shape.c @@ -93,7 +93,7 @@ Array mode_style_array(void) /// @param what SHAPE_CURSOR or SHAPE_MOUSE ('mouseshape') /// /// @returns error message for an illegal option, NULL otherwise. -char_u *parse_shape_opt(int what) +char *parse_shape_opt(int what) { char_u *modep; char_u *colonp; @@ -126,10 +126,10 @@ char_u *parse_shape_opt(int what) commap = vim_strchr(modep, ','); if (colonp == NULL || (commap != NULL && commap < colonp)) { - return (char_u *)N_("E545: Missing colon"); + return N_("E545: Missing colon"); } if (colonp == modep) { - return (char_u *)N_("E546: Illegal mode"); + return N_("E546: Illegal mode"); } // Repeat for all modes before the colon. @@ -154,7 +154,7 @@ char_u *parse_shape_opt(int what) } if (idx == SHAPE_IDX_COUNT || (shape_table[idx].used_for & what) == 0) { - return (char_u *)N_("E546: Illegal mode"); + return N_("E546: Illegal mode"); } if (len == 2 && modep[0] == 'v' && modep[1] == 'e') { found_ve = true; @@ -189,12 +189,12 @@ char_u *parse_shape_opt(int what) if (len != 0) { p += len; if (!ascii_isdigit(*p)) { - return (char_u *)N_("E548: digit expected"); + return N_("E548: digit expected"); } int n = getdigits_int(&p, false, 0); if (len == 3) { // "ver" or "hor" if (n == 0) { - return (char_u *)N_("E549: Illegal percentage"); + return N_("E549: Illegal percentage"); } if (round == 2) { if (TOLOWER_ASC(i) == 'v') { diff --git a/src/nvim/cursor_shape.h b/src/nvim/cursor_shape.h index 06eaa431a0..93bddd47c7 100644 --- a/src/nvim/cursor_shape.h +++ b/src/nvim/cursor_shape.h @@ -24,13 +24,13 @@ typedef enum { SHAPE_IDX_MORE = 14, ///< Hit-return or More SHAPE_IDX_MOREL = 15, ///< Hit-return or More in last line SHAPE_IDX_SM = 16, ///< showing matching paren - SHAPE_IDX_COUNT = 17 + SHAPE_IDX_COUNT = 17, } ModeShape; typedef enum { SHAPE_BLOCK = 0, ///< block cursor SHAPE_HOR = 1, ///< horizontal bar cursor - SHAPE_VER = 2 ///< vertical bar cursor + SHAPE_VER = 2, ///< vertical bar cursor } CursorShape; #define MSHAPE_NUMBERED 1000 // offset for shapes identified by number diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index aeaf2555b1..3ac128a20f 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -88,7 +88,7 @@ void do_debug(char_u *cmd) debug_mode = true; if (!debug_did_msg) { - MSG(_("Entering Debug mode. Type \"cont\" to continue.")); + msg(_("Entering Debug mode. Type \"cont\" to continue.")); } if (debug_oldval != NULL) { smsg(_("Oldval = \"%s\""), debug_oldval); @@ -101,7 +101,7 @@ void do_debug(char_u *cmd) debug_newval = NULL; } if (sourcing_name != NULL) { - msg(sourcing_name); + msg((char *)sourcing_name); } if (sourcing_lnum != 0) { smsg(_("line %" PRId64 ": %s"), (int64_t)sourcing_lnum, cmd); @@ -321,7 +321,7 @@ static void do_checkbacktracelevel(void) { if (debug_backtrace_level < 0) { debug_backtrace_level = 0; - MSG(_("frame is zero")); + msg(_("frame is zero")); } else { int max = get_maxbacktrace_level(); if (debug_backtrace_level > max) { @@ -496,7 +496,7 @@ static int dbg_parsearg(char_u *arg, garray_T *gap) bp->dbg_type = DBG_FILE; } else if (gap != &prof_ga && STRNCMP(p, "here", 4) == 0) { if (curbuf->b_ffname == NULL) { - EMSG(_(e_noname)); + emsg(_(e_noname)); return FAIL; } bp->dbg_type = DBG_FILE; @@ -504,7 +504,7 @@ static int dbg_parsearg(char_u *arg, garray_T *gap) } else if (gap != &prof_ga && STRNCMP(p, "expr", 4) == 0) { bp->dbg_type = DBG_EXPR; } else { - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return FAIL; } p = skipwhite(p + 4); @@ -523,7 +523,7 @@ static int dbg_parsearg(char_u *arg, garray_T *gap) if ((!here && *p == NUL) || (here && *p != NUL) || (bp->dbg_type == DBG_FUNC && strstr((char *)p, "()") != NULL)) { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); return FAIL; } @@ -661,7 +661,7 @@ void ex_breakdel(exarg_T *eap) } if (todel < 0) { - EMSG2(_("E161: Breakpoint not found: %s"), eap->arg); + semsg(_("E161: Breakpoint not found: %s"), eap->arg); } else { while (!GA_EMPTY(gap)) { xfree(DEBUGGY(gap, todel).dbg_name); @@ -696,7 +696,7 @@ void ex_breaklist(exarg_T *eap) struct debuggy *bp; if (GA_EMPTY(&dbg_breakp)) { - MSG(_("No breakpoints defined")); + msg(_("No breakpoints defined")); } else { for (int i = 0; i < dbg_breakp.ga_len; i++) { bp = &BREAKP(i); diff --git a/src/nvim/decoration.h b/src/nvim/decoration.h index 97ae9ed5d8..611b4223da 100644 --- a/src/nvim/decoration.h +++ b/src/nvim/decoration.h @@ -31,8 +31,7 @@ typedef kvec_t(VirtTextChunk) VirtText; typedef kvec_t(struct virt_line { VirtText line; bool left_col; }) VirtLines; -struct Decoration -{ +struct Decoration { VirtText virt_text; VirtLines virt_lines; diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 80b8920a7f..1cc9399465 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -168,7 +168,7 @@ void diff_buf_add(buf_T *buf) } } - EMSGN(_("E96: Cannot diff more than %" PRId64 " buffers"), DB_COUNT); + semsg(_("E96: Cannot diff more than %" PRId64 " buffers"), (int64_t)DB_COUNT); } /// @@ -638,7 +638,8 @@ static int diff_check_sanity(tabpage_T *tp, diff_T *dp) void diff_redraw(bool dofold) { win_T *wp_other = NULL; - bool used_max_fill = false; + bool used_max_fill_other = false; + bool used_max_fill_curwin = false; need_diff_redraw = false; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { @@ -663,16 +664,24 @@ void diff_redraw(bool dofold) } else if ((n > 0) && (n > wp->w_topfill)) { wp->w_topfill = n; if (wp == curwin) { - used_max_fill = true; + used_max_fill_curwin = true; + } else if (wp_other != NULL) { + used_max_fill_other = true; } } check_topfill(wp, false); } } - if (wp_other != NULL && used_max_fill && curwin->w_p_scb) { - // The current window was set to used the maximum number of filler - // lines, may need to reduce them. - diff_set_topline(wp_other, curwin); + if (wp_other != NULL && curwin->w_p_scb) { + if (used_max_fill_curwin) { + // The current window was set to used the maximum number of filler + // lines, may need to reduce them. + diff_set_topline(wp_other, curwin); + } else if (used_max_fill_other) { + // The other window was set to used the maximum number of filler + // lines, may need to reduce them. + diff_set_topline(curwin, wp_other); + } } } @@ -1030,9 +1039,9 @@ static int check_external_diff(diffio_T *diffio) if (!ok) { if (io_error) { - EMSG(_("E810: Cannot read or write temp files")); + emsg(_("E810: Cannot read or write temp files")); } - EMSG(_("E97: Cannot create diffs")); + emsg(_("E97: Cannot create diffs")); diff_a_works = kNone; return FAIL; } @@ -1073,7 +1082,7 @@ static int diff_file_internal(diffio_T *diffio) if (xdl_diff(&diffio->dio_orig.din_mmfile, &diffio->dio_new.din_mmfile, ¶m, &emit_cfg, &emit_cb) < 0) { - EMSG(_("E960: Problem creating the internal diff")); + emsg(_("E960: Problem creating the internal diff")); return FAIL; } return OK; @@ -1216,7 +1225,7 @@ void ex_diffpatch(exarg_T *eap) #ifdef UNIX if (dirbuf[0] != NUL) { if (os_chdir((char *)dirbuf) != 0) { - EMSG(_(e_prev_dir)); + emsg(_(e_prev_dir)); } shorten_fnames(true); } @@ -1235,7 +1244,7 @@ void ex_diffpatch(exarg_T *eap) bool info_ok = os_fileinfo((char *)tmp_new, &file_info); uint64_t filesize = os_fileinfo_size(&file_info); if (!info_ok || filesize == 0) { - EMSG(_("E816: Cannot read patch output")); + emsg(_("E816: Cannot read patch output")); } else { if (curbuf->b_fname != NULL) { newname = vim_strnsave(curbuf->b_fname, STRLEN(curbuf->b_fname) + 4); @@ -1527,7 +1536,7 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout) enum { DIFF_ED, DIFF_UNIFIED, - DIFF_NONE + DIFF_NONE, } diffstyle = DIFF_NONE; if (dout->dout_fname == NULL) { @@ -1535,7 +1544,7 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout) } else { fd = os_fopen((char *)dout->dout_fname, "r"); if (fd == NULL) { - EMSG(_("E98: Cannot read diff output")); + emsg(_("E98: Cannot read diff output")); return; } } @@ -1591,7 +1600,7 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout) } } else { assert(diffstyle == DIFF_UNIFIED); - if (STRNCMP(line, "@@ ", 3) != 0) { + if (STRNCMP(line, "@@ ", 3) != 0) { continue; // not the start of a diff block } if (parse_diff_unified(line, &lnum_orig, &count_orig, @@ -1699,7 +1708,7 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout) notset = false; // "*dp" has been set } - // for remaining diff blocks orig and new are equal +// for remaining diff blocks orig and new are equal while (dp != NULL) { if (notset) { diff_copy_entry(dprev, dp, idx_orig, idx_new); @@ -2488,7 +2497,7 @@ void ex_diffgetput(exarg_T *eap) // Find the current buffer in the list of diff buffers. int idx_cur = diff_buf_idx(curbuf); if (idx_cur == DB_COUNT) { - EMSG(_("E99: Current buffer is not in diff mode")); + emsg(_("E99: Current buffer is not in diff mode")); return; } @@ -2507,9 +2516,9 @@ void ex_diffgetput(exarg_T *eap) if (idx_other == DB_COUNT) { if (found_not_ma) { - EMSG(_("E793: No other buffer in diff mode is modifiable")); + emsg(_("E793: No other buffer in diff mode is modifiable")); } else { - EMSG(_("E100: No other buffer in diff mode")); + emsg(_("E100: No other buffer in diff mode")); } return; } @@ -2520,7 +2529,7 @@ void ex_diffgetput(exarg_T *eap) && (curtab->tp_diffbuf[i] != NULL) && ((eap->cmdidx != CMD_diffput) || MODIFIABLE(curtab->tp_diffbuf[i]))) { - EMSG(_("E101: More than two buffers in diff mode, don't know " + emsg(_("E101: More than two buffers in diff mode, don't know " "which one to use")); return; } @@ -2549,7 +2558,7 @@ void ex_diffgetput(exarg_T *eap) buf = buflist_findnr(i); if (buf == NULL) { - EMSG2(_("E102: Can't find buffer \"%s\""), eap->arg); + semsg(_("E102: Can't find buffer \"%s\""), eap->arg); return; } @@ -2560,7 +2569,7 @@ void ex_diffgetput(exarg_T *eap) idx_other = diff_buf_idx(buf); if (idx_other == DB_COUNT) { - EMSG2(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg); + semsg(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg); return; } } @@ -2601,7 +2610,7 @@ void ex_diffgetput(exarg_T *eap) if (!curbuf->b_changed) { change_warning(curbuf, 0); if (diff_buf_idx(curbuf) != idx_to) { - EMSG(_("E787: Buffer changed unexpectedly")); + emsg(_("E787: Buffer changed unexpectedly")); goto theend; } } @@ -3138,7 +3147,7 @@ static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf) } // sanity check - if (STRNCMP(mb[0].ptr, "@@ ", 3) != 0) { + if (STRNCMP(mb[0].ptr, "@@ ", 3) != 0) { return 0; } diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c index 0fa6ebcd94..d1dd9b8309 100644 --- a/src/nvim/digraph.c +++ b/src/nvim/digraph.c @@ -1628,18 +1628,18 @@ void putdigraph(char_u *str) char2 = *str++; if (char2 == 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } if ((char1 == ESC) || (char2 == ESC)) { - EMSG(_("E104: Escape not allowed in digraph")); + emsg(_("E104: Escape not allowed in digraph")); return; } str = skipwhite(str); if (!ascii_isdigit(*str)) { - EMSG(_(e_number_exp)); + emsg(_(e_number_exp)); return; } int n = getdigits_int(&str, true, 0); @@ -1821,7 +1821,7 @@ typedef struct { /// @return NULL if OK, an error message for failure. This only needs to be /// used when setting the option, not later when the value has already /// been checked. -char_u *keymap_init(void) +char *keymap_init(void) { curbuf->b_kmap_state &= ~KEYMAP_INIT; @@ -1850,7 +1850,7 @@ char_u *keymap_init(void) if (source_runtime(buf, 0) == FAIL) { xfree(buf); - return (char_u *)N_("E544: Keymap file not found"); + return N_("E544: Keymap file not found"); } } xfree(buf); @@ -1873,7 +1873,7 @@ void ex_loadkeymap(exarg_T *eap) char_u *save_cpo = p_cpo; if (!getline_equal(eap->getline, eap->cookie, getsourceline)) { - EMSG(_("E105: Using :loadkeymap not in a sourced file")); + emsg(_("E105: Using :loadkeymap not in a sourced file")); return; } @@ -1908,7 +1908,7 @@ void ex_loadkeymap(exarg_T *eap) || (*kp->from == NUL) || (*kp->to == NUL)) { if (*kp->to == NUL) { - EMSG(_("E791: Empty keymap entry")); + emsg(_("E791: Empty keymap entry")); } xfree(kp->from); xfree(kp->to); diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 0cfda53091..9c333f5760 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1398,20 +1398,20 @@ bool edit(int cmdchar, bool startln, long count) // Don't allow inserting in the sandbox. if (sandbox != 0) { - EMSG(_(e_sandbox)); + emsg(_(e_sandbox)); return false; } // Don't allow changes in the buffer while editing the cmdline. The // caller of getcmdline() may get confused. if (textlock != 0) { - EMSG(_(e_secure)); + emsg(_(e_secure)); return false; } // Don't allow recursive insert mode when busy with completion. if (compl_started || compl_busy || pum_visible()) { - EMSG(_(e_secure)); + emsg(_(e_secure)); return false; } @@ -3005,7 +3005,7 @@ static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, msg_hist_off = true; // reset in msg_trunc_attr() vim_snprintf((char *)IObuff, IOSIZE, _("Scanning dictionary: %s"), (char *)files[i]); - (void)msg_trunc_attr(IObuff, true, HL_ATTR(HLF_R)); + (void)msg_trunc_attr((char *)IObuff, true, HL_ATTR(HLF_R)); } if (fp == NULL) { @@ -3329,7 +3329,7 @@ void get_complete_info(list_T *what_list, dict_T *retdict) // Return Insert completion mode name string static char_u *ins_compl_mode(void) { - if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || ctrl_x_mode == CTRL_X_SCROLL || compl_started) { + if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || ctrl_x_mode == CTRL_X_SCROLL || compl_started) { return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT]; } return (char_u *)""; @@ -3904,7 +3904,6 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) assert(wp); while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin && wp->w_buffer->b_scanned) { - ; } buf = wp->w_buffer; } else { @@ -3917,7 +3916,6 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) : (!buf->b_p_bl || (buf->b_ml.ml_mfp == NULL) != (flag == 'u'))) || buf->b_scanned)) { - ; } } return buf; @@ -3976,13 +3974,13 @@ static void expand_by_function(int type, char_u *base) } if (curwin_save != curwin || curbuf_save != curbuf) { - EMSG(_(e_complwin)); + emsg(_(e_complwin)); goto theend; } curwin->w_cursor = pos; // restore the cursor position validate_cursor(); if (!equalpos(curwin->w_cursor, pos)) { - EMSG(_(e_compldel)); + emsg(_(e_compldel)); goto theend; } @@ -4211,7 +4209,7 @@ static int ins_compl_get_exp(pos_T *ini) : ins_buf->b_sfname == NULL ? ins_buf->b_fname : ins_buf->b_sfname); - (void)msg_trunc_attr(IObuff, true, HL_ATTR(HLF_R)); + (void)msg_trunc_attr((char *)IObuff, true, HL_ATTR(HLF_R)); } else if (*e_cpt == NUL) { break; } else { @@ -4235,7 +4233,7 @@ static int ins_compl_get_exp(pos_T *ini) msg_hist_off = true; // reset in msg_trunc_attr() type = CTRL_X_TAGS; vim_snprintf((char *)IObuff, IOSIZE, "%s", _("Scanning tags.")); - (void)msg_trunc_attr(IObuff, true, HL_ATTR(HLF_R)); + (void)msg_trunc_attr((char *)IObuff, true, HL_ATTR(HLF_R)); } else { type = -1; } @@ -4427,7 +4425,7 @@ static int ins_compl_get_exp(pos_T *ini) // when ADDING, the text before the cursor matches, skip it if ((compl_cont_status & CONT_ADDING) && ins_buf == curbuf && ini->lnum == pos->lnum - && ini->col == pos->col) { + && ini->col == pos->col) { continue; } ptr = ml_get_buf(ins_buf, pos->lnum, false) + pos->col; @@ -4838,7 +4836,7 @@ static int ins_compl_next(int allow_get_expansion, int count, int insert_match, msg_hist_off = true; vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead, s > compl_shown_match->cp_fname ? "<" : "", s); - msg(IObuff); + msg((char *)IObuff); msg_hist_off = false; redraw_cmdline = false; // don't overwrite! } @@ -5100,7 +5098,6 @@ static int ins_complete(int c, bool enable_pum) || ctrl_x_mode == CTRL_X_PATH_DEFINES) { if (!(compl_cont_status & CONT_ADDING)) { while (--startcol >= 0 && vim_isIDc(line[startcol])) { - ; } compl_col += ++startcol; compl_length = curs_col - startcol; @@ -5223,7 +5220,7 @@ static int ins_complete(int c, bool enable_pum) funcname = ctrl_x_mode == CTRL_X_FUNCTION ? curbuf->b_p_cfu : curbuf->b_p_ofu; if (*funcname == NUL) { - EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION + semsg(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION ? "completefunc" : "omnifunc"); // restore did_ai, so that adding comment leader works did_ai = save_did_ai; @@ -5244,13 +5241,13 @@ static int ins_complete(int c, bool enable_pum) State = save_State; if (curwin_save != curwin || curbuf_save != curbuf) { - EMSG(_(e_complwin)); + emsg(_(e_complwin)); return FAIL; } curwin->w_cursor = pos; // restore the cursor position validate_cursor(); if (!equalpos(curwin->w_cursor, pos)) { - EMSG(_(e_compldel)); + emsg(_(e_compldel)); return FAIL; } @@ -5788,7 +5785,6 @@ void insertchar(int c, int flags, int second_indent) // Skip white space before the cursor i = curwin->w_cursor.col; while (--i >= 0 && ascii_iswhite(line[i])) { - ; } i++; @@ -7021,7 +7017,7 @@ int stuff_inserted(int c, long count, int no_esc) ptr = get_last_insert(); if (ptr == NULL) { - EMSG(_(e_noinstext)); + emsg(_(e_noinstext)); return FAIL; } @@ -7373,7 +7369,8 @@ void fixthisline(IndentGetter get_the_indent) } } -void fix_indent(void) { +void fix_indent(void) +{ if (p_paste) { return; } @@ -7621,7 +7618,7 @@ int hkmap(int c) enum { hALEF = 0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD, KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN, - PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV + PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV, }; static char_u map[26] = { (char_u)hALEF /*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, @@ -7969,7 +7966,7 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) if (reg_recording != 0 || restart_edit != NUL) { showmode(); } else if (p_smd) { - MSG(""); + msg(""); } // Exit Insert mode return true; @@ -8582,7 +8579,6 @@ static void ins_mousescroll(int dir) } - static void ins_left(void) { pos_T tpos; diff --git a/src/nvim/eval.c b/src/nvim/eval.c index b31e1e81d4..b27a11c248 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -501,7 +501,7 @@ int var_redir_start(char_u *name, int append) // Catch a bad name early. if (!eval_isnamec1(*name)) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return FAIL; } @@ -521,9 +521,9 @@ int var_redir_start(char_u *name, int append) clear_lval(redir_lval); if (redir_endp != NULL && *redir_endp != NUL) { // Trailing characters are present after the variable name - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } else { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } redir_endp = NULL; // don't store a value, only cleanup var_redir_stop(); @@ -728,7 +728,7 @@ static int eval1_emsg(char_u **arg, typval_T *rettv, bool evaluate) if (!aborting() && did_emsg == did_emsg_before && called_emsg == called_emsg_before) { - emsgf(_(e_invexpr2), start); + semsg(_(e_invexpr2), start); } } return ret; @@ -771,7 +771,7 @@ int eval_expr_typval(const typval_T *expr, typval_T *argv, int argc, typval_T *r } if (*skipwhite(s) != NUL) { // check for trailing chars after expr tv_clear(rettv); - emsgf(_(e_invexpr2), s); + semsg(_(e_invexpr2), s); return FAIL; } } @@ -1029,7 +1029,7 @@ list_T *eval_spell_expr(char_u *badword, char_u *expr) int get_spellword(list_T *const list, const char **ret_word) { if (tv_list_len(list) != 2) { - EMSG(_("E5700: Expression from 'spellsuggest' must yield lists with " + emsg(_("E5700: Expression from 'spellsuggest' must yield lists with " "exactly two values")); return -1; } @@ -1256,7 +1256,7 @@ static list_T *heredoc_get(exarg_T *eap, char_u *cmd) char_u *text_indent = NULL; if (eap->getline == NULL) { - EMSG(_("E991: cannot use =<< here")); + emsg(_("E991: cannot use =<< here")); return NULL; } @@ -1283,16 +1283,16 @@ static list_T *heredoc_get(exarg_T *eap, char_u *cmd) marker = skipwhite(cmd); p = skiptowhite(marker); if (*skipwhite(p) != NUL && *skipwhite(p) != '"') { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return NULL; } *p = NUL; if (islower(*marker)) { - EMSG(_("E221: Marker cannot start with lower case letter")); + emsg(_("E221: Marker cannot start with lower case letter")); return NULL; } } else { - EMSG(_("E172: Missing marker")); + emsg(_("E172: Missing marker")); return NULL; } @@ -1303,7 +1303,7 @@ static list_T *heredoc_get(exarg_T *eap, char_u *cmd) char_u *theline = eap->getline(NUL, eap->cookie, 0, false); if (theline == NULL) { - EMSG2(_("E990: Missing end marker '%s'"), marker); + semsg(_("E990: Missing end marker '%s'"), marker); break; } @@ -1385,7 +1385,7 @@ static void ex_let_const(exarg_T *eap, const bool is_const) && expr[1] == '=') || STRNCMP(expr, "..=", 3) == 0)) { // ":let" without "=": list variables if (*arg == '[') { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else if (!ends_excmd(*arg)) { // ":let var1 var2" arg = (char_u *)list_arg_vars(eap, (const char *)arg, &first); @@ -1475,18 +1475,18 @@ static int ex_let_vars(char_u *arg_start, typval_T *tv, int copy, int semicolon, // ":let [v1, v2] = list" or ":for [v1, v2] in listlist" if (tv->v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return FAIL; } list_T *const l = tv->vval.v_list; const int len = tv_list_len(l); if (semicolon == 0 && var_count < len) { - EMSG(_("E687: Less targets than List items")); + emsg(_("E687: Less targets than List items")); return FAIL; } if (var_count - semicolon > len) { - EMSG(_("E688: More targets than List items")); + emsg(_("E688: More targets than List items")); return FAIL; } // List l may actually be NULL, but it should fail with E688 or even earlier @@ -1555,7 +1555,7 @@ static const char_u *skip_var_list(const char_u *arg, int *var_count, int *semic p = skipwhite(p + 1); // skip whites after '[', ';' or ',' s = skip_var_one(p); if (s == p) { - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return NULL; } ++*var_count; @@ -1565,12 +1565,12 @@ static const char_u *skip_var_list(const char_u *arg, int *var_count, int *semic break; } else if (*p == ';') { if (*semicolon == 1) { - EMSG(_("E452: Double ; in list of variables")); + emsg(_("E452: Double ; in list of variables")); return NULL; } *semicolon = 1; } else if (*p != ',') { - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return NULL; } } @@ -1690,7 +1690,7 @@ static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first) FNE_INCL_BR | FNE_CHECK_START); if (!ascii_iswhite(*arg) && !ends_excmd(*arg)) { emsg_severe = true; - EMSG(_(e_trailing)); + emsg(_(e_trailing)); break; } } else { @@ -1703,7 +1703,7 @@ static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first) * curly braces fails overrule the exception error message. */ if (len < 0 && !aborting()) { emsg_severe = true; - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); break; } error = TRUE; @@ -1739,7 +1739,7 @@ static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first) case 'l': list_func_vars(first); break; default: - EMSG2(_("E738: Can't list variables for %s"), name); + semsg(_("E738: Can't list variables for %s"), name); } } else { char *const s = encode_tv2echo(&tv, NULL); @@ -1794,7 +1794,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons */ if (*arg == '$') { if (is_const) { - EMSG(_("E996: Cannot lock an environment variable")); + emsg(_("E996: Cannot lock an environment variable")); return NULL; } // Find the end of the name. @@ -1802,13 +1802,13 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons char *name = (char *)arg; len = get_env_len((const char_u **)&arg); if (len == 0) { - EMSG2(_(e_invarg2), name - 1); + semsg(_(e_invarg2), name - 1); } else { if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL) { - EMSG2(_(e_letwrong), op); + semsg(_(e_letwrong), op); } else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg)) == NULL) { - EMSG(_(e_letunexp)); + emsg(_(e_letunexp)); } else if (!check_secure()) { const char c1 = name[len]; name[len] = NUL; @@ -1843,7 +1843,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons // ":let &g:option = expr": Set global option value. } else if (*arg == '&') { if (is_const) { - EMSG(_("E996: Cannot lock an option")); + emsg(_("E996: Cannot lock an option")); return NULL; } // Find the end of the name. @@ -1851,7 +1851,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons if (p == NULL || (endchars != NULL && vim_strchr(endchars, *skipwhite((const char_u *)p)) == NULL)) { - EMSG(_(e_letunexp)); + emsg(_(e_letunexp)); } else { int opt_type; long numval; @@ -1870,7 +1870,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons opt_flags); if ((opt_type == 1 && *op == '.') || (opt_type == 0 && *op != '.')) { - EMSG2(_(e_letwrong), op); + semsg(_(e_letwrong), op); s = NULL; // don't set the value } else { if (opt_type == 1) { // number @@ -1906,15 +1906,15 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons // ":let @r = expr": Set register contents. } else if (*arg == '@') { if (is_const) { - EMSG(_("E996: Cannot lock a register")); + emsg(_("E996: Cannot lock a register")); return NULL; } arg++; if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL) { - emsgf(_(e_letwrong), op); + semsg(_(e_letwrong), op); } else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL) { - EMSG(_(e_letunexp)); + emsg(_(e_letunexp)); } else { char_u *s; @@ -1946,7 +1946,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons char_u *const p = get_lval(arg, tv, &lv, false, false, 0, FNE_CHECK_START); if (p != NULL && lv.ll_name != NULL) { if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL) { - EMSG(_(e_letunexp)); + emsg(_(e_letunexp)); } else { set_var_lval(&lv, p, tv, copy, is_const, (const char *)op); arg_end = p; @@ -1954,7 +1954,7 @@ static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, cons } clear_lval(&lv); } else { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } return arg_end; @@ -2018,7 +2018,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co // Don't expand the name when we already know there is an error. if (unlet && !ascii_iswhite(*p) && !ends_excmd(*p) && *p != '[' && *p != '.') { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return NULL; } @@ -2031,7 +2031,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co // aborting error, an interrupt, or an exception. if (!aborting() && !quiet) { emsg_severe = true; - EMSG2(_(e_invarg2), name); + semsg(_(e_invarg2), name); return NULL; } lp->ll_name_len = 0; @@ -2054,7 +2054,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co (flags & GLV_READ_ONLY) ? NULL : &ht, flags & GLV_NO_AUTOLOAD); if (v == NULL && !quiet) { - emsgf(_("E121: Undefined variable: %.*s"), + semsg(_("E121: Undefined variable: %.*s"), (int)lp->ll_name_len, lp->ll_name); } if (v == NULL) { @@ -2070,13 +2070,13 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co && !(lp->ll_tv->v_type == VAR_DICT && lp->ll_tv->vval.v_dict != NULL) && !(lp->ll_tv->v_type == VAR_BLOB && lp->ll_tv->vval.v_blob != NULL)) { if (!quiet) { - EMSG(_("E689: Can only index a List, Dictionary or Blob")); + emsg(_("E689: Can only index a List, Dictionary or Blob")); } return NULL; } if (lp->ll_range) { if (!quiet) { - EMSG(_("E708: [:] must come last")); + emsg(_("E708: [:] must come last")); } return NULL; } @@ -2089,7 +2089,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co } if (len == 0) { if (!quiet) { - EMSG(_("E713: Cannot use empty key after .")); + emsg(_("E713: Cannot use empty key after .")); } return NULL; } @@ -2116,7 +2116,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co if (*p == ':') { if (lp->ll_tv->v_type == VAR_DICT) { if (!quiet) { - EMSG(_(e_dictrange)); + emsg(_(e_dictrange)); } tv_clear(&var1); return NULL; @@ -2125,7 +2125,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co && !(rettv->v_type == VAR_LIST && rettv->vval.v_list != NULL) && !(rettv->v_type == VAR_BLOB && rettv->vval.v_blob != NULL)) { if (!quiet) { - EMSG(_("E709: [:] requires a List or Blob value")); + emsg(_("E709: [:] requires a List or Blob value")); } tv_clear(&var1); return NULL; @@ -2153,7 +2153,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co if (*p != ']') { if (!quiet) { - EMSG(_(e_missbrac)); + emsg(_(e_missbrac)); } tv_clear(&var1); tv_clear(&var2); @@ -2201,7 +2201,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co if (lp->ll_di != NULL && tv_is_luafunc(&lp->ll_di->di_tv) && len == -1 && rettv == NULL) { tv_clear(&var1); - EMSG2(e_illvar, "v:['lua']"); + semsg(e_illvar, "v:['lua']"); return NULL; } @@ -2209,7 +2209,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co // Can't add "v:" or "a:" variable. if (lp->ll_dict == &vimvardict || &lp->ll_dict->dv_hashtab == get_funccal_args_ht()) { - EMSG2(_(e_illvar), name); + semsg(_(e_illvar), name); tv_clear(&var1); return NULL; } @@ -2217,7 +2217,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co // Key does not exist in dict: may need to add it. if (*p == '[' || *p == '.' || unlet) { if (!quiet) { - emsgf(_(e_dictkey), key); + semsg(_(e_dictkey), key); } tv_clear(&var1); return NULL; @@ -2253,7 +2253,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co if (lp->ll_n1 < 0 || lp->ll_n1 > bloblen || (lp->ll_range && lp->ll_n1 == bloblen)) { if (!quiet) { - EMSGN(_(e_blobidx), lp->ll_n1); + semsg(_(e_blobidx), (int64_t)lp->ll_n1); } tv_clear(&var2); return NULL; @@ -2263,7 +2263,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co tv_clear(&var2); if (lp->ll_n2 < 0 || lp->ll_n2 >= bloblen || lp->ll_n2 < lp->ll_n1) { if (!quiet) { - EMSGN(_(e_blobidx), lp->ll_n2); + semsg(_(e_blobidx), (int64_t)lp->ll_n2); } return NULL; } @@ -2293,7 +2293,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co if (lp->ll_li == NULL) { tv_clear(&var2); if (!quiet) { - EMSGN(_(e_listidx), lp->ll_n1); + semsg(_(e_listidx), (int64_t)lp->ll_n1); } return NULL; } @@ -2309,7 +2309,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co ni = tv_list_find(lp->ll_list, lp->ll_n2); if (ni == NULL) { if (!quiet) { - EMSGN(_(e_listidx), lp->ll_n2); + semsg(_(e_listidx), (int64_t)lp->ll_n2); } return NULL; } @@ -2322,7 +2322,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co } if (lp->ll_n2 < lp->ll_n1) { if (!quiet) { - EMSGN(_(e_listidx), lp->ll_n2); + semsg(_(e_listidx), (int64_t)lp->ll_n2); } return NULL; } @@ -2367,7 +2367,7 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co *endp = NUL; if (lp->ll_blob != NULL) { if (op != NULL && *op != '=') { - EMSG2(_(e_letwrong), op); + semsg(_(e_letwrong), op); return; } if (var_check_lock(lp->ll_blob->bv_lock, lp->ll_name, TV_CSTRING)) { @@ -2380,7 +2380,7 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co } if (lp->ll_n2 - lp->ll_n1 + 1 != tv_blob_len(rettv->vval.v_blob)) { - EMSG(_("E972: Blob value does not have the right number of bytes")); + emsg(_("E972: Blob value does not have the right number of bytes")); return; } if (lp->ll_empty2) { @@ -2412,7 +2412,7 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co typval_T tv; if (is_const) { - EMSG(_(e_cannot_mod)); + emsg(_(e_cannot_mod)); *endp = cc; return; } @@ -2442,7 +2442,7 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co int ll_n1 = lp->ll_n1; if (is_const) { - EMSG(_("E996: Cannot lock a range")); + emsg(_("E996: Cannot lock a range")); return; } @@ -2487,12 +2487,12 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co lp->ll_n1++; } if (ri != NULL) { - EMSG(_("E710: List value has more items than target")); + emsg(_("E710: List value has more items than target")); } else if (lp->ll_empty2 ? (lp->ll_li != NULL && TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) != NULL) : lp->ll_n1 != lp->ll_n2) { - EMSG(_("E711: List value has not enough items")); + emsg(_("E711: List value has not enough items")); } } else { typval_T oldtv = TV_INITIAL_VALUE; @@ -2500,14 +2500,14 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, co bool watched = tv_dict_is_watched(dict); if (is_const) { - EMSG(_("E996: Cannot lock a list or dict")); + emsg(_("E996: Cannot lock a list or dict")); return; } // Assign to a List or Dictionary item. if (lp->ll_newkey != NULL) { if (op != NULL && *op != '=') { - EMSG2(_(e_letwrong), op); + semsg(_(e_letwrong), op); return; } @@ -2579,7 +2579,7 @@ void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip) expr = skipwhite(expr); if (expr[0] != 'i' || expr[1] != 'n' || !ascii_iswhite(expr[2])) { - EMSG(_("E690: Missing \"in\" after :for")); + emsg(_("E690: Missing \"in\" after :for")); return fi; } @@ -2613,7 +2613,7 @@ void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip) } tv_clear(&tv); } else { - EMSG(_(e_listblobreq)); + emsg(_(e_listblobreq)); tv_clear(&tv); } } @@ -2837,7 +2837,7 @@ static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep, ex_unletlock_ lv.ll_tv = NULL; arg++; if (get_env_len((const char_u **)&arg) == 0) { - EMSG2(_(e_invarg2), arg - 1); + semsg(_(e_invarg2), arg - 1); return; } if (!error && !eap->skip && callback(&lv, arg, eap, deep) == FAIL) { @@ -2855,7 +2855,7 @@ static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep, ex_unletlock_ || (!ascii_iswhite(*name_end) && !ends_excmd(*name_end))) { if (name_end != NULL) { emsg_severe = true; - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } if (!(eap->skip || error)) { clear_lval(&lv); @@ -3037,7 +3037,7 @@ int do_unlet(const char *const name, const size_t name_len, const bool forceit) if (forceit) { return OK; } - EMSG2(_("E108: No such variable: \"%s\""), name); + semsg(_("E108: No such variable: \"%s\""), name); return FAIL; } @@ -3065,7 +3065,7 @@ static int do_lock_var(lval_T *lp, char_u *name_end FUNC_ATTR_UNUSED, exarg_T *e if (lp->ll_tv == NULL) { if (*lp->ll_name == '$') { - EMSG2(_(e_lock_unlock), lp->ll_name); + semsg(_(e_lock_unlock), lp->ll_name); ret = FAIL; } else { // Normal name or expanded name. @@ -3078,7 +3078,7 @@ static int do_lock_var(lval_T *lp, char_u *name_end FUNC_ATTR_UNUSED, exarg_T *e && di->di_tv.v_type != VAR_LIST) { // For historical reasons this error is not given for Lists and // Dictionaries. E.g. b: dictionary may be locked/unlocked. - EMSG2(_(e_lock_unlock), lp->ll_name); + semsg(_(e_lock_unlock), lp->ll_name); ret = FAIL; } else { if (lock) { @@ -3359,7 +3359,7 @@ int eval0(char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate) // Also check called_emsg for when using assert_fails(). if (!aborting() && did_emsg == did_emsg_before && called_emsg == called_emsg_before) { - emsgf(_(e_invexpr2), arg); + semsg(_(e_invexpr2), arg); } ret = FAIL; } @@ -3421,7 +3421,7 @@ int eval1(char_u **arg, typval_T *rettv, int evaluate) * Check for the ":". */ if ((*arg)[0] != ':') { - EMSG(_("E109: Missing ':' after '?'")); + emsg(_("E109: Missing ':' after '?'")); if (evaluate && result) { tv_clear(rettv); } @@ -3978,7 +3978,7 @@ static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string) ) : f1 / f2); } else { - EMSG(_("E804: Cannot use '%' with Float")); + emsg(_("E804: Cannot use '%' with Float")); return FAIL; } rettv->v_type = VAR_FLOAT; @@ -4107,7 +4107,7 @@ static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string) for (bp = *arg + 2; ascii_isxdigit(bp[0]); bp += 2) { if (!ascii_isxdigit(bp[1])) { if (blob != NULL) { - EMSG(_("E973: Blob literal should have an even number of hex " + emsg(_("E973: Blob literal should have an even number of hex " "characters")); ga_clear(&blob->bv_ga); XFREE_CLEAR(blob); @@ -4130,7 +4130,7 @@ static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string) // decimal, hex or octal number vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0, true); if (len == 0) { - EMSG2(_(e_invexpr2), *arg); + semsg(_(e_invexpr2), *arg); ret = FAIL; break; } @@ -4205,7 +4205,7 @@ static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string) if (**arg == ')') { ++*arg; } else if (ret == OK) { - EMSG(_("E110: Missing ')'")); + emsg(_("E110: Missing ')'")); tv_clear(rettv); ret = FAIL; } @@ -4378,9 +4378,9 @@ static int eval_lambda(char_u **const arg, typval_T *const rettv, const bool eva } else if (**arg != '(') { if (verbose) { if (*skipwhite(*arg) == '(') { - EMSG(_(e_nowhitespace)); + emsg(_(e_nowhitespace)); } else { - EMSG2(_(e_missingparen), "lambda"); + semsg(_(e_missingparen), "lambda"); } } tv_clear(rettv); @@ -4431,21 +4431,21 @@ static int eval_method(char_u **const arg, typval_T *const rettv, const bool eva if (len <= 0) { if (verbose) { if (lua_funcname == NULL) { - EMSG(_("E260: Missing name after ->")); + emsg(_("E260: Missing name after ->")); } else { - EMSG2(_(e_invexpr2), name); + semsg(_(e_invexpr2), name); } } ret = FAIL; } else { if (**arg != '(') { if (verbose) { - EMSG2(_(e_missingparen), name); + semsg(_(e_missingparen), name); } ret = FAIL; } else if (ascii_iswhite((*arg)[-1])) { if (verbose) { - EMSG(_(e_nowhitespace)); + emsg(_(e_nowhitespace)); } ret = FAIL; } else if (lua_funcname != NULL) { @@ -4489,18 +4489,18 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) case VAR_FUNC: case VAR_PARTIAL: if (verbose) { - EMSG(_("E695: Cannot index a Funcref")); + emsg(_("E695: Cannot index a Funcref")); } return FAIL; case VAR_FLOAT: if (verbose) { - EMSG(_(e_float_as_string)); + emsg(_(e_float_as_string)); } return FAIL; case VAR_BOOL: case VAR_SPECIAL: if (verbose) { - EMSG(_("E909: Cannot index a special variable")); + emsg(_("E909: Cannot index a special variable")); } return FAIL; case VAR_UNKNOWN: @@ -4524,7 +4524,6 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) */ key = *arg + 1; for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len) { - ; } if (len == 0) { return FAIL; @@ -4573,7 +4572,7 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) // Check for the ']'. if (**arg != ']') { if (verbose) { - EMSG(_(e_missbrac)); + emsg(_(e_missbrac)); } tv_clear(&var1); if (range) { @@ -4681,7 +4680,7 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) rettv->v_type = VAR_NUMBER; rettv->vval.v_number = v; } else { - EMSGN(_(e_blobidx), n1); + semsg(_(e_blobidx), (int64_t)n1); } } break; @@ -4695,7 +4694,7 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) // list. A list index out of range is an error. if (!range) { if (verbose) { - EMSGN(_(e_listidx), n1); + semsg(_(e_listidx), (int64_t)n1); } return FAIL; } @@ -4730,7 +4729,7 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) case VAR_DICT: { if (range) { if (verbose) { - EMSG(_(e_dictrange)); + emsg(_(e_dictrange)); } if (len == -1) { tv_clear(&var1); @@ -4750,7 +4749,7 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose) (const char *)key, len); if (item == NULL && verbose) { - emsgf(_(e_dictkey), key); + semsg(_(e_dictkey), key); } if (len == -1) { tv_clear(&var1); @@ -4802,7 +4801,7 @@ int get_option_tv(const char **const arg, typval_T *const rettv, const bool eval char *option_end = (char *)find_option_end(arg, &opt_flags); if (option_end == NULL) { if (rettv != NULL) { - EMSG2(_("E112: Option name missing: %s"), *arg); + semsg(_("E112: Option name missing: %s"), *arg); } return FAIL; } @@ -4819,7 +4818,7 @@ int get_option_tv(const char **const arg, typval_T *const rettv, const bool eval if (opt_type == -3) { // invalid name if (rettv != NULL) { - EMSG2(_("E113: Unknown option: %s"), *arg); + semsg(_("E113: Unknown option: %s"), *arg); } ret = FAIL; } else if (rettv != NULL) { @@ -4872,7 +4871,7 @@ static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate) } if (*p != '"') { - EMSG2(_("E114: Missing quote: %s"), *arg); + semsg(_("E114: Missing quote: %s"), *arg); return FAIL; } @@ -5010,7 +5009,7 @@ static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate) } if (*p != '\'') { - EMSG2(_("E115: Missing quote: %s"), *arg); + semsg(_("E115: Missing quote: %s"), *arg); return FAIL; } @@ -5105,14 +5104,14 @@ static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate) break; } if (**arg != ',') { - emsgf(_("E696: Missing comma in List: %s"), *arg); + semsg(_("E696: Missing comma in List: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != ']') { - emsgf(_("E697: Missing end of List ']': %s"), *arg); + semsg(_("E697: Missing end of List ']': %s"), *arg); failret: if (evaluate) { tv_list_free(l); @@ -5129,7 +5128,8 @@ failret: } /// @param ic ignore case -bool func_equal(typval_T *tv1, typval_T *tv2, bool ic) { +bool func_equal(typval_T *tv1, typval_T *tv2, bool ic) +{ char_u *s1, *s2; dict_T *d1, *d2; int a1, a2; @@ -5632,7 +5632,6 @@ bool set_ref_in_item(typval_T *tv, int copyID, ht_stack_T **ht_stack, list_stack } - /// Mark all lists and dicts referenced in given mark /// /// @returns true if setting references failed somehow. @@ -5742,7 +5741,7 @@ static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate, bool literal goto failret; } if (**arg != ':') { - EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg); + semsg(_("E720: Missing colon in Dictionary: %s"), *arg); tv_clear(&tvkey); goto failret; } @@ -5765,7 +5764,7 @@ static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate, bool literal if (evaluate) { item = tv_dict_find(d, (const char *)key, -1); if (item != NULL) { - EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key); + semsg(_("E721: Duplicate key in Dictionary: \"%s\""), key); tv_clear(&tvkey); tv_clear(&tv); goto failret; @@ -5783,14 +5782,14 @@ static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate, bool literal break; } if (**arg != ',') { - EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg); + semsg(_("E722: Missing comma in Dictionary: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != '}') { - EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg); + semsg(_("E723: Missing end of Dictionary '}': %s"), *arg); failret: if (d != NULL) { tv_dict_free(d); @@ -6352,7 +6351,7 @@ int assert_match_common(typval_T *argvars, assert_type_T atype) const char *const text = tv_get_string_buf_chk(&argvars[1], buf2); if (pat == NULL || text == NULL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else if (pattern_match((char_u *)pat, (char_u *)text, false) != (atype == ASSERT_MATCH)) { garray_T ga; @@ -6420,7 +6419,7 @@ void filter_map(typval_T *argvars, typval_T *rettv, int map) return; } } else { - EMSG2(_(e_listdictblobarg), ermsg); + semsg(_(e_listdictblobarg), ermsg); return; } @@ -6483,7 +6482,7 @@ void filter_map(typval_T *argvars, typval_T *rettv, int map) break; } if (tv.v_type != VAR_NUMBER) { - EMSG(_(e_invalblob)); + emsg(_(e_invalblob)); return; } if (map) { @@ -6599,14 +6598,14 @@ void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref, FunPtr } if (s == NULL || *s == NUL || (use_string && ascii_isdigit(*s)) || (is_funcref && trans_name == NULL)) { - emsgf(_(e_invarg2), (use_string + semsg(_(e_invarg2), (use_string ? tv_get_string(&argvars[0]) : (const char *)s)); // Don't check an autoload name for existence here. } else if (trans_name != NULL && (is_funcref ? find_func(trans_name) == NULL : !translated_function_exists((const char *)trans_name))) { - emsgf(_("E700: Unknown function: %s"), s); + semsg(_("E700: Unknown function: %s"), s); } else { int dict_idx = 0; int arg_idx = 0; @@ -6642,7 +6641,7 @@ void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref, FunPtr } if (dict_idx > 0) { if (argvars[dict_idx].v_type != VAR_DICT) { - EMSG(_("E922: expected a dict")); + emsg(_("E922: expected a dict")); xfree(name); goto theend; } @@ -6652,7 +6651,7 @@ void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref, FunPtr } if (arg_idx > 0) { if (argvars[arg_idx].v_type != VAR_LIST) { - EMSG(_("E923: Second argument of function() must be " + emsg(_("E923: Second argument of function() must be " "a list or a dict")); xfree(name); goto theend; @@ -6810,7 +6809,7 @@ void get_qf_loc_list(int is_qf, win_T *wp, typval_T *what_arg, typval_T *rettv) qf_get_properties(wp, d, rettv->vval.v_dict); } } else { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); } } } @@ -7015,7 +7014,7 @@ void get_user_input(const typval_T *const argvars, typval_T *const rettv, const char def[1] = { 0 }; if (argvars[0].v_type == VAR_DICT) { if (argvars[1].v_type != VAR_UNKNOWN) { - EMSG(_("E5050: {opts} must be the only argument")); + emsg(_("E5050: {opts} must be the only argument")); return; } dict_T *const dict = argvars[0].vval.v_dict; @@ -7134,7 +7133,7 @@ void get_user_input(const typval_T *const argvars, typval_T *const rettv, const void dict_list(typval_T *const tv, typval_T *const rettv, const DictListType what) { if (tv->v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } if (tv->vval.v_dict == NULL) { @@ -7197,14 +7196,14 @@ char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable) } if (cmd_tv->v_type != VAR_LIST) { - EMSG2(_(e_invarg2), "expected String or List"); + semsg(_(e_invarg2), "expected String or List"); return NULL; } list_T *argl = cmd_tv->vval.v_list; int argc = tv_list_len(argl); if (!argc) { - EMSG(_(e_invarg)); // List must have at least one item. + emsg(_(e_invarg)); // List must have at least one item. return NULL; } @@ -7214,7 +7213,7 @@ char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable) if (arg0 && executable) { char buf[IOSIZE]; snprintf(buf, sizeof(buf), "'%s' is not executable", arg0); - EMSG3(_(e_invargNval), "cmd", buf); + semsg(_(e_invargNval), "cmd", buf); *executable = false; } return NULL; @@ -7294,7 +7293,7 @@ int matchadd_dict_arg(typval_T *tv, const char **conceal_char, win_T **win) dictitem_T *di; if (tv->v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return FAIL; } @@ -7305,7 +7304,7 @@ int matchadd_dict_arg(typval_T *tv, const char **conceal_char, win_T **win) 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)); + emsg(_(e_invalwindow)); return FAIL; } } @@ -7684,7 +7683,7 @@ bool callback_from_typval(Callback *const callback, typval_T *const arg) } if (r == FAIL) { - EMSG(_("E921: Invalid callback argument")); + emsg(_("E921: Invalid callback argument")); return false; } return true; @@ -7968,7 +7967,7 @@ bool write_list(FileDescriptor *const fp, const list_T *const list, const bool b } return true; write_list_error: - emsgf(_(e_write2), os_strerror(error)); + semsg(_(e_write2), os_strerror(error)); return false; } @@ -7996,7 +7995,7 @@ bool write_blob(FileDescriptor *const fp, const blob_T *const blob) } return true; write_blob_error: - EMSG2(_(e_write2), os_strerror(error)); + semsg(_(e_write2), os_strerror(error)); return false; } @@ -8063,7 +8062,7 @@ char *save_tv_as_string(typval_T *tv, ptrdiff_t *const len, bool endnl) *len += 1; } } else { - EMSGN(_(e_nobufnr), tv->vval.v_number); + semsg(_(e_nobufnr), tv->vval.v_number); *len = -1; return NULL; } @@ -8397,7 +8396,7 @@ int get_name_len(const char **const arg, char **alias, bool evaluate, bool verbo // Only give an error when there is something, otherwise it will be // reported at a higher level. if (len == 0 && verbose && **arg != NUL) { - EMSG2(_(e_invexpr2), *arg); + semsg(_(e_invexpr2), *arg); } return len; @@ -8864,7 +8863,7 @@ int get_var_tv(const char *name, int len, typval_T *rettv, dictitem_T **dip, int if (tv == NULL) { if (rettv != NULL && verbose) { - emsgf(_("E121: Undefined variable: %.*s"), len, name); + semsg(_("E121: Undefined variable: %.*s"), len, name); } ret = FAIL; } else if (rettv != NULL) { @@ -9441,7 +9440,7 @@ static void set_var_const(const char *name, const size_t name_len, typval_T *con const bool watched = tv_dict_is_watched(dict); if (ht == NULL || *varname == NUL) { - EMSG2(_(e_illvar), name); + semsg(_(e_illvar), name); return; } v = find_var_in_ht(ht, 0, varname, name_len - (size_t)(varname - name), true); @@ -9458,7 +9457,7 @@ static void set_var_const(const char *name, const size_t name_len, typval_T *con typval_T oldtv = TV_INITIAL_VALUE; if (v != NULL) { if (is_const) { - EMSG(_(e_cannot_mod)); + emsg(_(e_cannot_mod)); return; } @@ -9497,7 +9496,7 @@ static void set_var_const(const char *name, const size_t name_len, typval_T *con } return; } else if (v->di_tv.v_type != tv->v_type) { - EMSG2(_("E963: setting %s to value with wrong type"), name); + semsg(_("E963: setting %s to value with wrong type"), name); return; } } @@ -9509,7 +9508,7 @@ static void set_var_const(const char *name, const size_t name_len, typval_T *con } else { // Add a new variable. // Can't add "v:" or "a:" variable. if (ht == &vimvarht || ht == get_funccal_args_ht()) { - emsgf(_(e_illvar), name); + semsg(_(e_illvar), name); return; } @@ -9597,7 +9596,7 @@ bool var_check_ro(const int flags, const char *name, size_t name_len) name_len = strlen(name); } - emsgf(_(error_message), (int)name_len, name); + semsg(_(error_message), (int)name_len, name); return true; } @@ -9630,7 +9629,7 @@ bool var_check_fixed(const int flags, const char *name, size_t name_len) } else if (name_len == TV_CSTRING) { name_len = strlen(name); } - EMSG3(_("E795: Cannot delete variable %.*s"), (int)name_len, name); + semsg(_("E795: Cannot delete variable %.*s"), (int)name_len, name); return true; } return false; @@ -9652,14 +9651,14 @@ bool var_check_func_name(const char *const name, const bool new_var) if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':') && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':') ? name[2] : name[0])) { - EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name); + semsg(_("E704: Funcref variable name must start with a capital: %s"), name); return false; } // Don't allow hiding a function. When "v" is not NULL we might be // assigning another function to the same var, the type is checked // below. if (new_var && function_exists(name, false)) { - EMSG2(_("E705: Variable name conflicts with existing function: %s"), + semsg(_("E705: Variable name conflicts with existing function: %s"), name); return false; } @@ -9681,7 +9680,7 @@ bool valid_varname(const char *varname) if (!eval_isnamec1((int)(uint8_t)(*p)) && (p == varname || !ascii_isdigit(*p)) && *p != AUTOLOAD_CHAR) { - emsgf(_(e_illvar), varname); + semsg(_(e_illvar), varname); return false; } } @@ -9712,7 +9711,7 @@ int var_item_copy(const vimconv_T *const conv, typval_T *const from, typval_T *c int ret = OK; if (recurse >= DICT_MAXNEST) { - EMSG(_("E698: variable nested too deep for making a copy")); + emsg(_("E698: variable nested too deep for making a copy")); return FAIL; } ++recurse; @@ -9814,7 +9813,7 @@ void ex_echo(exarg_T *eap) // exception. if (!aborting() && did_emsg == did_emsg_before && called_emsg == called_emsg_before) { - EMSG2(_(e_invexpr2), p); + semsg(_(e_invexpr2), p); } need_clr_eos = false; break; @@ -9928,13 +9927,13 @@ void ex_execute(exarg_T *eap) if (eap->cmdidx == CMD_echomsg) { msg_ext_set_kind("echomsg"); - MSG_ATTR(ga.ga_data, echo_attr); + msg_attr(ga.ga_data, echo_attr); ui_flush(); } else if (eap->cmdidx == CMD_echoerr) { // We don't want to abort following commands, restore did_emsg. save_did_emsg = did_emsg; msg_ext_set_kind("echoerr"); - EMSG((char_u *)ga.ga_data); + emsg(ga.ga_data); if (!force_abort) { did_emsg = save_did_emsg; } @@ -10434,10 +10433,10 @@ void option_last_set_msg(LastSet last_set) bool should_free; char_u *p = get_scriptname(last_set, &should_free); verbose_enter(); - MSG_PUTS(_("\n\tLast set from ")); - MSG_PUTS(p); + msg_puts(_("\n\tLast set from ")); + msg_puts((char *)p); if (last_set.script_ctx.sc_lnum > 0) { - MSG_PUTS(_(line_msg)); + msg_puts(_(line_msg)); msg_outnum((long)last_set.script_ctx.sc_lnum); } if (should_free) { @@ -10837,7 +10836,7 @@ bool common_job_callbacks(dict_T *vopts, CallbackReader *on_stdout, CallbackRead Callback *on_exit) { if (tv_dict_get_callback(vopts, S_LEN("on_stdout"), &on_stdout->cb) - &&tv_dict_get_callback(vopts, S_LEN("on_stderr"), &on_stderr->cb) + && tv_dict_get_callback(vopts, S_LEN("on_stderr"), &on_stderr->cb) && tv_dict_get_callback(vopts, S_LEN("on_exit"), on_exit)) { on_stdout->buffered = tv_dict_get_number(vopts, "stdout_buffered"); on_stderr->buffered = tv_dict_get_number(vopts, "stderr_buffered"); @@ -10865,9 +10864,9 @@ Channel *find_job(uint64_t id, bool show_error) || process_is_stopped(&data->stream.proc)) { if (show_error) { if (data && data->streamtype != kChannelStreamProc) { - EMSG(_(e_invchanjob)); + emsg(_(e_invchanjob)); } else { - EMSG(_(e_invchan)); + emsg(_(e_invchan)); } } return NULL; @@ -10883,7 +10882,7 @@ void script_host_eval(char *name, typval_T *argvars, typval_T *rettv) } if (argvars[0].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -10897,7 +10896,7 @@ void script_host_eval(char *name, typval_T *argvars, typval_T *rettv) typval_T eval_call_provider(char *provider, char *method, list_T *arguments, bool discard) { if (!eval_has_provider(provider)) { - emsgf("E319: No \"%s\" provider found. Run \":checkhealth provider\"", + semsg("E319: No \"%s\" provider found. Run \":checkhealth provider\"", provider); return (typval_T){ .v_type = VAR_NUMBER, @@ -10989,7 +10988,7 @@ bool eval_has_provider(const char *feat) // Show a hint if Call() is defined but g:loaded_xx_provider is missing. snprintf(buf, sizeof(buf), "provider#%s#Call", name); if (!!find_func((char_u *)buf) && p_lpl) { - emsgf("provider: %s: missing required variable g:loaded_%s_provider", + semsg("provider: %s: missing required variable g:loaded_%s_provider", name, name); } return false; @@ -11004,7 +11003,7 @@ bool eval_has_provider(const char *feat) // Call() must be defined if provider claims to be working. snprintf(buf, sizeof(buf), "provider#%s#Call", name); if (!find_func((char_u *)buf)) { - emsgf("provider: %s: g:loaded_%s_provider=2 but %s is not defined", + semsg("provider: %s: g:loaded_%s_provider=2 but %s is not defined", name, name, buf); ok = false; } @@ -11034,13 +11033,13 @@ void ex_checkhealth(exarg_T *eap) if (!found) { const char *vimruntime_env = os_getenv("VIMRUNTIME"); if (vimruntime_env == NULL) { - EMSG(_("E5009: $VIMRUNTIME is empty or unset")); + emsg(_("E5009: $VIMRUNTIME is empty or unset")); } else { bool rtp_ok = NULL != strstr((char *)p_rtp, vimruntime_env); if (rtp_ok) { - EMSG2(_("E5009: Invalid $VIMRUNTIME: %s"), vimruntime_env); + semsg(_("E5009: Invalid $VIMRUNTIME: %s"), vimruntime_env); } else { - EMSG(_("E5009: Invalid 'runtimepath'")); + emsg(_("E5009: Invalid 'runtimepath'")); } } return; @@ -11129,9 +11128,9 @@ int typval_compare(typval_T *typ1, typval_T *typ2, exprtype_T type, bool ic) } else if (typ1->v_type != typ2->v_type || (type != EXPR_EQUAL && type != EXPR_NEQUAL)) { if (typ1->v_type != typ2->v_type) { - EMSG(_("E977: Can only compare Blob with Blob")); + emsg(_("E977: Can only compare Blob with Blob")); } else { - EMSG(_(e_invalblob)); + emsg(_(e_invalblob)); } tv_clear(typ1); return FAIL; @@ -11152,9 +11151,9 @@ int typval_compare(typval_T *typ1, typval_T *typ2, exprtype_T type, bool ic) } else if (typ1->v_type != typ2->v_type || (type != EXPR_EQUAL && type != EXPR_NEQUAL)) { if (typ1->v_type != typ2->v_type) { - EMSG(_("E691: Can only compare List with List")); + emsg(_("E691: Can only compare List with List")); } else { - EMSG(_("E692: Invalid operation for List")); + emsg(_("E692: Invalid operation for List")); } tv_clear(typ1); return FAIL; @@ -11175,9 +11174,9 @@ int typval_compare(typval_T *typ1, typval_T *typ2, exprtype_T type, bool ic) } else if (typ1->v_type != typ2->v_type || (type != EXPR_EQUAL && type != EXPR_NEQUAL)) { if (typ1->v_type != typ2->v_type) { - EMSG(_("E735: Can only compare Dictionary with Dictionary")); + emsg(_("E735: Can only compare Dictionary with Dictionary")); } else { - EMSG(_("E736: Invalid operation for Dictionary")); + emsg(_("E736: Invalid operation for Dictionary")); } tv_clear(typ1); return FAIL; @@ -11191,7 +11190,7 @@ int typval_compare(typval_T *typ1, typval_T *typ2, exprtype_T type, bool ic) } else if (tv_is_func(*typ1) || tv_is_func(*typ2)) { if (type != EXPR_EQUAL && type != EXPR_NEQUAL && type != EXPR_IS && type != EXPR_ISNOT) { - EMSG(_("E694: Invalid operation for Funcrefs")); + emsg(_("E694: Invalid operation for Funcrefs")); tv_clear(typ1); return FAIL; } diff --git a/src/nvim/eval.h b/src/nvim/eval.h index 3d656656de..d34348a274 100644 --- a/src/nvim/eval.h +++ b/src/nvim/eval.h @@ -70,7 +70,7 @@ typedef struct lval_S { typedef enum { VAR_FLAVOUR_DEFAULT = 1, // doesn't start with uppercase VAR_FLAVOUR_SESSION = 2, // starts with uppercase, some lower - VAR_FLAVOUR_SHADA = 4 // all uppercase + VAR_FLAVOUR_SHADA = 4, // all uppercase } var_flavour_T; /// Defines for Vim variables diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c index c8734c9b9c..5008945f09 100644 --- a/src/nvim/eval/decode.c +++ b/src/nvim/eval/decode.c @@ -118,7 +118,7 @@ static inline int json_decoder_pop(ValuesStackItem obj, ValuesStack *const stack if (last_container.container.v_type == VAR_LIST) { if (tv_list_len(last_container.container.vval.v_list) != 0 && !obj.didcomma) { - EMSG2(_("E474: Expected comma before list item: %s"), val_location); + semsg(_("E474: Expected comma before list item: %s"), val_location); tv_clear(&obj.val); return FAIL; } @@ -126,7 +126,7 @@ static inline int json_decoder_pop(ValuesStackItem obj, ValuesStack *const stack tv_list_append_owned_tv(last_container.container.vval.v_list, obj.val); } else if (last_container.stack_index == kv_size(*stack) - 2) { if (!obj.didcolon) { - EMSG2(_("E474: Expected colon before dictionary value: %s"), + semsg(_("E474: Expected colon before dictionary value: %s"), val_location); tv_clear(&obj.val); return FAIL; @@ -153,13 +153,13 @@ static inline int json_decoder_pop(ValuesStackItem obj, ValuesStack *const stack } else { // Object with key only if (!obj.is_special_string && obj.val.v_type != VAR_STRING) { - EMSG2(_("E474: Expected string key: %s"), *pp); + semsg(_("E474: Expected string key: %s"), *pp); tv_clear(&obj.val); return FAIL; } else if (!obj.didcomma && (last_container.special_val == NULL && (DICT_LEN(last_container.container.vval.v_dict) != 0))) { - EMSG2(_("E474: Expected comma before dictionary key: %s"), val_location); + semsg(_("E474: Expected comma before dictionary key: %s"), val_location); tv_clear(&obj.val); return FAIL; } @@ -330,21 +330,21 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, if (*p == '\\') { p++; if (p == e) { - emsgf(_("E474: Unfinished escape sequence: %.*s"), + semsg(_("E474: Unfinished escape sequence: %.*s"), (int)buf_len, buf); goto parse_json_string_fail; } switch (*p) { case 'u': if (p + 4 >= e) { - emsgf(_("E474: Unfinished unicode escape sequence: %.*s"), + semsg(_("E474: Unfinished unicode escape sequence: %.*s"), (int)buf_len, buf); goto parse_json_string_fail; } else if (!ascii_isxdigit(p[1]) || !ascii_isxdigit(p[2]) || !ascii_isxdigit(p[3]) || !ascii_isxdigit(p[4])) { - emsgf(_("E474: Expected four hex digits after \\u: %.*s"), + semsg(_("E474: Expected four hex digits after \\u: %.*s"), LENP(p - 1, e)); goto parse_json_string_fail; } @@ -365,14 +365,14 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, p++; break; default: - emsgf(_("E474: Unknown escape sequence: %.*s"), LENP(p - 1, e)); + semsg(_("E474: Unknown escape sequence: %.*s"), LENP(p - 1, e)); goto parse_json_string_fail; } } else { uint8_t p_byte = (uint8_t)*p; // unescaped = %x20-21 / %x23-5B / %x5D-10FFFF if (p_byte < 0x20) { - emsgf(_("E474: ASCII control characters cannot be present " + semsg(_("E474: ASCII control characters cannot be present " "inside string: %.*s"), LENP(p, e)); goto parse_json_string_fail; } @@ -385,10 +385,10 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, // The only exception is U+00C3 which is represented as 0xC3 0x83. if (ch >= 0x80 && p_byte == ch && !(ch == 0xC3 && p + 1 < e && (uint8_t)p[1] == 0x83)) { - emsgf(_("E474: Only UTF-8 strings allowed: %.*s"), LENP(p, e)); + semsg(_("E474: Only UTF-8 strings allowed: %.*s"), LENP(p, e)); goto parse_json_string_fail; } else if (ch > 0x10FFFF) { - emsgf(_("E474: Only UTF-8 code points up to U+10FFFF " + semsg(_("E474: Only UTF-8 code points up to U+10FFFF " "are allowed to appear unescaped: %.*s"), LENP(p, e)); goto parse_json_string_fail; } @@ -399,7 +399,7 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, } } if (p == e || *p != '"') { - emsgf(_("E474: Expected string end: %.*s"), (int)buf_len, buf); + semsg(_("E474: Expected string end: %.*s"), (int)buf_len, buf); goto parse_json_string_fail; } if (len == 0) { @@ -546,7 +546,7 @@ static inline int parse_json_number(const char *const buf, const size_t buf_len, p++; } if (p != ints + 1 && *ints == '0') { - emsgf(_("E474: Leading zeroes are not allowed: %.*s"), LENP(s, e)); + semsg(_("E474: Leading zeroes are not allowed: %.*s"), LENP(s, e)); goto parse_json_number_fail; } if (p >= e || p == ints) { @@ -575,13 +575,13 @@ static inline int parse_json_number(const char *const buf, const size_t buf_len, } parse_json_number_check: if (p == ints) { - emsgf(_("E474: Missing number after minus sign: %.*s"), LENP(s, e)); + semsg(_("E474: Missing number after minus sign: %.*s"), LENP(s, e)); goto parse_json_number_fail; } else if (p == fracs || (fracs != NULL && exps_s == fracs + 1)) { - emsgf(_("E474: Missing number after decimal dot: %.*s"), LENP(s, e)); + semsg(_("E474: Missing number after decimal dot: %.*s"), LENP(s, e)); goto parse_json_number_fail; } else if (p == exps) { - emsgf(_("E474: Missing exponent: %.*s"), LENP(s, e)); + semsg(_("E474: Missing exponent: %.*s"), LENP(s, e)); goto parse_json_number_fail; } typval_T tv = { @@ -593,7 +593,7 @@ parse_json_number_check: // Convert floating-point number const size_t num_len = string2float(s, &tv.vval.v_float); if (exp_num_len != num_len) { - emsgf(_("E685: internal error: while converting number \"%.*s\" " + semsg(_("E685: internal error: while converting number \"%.*s\" " "to float string2float consumed %zu bytes in place of %zu"), (int)exp_num_len, s, num_len, exp_num_len); } @@ -604,7 +604,7 @@ parse_json_number_check: int num_len; vim_str2nr((char_u *)s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true); if ((int)exp_num_len != num_len) { - emsgf(_("E685: internal error: while converting number \"%.*s\" " + semsg(_("E685: internal error: while converting number \"%.*s\" " "to integer vim_str2nr consumed %i bytes in place of %zu"), (int)exp_num_len, s, num_len, exp_num_len); } @@ -656,7 +656,7 @@ int json_decode_string(const char *const buf, const size_t buf_len, typval_T *co p++; } if (p == e) { - EMSG(_("E474: Attempt to decode a blank string")); + emsg(_("E474: Attempt to decode a blank string")); return FAIL; } int ret = OK; @@ -673,26 +673,26 @@ json_decode_string_cycle_start: case '}': case ']': { if (kv_size(container_stack) == 0) { - emsgf(_("E474: No container to close: %.*s"), LENP(p, e)); + semsg(_("E474: No container to close: %.*s"), LENP(p, e)); goto json_decode_string_fail; } ContainerStackItem last_container = kv_last(container_stack); if (*p == '}' && last_container.container.v_type != VAR_DICT) { - emsgf(_("E474: Closing list with curly bracket: %.*s"), LENP(p, e)); + semsg(_("E474: Closing list with curly bracket: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (*p == ']' && last_container.container.v_type != VAR_LIST) { - emsgf(_("E474: Closing dictionary with square bracket: %.*s"), + semsg(_("E474: Closing dictionary with square bracket: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (didcomma) { - emsgf(_("E474: Trailing comma: %.*s"), LENP(p, e)); + semsg(_("E474: Trailing comma: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (didcolon) { - emsgf(_("E474: Expected value after colon: %.*s"), LENP(p, e)); + semsg(_("E474: Expected value after colon: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (last_container.stack_index != kv_size(stack) - 1) { assert(last_container.stack_index < kv_size(stack) - 1); - emsgf(_("E474: Expected value: %.*s"), LENP(p, e)); + semsg(_("E474: Expected value: %.*s"), LENP(p, e)); goto json_decode_string_fail; } if (kv_size(stack) == 1) { @@ -711,19 +711,19 @@ json_decode_string_cycle_start: } case ',': { if (kv_size(container_stack) == 0) { - emsgf(_("E474: Comma not inside container: %.*s"), LENP(p, e)); + semsg(_("E474: Comma not inside container: %.*s"), LENP(p, e)); goto json_decode_string_fail; } ContainerStackItem last_container = kv_last(container_stack); if (didcomma) { - emsgf(_("E474: Duplicate comma: %.*s"), LENP(p, e)); + semsg(_("E474: Duplicate comma: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (didcolon) { - emsgf(_("E474: Comma after colon: %.*s"), LENP(p, e)); + semsg(_("E474: Comma after colon: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (last_container.container.v_type == VAR_DICT && last_container.stack_index != kv_size(stack) - 1) { - emsgf(_("E474: Using comma in place of colon: %.*s"), LENP(p, e)); + semsg(_("E474: Using comma in place of colon: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (last_container.special_val == NULL ? (last_container.container.v_type == VAR_DICT @@ -731,7 +731,7 @@ json_decode_string_cycle_start: : (tv_list_len(last_container.container.vval.v_list) == 0)) : (tv_list_len(last_container.special_val) == 0)) { - emsgf(_("E474: Leading comma: %.*s"), LENP(p, e)); + semsg(_("E474: Leading comma: %.*s"), LENP(p, e)); goto json_decode_string_fail; } didcomma = true; @@ -739,21 +739,21 @@ json_decode_string_cycle_start: } case ':': { if (kv_size(container_stack) == 0) { - emsgf(_("E474: Colon not inside container: %.*s"), LENP(p, e)); + semsg(_("E474: Colon not inside container: %.*s"), LENP(p, e)); goto json_decode_string_fail; } ContainerStackItem last_container = kv_last(container_stack); if (last_container.container.v_type != VAR_DICT) { - emsgf(_("E474: Using colon not in dictionary: %.*s"), LENP(p, e)); + semsg(_("E474: Using colon not in dictionary: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (last_container.stack_index != kv_size(stack) - 2) { - emsgf(_("E474: Unexpected colon: %.*s"), LENP(p, e)); + semsg(_("E474: Unexpected colon: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (didcomma) { - emsgf(_("E474: Colon after comma: %.*s"), LENP(p, e)); + semsg(_("E474: Colon after comma: %.*s"), LENP(p, e)); goto json_decode_string_fail; } else if (didcolon) { - emsgf(_("E474: Duplicate colon: %.*s"), LENP(p, e)); + semsg(_("E474: Duplicate colon: %.*s"), LENP(p, e)); goto json_decode_string_fail; } didcolon = true; @@ -766,7 +766,7 @@ json_decode_string_cycle_start: continue; case 'n': if ((p + 3) >= e || strncmp(p + 1, "ull", 3) != 0) { - emsgf(_("E474: Expected null: %.*s"), LENP(p, e)); + semsg(_("E474: Expected null: %.*s"), LENP(p, e)); goto json_decode_string_fail; } p += 3; @@ -778,7 +778,7 @@ json_decode_string_cycle_start: break; case 't': if ((p + 3) >= e || strncmp(p + 1, "rue", 3) != 0) { - emsgf(_("E474: Expected true: %.*s"), LENP(p, e)); + semsg(_("E474: Expected true: %.*s"), LENP(p, e)); goto json_decode_string_fail; } p += 3; @@ -790,7 +790,7 @@ json_decode_string_cycle_start: break; case 'f': if ((p + 4) >= e || strncmp(p + 1, "alse", 4) != 0) { - emsgf(_("E474: Expected false: %.*s"), LENP(p, e)); + semsg(_("E474: Expected false: %.*s"), LENP(p, e)); goto json_decode_string_fail; } p += 4; @@ -874,7 +874,7 @@ json_decode_string_cycle_start: break; } default: - emsgf(_("E474: Unidentified byte: %.*s"), LENP(p, e)); + semsg(_("E474: Unidentified byte: %.*s"), LENP(p, e)); goto json_decode_string_fail; } didcomma = false; @@ -893,7 +893,7 @@ json_decode_string_after_cycle: case CAR: break; default: - emsgf(_("E474: Trailing characters: %.*s"), LENP(p, e)); + semsg(_("E474: Trailing characters: %.*s"), LENP(p, e)); goto json_decode_string_fail; } } @@ -901,7 +901,7 @@ json_decode_string_after_cycle: *rettv = kv_pop(stack).val; goto json_decode_string_ret; } - emsgf(_("E474: Unexpected end of input: %.*s"), (int)buf_len, buf); + semsg(_("E474: Unexpected end of input: %.*s"), (int)buf_len, buf); json_decode_string_fail: ret = FAIL; while (kv_size(stack)) { diff --git a/src/nvim/eval/encode.c b/src/nvim/eval/encode.c index 2d4d9fdea9..b457353838 100644 --- a/src/nvim/eval/encode.c +++ b/src/nvim/eval/encode.c @@ -197,7 +197,7 @@ static int conv_error(const char *const msg, const MPConvStack *const mpstack, } } } - emsgf(msg, _(objname), (kv_size(*mpstack) == 0 + semsg(msg, _(objname), (kv_size(*mpstack) == 0 ? _("itself") : (char *)msg_ga.ga_data)); ga_clear(&msg_ga); @@ -381,7 +381,7 @@ int encode_read_from_list(ListReaderState *const state, char *const buf, const s } else { \ ga_concat(gap, "function("); \ TYPVAL_ENCODE_CONV_STRING(tv, fun_, strlen(fun_)); \ - }\ + } \ } while (0) #define TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS(tv, len) \ @@ -448,7 +448,7 @@ int encode_read_from_list(ListReaderState *const state, char *const buf, const s /* Only give this message once for a recursive call to avoid */ \ /* flooding the user with errors. */ \ did_echo_string_emsg = true; \ - EMSG(_("E724: unable to correctly dump variable " \ + emsg(_("E724: unable to correctly dump variable " \ "with self-referencing container")); \ } \ char ebuf[NUMBUFLEN + 7]; \ @@ -528,7 +528,7 @@ int encode_read_from_list(ListReaderState *const state, char *const buf, const s /* Only give this message once for a recursive call to avoid */ \ /* flooding the user with errors. */ \ did_echo_string_emsg = true; \ - EMSG(_("E724: unable to correctly dump variable " \ + emsg(_("E724: unable to correctly dump variable " \ "with self-referencing container")); \ } \ } while (0) @@ -558,11 +558,11 @@ int encode_read_from_list(ListReaderState *const state, char *const buf, const s const float_T flt_ = (flt); \ switch (xfpclassify(flt_)) { \ case FP_NAN: { \ - EMSG(_("E474: Unable to represent NaN value in JSON")); \ + emsg(_("E474: Unable to represent NaN value in JSON")); \ return FAIL; \ } \ case FP_INFINITE: { \ - EMSG(_("E474: Unable to represent infinity in JSON")); \ + emsg(_("E474: Unable to represent infinity in JSON")); \ return FAIL; \ } \ default: { \ @@ -630,14 +630,14 @@ static inline int convert_to_json_string(garray_T *const gap, const char *const break; default: if (ch > 0x7F && shift == 1) { - emsgf(_("E474: String \"%.*s\" contains byte that does not start " + semsg(_("E474: String \"%.*s\" contains byte that does not start " "any UTF-8 character"), (int)(utf_len - (i - shift)), utf_buf + i - shift); xfree(tofree); return FAIL; } else if ((SURROGATE_HI_START <= ch && ch <= SURROGATE_HI_END) || (SURROGATE_LO_START <= ch && ch <= SURROGATE_LO_END)) { - emsgf(_("E474: UTF-8 string contains code point which belongs " + semsg(_("E474: UTF-8 string contains code point which belongs " "to a surrogate pair: %.*s"), (int)(utf_len - (i - shift)), utf_buf + i - shift); xfree(tofree); @@ -719,7 +719,7 @@ static inline int convert_to_json_string(garray_T *const gap, const char *const #define TYPVAL_ENCODE_CONV_EXT_STRING(tv, buf, len, type) \ do { \ xfree(buf); \ - EMSG(_("E474: Unable to convert EXT string to JSON")); \ + emsg(_("E474: Unable to convert EXT string to JSON")); \ return FAIL; \ } while (0) @@ -792,7 +792,7 @@ bool encode_check_json_key(const typval_T *const tv) #define TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK(label, key) \ do { \ if (!encode_check_json_key(&key)) { \ - EMSG(_("E474: Invalid key in special dictionary")); \ + emsg(_("E474: Invalid key in special dictionary")); \ goto label; \ } \ } while (0) diff --git a/src/nvim/eval/executor.c b/src/nvim/eval/executor.c index 8eceda84cf..ed4f36f4c7 100644 --- a/src/nvim/eval/executor.c +++ b/src/nvim/eval/executor.c @@ -144,6 +144,6 @@ int eexe_mod_op(typval_T *const tv1, const typval_T *const tv2, const char *cons } } - EMSG2(_(e_letwrong), op); + semsg(_(e_letwrong), op); return FAIL; } diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 1c78e25639..44af53b7c0 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -4,6 +4,7 @@ #include <float.h> #include <math.h> +#include "nvim/api/private/converter.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/ascii.h" @@ -277,12 +278,12 @@ static void api_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr) Object result = fn(VIML_INTERNAL_CALL, args, &err); if (ERROR_SET(&err)) { - emsgf_multiline((const char *)e_api_error, err.msg); + semsg_multiline((const char *)e_api_error, err.msg); goto end; } if (!object_to_vim(result, rettv, &err)) { - EMSG2(_("Error converting the call result: %s"), err.msg); + semsg(_("Error converting the call result: %s"), err.msg); } end: @@ -339,7 +340,7 @@ static void f_add(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } } else { - EMSG(_(e_listblobreq)); + emsg(_(e_listblobreq)); } } @@ -737,7 +738,8 @@ static void buf_win_common(typval_T *argvars, typval_T *rettv, bool get_nr) } /// "bufwinid(nr)" function -static void f_bufwinid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { +static void f_bufwinid(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ buf_win_common(argvars, rettv, false); } @@ -812,7 +814,7 @@ buf_T *get_buf_arg(typval_T *arg) buf = tv_get_buf(arg, false); emsg_off--; if (buf == NULL) { - EMSG2(_("E158: Invalid buffer name: %s"), tv_get_string(arg)); + semsg(_("E158: Invalid buffer name: %s"), tv_get_string(arg)); } return buf; } @@ -874,7 +876,7 @@ static void f_byteidxcomp(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[1].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } if (argvars[1].vval.v_list == NULL) { @@ -903,7 +905,7 @@ static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } selfdict = argvars[2].vval.v_dict; @@ -935,7 +937,7 @@ static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_NUMBER || (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_UNKNOWN)) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -951,14 +953,14 @@ static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr) } else if (!strcmp(stream, "rpc")) { part = kChannelPartRpc; } else { - EMSG2(_("Invalid channel stream \"%s\""), stream); + semsg(_("Invalid channel stream \"%s\""), stream); return; } } const char *error; rettv->vval.v_number = channel_close(argvars[0].vval.v_number, part, &error); if (!rettv->vval.v_number) { - EMSG(error); + emsg(error); } } @@ -974,7 +976,7 @@ static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type == VAR_UNKNOWN) { // First argument is the channel id and second is the data to write - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -999,7 +1001,7 @@ static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char *error = NULL; rettv->vval.v_number = channel_send(id, input, input_len, true, &error); if (error) { - EMSG(error); + emsg(error); } } @@ -1026,7 +1028,7 @@ static void f_charidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) || argvars[1].v_type != VAR_NUMBER || (argvars[2].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_NUMBER)) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1040,7 +1042,7 @@ static void f_charidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) countcc = (int)tv_get_number(&argvars[2]); } if (countcc < 0 || countcc > 1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1128,7 +1130,7 @@ static win_T *get_optional_window(typval_T *argvars, int idx) if (argvars[idx].v_type != VAR_UNKNOWN) { win = find_win_by_nr_or_id(&argvars[idx]); if (win == NULL) { - EMSG(_(e_invalwindow)); + emsg(_(e_invalwindow)); return NULL; } } @@ -1194,7 +1196,7 @@ static void f_col(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if ((State & INSERT) == 0) { - EMSG(_("E785: complete() can only be used in Insert mode")); + emsg(_("E785: complete() can only be used in Insert mode")); return; } @@ -1205,7 +1207,7 @@ static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[1].v_type != VAR_LIST) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1247,7 +1249,7 @@ static void f_complete_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_UNKNOWN) { if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } what_list = argvars[0].vval.v_list; @@ -1370,7 +1372,7 @@ static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (!error) { li = tv_list_find(l, idx); if (li == NULL) { - EMSGN(_(e_listidx), idx); + semsg(_(e_listidx), (int64_t)idx); } } } @@ -1393,7 +1395,7 @@ static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr) if ((d = argvars[0].vval.v_dict) != NULL) { if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[3].v_type != VAR_UNKNOWN) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } } @@ -1408,7 +1410,7 @@ static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } } else { - EMSG2(_(e_listdictarg), "count()"); + semsg(_(e_listdictarg), "count()"); } rettv->vval.v_number = n; } @@ -1445,13 +1447,13 @@ static void f_ctxget(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type == VAR_NUMBER) { index = argvars[0].vval.v_number; } else if (argvars[0].v_type != VAR_UNKNOWN) { - EMSG2(_(e_invarg2), "expected nothing or a Number as an argument"); + semsg(_(e_invarg2), "expected nothing or a Number as an argument"); return; } Context *ctx = ctx_get(index); if (ctx == NULL) { - EMSG3(_(e_invargNval), "index", "out of bounds"); + semsg(_(e_invargNval), "index", "out of bounds"); return; } @@ -1466,7 +1468,7 @@ static void f_ctxget(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_ctxpop(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (!ctx_restore(NULL, kCtxAll)) { - EMSG(_("Context stack is empty")); + emsg(_("Context stack is empty")); } } @@ -1495,7 +1497,7 @@ static void f_ctxpush(typval_T *argvars, typval_T *rettv, FunPtr fptr) } }); } else if (argvars[0].v_type != VAR_UNKNOWN) { - EMSG2(_(e_invarg2), "expected nothing or a List as an argument"); + semsg(_(e_invarg2), "expected nothing or a List as an argument"); return; } ctx_save(NULL, types); @@ -1505,7 +1507,7 @@ static void f_ctxpush(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_ctxset(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_DICT) { - EMSG2(_(e_invarg2), "expected dictionary as first argument"); + semsg(_(e_invarg2), "expected dictionary as first argument"); return; } @@ -1513,13 +1515,13 @@ static void f_ctxset(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type == VAR_NUMBER) { index = argvars[1].vval.v_number; } else if (argvars[1].v_type != VAR_UNKNOWN) { - EMSG2(_(e_invarg2), "expected nothing or a Number as second argument"); + semsg(_(e_invarg2), "expected nothing or a Number as second argument"); return; } Context *ctx = ctx_get(index); if (ctx == NULL) { - EMSG3(_(e_invargNval), "index", "out of bounds"); + semsg(_(e_invargNval), "index", "out of bounds"); return; } @@ -1566,7 +1568,7 @@ static void f_cursor(typval_T *argvars, typval_T *rettv, FunPtr fptr) colnr_T curswant = -1; if (list2fpos(argvars, &pos, NULL, &curswant) == FAIL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1613,7 +1615,7 @@ static void f_debugbreak(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = FAIL; pid = (int)tv_get_number(&argvars[0]); if (pid == 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { #ifdef WIN32 HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid); @@ -1638,7 +1640,7 @@ static void f_deepcopy(typval_T *argvars, typval_T *rettv, FunPtr fptr) noref = tv_get_number_chk(&argvars[1], NULL); } if (noref < 0 || noref > 1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { var_item_copy(NULL, &argvars[0], rettv, true, (noref == 0 ? get_copyID() @@ -1656,7 +1658,7 @@ static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char *const name = tv_get_string(&argvars[0]); if (*name == NUL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1678,7 +1680,7 @@ static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr) // delete a directory recursively rettv->vval.v_number = delete_recursive(name); } else { - emsgf(_(e_invexpr2), flags); + semsg(_(e_invexpr2), flags); } } @@ -1690,17 +1692,17 @@ static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_DICT) { - emsgf(_(e_invarg2), "dict"); + semsg(_(e_invarg2), "dict"); return; } else if (argvars[0].vval.v_dict == NULL) { const char *const arg_errmsg = _("dictwatcheradd() argument"); const size_t arg_errmsg_len = strlen(arg_errmsg); - emsgf(_(e_readonlyvar), (int)arg_errmsg_len, arg_errmsg); + semsg(_(e_readonlyvar), (int)arg_errmsg_len, arg_errmsg); return; } if (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_NUMBER) { - emsgf(_(e_invarg2), "key"); + semsg(_(e_invarg2), "key"); return; } @@ -1712,7 +1714,7 @@ static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr) Callback callback; if (!callback_from_typval(&callback, &argvars[2])) { - emsgf(_(e_invarg2), "funcref"); + semsg(_(e_invarg2), "funcref"); return; } @@ -1728,12 +1730,12 @@ static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_DICT) { - emsgf(_(e_invarg2), "dict"); + semsg(_(e_invarg2), "dict"); return; } if (argvars[2].v_type != VAR_FUNC && argvars[2].v_type != VAR_STRING) { - emsgf(_(e_invarg2), "funcref"); + semsg(_(e_invarg2), "funcref"); return; } @@ -1749,7 +1751,7 @@ static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (!tv_dict_watcher_remove(argvars[0].vval.v_dict, key_pattern, strlen(key_pattern), callback)) { - EMSG("Couldn't find a watcher matching key and callback"); + emsg("Couldn't find a watcher matching key and callback"); } callback_free(&callback); @@ -1811,7 +1813,7 @@ static void f_deletebufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (wp->w_buffer == buf) { if (wp->w_cursor.lnum > last) { wp->w_cursor.lnum -= count; - } else if (wp->w_cursor.lnum> first) { + } else if (wp->w_cursor.lnum > first) { wp->w_cursor.lnum = first; } if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) { @@ -2037,13 +2039,13 @@ static void f_eval(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char *const expr_start = s; if (s == NULL || eval1((char_u **)&s, rettv, true) == FAIL) { if (expr_start != NULL && !aborting()) { - EMSG2(_(e_invexpr2), expr_start); + semsg(_(e_invexpr2), expr_start); } need_clr_eos = false; rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } else if (*s != NUL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } } @@ -2201,7 +2203,7 @@ static void f_win_execute(typval_T *argvars, typval_T *rettv, FunPtr fptr) /// "exepath()" function static void f_exepath(typval_T *argvars, typval_T *rettv, FunPtr fptr) { - if (tv_check_for_string(&argvars[0]) == FAIL) { + if (tv_check_for_nonempty_string(&argvars[0]) == FAIL) { return; } @@ -2261,7 +2263,7 @@ static void f_exists(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_expand(typval_T *argvars, typval_T *rettv, FunPtr fptr) { size_t len; - char_u *errormsg; + char *errormsg; int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND; expand_T xpc; bool error = false; @@ -2346,7 +2348,7 @@ static void f_menu_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) // Expand all the special characters in a command string. static void f_expandcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr) { - char_u *errormsg = NULL; + char *errormsg = NULL; rettv->v_type = VAR_STRING; char_u *cmdstr = (char_u *)xstrdup(tv_get_string(&argvars[0])); @@ -2362,7 +2364,7 @@ static void f_expandcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr) expand_filename(&eap, &cmdstr, &errormsg); if (errormsg != NULL && *errormsg != NUL) { - EMSG(errormsg); + emsg(errormsg); } rettv->vval.v_string = cmdstr; } @@ -2376,7 +2378,7 @@ static void f_flatten(typval_T *argvars, typval_T *rettv, FunPtr fptr) bool error = false; if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listarg), "flatten()"); + semsg(_(e_listarg), "flatten()"); return; } @@ -2388,7 +2390,7 @@ static void f_flatten(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (maxdepth < 0) { - EMSG(_("E900: maxdepth must be non-negative number")); + emsg(_("E900: maxdepth must be non-negative number")); return; } } @@ -2430,7 +2432,7 @@ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr) } else { item = tv_list_find(l1, before); if (item == NULL) { - EMSGN(_(e_listidx), before); + semsg(_(e_listidx), (int64_t)before); return; } } @@ -2469,7 +2471,7 @@ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } if (i == 3) { - EMSG2(_(e_invarg2), action); + semsg(_(e_invarg2), action); return; } } @@ -2479,7 +2481,7 @@ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr) tv_copy(&argvars[0], rettv); } } else { - EMSG2(_(e_listdictarg), "extend()"); + semsg(_(e_listdictarg), "extend()"); } } @@ -2661,9 +2663,9 @@ static void f_fnamemodify(typval_T *argvars, typval_T *rettv, FunPtr fptr) char buf[NUMBUFLEN]; const char *fname = tv_get_string_chk(&argvars[0]); const char *const mods = tv_get_string_buf_chk(&argvars[1], buf); - if (fname == NULL || mods == NULL) { + if (fname == NULL) { fname = NULL; - } else { + } else if (mods != NULL && *mods != NUL) { len = strlen(fname); size_t usedlen = 0; if (*mods != NUL) { @@ -2926,7 +2928,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) tv_list_append_tv(rettv->vval.v_list, &pt->pt_argv[i]); } } else { - EMSG2(_(e_invarg2), what); + semsg(_(e_invarg2), what); } // When {what} == "dict" and pt->pt_dict == NULL, evaluate the @@ -2936,7 +2938,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } } else { - EMSG2(_(e_listdictblobarg), "get()"); + semsg(_(e_listdictblobarg), "get()"); } if (tv == NULL) { @@ -3362,7 +3364,7 @@ static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) | WILD_NO_BEEP | WILD_HOME_REPLACE; if (argvars[1].v_type != VAR_STRING) { - EMSG2(_(e_invarg2), "type must be a string"); + semsg(_(e_invarg2), "type must be a string"); return; } const char *const type = tv_get_string(&argvars[1]); @@ -3381,7 +3383,7 @@ static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -3396,7 +3398,7 @@ static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); xpc.xp_context = cmdcomplete_str_to_type(type); if (xpc.xp_context == EXPAND_NOTHING) { - EMSG2(_(e_invarg2), type); + semsg(_(e_invarg2), type); return; } @@ -3465,13 +3467,13 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr) break; } if (argvars[i].v_type != VAR_NUMBER) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } scope_number[i] = argvars[i].vval.v_number; // It is an error for the scope number to be less than `-1`. if (scope_number[i] < -1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } // Use the narrowest scope the user requested @@ -3492,7 +3494,7 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (scope_number[kCdScopeTabpage] > 0) { tp = find_tabpage(scope_number[kCdScopeTabpage]); if (!tp) { - EMSG(_("E5000: Cannot find tab number.")); + emsg(_("E5000: Cannot find tab number.")); return; } } @@ -3500,14 +3502,14 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr) // Find the window in `tp` by number, `NULL` if none. if (scope_number[kCdScopeWindow] >= 0) { if (scope_number[kCdScopeTabpage] < 0) { - EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); + emsg(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); return; } if (scope_number[kCdScopeWindow] > 0) { win = find_win_by_nr(&argvars[0], tp); if (!win) { - EMSG(_("E5002: Cannot find window number.")); + emsg(_("E5002: Cannot find window number.")); return; } } @@ -4148,12 +4150,12 @@ static void f_wait(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_NUMBER) { - EMSG2(_(e_invargval), "1"); + semsg(_(e_invargval), "1"); return; } if ((argvars[2].v_type != VAR_NUMBER && argvars[2].v_type != VAR_UNKNOWN) || (argvars[2].v_type == VAR_NUMBER && argvars[2].vval.v_number <= 0)) { - EMSG2(_(e_invargval), "3"); + semsg(_(e_invargval), "3"); return; } @@ -4260,7 +4262,7 @@ static void f_win_splitmove(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (wp == NULL || targetwin == NULL || wp == targetwin || !win_valid(wp) || !win_valid(targetwin) || win_valid_floating(wp) || win_valid_floating(targetwin)) { - EMSG(_(e_invalwindow)); + emsg(_(e_invalwindow)); rettv->vval.v_number = -1; return; } @@ -4270,7 +4272,7 @@ static void f_win_splitmove(typval_T *argvars, typval_T *rettv, FunPtr fptr) dictitem_T *di; if (argvars[2].v_type != VAR_DICT || argvars[2].vval.v_dict == NULL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -4552,9 +4554,6 @@ static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr) "windows", "winaltkeys", "writebackup", -#if defined(HAVE_WSL) - "wsl", -#endif "nvim", }; @@ -4601,6 +4600,8 @@ static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr) n = syntax_present(curwin); } else if (STRICMP(name, "clipboard_working") == 0) { n = eval_has_provider("clipboard"); + } else if (STRICMP(name, "wsl") == 0) { + n = has_wsl(); #ifdef UNIX } else if (STRICMP(name, "unnamedplus") == 0) { n = eval_has_provider("clipboard"); @@ -4615,13 +4616,27 @@ static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = n; } -/* - * "has_key()" function - */ +static bool has_wsl(void) +{ + static TriState has_wsl = kNone; + if (has_wsl == kNone) { + Error err = ERROR_INIT; + Object o = nlua_exec(STATIC_CSTR_AS_STRING("return vim.loop.os_uname()['release']:lower()" + ":match('microsoft') and true or false"), + (Array)ARRAY_DICT_INIT, &err); + assert(!ERROR_SET(&err)); + assert(o.type == kObjectTypeBoolean); + has_wsl = o.data.boolean ? kTrue : kFalse; + api_free_object(o); + } + return has_wsl == kTrue; +} + +/// "has_key()" function static void f_has_key(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } if (argvars[0].vval.v_dict == NULL) { @@ -4668,12 +4683,12 @@ static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) break; } if (argvars[i].v_type != VAR_NUMBER) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } scope_number[i] = argvars[i].vval.v_number; if (scope_number[i] < -1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } // Use the narrowest scope the user requested @@ -4694,7 +4709,7 @@ static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (scope_number[kCdScopeTabpage] > 0) { tp = find_tabpage(scope_number[kCdScopeTabpage]); if (!tp) { - EMSG(_("E5000: Cannot find tab number.")); + emsg(_("E5000: Cannot find tab number.")); return; } } @@ -4702,14 +4717,14 @@ static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) // Find the window in `tp` by number, `NULL` if none. if (scope_number[kCdScopeWindow] >= 0) { if (scope_number[kCdScopeTabpage] < 0) { - EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); + emsg(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); return; } if (scope_number[kCdScopeWindow] > 0) { win = find_win_by_nr(&argvars[0], tp); if (!win) { - EMSG(_("E5002: Cannot find window number.")); + emsg(_("E5002: Cannot find window number.")); return; } } @@ -4958,7 +4973,7 @@ static void f_index(typval_T *argvars, typval_T *rettv, FunPtr fptr) } return; } else if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listblobreq)); + emsg(_(e_listblobreq)); return; } list_T *const l = argvars[0].vval.v_list; @@ -5020,7 +5035,7 @@ static void f_inputlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) int mouse_used; if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listarg), "inputlist()"); + semsg(_(e_listarg), "inputlist()"); return; } @@ -5105,7 +5120,7 @@ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; // type error; errmsg already given } if (before < 0 || before > len) { - EMSG2(_(e_invarg2), tv_get_string(&argvars[2])); + semsg(_(e_invarg2), tv_get_string(&argvars[2])); return; } } @@ -5114,7 +5129,7 @@ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (val < 0 || val > 255) { - EMSG2(_(e_invarg2), tv_get_string(&argvars[1])); + semsg(_(e_invarg2), tv_get_string(&argvars[1])); return; } @@ -5126,7 +5141,7 @@ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) tv_copy(&argvars[0], rettv); } else if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listblobarg), "insert()"); + semsg(_(e_listblobarg), "insert()"); } else if (!var_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), N_("insert() argument"), TV_TRANSLATE)) { long before = 0; @@ -5142,7 +5157,7 @@ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (before != tv_list_len(l)) { item = tv_list_find(l, before); if (item == NULL) { - EMSGN(_(e_listidx), before); + semsg(_(e_listidx), (int64_t)before); l = NULL; } } @@ -5192,7 +5207,7 @@ static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr) FNE_CHECK_START); if (end != NULL && lv.ll_name != NULL) { if (*end != NUL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } else { if (lv.ll_tv == NULL) { di = find_var(lv.ll_name, lv.ll_name_len, NULL, true); @@ -5205,9 +5220,9 @@ static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr) || tv_islocked(&di->di_tv)); } } else if (lv.ll_range) { - EMSG(_("E786: Range not allowed")); + emsg(_("E786: Range not allowed")); } else if (lv.ll_newkey != NULL) { - EMSG2(_(e_dictkey), lv.ll_newkey); + semsg(_(e_dictkey), lv.ll_newkey); } else if (lv.ll_list != NULL) { // List item. rettv->vval.v_number = tv_islocked(TV_LIST_ITEM_TV(lv.ll_li)); @@ -5267,7 +5282,7 @@ static void f_jobpid(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_NUMBER) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -5293,7 +5308,7 @@ static void f_jobresize(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type != VAR_NUMBER || argvars[2].v_type != VAR_NUMBER) { // job id, width, height - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -5304,7 +5319,7 @@ static void f_jobresize(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (data->stream.proc.type != kProcessTypePty) { - EMSG(_(e_channotpty)); + emsg(_(e_channotpty)); return; } @@ -5447,7 +5462,7 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) { // Wrong argument types - EMSG2(_(e_invarg2), "expected dictionary"); + semsg(_(e_invarg2), "expected dictionary"); shell_free_argv(argv); return; } @@ -5481,19 +5496,19 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) } else if (!strncmp(s, "pipe", NUMBUFLEN)) { // Nothing to do, default value } else { - EMSG3(_(e_invargNval), "stdin", s); + semsg(_(e_invargNval), "stdin", s); } } if (pty && rpc) { - EMSG2(_(e_invarg2), "job cannot have both 'pty' and 'rpc' options set"); + semsg(_(e_invarg2), "job cannot have both 'pty' and 'rpc' options set"); shell_free_argv(argv); return; } #ifdef WIN32 if (pty && overlapped) { - EMSG2(_(e_invarg2), + semsg(_(e_invarg2), "job cannot have both 'pty' and 'overlapped' options set"); shell_free_argv(argv); return; @@ -5505,7 +5520,7 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) cwd = new_cwd; // The new cwd must be a directory. if (!os_isdir_executable((const char *)cwd)) { - EMSG2(_(e_invarg2), "expected valid directory"); + semsg(_(e_invarg2), "expected valid directory"); shell_free_argv(argv); return; } @@ -5513,7 +5528,7 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) job_env = tv_dict_find(job_opts, S_LEN("env")); if (job_env && job_env->di_tv.v_type != VAR_DICT) { - EMSG2(_(e_invarg2), "env"); + semsg(_(e_invarg2), "env"); shell_free_argv(argv); return; } @@ -5560,7 +5575,7 @@ static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_NUMBER) { // Only argument is the job id - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -5577,7 +5592,7 @@ static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) process_stop(&data->stream.proc); rettv->vval.v_number = 1; if (error) { - EMSG(error); + emsg(error); } } @@ -5592,7 +5607,7 @@ static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_LIST || (argvars[1].v_type != VAR_NUMBER && argvars[1].v_type != VAR_UNKNOWN)) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -5686,7 +5701,7 @@ static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_join(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } const char *const sep = (argvars[1].v_type == VAR_UNKNOWN @@ -5715,7 +5730,7 @@ static void f_json_decode(typval_T *argvars, typval_T *rettv, FunPtr fptr) size_t len; if (argvars[0].v_type == VAR_LIST) { if (!encode_vim_list_to_buf(argvars[0].vval.v_list, &len, &tofree)) { - EMSG(_("E474: Failed to convert list to string")); + emsg(_("E474: Failed to convert list to string")); return; } s = tofree; @@ -5732,7 +5747,7 @@ static void f_json_decode(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } if (json_decode_string(s, len, rettv) == FAIL) { - emsgf(_("E474: Failed to parse %.*s"), (int)len, s); + semsg(_("E474: Failed to parse %.*s"), (int)len, s); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } @@ -5796,7 +5811,7 @@ static void f_len(typval_T *argvars, typval_T *rettv, FunPtr fptr) case VAR_FLOAT: case VAR_PARTIAL: case VAR_FUNC: - EMSG(_("E701: Invalid type for len()")); + emsg(_("E701: Invalid type for len()")); break; } } @@ -5837,7 +5852,7 @@ static void libcall_common(typval_T *argvars, typval_T *rettv, int out_type) str_out, &int_out); if (!success) { - EMSG2(_(e_libcall), funcname); + semsg(_(e_libcall), funcname); return; } @@ -5935,7 +5950,7 @@ static void f_list2str(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -6323,7 +6338,7 @@ static void f_matchadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (id >= 1 && id <= 3) { - EMSGN(_("E798: ID is reserved for \":match\": %" PRId64), id); + semsg(_("E798: ID is reserved for \":match\": %" PRId64), (int64_t)id); return; } @@ -6341,7 +6356,7 @@ static void f_matchaddpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[1].v_type != VAR_LIST) { - EMSG2(_(e_listarg), "matchaddpos()"); + semsg(_(e_listarg), "matchaddpos()"); return; } @@ -6373,7 +6388,7 @@ static void f_matchaddpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) // id == 3 is ok because matchaddpos() is supposed to substitute :3match if (id == 1 || id == 2) { - EMSGN(_("E798: ID is reserved for \"match\": %" PRId64), id); + semsg(_("E798: ID is reserved for \"match\": %" PRId64), (int64_t)id); return; } @@ -6492,7 +6507,7 @@ static void max_min(const typval_T *const tv, typval_T *const rettv, const bool } }); } else { - EMSG2(_(e_listdictarg), domax ? "max()" : "min()"); + semsg(_(e_listdictarg), domax ? "max()" : "min()"); return; } rettv->vval.v_number = n; @@ -6548,7 +6563,7 @@ static void f_mkdir(typval_T *argvars, typval_T *rettv, FunPtr fptr) char *failed_dir; int ret = os_mkdir_recurse(dir, prot, &failed_dir); if (ret != 0) { - EMSG3(_(e_mkdir), failed_dir, os_strerror(ret)); + semsg(_(e_mkdir), failed_dir, os_strerror(ret)); xfree(failed_dir); rettv->vval.v_number = FAIL; return; @@ -6581,7 +6596,7 @@ static void f_msgpackdump(typval_T *argvars, typval_T *rettv, FunPtr fptr) FUNC_ATTR_NONNULL_ALL { if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listarg), "msgpackdump()"); + semsg(_(e_listarg), "msgpackdump()"); return; } list_T *const list = argvars[0].vval.v_list; @@ -6614,21 +6629,21 @@ static int msgpackparse_convert_item(const msgpack_object data, const msgpack_un { switch (result) { case MSGPACK_UNPACK_PARSE_ERROR: - EMSG2(_(e_invarg2), "Failed to parse msgpack string"); + semsg(_(e_invarg2), "Failed to parse msgpack string"); return FAIL; case MSGPACK_UNPACK_NOMEM_ERROR: - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); return FAIL; case MSGPACK_UNPACK_CONTINUE: if (fail_if_incomplete) { - EMSG2(_(e_invarg2), "Incomplete msgpack string"); + semsg(_(e_invarg2), "Incomplete msgpack string"); return FAIL; } return NOTDONE; case MSGPACK_UNPACK_SUCCESS: { typval_T tv = { .v_type = VAR_UNKNOWN }; if (msgpack_to_vim(data, &tv) == FAIL) { - EMSG2(_(e_invarg2), "Failed to convert msgpack string"); + semsg(_(e_invarg2), "Failed to convert msgpack string"); return FAIL; } tv_list_append_owned_tv(ret_list, tv); @@ -6646,27 +6661,27 @@ static void msgpackparse_unpack_list(const list_T *const list, list_T *const ret return; } if (TV_LIST_ITEM_TV(tv_list_first(list))->v_type != VAR_STRING) { - EMSG2(_(e_invarg2), "List item is not a string"); + semsg(_(e_invarg2), "List item is not a string"); return; } ListReaderState lrstate = encode_init_lrstate(list); msgpack_unpacker *const unpacker = msgpack_unpacker_new(IOSIZE); if (unpacker == NULL) { - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); return; } msgpack_unpacked unpacked; msgpack_unpacked_init(&unpacked); do { if (!msgpack_unpacker_reserve_buffer(unpacker, IOSIZE)) { - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); goto end; } size_t read_bytes; const int rlret = encode_read_from_list(&lrstate, msgpack_unpacker_buffer(unpacker), IOSIZE, &read_bytes); if (rlret == FAIL) { - EMSG2(_(e_invarg2), "List item is not a string"); + semsg(_(e_invarg2), "List item is not a string"); goto end; } msgpack_unpacker_buffer_consumed(unpacker, read_bytes); @@ -6720,7 +6735,7 @@ static void f_msgpackparse(typval_T *argvars, typval_T *rettv, FunPtr fptr) FUNC_ATTR_NONNULL_ALL { if (argvars[0].v_type != VAR_LIST && argvars[0].v_type != VAR_BLOB) { - EMSG2(_(e_listblobarg), "msgpackparse()"); + semsg(_(e_listblobarg), "msgpackparse()"); return; } list_T *const ret_list = tv_list_alloc_ret(rettv, kListLenMayKnow); @@ -6767,11 +6782,11 @@ static void f_nr2char(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (num < 0) { - EMSG(_("E5070: Character number must not be less than zero")); + emsg(_("E5070: Character number must not be less than zero")); return; } if (num > INT_MAX) { - emsgf(_("E5071: Character number must not be greater than INT_MAX (%i)"), + semsg(_("E5071: Character number must not be greater than INT_MAX (%i)"), INT_MAX); return; } @@ -7033,9 +7048,9 @@ static void f_range(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; // Type error; errmsg already given. } if (stride == 0) { - EMSG(_("E726: Stride is zero")); + emsg(_("E726: Stride is zero")); } else if (stride > 0 ? end + 1 < start : end - 1 > start) { - EMSG(_("E727: Start past end")); + emsg(_("E727: Start past end")); } else { tv_list_alloc_ret(rettv, (end - start) / stride); for (i = start; stride > 0 ? i <= end : i >= end; i += stride) { @@ -7163,18 +7178,18 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char *const fname = tv_get_string(&argvars[0]); if (os_isdir((const char_u *)fname)) { - EMSG2(_(e_isadir2), fname); + semsg(_(e_isadir2), fname); return; } if (*fname == NUL || (fd = os_fopen(fname, READBIN)) == NULL) { - EMSG2(_(e_notopen), *fname == NUL ? _("<empty>") : fname); + semsg(_(e_notopen), *fname == NUL ? _("<empty>") : fname); return; } if (blob) { tv_blob_alloc_ret(rettv); if (!read_blob(fd, rettv->vval.v_blob)) { - EMSG2(_(e_notread), fname); + semsg(_(e_notread), fname); // An empty blob is returned on error. tv_blob_free(rettv->vval.v_blob); rettv->vval.v_blob = NULL; @@ -7492,14 +7507,14 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type == VAR_DICT) { if (argvars[2].v_type != VAR_UNKNOWN) { - EMSG2(_(e_toomanyarg), "remove()"); + semsg(_(e_toomanyarg), "remove()"); } else if ((d = argvars[0].vval.v_dict) != NULL && !var_check_lock(d->dv_lock, arg_errmsg, TV_TRANSLATE)) { const char *key = tv_get_string_chk(&argvars[1]); if (key != NULL) { di = tv_dict_find(d, key, -1); if (di == NULL) { - EMSG2(_(e_dictkey), key); + semsg(_(e_dictkey), key); } else if (!var_check_fixed(di->di_flags, arg_errmsg, TV_TRANSLATE) && !var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE)) { *rettv = di->di_tv; @@ -7529,7 +7544,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) idx = len + idx; } if (idx < 0 || idx >= len) { - EMSGN(_(e_blobidx), idx); + semsg(_(e_blobidx), (int64_t)idx); return; } if (argvars[2].v_type == VAR_UNKNOWN) { @@ -7549,7 +7564,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) end = len + end; } if (end >= len || idx > end) { - EMSGN(_(e_blobidx), end); + semsg(_(e_blobidx), (int64_t)end); return; } blob_T *const blob = tv_blob_alloc(); @@ -7568,7 +7583,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } } else if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listdictblobarg), "remove()"); + semsg(_(e_listdictblobarg), "remove()"); } else if (!var_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), arg_errmsg, TV_TRANSLATE)) { bool error = false; @@ -7577,7 +7592,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (error) { // Type error: do nothing, errmsg already given. } else if ((item = tv_list_find(l, idx)) == NULL) { - EMSGN(_(e_listidx), idx); + semsg(_(e_listidx), (int64_t)idx); } else { if (argvars[2].v_type == VAR_UNKNOWN) { // Remove one item, return its value. @@ -7590,7 +7605,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (error) { // Type error: do nothing. } else if ((item2 = tv_list_find(l, end)) == NULL) { - EMSGN(_(e_listidx), end); + semsg(_(e_listidx), (int64_t)end); } else { int cnt = 0; @@ -7601,7 +7616,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) } } if (li == NULL) { // Didn't find "item2" after "item". - EMSG(_(e_invrange)); + emsg(_(e_invrange)); } else { tv_list_move_items(l, item, item2, tv_list_alloc_ret(rettv, cnt), cnt); @@ -7723,7 +7738,7 @@ static void f_resolve(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (limit-- == 0) { xfree(p); xfree(remain); - EMSG(_("E655: Too many symbolic links (cycle?)")); + emsg(_("E655: Too many symbolic links (cycle?)")); rettv->vval.v_string = NULL; xfree(buf); return; @@ -7852,7 +7867,7 @@ static void f_reverse(typval_T *argvars, typval_T *rettv, FunPtr fptr) } tv_blob_set_ret(rettv, b); } else if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listblobarg), "reverse()"); + semsg(_(e_listblobarg), "reverse()"); } else { list_T *const l = argvars[0].vval.v_list; if (!var_check_lock(tv_list_locked(l), N_("reverse() argument"), @@ -7919,7 +7934,7 @@ static int get_search_arg(typval_T *varp, int *flagsp) } } if (mask == 0) { - emsgf(_(e_invarg2), flags); + semsg(_(e_invarg2), flags); dir = 0; } else { *flagsp |= mask; @@ -7991,7 +8006,7 @@ static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp) */ if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0) || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { - EMSG2(_(e_invarg2), tv_get_string(&argvars[1])); + semsg(_(e_invarg2), tv_get_string(&argvars[1])); goto theend; } @@ -8044,12 +8059,12 @@ static void f_rpcnotify(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number < 0) { - EMSG2(_(e_invarg2), "Channel id must be a positive integer"); + semsg(_(e_invarg2), "Channel id must be a positive integer"); return; } if (argvars[1].v_type != VAR_STRING) { - EMSG2(_(e_invarg2), "Event type must be a string"); + semsg(_(e_invarg2), "Event type must be a string"); return; } @@ -8061,7 +8076,7 @@ static void f_rpcnotify(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (!rpc_send_event((uint64_t)argvars[0].vval.v_number, tv_get_string(&argvars[1]), args)) { - EMSG2(_(e_invarg2), "Channel doesn't exist"); + semsg(_(e_invarg2), "Channel doesn't exist"); return; } @@ -8080,12 +8095,12 @@ static void f_rpcrequest(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number <= 0) { - EMSG2(_(e_invarg2), "Channel id must be a positive integer"); + semsg(_(e_invarg2), "Channel id must be a positive integer"); return; } if (argvars[1].v_type != VAR_STRING) { - EMSG2(_(e_invarg2), "Method name must be a string"); + semsg(_(e_invarg2), "Method name must be a string"); return; } @@ -8147,10 +8162,10 @@ static void f_rpcrequest(typval_T *argvars, typval_T *rettv, FunPtr fptr) } msg_ext_set_kind("rpc_error"); if (name) { - emsgf_multiline("Error invoking '%s' on channel %" PRIu64 " (%s):\n%s", + semsg_multiline("Error invoking '%s' on channel %" PRIu64 " (%s):\n%s", method, chan_id, name, err.msg); } else { - emsgf_multiline("Error invoking '%s' on channel %" PRIu64 ":\n%s", + semsg_multiline("Error invoking '%s' on channel %" PRIu64 ":\n%s", method, chan_id, err.msg); } @@ -8158,7 +8173,7 @@ static void f_rpcrequest(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (!object_to_vim(result, rettv, &err)) { - EMSG2(_("Error converting the call result: %s"), err.msg); + semsg(_("Error converting the call result: %s"), err.msg); } end: @@ -8179,7 +8194,7 @@ static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_STRING || (argvars[1].v_type != VAR_LIST && argvars[1].v_type != VAR_UNKNOWN)) { // Wrong argument types - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -8192,7 +8207,7 @@ static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) int i = 0; TV_LIST_ITER_CONST(args, arg, { if (TV_LIST_ITEM_TV(arg)->v_type != VAR_STRING) { - emsgf(_("E5010: List item %d of the second argument is not a string"), + semsg(_("E5010: List item %d of the second argument is not a string"), i); return; } @@ -8201,7 +8216,7 @@ static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].vval.v_string == NULL || argvars[0].vval.v_string[0] == NUL) { - EMSG(_(e_api_spawn_failed)); + emsg(_(e_api_spawn_failed)); return; } @@ -8245,7 +8260,7 @@ static void f_rpcstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_NUMBER) { // Wrong argument types - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -8258,7 +8273,7 @@ static void f_rpcstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = channel_close(argvars[0].vval.v_number, kChannelPartRpc, &error); if (!rettv->vval.v_number) { - EMSG(error); + emsg(error); } } } @@ -8445,7 +8460,7 @@ static int searchpair_cmn(typval_T *argvars, pos_T *match_pos) // Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set. if ((flags & (SP_END | SP_SUBPAT)) != 0 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { - EMSG2(_(e_invarg2), tv_get_string(&argvars[3])); + semsg(_(e_invarg2), tv_get_string(&argvars[3])); goto theend; } @@ -8464,19 +8479,19 @@ static int searchpair_cmn(typval_T *argvars, pos_T *match_pos) if (skip->v_type != VAR_FUNC && skip->v_type != VAR_PARTIAL && skip->v_type != VAR_STRING) { - emsgf(_(e_invarg2), tv_get_string(&argvars[4])); + semsg(_(e_invarg2), tv_get_string(&argvars[4])); goto theend; // Type error. } if (argvars[5].v_type != VAR_UNKNOWN) { lnum_stop = tv_get_number_chk(&argvars[5], NULL); if (lnum_stop < 0) { - emsgf(_(e_invarg2), tv_get_string(&argvars[5])); + semsg(_(e_invarg2), tv_get_string(&argvars[5])); goto theend; } if (argvars[6].v_type != VAR_UNKNOWN) { time_limit = tv_get_number_chk(&argvars[6], NULL); if (time_limit < 0) { - emsgf(_(e_invarg2), tv_get_string(&argvars[6])); + semsg(_(e_invarg2), tv_get_string(&argvars[6])); goto theend; } } @@ -8741,7 +8756,7 @@ static void f_serverstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) // If the user supplied an address, use it, otherwise use a temp. if (argvars[0].v_type != VAR_UNKNOWN) { if (argvars[0].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } else { address = xstrdup(tv_get_string(argvars)); @@ -8754,7 +8769,7 @@ static void f_serverstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) xfree(address); if (result != 0) { - EMSG2("Failed to start server: %s", + semsg("Failed to start server: %s", result > 0 ? "Unknown system error" : uv_strerror(result)); return; } @@ -8780,7 +8795,7 @@ static void f_serverstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[0].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -8859,7 +8874,7 @@ static void f_setcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr) dictitem_T *di; if (argvars[0].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } @@ -8926,7 +8941,7 @@ static void f_setfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (strlen(mode_str) != 9) { - EMSG2(_(e_invarg2), mode_str); + semsg(_(e_invarg2), mode_str); return; } @@ -8977,10 +8992,10 @@ static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv) typval_T *list_arg = &args[0]; if (list_arg->v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } else if (recursive != 0) { - EMSG(_(e_au_recursive)); + emsg(_(e_au_recursive)); return; } @@ -8989,7 +9004,7 @@ static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv) // Option argument was not given. goto skip_args; } else if (action_arg->v_type != VAR_STRING) { - EMSG(_(e_stringreq)); + emsg(_(e_stringreq)); return; } const char *const act = tv_get_string_chk(action_arg); @@ -8997,7 +9012,7 @@ static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv) && act[1] == NUL) { action = *act; } else { - EMSG2(_(e_invact), act); + semsg(_(e_invact), act); return; } @@ -9014,7 +9029,7 @@ static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv) } else if (what_arg->v_type == VAR_DICT && what_arg->vval.v_dict != NULL) { what = what_arg->vval.v_dict; } else { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } @@ -9057,7 +9072,7 @@ static void f_setmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } if (win == NULL) { @@ -9071,7 +9086,7 @@ static void f_setmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) TV_LIST_ITER_CONST(l, li, { if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT || (d = TV_LIST_ITEM_TV(li)->vval.v_dict) == NULL) { - emsgf(_("E474: List item %d is either not a dictionary " + semsg(_("E474: List item %d is either not a dictionary " "or an empty one"), li_idx); return; } @@ -9080,7 +9095,7 @@ static void f_setmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) || tv_dict_find(d, S_LEN("pos1")) != NULL) && tv_dict_find(d, S_LEN("priority")) != NULL && tv_dict_find(d, S_LEN("id")) != NULL)) { - emsgf(_("E474: List item %d is missing one of the required keys"), + semsg(_("E474: List item %d is missing one of the required keys"), li_idx); return; } @@ -9182,7 +9197,7 @@ static void f_setpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = 0; } } else { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } } } @@ -9272,7 +9287,7 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr) const int ret = get_yank_type((char_u **)&stropt, &yank_type, &block_len); if (ret == FAIL || *(++stropt) != NUL) { - EMSG2(_(e_invargval), "value"); + semsg(_(e_invargval), "value"); return; } } @@ -9293,7 +9308,7 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr) bool set_unnamed = false; if (argvars[2].v_type != VAR_UNKNOWN) { if (yank_type != kMTUnknown) { - EMSG2(_(e_toomanyarg), "setreg"); + semsg(_(e_toomanyarg), "setreg"); return; } @@ -9433,7 +9448,7 @@ static void f_settagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) // second argument: dict with items to set in the tag stack if (argvars[1].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } d = argvars[1].vval.v_dict; @@ -9455,11 +9470,11 @@ static void f_settagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) && actstr[1] == NUL) { action = *actstr; } else { - EMSG2(_(e_invact2), actstr); + semsg(_(e_invact2), actstr); return; } } else { - EMSG(_(e_stringreq)); + emsg(_(e_stringreq)); return; } @@ -9542,7 +9557,7 @@ static void f_sign_define(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (argvars[1].v_type != VAR_UNKNOWN && argvars[1].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } @@ -9588,7 +9603,7 @@ static void f_sign_getplaced(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type != VAR_UNKNOWN) { if (argvars[1].v_type != VAR_DICT || ((dict = argvars[1].vval.v_dict) == NULL)) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } if ((di = tv_dict_find(dict, "lnum", -1)) != NULL) { @@ -9639,7 +9654,7 @@ static void f_sign_jump(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (sign_id <= 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -9676,7 +9691,7 @@ static void f_sign_place(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[4].v_type != VAR_UNKNOWN && (argvars[4].v_type != VAR_DICT || ((dict = argvars[4].vval.v_dict) == NULL))) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } @@ -9692,7 +9707,7 @@ static void f_sign_placelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) tv_list_alloc_ret(rettv, kListLenMayKnow); if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } @@ -9702,7 +9717,7 @@ static void f_sign_placelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (TV_LIST_ITEM_TV(li)->v_type == VAR_DICT) { sign_id = sign_place_from_dict(NULL, NULL, NULL, NULL, TV_LIST_ITEM_TV(li)->vval.v_dict); } else { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); } tv_list_append_number(rettv->vval.v_list, sign_id); }); @@ -9748,13 +9763,13 @@ static void f_sign_unplace(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } if (argvars[1].v_type != VAR_UNKNOWN) { if (argvars[1].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } dict = argvars[1].vval.v_dict; @@ -9771,7 +9786,7 @@ static void f_sign_unplacelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) tv_list_alloc_ret(rettv, kListLenMayKnow); if (argvars[0].v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return; } @@ -9780,7 +9795,7 @@ static void f_sign_unplacelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (TV_LIST_ITEM_TV(li)->v_type == VAR_DICT) { retval = sign_unplace_from_dict(NULL, TV_LIST_ITEM_TV(li)->vval.v_dict); } else { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); } tv_list_append_number(rettv->vval.v_list, retval); }); @@ -9801,12 +9816,12 @@ static void f_simplify(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } if (argvars[2].v_type != VAR_DICT && argvars[2].v_type != VAR_UNKNOWN) { // Wrong argument types - EMSG2(_(e_invarg2), "expected dictionary"); + semsg(_(e_invarg2), "expected dictionary"); return; } @@ -9819,7 +9834,7 @@ static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr) } else if (strcmp(mode, "pipe") == 0) { tcp = false; } else { - EMSG2(_(e_invarg2), "invalid mode"); + semsg(_(e_invarg2), "invalid mode"); return; } @@ -9842,7 +9857,7 @@ static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr) uint64_t id = channel_connect(tcp, address, rpc, on_data, 50, &error); if (error) { - EMSG2(_("connection failed: %s"), error); + semsg(_("connection failed: %s"), error); } rettv->vval.v_number = (varnumber_T)id; @@ -10051,7 +10066,7 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) : N_("uniq() argument")); if (argvars[0].v_type != VAR_LIST) { - EMSG2(_(e_listarg), sort ? "sort()" : "uniq()"); + semsg(_(e_listarg), sort ? "sort()" : "uniq()"); } else { list_T *const l = argvars[0].vval.v_list; if (var_check_lock(tv_list_locked(l), arg_errmsg, TV_TRANSLATE)) { @@ -10091,7 +10106,7 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) } else if (argvars[1].v_type != VAR_NUMBER) { info.item_compare_func = tv_get_string(&argvars[1]); } else if (i != 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); goto theend; } if (info.item_compare_func != NULL) { @@ -10120,7 +10135,7 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) if (argvars[2].v_type != VAR_UNKNOWN) { // optional third argument: {dict} if (argvars[2].v_type != VAR_DICT) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); goto theend; } info.item_compare_selfdict = argvars[2].vval.v_dict; @@ -10139,7 +10154,7 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) : item_compare2_not_keeping_zero), &info.item_compare_func_err); if (info.item_compare_func_err) { - EMSG(_("E702: Sort compare function failed")); + emsg(_("E702: Sort compare function failed")); } } else { ListSorter item_compare_func_ptr; @@ -10159,7 +10174,7 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) listitem_T *const prev_li = TV_LIST_ITEM_PREV(l, li); if (item_compare_func_ptr(&prev_li, &li) == 0) { if (info.item_compare_func_err) { // -V547 - EMSG(_("E882: Uniq compare function failed")); + emsg(_("E882: Uniq compare function failed")); break; } li = tv_list_item_remove(l, li); @@ -10187,7 +10202,7 @@ static void f_sort(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_stdioopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_DICT) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -10208,7 +10223,7 @@ static void f_stdioopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char *error; uint64_t id = channel_from_stdio(rpc, on_stdin, &error); if (!id) { - EMSG2(e_stdiochan2, error); + semsg(e_stdiochan2, error); } @@ -10261,7 +10276,7 @@ static void f_spellbadword(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (*curwin->w_s->b_p_spl == NUL) { - EMSG(_(e_no_spell)); + emsg(_(e_no_spell)); curwin->w_p_spell = wo_spell_save; return; } @@ -10323,7 +10338,7 @@ static void f_spellsuggest(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (*curwin->w_s->b_p_spl == NUL) { - EMSG(_(e_no_spell)); + emsg(_(e_no_spell)); curwin->w_p_spell = wo_spell_save; return; } @@ -10459,7 +10474,7 @@ static void f_stdpath(typval_T *argvars, typval_T *rettv, FunPtr fptr) } else if (strequal(p, "data_dirs")) { get_xdg_var_list(kXDGDataDirs, rettv); } else { - EMSG2(_("E6100: \"%s\" is not a valid stdpath"), p); + semsg(_("E6100: \"%s\" is not a valid stdpath"), p); } } @@ -10502,7 +10517,7 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type != VAR_UNKNOWN) { base = tv_get_number(&argvars[1]); if (base != 2 && base != 8 && base != 10 && base != 16) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } if (argvars[2].v_type != VAR_UNKNOWN && tv_get_number(&argvars[2])) { @@ -10682,7 +10697,7 @@ static void f_strchars(typval_T *argvars, typval_T *rettv, FunPtr fptr) skipcc = tv_get_number_chk(&argvars[1], NULL); } if (skipcc < 0 || skipcc > 1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { func_mb_ptr2char_adv = skipcc ? mb_ptr2char_adv : mb_cptr2char_adv; while (*s != NUL) { @@ -10918,7 +10933,7 @@ static void f_submatch(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (no < 0 || no >= NSUBEXP) { - emsgf(_("E935: invalid submatch number: %d"), no); + semsg(_("E935: invalid submatch number: %d"), no); return; } int retList = 0; @@ -11220,7 +11235,7 @@ static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr) ? tabpage_index(lastused_tabpage) : nr; } else { - EMSG2(_(e_invexpr2), arg); + semsg(_(e_invexpr2), arg); } } } else { @@ -11230,7 +11245,6 @@ static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr) } - /* * Common code for tabpagewinnr() and winnr(). */ @@ -11279,7 +11293,7 @@ static int get_winnr(tabpage_T *tp, typval_T *argvar) } if (invalid_arg) { - EMSG2(_(e_invexpr2), arg); + semsg(_(e_invexpr2), arg); nr = 0; } } @@ -11371,7 +11385,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) } if (curbuf->b_changed) { - EMSG(_("Can only call this function in an unmodified buffer")); + emsg(_("Can only call this function in an unmodified buffer")); return; } @@ -11385,7 +11399,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) { // Wrong argument type - EMSG2(_(e_invarg2), "expected dictionary"); + semsg(_(e_invarg2), "expected dictionary"); shell_free_argv(argv); return; } @@ -11408,7 +11422,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) cwd = new_cwd; // The new cwd must be a directory. if (!os_isdir_executable(cwd)) { - EMSG2(_(e_invarg2), "expected valid directory"); + semsg(_(e_invarg2), "expected valid directory"); shell_free_argv(argv); return; } @@ -11416,7 +11430,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) job_env = tv_dict_find(job_opts, S_LEN("env")); if (job_env && job_env->di_tv.v_type != VAR_DICT) { - EMSG2(_(e_invarg2), "env"); + semsg(_(e_invarg2), "env"); shell_free_argv(argv); return; } @@ -11499,7 +11513,7 @@ static void f_timer_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_UNKNOWN) { if (argvars[0].v_type != VAR_NUMBER) { - EMSG(_(e_number_exp)); + emsg(_(e_number_exp)); return; } tv_list_alloc_ret(rettv, 1); @@ -11516,7 +11530,7 @@ static void f_timer_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_timer_pause(typval_T *argvars, typval_T *unused, FunPtr fptr) { if (argvars[0].v_type != VAR_NUMBER) { - EMSG(_(e_number_exp)); + emsg(_(e_number_exp)); return; } int paused = (bool)tv_get_number(&argvars[1]); @@ -11543,7 +11557,7 @@ static void f_timer_start(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_DICT || (dict = argvars[2].vval.v_dict) == NULL) { - EMSG2(_(e_invarg2), tv_get_string(&argvars[2])); + semsg(_(e_invarg2), tv_get_string(&argvars[2])); return; } dictitem_T *const di = tv_dict_find(dict, S_LEN("repeat")); @@ -11568,7 +11582,7 @@ static void f_timer_start(typval_T *argvars, typval_T *rettv, FunPtr fptr) static void f_timer_stop(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_NUMBER) { - EMSG(_(e_number_exp)); + emsg(_(e_number_exp)); return; } @@ -11682,7 +11696,7 @@ static void f_tr(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_string = ga.ga_data; return; error: - EMSG2(_(e_invarg2), fromstr); + semsg(_(e_invarg2), fromstr); ga_clear(&ga); return; } @@ -11716,7 +11730,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, FunPtr fptr) return; } if (dir < 0 || dir > 2) { - emsgf(_(e_invarg2), tv_get_string(&argvars[2])); + semsg(_(e_invarg2), tv_get_string(&argvars[2])); return; } } @@ -12076,7 +12090,7 @@ static void f_winrestview(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[0].v_type != VAR_DICT || (dict = argvars[0].vval.v_dict) == NULL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { dictitem_T *di; if ((di = tv_dict_find(dict, S_LEN("lnum"))) != NULL) { @@ -12183,7 +12197,7 @@ static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr) } }); } else if (argvars[0].v_type != VAR_BLOB) { - EMSG2(_(e_invarg2), + semsg(_(e_invarg2), _("writefile() first argument must be a List or a Blob")); return; } @@ -12208,7 +12222,7 @@ static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr) do_fsync = false; break; default: // Using %s, p and not %c, *p to preserve multibyte characters - emsgf(_("E5060: Unknown flag: %s"), p); + semsg(_("E5060: Unknown flag: %s"), p); return; } } @@ -12222,11 +12236,11 @@ static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr) FileDescriptor fp; int error; if (*fname == NUL) { - EMSG(_("E482: Can't open file with an empty name")); + emsg(_("E482: Can't open file with an empty name")); } else if ((error = file_open(&fp, fname, ((append ? kFileAppend : kFileTruncate) | kFileCreate), 0666)) != 0) { - emsgf(_("E482: Can't open file %s for writing: %s"), + semsg(_("E482: Can't open file %s for writing: %s"), fname, os_strerror(error)); } else { bool write_ok; @@ -12239,7 +12253,7 @@ static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_number = 0; } if ((error = file_close(&fp, do_fsync)) != 0) { - emsgf(_("E80: Error when closing file %s: %s"), + semsg(_("E80: Error when closing file %s: %s"), fname, os_strerror(error)); } } diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index 6300ce6150..3e37e8cbb6 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -63,7 +63,7 @@ void list_write_log(const char *const fname) FileDescriptor fp; const int fo_ret = file_open(&fp, fname, kFileCreate|kFileAppend, 0600); if (fo_ret != 0) { - emsgf(_("E5142: Failed to open file %s: %s"), fname, os_strerror(fo_ret)); + semsg(_("E5142: Failed to open file %s: %s"), fname, os_strerror(fo_ret)); return; } for (ListLog *chunk = list_log_first; chunk != NULL;) { @@ -85,7 +85,7 @@ void list_write_log(const char *const fname) sizeof(chunk->entries[0]) * (chunk->size - i)); chunk->size -= i; } - emsgf(_("E5143: Failed to write to file %s: %s"), + semsg(_("E5143: Failed to write to file %s: %s"), fname, os_strerror((int)fw_ret)); return; } @@ -96,7 +96,7 @@ void list_write_log(const char *const fname) } const int fc_ret = file_close(&fp, true); if (fc_ret != 0) { - emsgf(_("E5144: Failed to close file %s: %s"), fname, os_strerror(fc_ret)); + semsg(_("E5144: Failed to close file %s: %s"), fname, os_strerror(fc_ret)); } } @@ -1041,7 +1041,7 @@ const char *tv_list_find_str(list_T *const l, const int n) { const listitem_T *const li = tv_list_find(l, n); if (li == NULL) { - EMSG2(_(e_listidx), (int64_t)n); + semsg(_(e_listidx), (int64_t)n); return NULL; } return tv_get_string(TV_LIST_ITEM_TV(li)); @@ -1399,7 +1399,7 @@ void tv_dict_item_remove(dict_T *const dict, dictitem_T *const item) { hashitem_T *const hi = hash_find(&dict->dv_hashtab, item->di_key); if (HASHITEM_EMPTY(hi)) { - emsgf(_(e_intern2), "tv_dict_item_remove()"); + semsg(_(e_intern2), "tv_dict_item_remove()"); } else { hash_remove(&dict->dv_hashtab, hi); } @@ -1687,7 +1687,7 @@ bool tv_dict_get_callback(dict_T *const d, const char *const key, const ptrdiff_ } if (!tv_is_func(di->di_tv) && di->di_tv.v_type != VAR_STRING) { - EMSG(_("E6000: Argument is not a function or function name")); + emsg(_("E6000: Argument is not a function or function name")); return false; } @@ -1961,7 +1961,7 @@ void tv_dict_extend(dict_T *const d1, dict_T *const d2, const char *const action NULL); } } else if (*action == 'e') { - emsgf(_("E737: Key already exists: %s"), di2->di_key); + semsg(_("E737: Key already exists: %s"), di2->di_key); break; } else if (*action == 'f' && di2 != di1) { typval_T oldtv; @@ -2599,7 +2599,7 @@ void tv_copy(const typval_T *const from, typval_T *const to) } break; case VAR_UNKNOWN: - emsgf(_(e_intern2), "tv_copy(UNKNOWN)"); + semsg(_(e_intern2), "tv_copy(UNKNOWN)"); break; } } @@ -2620,7 +2620,7 @@ void tv_item_lock(typval_T *const tv, const int deep, const bool lock, const boo static int recurse = 0; if (recurse >= DICT_MAXNEST) { - EMSG(_("E743: variable nested too deep for (un)lock")); + emsg(_("E743: variable nested too deep for (un)lock")); return; } if (deep == 0) { @@ -2778,7 +2778,7 @@ bool var_check_lock(VarLockStatus lock, const char *name, size_t name_len) name_len = strlen(name); } - emsgf(_(error_message), (int)name_len, name); + semsg(_(error_message), (int)name_len, name); return true; } @@ -2896,29 +2896,29 @@ bool tv_check_str_or_nr(const typval_T *const tv) case VAR_STRING: return true; case VAR_FLOAT: - EMSG(_("E805: Expected a Number or a String, Float found")); + emsg(_("E805: Expected a Number or a String, Float found")); return false; case VAR_PARTIAL: case VAR_FUNC: - EMSG(_("E703: Expected a Number or a String, Funcref found")); + emsg(_("E703: Expected a Number or a String, Funcref found")); return false; case VAR_LIST: - EMSG(_("E745: Expected a Number or a String, List found")); + emsg(_("E745: Expected a Number or a String, List found")); return false; case VAR_DICT: - EMSG(_("E728: Expected a Number or a String, Dictionary found")); + emsg(_("E728: Expected a Number or a String, Dictionary found")); return false; case VAR_BLOB: - EMSG(_("E974: Expected a Number or a String, Blob found")); + emsg(_("E974: Expected a Number or a String, Blob found")); return false; case VAR_BOOL: - EMSG(_("E5299: Expected a Number or a String, Boolean found")); + emsg(_("E5299: Expected a Number or a String, Boolean found")); return false; case VAR_SPECIAL: - EMSG(_("E5300: Expected a Number or a String")); + emsg(_("E5300: Expected a Number or a String")); return false; case VAR_UNKNOWN: - EMSG2(_(e_intern2), "tv_check_str_or_nr(UNKNOWN)"); + semsg(_(e_intern2), "tv_check_str_or_nr(UNKNOWN)"); return false; } abort(); @@ -2963,7 +2963,7 @@ bool tv_check_num(const typval_T *const tv) case VAR_FLOAT: case VAR_BLOB: case VAR_UNKNOWN: - EMSG(_(num_errors[tv->v_type])); + emsg(_(num_errors[tv->v_type])); return false; } abort(); @@ -3008,7 +3008,7 @@ bool tv_check_str(const typval_T *const tv) case VAR_FLOAT: case VAR_BLOB: case VAR_UNKNOWN: - EMSG(_(str_errors[tv->v_type])); + emsg(_(str_errors[tv->v_type])); return false; } abort(); @@ -3055,7 +3055,7 @@ varnumber_T tv_get_number_chk(const typval_T *const tv, bool *const ret_error) case VAR_DICT: case VAR_BLOB: case VAR_FLOAT: - EMSG(_(num_errors[tv->v_type])); + emsg(_(num_errors[tv->v_type])); break; case VAR_NUMBER: return tv->vval.v_number; @@ -3072,7 +3072,7 @@ varnumber_T tv_get_number_chk(const typval_T *const tv, bool *const ret_error) case VAR_SPECIAL: return 0; case VAR_UNKNOWN: - emsgf(_(e_intern2), "tv_get_number(UNKNOWN)"); + semsg(_(e_intern2), "tv_get_number(UNKNOWN)"); break; } if (ret_error != NULL) { @@ -3119,41 +3119,53 @@ float_T tv_get_float(const typval_T *const tv) return tv->vval.v_float; case VAR_PARTIAL: case VAR_FUNC: - EMSG(_("E891: Using a Funcref as a Float")); + emsg(_("E891: Using a Funcref as a Float")); break; case VAR_STRING: - EMSG(_("E892: Using a String as a Float")); + emsg(_("E892: Using a String as a Float")); break; case VAR_LIST: - EMSG(_("E893: Using a List as a Float")); + emsg(_("E893: Using a List as a Float")); break; case VAR_DICT: - EMSG(_("E894: Using a Dictionary as a Float")); + emsg(_("E894: Using a Dictionary as a Float")); break; case VAR_BOOL: - EMSG(_("E362: Using a boolean value as a Float")); + emsg(_("E362: Using a boolean value as a Float")); break; case VAR_SPECIAL: - EMSG(_("E907: Using a special value as a Float")); + emsg(_("E907: Using a special value as a Float")); break; case VAR_BLOB: - EMSG(_("E975: Using a Blob as a Float")); + emsg(_("E975: Using a Blob as a Float")); break; case VAR_UNKNOWN: - emsgf(_(e_intern2), "tv_get_float(UNKNOWN)"); + semsg(_(e_intern2), "tv_get_float(UNKNOWN)"); break; } return 0; } -// Give an error and return FAIL unless "tv" is a non-empty string. +// Give an error and return FAIL unless "tv" is a string. int tv_check_for_string(const typval_T *const tv) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE { - if (tv->v_type != VAR_STRING - || tv->vval.v_string == NULL - || *tv->vval.v_string == NUL) { - EMSG(_(e_stringreq)); + if (tv->v_type != VAR_STRING) { + emsg(_(e_stringreq)); + return FAIL; + } + return OK; +} + +// Give an error and return FAIL unless "tv" is a non-empty string. +int tv_check_for_nonempty_string(const typval_T *const tv) + FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE +{ + if (tv_check_for_string(tv) == FAIL) { + return FAIL; + } + if (tv->vval.v_string == NULL || *tv->vval.v_string == NUL) { + emsg(_(e_non_empty_string_required)); return FAIL; } return OK; @@ -3195,7 +3207,7 @@ const char *tv_get_string_buf_chk(const typval_T *const tv, char *const buf) case VAR_FLOAT: case VAR_BLOB: case VAR_UNKNOWN: - EMSG(_(str_errors[tv->v_type])); + emsg(_(str_errors[tv->v_type])); return false; } return NULL; diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h index a28feffd0b..69732f1a7d 100644 --- a/src/nvim/eval/typval.h +++ b/src/nvim/eval/typval.h @@ -30,7 +30,7 @@ typedef uint64_t uvarnumber_T; typedef double float_T; /// Refcount for dict or list that should not be freed -enum { DO_NOT_FREE_CNT = (INT_MAX / 2) }; +enum { DO_NOT_FREE_CNT = (INT_MAX / 2), }; /// Additional values for tv_list_alloc() len argument enum ListLenSpecials { @@ -831,7 +831,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) /// Iterate over a list /// @@ -893,7 +893,7 @@ static inline bool tv_get_float_chk(const typval_T *const tv, REAL_FATTR_NONNULL_ALL REAL_FATTR_WARN_UNUSED_RESULT; // FIXME circular dependency, cannot import message.h. -bool emsgf(const char *const fmt, ...); +bool semsg(const char *const fmt, ...); /// Get the float value /// @@ -913,7 +913,7 @@ static inline bool tv_get_float_chk(const typval_T *const tv, float_T *const ret *ret_f = (float_T)tv->vval.v_number; return true; } - emsgf("%s", _("E808: Number or Float required")); + semsg("%s", _("E808: Number or Float required")); return false; } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 3c7532df7b..6fe75e5e1f 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -103,7 +103,7 @@ static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, i || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)) { if (!skip) { - EMSG2(_("E125: Illegal argument: %s"), arg); + semsg(_("E125: Illegal argument: %s"), arg); } break; } @@ -116,7 +116,7 @@ static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, i // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; i++) { if (STRCMP(((char_u **)(newargs->ga_data))[i], arg) == 0) { - EMSG2(_("E853: Duplicate argument name: %s"), arg); + semsg(_("E853: Duplicate argument name: %s"), arg); xfree(arg); goto err_ret; } @@ -151,7 +151,7 @@ static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, i mustend = true; } } else if (any_default) { - EMSG(_("E989: Non-default argument follows default argument")); + emsg(_("E989: Non-default argument follows default argument")); mustend = true; } if (*p == ',') { @@ -163,7 +163,7 @@ static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, i p = skipwhite(p); if (mustend && *p != endchar) { if (!skip) { - EMSG2(_(e_invarg2), *argp); + semsg(_(e_invarg2), *argp); } break; } @@ -395,7 +395,7 @@ void emsg_funcname(char *ermsg, const char_u *name) p = (char_u *)name; } - EMSG2(_(ermsg), p); + semsg(_(ermsg), p); if (p != name) { xfree(p); @@ -829,7 +829,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett // If depth of calling is getting too high, don't execute the function if (depth >= p_mfd) { - EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'")); + emsg(_("E132: Function call depth is higher than 'maxfuncdepth'")); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; @@ -1244,7 +1244,7 @@ void save_funccal(funccal_entry_T *entry) void restore_funccal(void) { if (funccal_stack == NULL) { - IEMSG("INTERNAL: restore_funccal()"); + iemsg("INTERNAL: restore_funccal()"); } else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; @@ -1360,7 +1360,7 @@ int func_call(char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict TV_LIST_ITER(args->vval.v_list, item, { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { - EMSG(_("E699: Too many arguments")); + emsg(_("E699: Too many arguments")); goto func_call_skip_call; } // Make a copy of each argument. This is needed to be able to set @@ -1635,11 +1635,11 @@ static void list_func_head(ufunc_T *fp, int indent, bool force) { msg_start(); if (indent) { - MSG_PUTS(" "); + msg_puts(" "); } - MSG_PUTS(force ? "function! " : "function "); + msg_puts(force ? "function! " : "function "); if (fp->uf_name[0] == K_SPECIAL) { - MSG_PUTS_ATTR("<SNR>", HL_ATTR(HLF_8)); + msg_puts_attr("<SNR>", HL_ATTR(HLF_8)); msg_puts((const char *)fp->uf_name + 3); } else { msg_puts((const char *)fp->uf_name); @@ -1732,7 +1732,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) { - EMSG(_("E129: Function name required")); + emsg(_("E129: Function name required")); } goto theend; } @@ -1744,7 +1744,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, */ if (!aborting()) { if (end != NULL) { - emsgf(_(e_invarg2), start); + semsg(_(e_invarg2), start); } } else { *pp = (char_u *)find_name_end(start, NULL, NULL, FNE_INCL_BR); @@ -1767,7 +1767,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, if (is_luafunc(lv.ll_tv->vval.v_partial) && *end == '.') { len = check_luafunc_name((const char *)end+1, true); if (len == 0) { - EMSG2(e_invexpr2, "v:lua"); + semsg(e_invexpr2, "v:lua"); goto theend; } name = xmallocz(len); @@ -1784,7 +1784,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) { - EMSG(_(e_funcref)); + emsg(_(e_funcref)); } else { *pp = (char_u *)end; } @@ -1862,7 +1862,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, || eval_fname_sid((const char *)(*pp))) { // It's "s:" or "<SID>". if (current_sctx.sc_sid <= 0) { - EMSG(_(e_usingsid)); + emsg(_(e_usingsid)); goto theend; } sid_buf_len = snprintf(sid_buf, sizeof(sid_buf), @@ -1871,7 +1871,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, } } else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, lv.ll_name_len)) { - EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"), + semsg(_("E128: Function name must start with a capital or \"s:\": %s"), start); goto theend; } @@ -1880,7 +1880,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp, char_u *cp = xmemrchr(lv.ll_name, ':', lv.ll_name_len); if (cp != NULL && cp < end) { - EMSG2(_("E884: Function name cannot contain a colon: %s"), start); + semsg(_("E884: Function name cannot contain a colon: %s"), start); goto theend; } } @@ -2025,7 +2025,7 @@ void ex_function(exarg_T *eap) */ if (!aborting()) { if (fudi.fd_newkey != NULL) { - EMSG2(_(e_dictkey), fudi.fd_newkey); + semsg(_(e_dictkey), fudi.fd_newkey); } xfree(fudi.fd_newkey); return; @@ -2047,7 +2047,7 @@ void ex_function(exarg_T *eap) // if (!paren) { if (!ends_excmd(*skipwhite(p))) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); goto ret_free; } eap->nextcmd = check_nextcmd(p); @@ -2093,7 +2093,7 @@ void ex_function(exarg_T *eap) p = skipwhite(p); if (*p != '(') { if (!eap->skip) { - EMSG2(_("E124: Missing '(': %s"), eap->arg); + semsg(_("E124: Missing '(': %s"), eap->arg); goto ret_free; } // attempt to continue by skipping some text @@ -2126,7 +2126,7 @@ void ex_function(exarg_T *eap) } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { - EMSG(_("E862: Cannot use g: here")); + emsg(_("E862: Cannot use g: here")); } } @@ -2171,7 +2171,7 @@ void ex_function(exarg_T *eap) if (*p == '\n') { line_arg = p + 1; } else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } /* @@ -2183,7 +2183,7 @@ void ex_function(exarg_T *eap) // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) { - EMSG(_(e_funcdict)); + emsg(_(e_funcdict)); } else if (name != NULL && find_func(name) != NULL) { emsg_funcname(e_funcexts, name); } @@ -2234,7 +2234,7 @@ void ex_function(exarg_T *eap) lines_left = Rows - 1; } if (theline == NULL) { - EMSG(_("E126: Missing :endfunction")); + emsg(_("E126: Missing :endfunction")); goto erret; } if (show_block) { @@ -2349,7 +2349,7 @@ void ex_function(exarg_T *eap) // heredoc: Check for ":python <<EOF", ":lua <<EOF", etc. arg = skipwhite(skiptowhite(p)); - if (arg[0] == '<' && arg[1] =='<' + if (arg[0] == '<' && arg[1] == '<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') @@ -2383,7 +2383,7 @@ void ex_function(exarg_T *eap) arg = skipwhite(skiptowhite(arg)); if (arg[0] == '=' && arg[1] == '<' - && arg[2] =='<' + && arg[2] == '<' && (p[0] == 'l' && p[1] == 'e' && (!ASCII_ISALNUM(p[2]) @@ -2475,7 +2475,7 @@ void ex_function(exarg_T *eap) fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { - EMSG(_(e_funcdict)); + emsg(_(e_funcdict)); goto erret; } if (fudi.fd_di == NULL) { @@ -2516,7 +2516,7 @@ void ex_function(exarg_T *eap) xfree(scriptname); } if (j == FAIL) { - EMSG2(_("E746: Function name does not match script file name: %s"), + semsg(_("E746: Function name does not match script file name: %s"), name); goto erret; } @@ -2709,13 +2709,13 @@ void ex_delfunction(exarg_T *eap) xfree(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) { - EMSG(_(e_funcref)); + emsg(_(e_funcref)); } return; } if (!ends_excmd(*skipwhite(p))) { xfree(name); - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return; } eap->nextcmd = check_nextcmd(p); @@ -2731,18 +2731,18 @@ void ex_delfunction(exarg_T *eap) if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) { - EMSG2(_(e_nofunc), eap->arg); + semsg(_(e_nofunc), eap->arg); } return; } if (fp->uf_calls > 0) { - EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg); + semsg(_("E131: Cannot delete function %s: It is in use"), eap->arg); return; } // check `uf_refcount > 2` because deleting a function should also reduce // the reference count, and 1 is the initial refcount. if (fp->uf_refcount > 2) { - EMSG2(_("Cannot delete function %s: It is being used internally"), + semsg(_("Cannot delete function %s: It is being used internally"), eap->arg); return; } @@ -2878,7 +2878,7 @@ void ex_return(exarg_T *eap) int returning = FALSE; if (current_funccal == NULL) { - EMSG(_("E133: :return not inside a function")); + emsg(_("E133: :return not inside a function")); return; } @@ -2953,7 +2953,7 @@ void ex_call(exarg_T *eap) tofree = trans_function_name(&arg, false, TFN_INT, &fudi, &partial); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. - EMSG2(_(e_dictkey), fudi.fd_newkey); + semsg(_(e_dictkey), fudi.fd_newkey); xfree(fudi.fd_newkey); } if (tofree == NULL) { @@ -2979,7 +2979,7 @@ void ex_call(exarg_T *eap) rettv.v_type = VAR_UNKNOWN; // tv_clear() uses this. if (*startarg != '(') { - EMSG2(_(e_missingparen), eap->arg); + semsg(_(e_missingparen), eap->arg); goto end; } @@ -2989,7 +2989,7 @@ void ex_call(exarg_T *eap) if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. - EMSG(_(e_invrange)); + emsg(_(e_invrange)); break; } curwin->w_cursor.lnum = lnum; @@ -3038,7 +3038,7 @@ void ex_call(exarg_T *eap) if (!ends_excmd(*arg)) { if (!failed) { emsg_severe = true; - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } } else { eap->nextcmd = check_nextcmd(arg); diff --git a/src/nvim/event/process.h b/src/nvim/event/process.h index 2b22cd95dc..c20feb2c7a 100644 --- a/src/nvim/event/process.h +++ b/src/nvim/event/process.h @@ -8,7 +8,7 @@ typedef enum { kProcessTypeUv, - kProcessTypePty + kProcessTypePty, } ProcessType; typedef struct process Process; diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 17ab138d75..1bd9411fa5 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -14,8 +14,8 @@ #include <string.h> #include "nvim/api/buffer.h" -#include "nvim/api/private/defs.h" #include "nvim/api/extmark.h" +#include "nvim/api/private/defs.h" #include "nvim/ascii.h" #include "nvim/buffer.h" #include "nvim/buffer_updates.h" @@ -120,7 +120,7 @@ void do_ascii(const exarg_T *const eap) int cc[MAX_MCO]; int c = utfc_ptr2char(get_cursor_pos_ptr(), cc); if (c == NUL) { - MSG("NUL"); + msg("NUL"); return; } @@ -222,7 +222,7 @@ void do_ascii(const exarg_T *const eap) xstrlcpy((char *)IObuff + iobuff_len, " ...", sizeof(IObuff) - iobuff_len); } - msg(IObuff); + msg((char *)IObuff); } /* @@ -303,8 +303,9 @@ void ex_align(exarg_T *eap) * Now try to move the line as much as possible to * the right. Stop when it moves too far. */ - do + do{ (void)set_indent(++new_indent, 0); + } while (linelen(NULL) <= width); --new_indent; break; @@ -522,14 +523,14 @@ void ex_sort(exarg_T *eap) } else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL) { s = skip_regexp(p + 1, *p, true, NULL); if (*s != *p) { - EMSG(_(e_invalpat)); + emsg(_(e_invalpat)); goto sortend; } *s = NUL; // Use last search pattern if sort pattern is empty. if (s == p + 1) { if (last_search_pat() == NULL) { - EMSG(_(e_noprevre)); + emsg(_(e_noprevre)); goto sortend; } regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC); @@ -542,14 +543,14 @@ void ex_sort(exarg_T *eap) p = s; // continue after the regexp regmatch.rm_ic = p_ic; } else { - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); goto sortend; } } // Can only have one of 'n', 'b', 'o' and 'x'. if (format_found > 1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); goto sortend; } @@ -719,7 +720,7 @@ sortend: xfree(sortbuf2); vim_regfree(regmatch.regprog); if (got_int) { - EMSG(_(e_interr)); + emsg(_(e_interr)); } } @@ -855,7 +856,7 @@ void ex_retab(exarg_T *eap) line_breakcheck(); } if (got_int) { - EMSG(_(e_interr)); + emsg(_(e_interr)); } // If a single value was given then it can be considered equal to @@ -913,7 +914,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) linenr_T last_line; // Last line in file after adding new text if (dest >= line1 && dest < line2) { - EMSG(_("E134: Cannot move a range of lines into itself")); + emsg(_("E134: Cannot move a range of lines into itself")); return FAIL; } @@ -1014,11 +1015,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) ml_delete(line1 + extra, true); } if (!global_busy && num_lines > p_report) { - if (num_lines == 1) { - MSG(_("1 line moved")); - } else { - smsg(_("%" PRId64 " lines moved"), (int64_t)num_lines); - } + smsg(NGETTEXT("1 line moved", "%" PRId64 " lines moved", num_lines), (int64_t)num_lines); } extmark_move_region(curbuf, line1-1, 0, start_byte, @@ -1163,7 +1160,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out } if (ins_prevcmd) { if (prevcmd == NULL) { - EMSG(_(e_noprev)); + emsg(_(e_noprev)); xfree(newcmd); return; } @@ -1322,7 +1319,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, curwin->w_cursor.lnum = line2; } else if ((do_in && (itmp = vim_tempname()) == NULL) || (do_out && (otmp = vim_tempname()) == NULL)) { - EMSG(_(e_notmp)); + emsg(_(e_notmp)); goto filterend; } @@ -1336,7 +1333,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, msg_putchar('\n'); // Keep message from buf_write(). no_wait_return--; if (!aborting()) { - EMSG2(_("E482: Can't create file %s"), itmp); // Will call wait_return. + semsg(_("E482: Can't create file %s"), itmp); // Will call wait_return. } goto filterend; } @@ -1380,7 +1377,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, READ_FILTER) != OK) { if (!aborting()) { msg_putchar('\n'); - EMSG2(_(e_notread), otmp); + semsg(_(e_notread), otmp); } goto error; } @@ -1441,7 +1438,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, if (do_in) { vim_snprintf(msg_buf, sizeof(msg_buf), _("%" PRId64 " lines filtered"), (int64_t)linecount); - if (msg((char_u *)msg_buf) && !msg_scroll) { + if (msg(msg_buf) && !msg_scroll) { // save message to display it after redraw set_keep_msg((char_u *)msg_buf, 0); } @@ -1461,7 +1458,7 @@ filterend: if (curbuf != old_curbuf) { --no_wait_return; - EMSG(_("E135: *Filter* Autocommands must not change current buffer")); + emsg(_("E135: *Filter* Autocommands must not change current buffer")); } if (itmp != NULL) { os_remove((char *)itmp); @@ -1500,7 +1497,7 @@ void do_shell(char_u *cmd, int flags) && msg_silent == 0) { FOR_ALL_BUFFERS(buf) { if (bufIsChanged(buf)) { - MSG_PUTS(_("[No write since last change]\n")); + msg_puts(_("[No write since last change]\n")); break; } } @@ -1739,7 +1736,7 @@ void ex_file(exarg_T *eap) && (*eap->arg != NUL || eap->line2 > 0 || eap->addr_count > 1)) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1809,7 +1806,7 @@ int do_write(exarg_T *eap) ffname = eap->arg; if (*ffname == NUL) { if (eap->cmdidx == CMD_saveas) { - EMSG(_(e_argreq)); + emsg(_(e_argreq)); goto theend; } other = FALSE; @@ -1839,7 +1836,7 @@ int do_write(exarg_T *eap) if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL) { // Overwriting a file that is loaded in another buffer is not a // good idea. - EMSG(_(e_bufloaded)); + emsg(_(e_bufloaded)); goto theend; } } @@ -1859,11 +1856,11 @@ int do_write(exarg_T *eap) /* * Not writing the whole file is only allowed with '!'. */ - if ( (eap->line1 != 1 - || eap->line2 != curbuf->b_ml.ml_line_count) - && !eap->forceit - && !eap->append - && !p_wa) { + if ((eap->line1 != 1 + || eap->line2 != curbuf->b_ml.ml_line_count) + && !eap->forceit + && !eap->append + && !p_wa) { if (p_confirm || cmdmod.confirm) { if (vim_dialog_yesno(VIM_QUESTION, NULL, (char_u *)_("Write partial file?"), 2) != VIM_YES) { @@ -1871,7 +1868,7 @@ int do_write(exarg_T *eap) } eap->forceit = TRUE; } else { - EMSG(_("E140: Use ! to write partial buffer")); + emsg(_("E140: Use ! to write partial buffer")); goto theend; } } @@ -1979,7 +1976,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int #ifdef UNIX // It is possible to open a directory on Unix. if (os_isdir(ffname)) { - EMSG2(_(e_isadir2), ffname); + semsg(_(e_isadir2), ffname); return FAIL; } #endif @@ -1992,7 +1989,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int } eap->forceit = TRUE; } else { - EMSG(_(e_exists)); + emsg(_(e_exists)); return FAIL; } } @@ -2032,7 +2029,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int } eap->forceit = TRUE; } else { - EMSG2(_("E768: Swap file exists: %s (:silent! overrides)"), + semsg(_("E768: Swap file exists: %s (:silent! overrides)"), swapname); xfree(swapname); return FAIL; @@ -2096,7 +2093,7 @@ void do_wqall(exarg_T *eap) break; } if (buf->b_ffname == NULL) { - EMSGN(_("E141: No file name for buffer %" PRId64), buf->b_fnum); + semsg(_("E141: No file name for buffer %" PRId64), (int64_t)buf->b_fnum); ++error; } else if (check_readonly(&eap->forceit, buf) || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname, @@ -2132,7 +2129,7 @@ int not_writing(void) if (p_write) { return FALSE; } - EMSG(_("E142: File not written: Writing is disabled by 'write' option")); + emsg(_("E142: File not written: Writing is disabled by 'write' option")); return TRUE; } @@ -2170,9 +2167,9 @@ static int check_readonly(int *forceit, buf_T *buf) return TRUE; } } else if (buf->b_p_ro) { - EMSG(_(e_readonly)); + emsg(_(e_readonly)); } else { - EMSG2(_("E505: \"%s\" is read-only (add ! to override)"), + semsg(_("E505: \"%s\" is read-only (add ! to override)"), buf->b_fname); } return TRUE; @@ -2901,7 +2898,7 @@ theend: static void delbuf_msg(char_u *name) { - EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"), + semsg(_("E143: Autocommands unexpectedly deleted new buffer %s"), name == NULL ? (char_u *)"" : name); xfree(name); au_new_curbuf.br_buf = NULL; @@ -3116,7 +3113,7 @@ void ex_z(exarg_T *eap) if (*x != 0) { if (!ascii_isdigit(*x)) { - EMSG(_("E144: non-numeric argument to :z")); + emsg(_("E144: non-numeric argument to :z")); return; } bigness = atol((char *)x); @@ -3135,7 +3132,6 @@ void ex_z(exarg_T *eap) // the number of '-' and '+' multiplies the distance if (*kind == '-' || *kind == '+') { for (x = kind + 1; *x == *kind; ++x) { - ; } } @@ -3227,14 +3223,14 @@ int check_secure(void) { if (secure) { secure = 2; - EMSG(_(e_curdir)); + emsg(_(e_curdir)); return TRUE; } // In the sandbox more things are not allowed, including the things // disallowed in secure mode. if (sandbox != 0) { - EMSG(_(e_sandbox)); + emsg(_(e_sandbox)); return TRUE; } return FALSE; @@ -3430,7 +3426,7 @@ static int check_regexp_delim(int c) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { if (isalpha(c)) { - EMSG(_("E146: Regular expressions can't be delimited by letters")); + emsg(_("E146: Regular expressions can't be delimited by letters")); return FAIL; } return OK; @@ -3509,7 +3505,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle if (*cmd == '\\') { ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { - EMSG(_(e_backslash)); + emsg(_(e_backslash)); return NULL; } if (*cmd != '&') { @@ -3555,7 +3551,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle } } else if (!eap->skip) { // use previous pattern and substitution if (old_sub.sub == NULL) { // there is no previous command - EMSG(_(e_nopresub)); + emsg(_(e_nopresub)); return NULL; } pat = NULL; // search_regcomp() will use previous pattern @@ -3580,7 +3576,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle if (ascii_isdigit(*cmd)) { i = getdigits_long(&cmd, true, 0); if (i <= 0 && !eap->skip && subflags.do_error) { - EMSG(_(e_zerocount)); + emsg(_(e_zerocount)); return NULL; } eap->line1 = eap->line2; @@ -3597,7 +3593,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle if (*cmd && *cmd != '"') { // if not end-of-line or comment eap->nextcmd = check_nextcmd(cmd); if (eap->nextcmd == NULL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return NULL; } } @@ -3608,14 +3604,14 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle if (!subflags.do_count && !MODIFIABLE(curbuf)) { // Substitution is not allowed in non-'modifiable' buffer - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); return NULL; } if (search_regcomp(pat, RE_SUBST, which_pat, (preview ? 0 : SEARCH_HIS), ®match) == FAIL) { if (subflags.do_error) { - EMSG(_(e_invcmd)); + emsg(_(e_invcmd)); } return NULL; } @@ -4370,7 +4366,7 @@ skip: } } if (!preview && !do_sub_msg(subflags.do_count) && subflags.do_ask) { - MSG(""); + msg(""); } } else { global_need_beginline = true; @@ -4381,13 +4377,13 @@ skip: } else if (!global_busy) { if (got_int) { // interrupted - EMSG(_(e_interr)); + emsg(_(e_interr)); } else if (got_match) { // did find something but nothing substituted - MSG(""); + msg(""); } else if (subflags.do_error) { // nothing found - EMSG2(_(e_patnotf2), get_search_pat()); + semsg(_(e_patnotf2), get_search_pat()); } } @@ -4409,7 +4405,7 @@ skip: if (got_quit || profile_passed_limit(timeout)) { // Too slow, disable. set_string_option_direct("icm", -1, (char_u *)"", OPT_FREE, SID_NONE); - } else if (*p_icm != NUL && pat != NULL) { + } else if (*p_icm != NUL && pat != NULL) { if (pre_src_id == 0) { // Get a unique new src_id, saved in a static pre_src_id = (int)nvim_create_namespace((String)STRING_INIT); @@ -4456,30 +4452,28 @@ bool do_sub_msg(bool count_only) } else { *msg_buf = NUL; } - if (sub_nsubs == 1) { - vim_snprintf_add(msg_buf, sizeof(msg_buf), - "%s", count_only ? _("1 match") : _("1 substitution")); - } else { - vim_snprintf_add(msg_buf, sizeof(msg_buf), - count_only ? _("%" PRId64 " matches") - : _("%" PRId64 " substitutions"), - (int64_t)sub_nsubs); - } - if (sub_nlines == 1) { - vim_snprintf_add(msg_buf, sizeof(msg_buf), - "%s", _(" on 1 line")); - } else { - vim_snprintf_add(msg_buf, sizeof(msg_buf), - _(" on %" PRId64 " lines"), (int64_t)sub_nlines); - } - if (msg((char_u *)msg_buf)) { + + char *msg_single = count_only + ? NGETTEXT("%" PRId64 " match on %" PRId64 " line", + "%" PRId64 " matches on %" PRId64 " line", sub_nsubs) + : NGETTEXT("%" PRId64 " substitution on %" PRId64 " line", + "%" PRId64 " substitutions on %" PRId64 " line", sub_nsubs); + char *msg_plural = count_only + ? NGETTEXT("%" PRId64 " match on %" PRId64 " lines", + "%" PRId64 " matches on %" PRId64 " lines", sub_nsubs) + : NGETTEXT("%" PRId64 " substitution on %" PRId64 " lines", + "%" PRId64 " substitutions on %" PRId64 " lines", sub_nsubs); + vim_snprintf_add((char *)msg_buf, sizeof(msg_buf), + NGETTEXT(msg_single, msg_plural, sub_nlines), + (int64_t)sub_nsubs, (int64_t)sub_nlines); + if (msg(msg_buf)) { // save message to display it after redraw set_keep_msg((char_u *)msg_buf, 0); } return true; } if (got_int) { - EMSG(_(e_interr)); + emsg(_(e_interr)); return true; } return false; @@ -4530,7 +4524,7 @@ void ex_global(exarg_T *eap) if (global_busy && (eap->line1 != 1 || eap->line2 != curbuf->b_ml.ml_line_count)) { // will increment global_busy to break out of the loop - EMSG(_("E147: Cannot do :global recursive with a range")); + emsg(_("E147: Cannot do :global recursive with a range")); return; } @@ -4550,7 +4544,7 @@ void ex_global(exarg_T *eap) if (*cmd == '\\') { ++cmd; if (vim_strchr((char_u *)"/?&", *cmd) == NULL) { - EMSG(_(e_backslash)); + emsg(_(e_backslash)); return; } if (*cmd == '&') { @@ -4561,7 +4555,7 @@ void ex_global(exarg_T *eap) ++cmd; pat = (char_u *)""; } else if (*cmd == NUL) { - EMSG(_("E148: Regular expression missing from global")); + emsg(_("E148: Regular expression missing from global")); return; } else if (check_regexp_delim(*cmd) == FAIL) { return; @@ -4578,7 +4572,7 @@ void ex_global(exarg_T *eap) } if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, ®match) == FAIL) { - EMSG(_(e_invcmd)); + emsg(_(e_invcmd)); return; } @@ -4604,7 +4598,7 @@ void ex_global(exarg_T *eap) // pass 2: execute the command for each line that has been marked if (got_int) { - MSG(_(e_interr)); + msg(_(e_interr)); } else if (ndone == 0) { if (type == 'v') { smsg(_("Pattern found in every line: %s"), pat); @@ -4724,7 +4718,6 @@ bool prepare_tagpreview(bool undo_sync) } - /* * ":help": open a read-only window on a help file */ @@ -4762,7 +4755,7 @@ void ex_help(exarg_T *eap) arg = eap->arg; if (eap->forceit && *arg == NUL && !curbuf->b_help) { - EMSG(_("E478: Don't panic!")); + emsg(_("E478: Don't panic!")); return; } @@ -4806,9 +4799,9 @@ void ex_help(exarg_T *eap) } if (i >= num_matches || n == FAIL) { if (lang != NULL) { - EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg); + semsg(_("E661: Sorry, no '%s' help for %s"), lang, arg); } else { - EMSG2(_("E149: Sorry, no help for %s"), arg); + semsg(_("E149: Sorry, no help for %s"), arg); } if (n != FAIL) { FreeWild(num_matches, matches); @@ -5175,7 +5168,7 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, bool // If tag contains "({" or "([", tag terminates at the "(". // This is for help on functions, e.g.: abs({expr}). - if (*s == '(' && (s[1] == '{' || s[1] =='[')) { + if (*s == '(' && (s[1] == '{' || s[1] == '[')) { break; } @@ -5350,7 +5343,7 @@ void fix_help_buffer(void) if (!add_pathsep((char *)NameBuff) || STRLCAT(NameBuff, "doc/*.??[tx]", sizeof(NameBuff)) >= MAXPATHL) { - EMSG(_(e_fnametoolong)); + emsg(_(e_fnametoolong)); continue; } @@ -5511,7 +5504,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, if (dirlen >= MAXPATHL || STRLCAT(NameBuff, "/**/*", sizeof(NameBuff)) >= MAXPATHL // NOLINT || STRLCAT(NameBuff, ext, sizeof(NameBuff)) >= MAXPATHL) { - EMSG(_(e_fnametoolong)); + emsg(_(e_fnametoolong)); return; } @@ -5522,7 +5515,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, EW_FILE|EW_SILENT) == FAIL || filecount == 0) { if (!got_int) { - EMSG2(_("E151: No match: %s"), NameBuff); + semsg(_("E151: No match: %s"), NameBuff); } return; } @@ -5534,14 +5527,14 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, memcpy(NameBuff, dir, dirlen + 1); if (!add_pathsep((char *)NameBuff) || STRLCAT(NameBuff, tagfname, sizeof(NameBuff)) >= MAXPATHL) { - EMSG(_(e_fnametoolong)); + emsg(_(e_fnametoolong)); return; } FILE *const fd_tags = os_fopen((char *)NameBuff, "w"); if (fd_tags == NULL) { if (!ignore_writeerr) { - EMSG2(_("E152: Cannot open %s for writing"), NameBuff); + semsg(_("E152: Cannot open %s for writing"), NameBuff); } FreeWild(filecount, files); return; @@ -5563,7 +5556,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, for (int fi = 0; fi < filecount && !got_int; fi++) { FILE *const fd = os_fopen((char *)files[fi], "r"); if (fd == NULL) { - EMSG2(_("E153: Unable to open %s for reading"), files[fi]); + semsg(_("E153: Unable to open %s for reading"), files[fi]); continue; } const char_u *const fname = files[fi] + dirlen + 1; @@ -5591,7 +5584,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, if (utf8 == kNone) { // first file utf8 = this_utf8; } else if (utf8 != this_utf8) { - EMSG2(_("E670: Mix of help file encodings within a language: %s"), + semsg(_("E670: Mix of help file encodings within a language: %s"), files[fi]); mix = !got_int; got_int = TRUE; @@ -5650,7 +5643,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, vim_snprintf((char *)NameBuff, MAXPATHL, _("E154: Duplicate tag \"%s\" in file %s/%s"), ((char_u **)ga.ga_data)[i], dir, p2 + 1); - EMSG(NameBuff); + emsg((char *)NameBuff); *p2 = '\t'; break; } @@ -5706,7 +5699,7 @@ static void do_helptags(char_u *dirname, bool add_help_tags, bool ignore_writeer STRLCPY(NameBuff, dirname, sizeof(NameBuff)); if (!add_pathsep((char *)NameBuff) || STRLCAT(NameBuff, "**", sizeof(NameBuff)) >= MAXPATHL) { - EMSG(_(e_fnametoolong)); + emsg(_(e_fnametoolong)); return; } @@ -5716,7 +5709,7 @@ static void do_helptags(char_u *dirname, bool add_help_tags, bool ignore_writeer if (gen_expand_wildcards(1, buff_list, &filecount, &files, EW_FILE|EW_SILENT) == FAIL || filecount == 0) { - EMSG2(_("E151: No match: %s"), NameBuff); + semsg(_("E151: No match: %s"), NameBuff); return; } @@ -5811,7 +5804,7 @@ void ex_helptags(exarg_T *eap) dirname = ExpandOne(&xpc, eap->arg, NULL, WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE); if (dirname == NULL || !os_isdir(dirname)) { - EMSG2(_("E150: Not a directory: %s"), eap->arg); + semsg(_("E150: Not a directory: %s"), eap->arg); } else { do_helptags(dirname, add_help_tags, false); } @@ -6132,7 +6125,7 @@ void ex_oldfiles(exarg_T *eap) long nr = 0; if (l == NULL) { - msg((char_u *)_("No old files")); + msg(_("No old files")); } else { msg_start(); msg_scroll = true; @@ -6144,7 +6137,7 @@ void ex_oldfiles(exarg_T *eap) const char *fname = tv_get_string(TV_LIST_ITEM_TV(li)); if (!message_filtered((char_u *)fname)) { msg_outnum(nr); - MSG_PUTS(": "); + msg_puts(": "); msg_outtrans((char_u *)tv_get_string(TV_LIST_ITEM_TV(li))); msg_clr_eos(); msg_putchar('\n'); diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c index 5d40d7a16a..f1d0cbc8bd 100644 --- a/src/nvim/ex_cmds2.c +++ b/src/nvim/ex_cmds2.c @@ -110,7 +110,7 @@ void ex_profile(exarg_T *eap) profile_set_wait(profile_zero()); set_vim_var_nr(VV_PROFILING, 1L); } else if (do_profiling == PROF_NONE) { - EMSG(_("E750: First use \":profile start {fname}\"")); + emsg(_("E750: First use \":profile start {fname}\"")); } else if (STRCMP(eap->arg, "stop") == 0) { profile_dump(); do_profiling = PROF_NONE; @@ -198,7 +198,7 @@ void ex_perldo(exarg_T *eap) // Command line expansion for :profile. static enum { PEXP_SUBCMD, ///< expand :profile sub-commands - PEXP_FUNC ///< expand :profile func {funcname} + PEXP_FUNC, ///< expand :profile func {funcname} } pexpand_what; static char *pexpand_cmds[] = { @@ -256,7 +256,7 @@ void profile_dump(void) if (profile_fname != NULL) { fd = os_fopen((char *)profile_fname, "w"); if (fd == NULL) { - EMSG2(_(e_notopen), profile_fname); + semsg(_(e_notopen), profile_fname); } else { script_dump_profile(fd); func_dump_profile(fd); @@ -550,7 +550,6 @@ bool check_changed(buf_T *buf, int flags) } - /// Ask the user what to do when abandoning a changed buffer. /// Must check 'write' option first! /// @@ -749,8 +748,8 @@ bool check_changed_any(bool hidden, bool unload) msg_didout = false; } if ((buf->terminal && channel_job_running((uint64_t)buf->b_p_channel)) - ? EMSG2(_("E947: Job still running in buffer \"%s\""), buf->b_fname) - : EMSG2(_("E162: No write since last change for buffer \"%s\""), + ? semsg(_("E947: Job still running in buffer \"%s\""), buf->b_fname) + : semsg(_("E162: No write since last change for buffer \"%s\""), buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname)) { save = no_wait_return; no_wait_return = false; @@ -791,7 +790,7 @@ theend: int check_fname(void) { if (curbuf->b_ffname == NULL) { - EMSG(_(e_noname)); + emsg(_(e_noname)); return FAIL; } return OK; @@ -810,7 +809,7 @@ int buf_write_all(buf_T *buf, int forceit) false, forceit, true, false)); if (curbuf != old_curbuf) { msg_source(HL_ATTR(HLF_W)); - MSG(_("Warning: Entered other buffer unexpectedly (check autocommands)")); + msg(_("Warning: Entered other buffer unexpectedly (check autocommands)")); } return retval; } @@ -965,7 +964,7 @@ static int do_arglist(char_u *str, int what, int after, bool will_edit) vim_regfree(regmatch.regprog); xfree(p); if (!didone) { - EMSG2(_(e_nomatch2), ((char_u **)new_ga.ga_data)[i]); + semsg(_(e_nomatch2), ((char_u **)new_ga.ga_data)[i]); } } ga_clear(&new_ga); @@ -975,7 +974,7 @@ static int do_arglist(char_u *str, int what, int after, bool will_edit) EW_DIR|EW_FILE|EW_ADDSLASH|EW_NOTFOUND); ga_clear(&new_ga); if (i == FAIL || exp_count == 0) { - EMSG(_(e_nomatch)); + emsg(_(e_nomatch)); return FAIL; } @@ -1136,11 +1135,11 @@ void do_argfile(exarg_T *eap, int argn) if (argn < 0 || argn >= ARGCOUNT) { if (ARGCOUNT <= 1) { - EMSG(_("E163: There is only one file to edit")); + emsg(_("E163: There is only one file to edit")); } else if (argn < 0) { - EMSG(_("E164: Cannot go before first file")); + emsg(_("E164: Cannot go before first file")); } else { - EMSG(_("E165: Cannot go beyond last file")); + emsg(_("E165: Cannot go beyond last file")); } } else { setpcmark(); @@ -1253,7 +1252,7 @@ void ex_argdelete(exarg_T *eap) // ":argdel" works like ":.argdel" if (eap->addr_count == 0) { if (curwin->w_arg_idx >= ARGCOUNT) { - EMSG(_("E610: No argument to delete")); + emsg(_("E610: No argument to delete")); return; } eap->line1 = eap->line2 = curwin->w_arg_idx + 1; @@ -1264,11 +1263,11 @@ void ex_argdelete(exarg_T *eap) linenr_T n = eap->line2 - eap->line1 + 1; if (*eap->arg != NUL) { // Can't have both a range and an argument. - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else if (n <= 0) { // Don't give an error for ":%argdel" if the list is empty. if (eap->line1 != 1 || eap->line2 != 0) { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); } } else { for (linenr_T i = eap->line1; i <= eap->line2; i++) { @@ -1618,7 +1617,7 @@ void ex_compiler(exarg_T *eap) // Try lua compiler snprintf((char *)buf, bufsize, "compiler/%s.lua", eap->arg); if (source_runtime((char *)buf, DIP_ALL) == FAIL) { - EMSG2(_("E666: compiler not supported: %s"), eap->arg); + semsg(_("E666: compiler not supported: %s"), eap->arg); } } xfree(buf); @@ -1798,7 +1797,7 @@ static void cmd_source(char_u *fname, exarg_T *eap) // ":source" read ex commands } else if (do_source((char *)fname, false, DOSO_NONE) == FAIL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); } } @@ -2252,7 +2251,7 @@ int do_source(char *fname, int check_other, int is_vimrc) } if (got_int) { - EMSG(_(e_interr)); + emsg(_(e_interr)); } sourcing_name = save_sourcing_name; sourcing_lnum = save_sourcing_lnum; @@ -2308,7 +2307,7 @@ void ex_scriptnames(exarg_T *eap) if (eap->addr_count > 0) { // :script {scriptId}: edit the script if (eap->line2 < 1 || eap->line2 > script_items.ga_len) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { eap->arg = SCRIPT_ITEM(eap->line2).sn_name; do_exedit(eap, NULL); @@ -2554,7 +2553,7 @@ retry: } else { // lines like ":map xx yy^M" will have failed if (!sp->error) { msg_source(HL_ATTR(HLF_W)); - EMSG(_("W15: Warning: Wrong line separator, ^M may be missing")); + emsg(_("W15: Warning: Wrong line separator, ^M may be missing")); } sp->error = true; sp->fileformat = EOL_UNIX; @@ -2668,7 +2667,7 @@ void ex_scriptencoding(exarg_T *eap) char_u *name; if (!getline_equal(eap->getline, eap->cookie, getsourceline)) { - EMSG(_("E167: :scriptencoding used outside of a sourced file")); + emsg(_("E167: :scriptencoding used outside of a sourced file")); return; } @@ -2693,7 +2692,7 @@ void ex_finish(exarg_T *eap) if (getline_equal(eap->getline, eap->cookie, getsourceline)) { do_finish(eap, false); } else { - EMSG(_("E168: :finish used outside of a sourced file")); + emsg(_("E168: :finish used outside of a sourced file")); } } @@ -2940,7 +2939,7 @@ void ex_language(exarg_T *eap) } # endif if (loc == NULL) { - EMSG2(_("E197: Cannot set language to \"%s\""), name); + semsg(_("E197: Cannot set language to \"%s\""), name); } else { # ifdef HAVE_NL_MSG_CAT_CNTR // Need to do this for GNU gettext, otherwise cached translations diff --git a/src/nvim/ex_cmds_defs.h b/src/nvim/ex_cmds_defs.h index 171f8ed5cd..6e5dd144ad 100644 --- a/src/nvim/ex_cmds_defs.h +++ b/src/nvim/ex_cmds_defs.h @@ -78,7 +78,7 @@ typedef enum { ADDR_QUICKFIX, // quickfix list entry number ADDR_UNSIGNED, // positive count or zero, defaults to 1 ADDR_OTHER, // something else, use line number for '$', '%', etc. - ADDR_NONE // no range used + ADDR_NONE, // no range used } cmd_addr_T; typedef struct exarg exarg_T; @@ -168,7 +168,7 @@ struct exarg { int force_enc; ///< ++enc= argument (index in cmd[]) int bad_char; ///< BAD_KEEP, BAD_DROP or replacement byte int useridx; ///< user command index - char_u *errmsg; ///< returned error message + char *errmsg; ///< returned error message LineGetter getline; ///< Function used to get the next line void *cookie; ///< argument for getline() cstack_T *cstack; ///< condition stack for ":if" etc. diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 532f8aa9b3..503af2d681 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -207,7 +207,7 @@ void do_exmode(void) RedrawingDisabled++; // don't redisplay the window no_wait_return++; // don't wait for return - MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode.")); + msg(_("Entering Ex mode. Type \"visual\" to go to Normal mode.")); while (exmode_active) { // Check for a ":normal" command and no more characters left. if (ex_normal_busy > 0 && typebuf.tb_len == 0) { @@ -228,7 +228,7 @@ void do_exmode(void) if ((prev_line != curwin->w_cursor.lnum || changedtick != buf_get_changedtick(curbuf)) && !ex_no_reprint) { if (curbuf->b_ml.ml_flags & ML_EMPTY) { - EMSG(_(e_emptybuf)); + emsg(_(e_emptybuf)); } else { if (ex_pressedreturn) { // go up one line, to overwrite the ":<CR>" line, so the @@ -244,9 +244,9 @@ void do_exmode(void) } } else if (ex_pressedreturn && !ex_no_reprint) { // must be at EOF if (curbuf->b_ml.ml_flags & ML_EMPTY) { - EMSG(_(e_emptybuf)); + emsg(_(e_emptybuf)); } else { - EMSG(_("E501: At end-of-file")); + emsg(_("E501: At end-of-file")); } } } @@ -354,7 +354,7 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) // here. The value of 200 allows nested function calls, ":source", etc. // Allow 200 or 'maxfuncdepth', whatever is larger. if (call_depth >= 200 && call_depth >= p_mfd) { - EMSG(_("E169: Command too recursive")); + emsg(_("E169: Command too recursive")); // When converting to an exception, we do not include the command name // since this is not an error of the specific command. do_errthrow((cstack_T *)NULL, (char_u *)NULL); @@ -777,13 +777,13 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) || (getline_equal(fgetline, cookie, get_func_line) && !func_has_ended(real_cookie)))) { if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) { - EMSG(_(e_endtry)); + emsg(_(e_endtry)); } else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) { - EMSG(_(e_endwhile)); + emsg(_(e_endwhile)); } else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) { - EMSG(_(e_endfor)); + emsg(_(e_endfor)); } else { - EMSG(_(e_endif)); + emsg(_(e_endif)); } } @@ -1256,7 +1256,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe char_u *p; linenr_T lnum; long n; - char_u *errormsg = NULL; // error message + char *errormsg = NULL; // error message char_u *after_modifier = NULL; exarg_T ea; const int save_msg_scroll = msg_scroll; @@ -1435,7 +1435,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe } if (ea.line2 < 0) { - errormsg = (char_u *)_(e_invrange); + errormsg = _(e_invrange); } else { if (ea.line2 == 0) { curwin->w_cursor.lnum = 1; @@ -1467,7 +1467,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (p == NULL) { if (!ea.skip) { - errormsg = (char_u *)_("E464: Ambiguous use of user-defined command"); + errormsg = _("E464: Ambiguous use of user-defined command"); } goto doend; } @@ -1481,7 +1481,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (!(flags & DOCMD_VERBOSE)) { append_command(cmdname); } - errormsg = IObuff; + errormsg = (char *)IObuff; did_emsg_syntax = true; verify_command(cmdname); } @@ -1511,21 +1511,21 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (!ea.skip) { if (sandbox != 0 && !(ea.argt & EX_SBOXOK)) { // Command not allowed in sandbox. - errormsg = (char_u *)_(e_sandbox); + errormsg = _(e_sandbox); goto doend; } if (!MODIFIABLE(curbuf) && (ea.argt & EX_MODIFY) // allow :put in terminals && (!curbuf->terminal || ea.cmdidx != CMD_put)) { // Command not allowed in non-'modifiable' buffer - errormsg = (char_u *)_(e_modifiable); + errormsg = _(e_modifiable); goto doend; } if (text_locked() && !(ea.argt & EX_CMDWIN) && !IS_USER_CMDIDX(ea.cmdidx)) { // Command not allowed when editing the command line. - errormsg = (char_u *)_(get_text_locked_msg()); + errormsg = _(get_text_locked_msg()); goto doend; } @@ -1544,13 +1544,13 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (!ni && !(ea.argt & EX_RANGE) && ea.addr_count > 0) { // no range allowed - errormsg = (char_u *)_(e_norange); + errormsg = _(e_norange); goto doend; } } if (!ni && !(ea.argt & EX_BANG) && ea.forceit) { // no <!> allowed - errormsg = (char_u *)_(e_nobang); + errormsg = _(e_nobang); goto doend; } @@ -1565,7 +1565,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (!global_busy && ea.line1 > ea.line2) { if (msg_silent == 0) { if ((flags & DOCMD_VERBOSE) || exmode_active) { - errormsg = (char_u *)_("E493: Backwards range given"); + errormsg = _("E493: Backwards range given"); goto doend; } if (ask_yesno(_("Backwards range given, OK to swap"), false) != 'y') { @@ -1627,7 +1627,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (ea.argt & EX_ARGOPT) { while (ea.arg[0] == '+' && ea.arg[1] == '+') { if (getargopt(&ea) == FAIL && !ni) { - errormsg = (char_u *)_(e_invarg); + errormsg = _(e_invarg); goto doend; } } @@ -1636,7 +1636,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { if (*ea.arg == '>') { // append if (*++ea.arg != '>') { // typed wrong - errormsg = (char_u *)_("E494: Use w or w>>"); + errormsg = _("E494: Use w or w>>"); goto doend; } ea.arg = skipwhite(ea.arg + 1); @@ -1755,7 +1755,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe case ADDR_NONE: case ADDR_UNSIGNED: case ADDR_QUICKFIX: - IEMSG(_("INTERNAL: Cannot use EX_DFLALL " + iemsg(_("INTERNAL: Cannot use EX_DFLALL " "with ADDR_NONE, ADDR_UNSIGNED or ADDR_QUICKFIX")); break; } @@ -1789,7 +1789,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe n = getdigits_long(&ea.arg, false, -1); ea.arg = skipwhite(ea.arg); if (n <= 0 && !ni && (ea.argt & EX_ZEROR) == 0) { - errormsg = (char_u *)_(e_zerocount); + errormsg = _(e_zerocount); goto doend; } if (ea.addr_type != ADDR_LINES) { // e.g. :buffer 2, :sleep 3 @@ -1817,12 +1817,12 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe if (!ni && !(ea.argt & EX_EXTRA) && *ea.arg != NUL && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & EX_TRLBAR) == 0)) { // no arguments allowed but there is something - errormsg = (char_u *)_(e_trailing); + errormsg = _(e_trailing); goto doend; } if (!ni && (ea.argt & EX_NEEDARG) && *ea.arg == NUL) { - errormsg = (char_u *)_(e_argreq); + errormsg = _(e_argreq); goto doend; } @@ -1982,7 +1982,7 @@ static char_u *do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGe ea.errmsg = NULL; (cmdnames[ea.cmdidx].cmd_func)(&ea); if (ea.errmsg != NULL) { - errormsg = (char_u *)_(ea.errmsg); + errormsg = _(ea.errmsg); } } @@ -2014,9 +2014,9 @@ doend: if (errormsg != NULL && *errormsg != NUL && !did_emsg) { if (flags & DOCMD_VERBOSE) { - if (errormsg != IObuff) { + if (errormsg != (char *)IObuff) { STRCPY(IObuff, errormsg); - errormsg = IObuff; + errormsg = (char *)IObuff; } append_command(*cmdlinep); } @@ -2056,7 +2056,7 @@ doend: // "cmdmod". // Return FAIL when the command is not to be executed. // May set "errormsg" to an error message. -int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) +int parse_command_modifiers(exarg_T *eap, char **errormsg, bool skip_only) { char_u *p; @@ -2260,7 +2260,7 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) cmdmod.tab = tabpage_index(curtab) + 1; } else { if (tabnr < 0 || tabnr > LAST_TAB_NR) { - *errormsg = (char_u *)_(e_invrange); + *errormsg = _(e_invrange); return false; } cmdmod.tab = tabnr + 1; @@ -2356,7 +2356,7 @@ static void undo_cmdmod(const exarg_T *eap, int save_msg_scroll) // Parse the address range, if any, in "eap". // May set the last search pattern, unless "silent" is true. // Return FAIL and set "errormsg" or return OK. -int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) +int parse_cmd_address(exarg_T *eap, char **errormsg, bool silent) FUNC_ATTR_NONNULL_ALL { int address_count = 1; @@ -2443,14 +2443,14 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) } else { // there is no Vim command which uses '%' and // ADDR_WINDOWS or ADDR_TABS - *errormsg = (char_u *)_(e_invrange); + *errormsg = _(e_invrange); return FAIL; } break; case ADDR_TABS_RELATIVE: case ADDR_UNSIGNED: case ADDR_QUICKFIX: - *errormsg = (char_u *)_(e_invrange); + *errormsg = _(e_invrange); return FAIL; case ADDR_ARGUMENTS: if (ARGCOUNT == 0) { @@ -2475,7 +2475,7 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) } else if (*eap->cmd == '*') { // '*' - visual area if (eap->addr_type != ADDR_LINES) { - *errormsg = (char_u *)_(e_invrange); + *errormsg = _(e_invrange); return FAIL; } @@ -3829,9 +3829,9 @@ char_u *skip_range(const char_u *cmd, int *ctx) static void addr_error(cmd_addr_T addr_type) { if (addr_type == ADDR_NONE) { - EMSG(_(e_norange)); + emsg(_(e_norange)); } else { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); } } @@ -4042,7 +4042,7 @@ static linenr_T get_address(exarg_T *eap, char_u **ptr, cmd_addr_T addr_type, in } else if (*cmd == '?' || *cmd == '/') { i = RE_SEARCH; } else { - EMSG(_(e_backslash)); + emsg(_(e_backslash)); cmd = NULL; goto error; } @@ -4125,7 +4125,7 @@ static linenr_T get_address(exarg_T *eap, char_u **ptr, cmd_addr_T addr_type, in } if (addr_type == ADDR_TABS_RELATIVE) { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); cmd = NULL; goto error; } else if (addr_type == ADDR_LOADED_BUFFERS || addr_type == ADDR_BUFFERS) { @@ -4172,7 +4172,7 @@ static void get_flags(exarg_T *eap) void ex_ni(exarg_T *eap) { if (!eap->skip) { - eap->errmsg = (char_u *)N_("E319: The command is not available in this version"); + eap->errmsg = N_("E319: The command is not available in this version"); } } @@ -4192,11 +4192,11 @@ static void ex_script_ni(exarg_T *eap) * Check range in Ex command for validity. * Return NULL when valid, error message when invalid. */ -static char_u *invalid_range(exarg_T *eap) +static char *invalid_range(exarg_T *eap) { buf_T *buf; if (eap->line1 < 0 || eap->line2 < 0 || eap->line1 > eap->line2) { - return (char_u *)_(e_invrange); + return _(e_invrange); } if (eap->argt & EX_RANGE) { @@ -4204,51 +4204,51 @@ static char_u *invalid_range(exarg_T *eap) case ADDR_LINES: if (eap->line2 > (curbuf->b_ml.ml_line_count + (eap->cmdidx == CMD_diffget))) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_ARGUMENTS: // add 1 if ARGCOUNT is 0 if (eap->line2 > ARGCOUNT + (!ARGCOUNT)) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_BUFFERS: if (eap->line1 < firstbuf->b_fnum || eap->line2 > lastbuf->b_fnum) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_LOADED_BUFFERS: buf = firstbuf; while (buf->b_ml.ml_mfp == NULL) { if (buf->b_next == NULL) { - return (char_u *)_(e_invrange); + return _(e_invrange); } buf = buf->b_next; } if (eap->line1 < buf->b_fnum) { - return (char_u *)_(e_invrange); + return _(e_invrange); } buf = lastbuf; while (buf->b_ml.ml_mfp == NULL) { if (buf->b_prev == NULL) { - return (char_u *)_(e_invrange); + return _(e_invrange); } buf = buf->b_prev; } if (eap->line2 > buf->b_fnum) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_WINDOWS: if (eap->line2 > LAST_WIN_NR) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_TABS: if (eap->line2 > LAST_TAB_NR) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_TABS_RELATIVE: @@ -4259,13 +4259,13 @@ static char_u *invalid_range(exarg_T *eap) assert(eap->line2 >= 0); // No error for value that is too big, will use the last entry. if (eap->line2 <= 0) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_QUICKFIX_VALID: if ((eap->line2 != 1 && (size_t)eap->line2 > qf_get_valid_size(eap)) || eap->line2 < 0) { - return (char_u *)_(e_invrange); + return _(e_invrange); } break; case ADDR_UNSIGNED: @@ -4387,7 +4387,7 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) // Expand file name in Ex command argument. // When an error is detected, "errormsgp" is set to a non-NULL pointer. // Return FAIL for failure, OK otherwise. -int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) +int expand_filename(exarg_T *eap, char_u **cmdlinep, char **errormsgp) { int has_wildcards; // need to expand wildcards char_u *repl; @@ -5116,23 +5116,16 @@ static int check_more(int message, bool forceit) if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL) { char_u buff[DIALOG_MSG_SIZE]; - if (n == 1) { - STRLCPY(buff, _("1 more file to edit. Quit anyway?"), - DIALOG_MSG_SIZE); - } else { - vim_snprintf((char *)buff, DIALOG_MSG_SIZE, - _("%d more files to edit. Quit anyway?"), n); - } + vim_snprintf((char *)buff, DIALOG_MSG_SIZE, + NGETTEXT("%d more file to edit. Quit anyway?", + "%d more files to edit. Quit anyway?", (unsigned long)n), n); if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) { return OK; } return FAIL; } - if (n == 1) { - EMSG(_("E173: 1 more file to edit")); - } else { - EMSGN(_("E173: %" PRId64 " more files to edit"), n); - } + semsg(NGETTEXT("E173: %" PRId64 " more file to edit", + "E173: %" PRId64 " more files to edit", (unsigned long)n), (int64_t)n); quitmore = 2; // next try to quit is allowed } return FAIL; @@ -5199,7 +5192,7 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t a if (!force && (cmd->uc_script_ctx.sc_sid != current_sctx.sc_sid || cmd->uc_script_ctx.sc_seq == current_sctx.sc_seq)) { - EMSG2(_("E174: Command already exists: add ! to replace it: %s"), + semsg(_("E174: Command already exists: add ! to replace it: %s"), name); goto fail; } @@ -5347,7 +5340,7 @@ static void uc_list(char_u *name, size_t name_len) // Put out the title first time if (!found) { - MSG_PUTS_TITLE(_("\n Name Args Address " + msg_puts_title(_("\n Name Args Address " "Complete Definition")); } found = true; @@ -5482,7 +5475,7 @@ static void uc_list(char_u *name, size_t name_len) } if (!found) { - MSG(_("No user-defined commands found")); + msg(_("No user-defined commands found")); } } @@ -5493,7 +5486,7 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int char_u *p; if (len == 0) { - EMSG(_("E175: No attribute specified")); + emsg(_("E175: No attribute specified")); return FAIL; } @@ -5539,7 +5532,7 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int } } else { wrong_nargs: - EMSG(_("E176: Invalid number of arguments")); + emsg(_("E176: Invalid number of arguments")); return FAIL; } } else if (STRNICMP(attr, "range", attrlen) == 0) { @@ -5550,7 +5543,7 @@ wrong_nargs: p = val; if (*def >= 0) { two_count: - EMSG(_("E177: Count cannot be specified twice")); + emsg(_("E177: Count cannot be specified twice")); return FAIL; } @@ -5559,7 +5552,7 @@ two_count: if (p != val + vallen || vallen == 0) { invalid_count: - EMSG(_("E178: Invalid default value for count")); + emsg(_("E178: Invalid default value for count")); return FAIL; } } @@ -5592,7 +5585,7 @@ invalid_count: } } else if (STRNICMP(attr, "complete", attrlen) == 0) { if (val == NULL) { - EMSG(_("E179: argument required for -complete")); + emsg(_("E179: argument required for -complete")); return FAIL; } @@ -5603,7 +5596,7 @@ invalid_count: } else if (STRNICMP(attr, "addr", attrlen) == 0) { *argt |= EX_RANGE; if (val == NULL) { - EMSG(_("E179: argument required for -addr")); + emsg(_("E179: argument required for -addr")); return FAIL; } if (parse_addr_type_arg(val, (int)vallen, addr_type_arg) == FAIL) { @@ -5615,7 +5608,7 @@ invalid_count: } else { char_u ch = attr[len]; attr[len] = '\0'; - EMSG2(_("E181: Invalid attribute: %s"), attr); + semsg(_("E181: Invalid attribute: %s"), attr); attr[len] = ch; return FAIL; } @@ -5664,7 +5657,7 @@ static void ex_command(exarg_T *eap) } } if (!ends_excmd(*p) && !ascii_iswhite(*p)) { - EMSG(_("E182: Invalid command name")); + emsg(_("E182: Invalid command name")); return; } end = p; @@ -5676,11 +5669,11 @@ static void ex_command(exarg_T *eap) if (!has_attr && ends_excmd(*p)) { uc_list(name, end - name); } else if (!ASCII_ISUPPER(*name)) { - EMSG(_("E183: User defined commands must start with an uppercase letter")); + emsg(_("E183: User defined commands must start with an uppercase letter")); } else if (name_len <= 4 && STRNCMP(name, "Next", name_len) == 0) { - EMSG(_("E841: Reserved name, cannot be used for user defined command")); + emsg(_("E841: Reserved name, cannot be used for user defined command")); } else if (compl > 0 && (argt & EX_EXTRA) == 0) { - EMSG(_(e_complete_used_without_nargs)); + emsg(_(e_complete_used_without_nargs)); } else { uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg, addr_type_arg, eap->forceit); @@ -5697,7 +5690,8 @@ void ex_comclear(exarg_T *eap) uc_clear(&curbuf->b_ucmds); } -static void free_ucmd(ucmd_T *cmd) { +static void free_ucmd(ucmd_T *cmd) +{ xfree(cmd->uc_name); xfree(cmd->uc_rep); xfree(cmd->uc_compl_arg); @@ -5734,7 +5728,7 @@ static void ex_delcommand(exarg_T *eap) } if (cmp != 0) { - EMSG2(_("E184: No such user-defined command: %s"), eap->arg); + semsg(_("E184: No such user-defined command: %s"), eap->arg); return; } @@ -5868,7 +5862,7 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd, ct_MODS, ct_REGISTER, ct_LT, - ct_NONE + ct_NONE, } type = ct_NONE; if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-') { @@ -6339,7 +6333,7 @@ int parse_addr_type_arg(char_u *value, int vallen, cmd_addr_T *addr_type_arg) for (i = 0; err[i] != NUL && !ascii_iswhite(err[i]); i++) {} err[i] = NUL; - EMSG2(_("E180: Invalid address type value: %s"), err); + semsg(_("E180: Invalid address type value: %s"), err); return FAIL; } @@ -6389,19 +6383,19 @@ int parse_compl_arg(const char_u *value, int vallen, int *complp, uint32_t *argt } if (i == (int)ARRAY_SIZE(command_complete)) { - EMSG2(_("E180: Invalid complete value: %s"), value); + semsg(_("E180: Invalid complete value: %s"), value); return FAIL; } if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST && arg != NULL) { - EMSG(_("E468: Completion argument only allowed for custom completion")); + emsg(_("E468: Completion argument only allowed for custom completion")); return FAIL; } if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST) && arg == NULL) { - EMSG(_("E467: Custom completion requires a function argument")); + emsg(_("E467: Custom completion requires a function argument")); return FAIL; } @@ -6438,20 +6432,20 @@ static void ex_colorscheme(exarg_T *eap) xfree(expr); if (p != NULL) { - MSG(p); + msg((char *)p); xfree(p); } else { - MSG("default"); + msg("default"); } } else if (load_colors(eap->arg) == FAIL) { - EMSG2(_("E185: Cannot find color scheme '%s'"), eap->arg); + semsg(_("E185: Cannot find color scheme '%s'"), eap->arg); } } static void ex_highlight(exarg_T *eap) { if (*eap->arg == NUL && eap->cmd[2] == '!') { - MSG(_("Greetings, Vim user!")); + msg(_("Greetings, Vim user!")); } do_highlight((const char *)eap->arg, eap->forceit, false); } @@ -6648,7 +6642,7 @@ void ex_win_close(int forceit, win_T *win, tabpage_T *tp) // Never close the autocommand window. if (win == aucmd_win) { - EMSG(_(e_autocmd_close)); + emsg(_(e_autocmd_close)); return; } @@ -6688,7 +6682,7 @@ static void ex_tabclose(exarg_T *eap) if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; } else if (first_tabpage->tp_next == NULL) { - EMSG(_("E784: Cannot close last tab page")); + emsg(_("E784: Cannot close last tab page")); } else { int tab_number = get_tabpage_arg(eap); if (eap->errmsg == NULL) { @@ -6713,7 +6707,7 @@ static void ex_tabonly(exarg_T *eap) if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; } else if (first_tabpage->tp_next == NULL) { - MSG(_("Already only one tab page")); + msg(_("Already only one tab page")); } else { int tab_number = get_tabpage_arg(eap); if (eap->errmsg == NULL) { @@ -6918,7 +6912,7 @@ static void ex_exit(exarg_T *eap) static void ex_print(exarg_T *eap) { if (curbuf->b_ml.ml_flags & ML_EMPTY) { - EMSG(_(e_emptybuf)); + emsg(_(e_emptybuf)); } else { for (; !got_int; os_breakcheck()) { print_line(eap->line1, @@ -7032,7 +7026,7 @@ void alist_set(alist_T *al, int count, char_u **files, int use_curbuf, int *fnum static int recursive = 0; if (recursive) { - EMSG(_(e_au_recursive)); + emsg(_(e_au_recursive)); return; } recursive++; @@ -7207,8 +7201,7 @@ void ex_splitview(exarg_T *eap) *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL) { // Reset 'scrollbind' when editing another file, but keep it when // doing ":split" without arguments. - if (*eap->arg != NUL - ) { + if (*eap->arg != NUL) { RESET_BINDING(curwin); } else { do_check_scrollbind(false); @@ -7353,7 +7346,7 @@ static void ex_mode(exarg_T *eap) must_redraw = CLEAR; ex_redraw(eap); } else { - EMSG(_(e_screenmode)); + emsg(_(e_screenmode)); } } @@ -7369,7 +7362,6 @@ static void ex_resize(exarg_T *eap) if (eap->addr_count > 0) { n = eap->line2; for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next) { - ; } } @@ -7558,17 +7550,16 @@ void do_exedit(exarg_T *eap, win_T *old_curwin) /// ":gui" and ":gvim" when there is no GUI. static void ex_nogui(exarg_T *eap) { - eap->errmsg = (char_u *)N_("E25: Nvim does not have a built-in GUI"); + eap->errmsg = N_("E25: Nvim does not have a built-in GUI"); } - static void ex_swapname(exarg_T *eap) { if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) { - MSG(_("No swap file")); + msg(_("No swap file")); } else { - msg(curbuf->b_ml.ml_mfp->mf_fname); + msg((char *)curbuf->b_ml.ml_mfp->mf_fname); } } @@ -7671,7 +7662,7 @@ static void ex_read(exarg_T *eap) } if (i != OK) { if (!aborting()) { - EMSG2(_(e_notopen), eap->arg); + semsg(_(e_notopen), eap->arg); } } else { if (empty && exmode_active) { @@ -7787,7 +7778,7 @@ bool changedir_func(char_u *new_dir, CdScope scope) if (STRCMP(new_dir, "-") == 0) { pdir = get_prevdir(scope); if (pdir == NULL) { - EMSG(_("E186: No previous directory")); + emsg(_("E186: No previous directory")); return false; } new_dir = pdir; @@ -7827,7 +7818,7 @@ bool changedir_func(char_u *new_dir, CdScope scope) post_chdir(scope, dir_differs); retval = true; } else { - EMSG(_(e_failed)); + emsg(_(e_failed)); } xfree(tofree); @@ -7886,10 +7877,10 @@ static void ex_pwd(exarg_T *eap) } smsg("[%s] %s", context, (char *)NameBuff); } else { - msg(NameBuff); + msg((char *)NameBuff); } } else { - EMSG(_("E187: Unknown")); + emsg(_("E187: Unknown")); } } @@ -7921,7 +7912,7 @@ static void ex_sleep(exarg_T *eap) case NUL: len *= 1000L; break; default: - EMSG2(_(e_invarg2), eap->arg); return; + semsg(_(e_invarg2), eap->arg); return; } do_sleep(len); } @@ -7956,10 +7947,10 @@ static void do_exmap(exarg_T *eap, int isabbrev) switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'), eap->arg, mode, isabbrev)) { case 1: - EMSG(_(e_invarg)); + emsg(_(e_invarg)); break; case 2: - EMSG(isabbrev ? _(e_noabbr) : _(e_nomap)); + emsg(isabbrev ? _(e_noabbr) : _(e_nomap)); break; } } @@ -7972,7 +7963,7 @@ static void ex_winsize(exarg_T *eap) char_u *arg = eap->arg; if (!ascii_isdigit(*arg)) { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); return; } int w = getdigits_int(&arg, false, 10); @@ -7982,7 +7973,7 @@ static void ex_winsize(exarg_T *eap) if (*p != NUL && *arg == NUL) { screen_resize(w, h); } else { - EMSG(_("E465: :winsize requires two number arguments")); + emsg(_("E465: :winsize requires two number arguments")); } } @@ -7994,7 +7985,7 @@ static void ex_wincmd(exarg_T *eap) if (*eap->arg == 'g' || *eap->arg == Ctrl_G) { // CTRL-W g and CTRL-W CTRL-G have an extra command character if (eap->arg[1] == NUL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } xchar = eap->arg[1]; @@ -8006,7 +7997,7 @@ static void ex_wincmd(exarg_T *eap) eap->nextcmd = check_nextcmd(p); p = skipwhite(p); if (*p != NUL && *p != '"' && eap->nextcmd == NULL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else if (!eap->skip) { // Pass flags on for ":vertical wincmd ]". postponed_split_flags = cmdmod.split; @@ -8054,8 +8045,7 @@ static void ex_operators(exarg_T *eap) default: // CMD_rshift or CMD_lshift if ( - (eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl - ) { + (eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl) { oa.op_type = OP_RSHIFT; } else { oa.op_type = OP_LSHIFT; @@ -8098,7 +8088,7 @@ static void ex_copymove(exarg_T *eap) * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n' */ if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count) { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); return; } @@ -8264,7 +8254,7 @@ static void ex_later(exarg_T *eap) } if (*p != NUL) { - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); } else { undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, file, false); @@ -8325,7 +8315,7 @@ static void ex_redir(exarg_T *eap) } if (*arg != NUL) { redir_reg = 0; - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); } } else if (*arg == '=' && arg[1] == '>') { int append; @@ -8347,7 +8337,7 @@ static void ex_redir(exarg_T *eap) } // TODO: redirect to a buffer else { - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); } } @@ -8456,7 +8446,7 @@ int vim_mkdir_emsg(const char *const name, const int prot) { int ret; if ((ret = os_mkdir(name, prot)) != 0) { - EMSG3(_(e_mkdir), name, os_strerror(ret)); + semsg(_(e_mkdir), name, os_strerror(ret)); return FAIL; } return OK; @@ -8474,17 +8464,17 @@ FILE *open_exfile(char_u *fname, int forceit, char *mode) #ifdef UNIX // with Unix it is possible to open a directory if (os_isdir(fname)) { - EMSG2(_(e_isadir2), fname); + semsg(_(e_isadir2), fname); return NULL; } #endif if (!forceit && *mode != 'a' && os_path_exists(fname)) { - EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname); + semsg(_("E189: \"%s\" exists (add ! to override)"), fname); return NULL; } if ((fd = os_fopen((char *)fname, mode)) == NULL) { - EMSG2(_("E190: Cannot open \"%s\" for writing"), fname); + semsg(_("E190: Cannot open \"%s\" for writing"), fname); } return fd; @@ -8498,15 +8488,15 @@ static void ex_mark(exarg_T *eap) pos_T pos; if (*eap->arg == NUL) { // No argument? - EMSG(_(e_argreq)); + emsg(_(e_argreq)); } else if (eap->arg[1] != NUL) { // more than one character? - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } else { pos = curwin->w_cursor; // save curwin->w_cursor curwin->w_cursor.lnum = eap->line2; beginline(BL_WHITE | BL_FIX); if (setmark(*eap->arg) == FAIL) { // set mark - EMSG(_("E191: Argument must be a letter or forward/backward quote")); + emsg(_("E191: Argument must be a letter or forward/backward quote")); } curwin->w_cursor = pos; // restore curwin->w_cursor } @@ -8584,7 +8574,7 @@ void restore_current_state(save_state_T *sst) static void ex_normal(exarg_T *eap) { if (curbuf->terminal && State & TERM_FOCUS) { - EMSG("Can't re-enter normal mode from terminal mode"); + emsg("Can't re-enter normal mode from terminal mode"); return; } save_state_T save_state; @@ -8593,11 +8583,11 @@ static void ex_normal(exarg_T *eap) char_u *p; if (ex_normal_lock > 0) { - EMSG(_(e_secure)); + emsg(_(e_secure)); return; } if (ex_normal_busy >= p_mmd) { - EMSG(_("E192: Recursive use of :normal too deep")); + emsg(_("E192: Recursive use of :normal too deep")); return; } @@ -8994,7 +8984,7 @@ ssize_t find_cmdline_var(const char_u *src, size_t *usedlen) /// Returns NULL if no match was found. "usedlen" then still contains the /// number of characters to skip. char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnump, - char_u **errormsg, int *escaped) + char **errormsg, int *escaped) { int i; char_u *s; @@ -9044,7 +9034,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum ? (FIND_IDENT | FIND_STRING | FIND_EVAL) : FIND_STRING)); if (resultlen == 0) { - *errormsg = (char_u *)""; + *errormsg = ""; return NULL; } // @@ -9097,7 +9087,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum result = (char_u *)tv_list_find_str(get_vim_var_list(VV_OLDFILES), i - 1); if (result == NULL) { - *errormsg = (char_u *)""; + *errormsg = ""; return NULL; } } else { @@ -9106,7 +9096,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum } buf = buflist_findnr(i); if (buf == NULL) { - *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'"); + *errormsg = _("E194: No alternate file name to substitute for '#'"); return NULL; } if (lnump != NULL) { @@ -9125,7 +9115,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_CFILE: // file name under cursor result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL); if (result == NULL) { - *errormsg = (char_u *)""; + *errormsg = ""; return NULL; } resultbuf = result; // remember allocated string @@ -9145,7 +9135,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum } result = autocmd_fname; if (result == NULL) { - *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\""); + *errormsg = _("E495: no autocommand file name to substitute for \"<afile>\""); return NULL; } result = path_try_shorten_fname(result); @@ -9153,7 +9143,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_ABUF: // buffer number for autocommand if (autocmd_bufnr <= 0) { - *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\""); + *errormsg = _("E496: no autocommand buffer number to substitute for \"<abuf>\""); return NULL; } snprintf(strbuf, sizeof(strbuf), "%d", autocmd_bufnr); @@ -9163,7 +9153,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_AMATCH: // match name for autocommand result = autocmd_match; if (result == NULL) { - *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\""); + *errormsg = _("E497: no autocommand match name to substitute for \"<amatch>\""); return NULL; } break; @@ -9171,14 +9161,14 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_SFILE: // file name for ":so" command result = sourcing_name; if (result == NULL) { - *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\""); + *errormsg = _("E498: no :source file name to substitute for \"<sfile>\""); return NULL; } break; case SPEC_SLNUM: // line in file for ":so" command if (sourcing_name == NULL || sourcing_lnum == 0) { - *errormsg = (char_u *)_("E842: no line number to use for \"<slnum>\""); + *errormsg = _("E842: no line number to use for \"<slnum>\""); return NULL; } snprintf(strbuf, sizeof(strbuf), "%" PRIdLINENR, sourcing_lnum); @@ -9187,7 +9177,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_SFLNUM: // line in script file if (current_sctx.sc_lnum + sourcing_lnum == 0) { - *errormsg = (char_u *)_("E961: no line number to use for \"<sflnum>\""); + *errormsg = _("E961: no line number to use for \"<sflnum>\""); return NULL; } snprintf((char *)strbuf, sizeof(strbuf), "%" PRIdLINENR, @@ -9197,7 +9187,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum case SPEC_SID: if (current_sctx.sc_sid <= 0) { - *errormsg = (char_u *)_(e_usingsid); + *errormsg = _(e_usingsid); return NULL; } snprintf(strbuf, sizeof(strbuf), "<SNR>%" PRIdSCID "_", @@ -9207,7 +9197,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum default: // should not happen - *errormsg = (char_u *)""; + *errormsg = ""; result = (char_u *)""; // avoid gcc warning break; } @@ -9224,7 +9214,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum valid |= modify_fname(src, tilde_file, usedlen, &result, &resultbuf, &resultlen); if (result == NULL) { - *errormsg = (char_u *)""; + *errormsg = ""; return NULL; } } @@ -9233,9 +9223,9 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH) { if (valid != VALID_HEAD + VALID_PATH) { // xgettext:no-c-format - *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\""); + *errormsg = _("E499: Empty file name for '%' or '#', only works with \":p:h\""); } else { - *errormsg = (char_u *)_("E500: Evaluates to an empty string"); + *errormsg = _("E500: Evaluates to an empty string"); } result = NULL; } else { @@ -9315,7 +9305,7 @@ static char_u *arg_all(void) */ char_u *expand_sfile(char_u *arg) { - char_u *errormsg; + char *errormsg; size_t len; char_u *result; char_u *newres; @@ -9405,7 +9395,7 @@ static void ex_behave(exarg_T *eap) set_option_value("mousemodel", 0L, "extend", 0); set_option_value("keymodel", 0L, "", 0); } else { - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); } } @@ -9516,7 +9506,7 @@ static void ex_filetype(exarg_T *eap) filetype_detect = kFalse; } } else { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } } @@ -9604,7 +9594,7 @@ static void ex_match(exarg_T *eap) if (eap->line2 <= 3) { id = eap->line2; } else { - EMSG(e_invcmd); + emsg(e_invcmd); return; } @@ -9627,7 +9617,7 @@ static void ex_match(exarg_T *eap) if (*p == NUL) { // There must be two arguments. xfree(g); - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); return; } end = skip_regexp(p + 1, *p, true, NULL); @@ -9639,7 +9629,7 @@ static void ex_match(exarg_T *eap) } if (*end != *p) { xfree(g); - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return; } @@ -9717,7 +9707,7 @@ static void ex_terminal(exarg_T *eap) xfree(name); } else { // No {cmd}: run the job with tokenized 'shell'. if (*p_sh == NUL) { - EMSG(_(e_shellempty)); + emsg(_(e_shellempty)); return; } @@ -9874,287 +9864,287 @@ void verify_command(char_u *cmd) if (strcmp("smile", (char *)cmd)) { return; // acceptable non-existing command } - MSG(" #xxn` #xnxx` ,+x@##@Mz;` .xxx" + msg(" #xxn` #xnxx` ,+x@##@Mz;` .xxx" "xxxxxxnz+, znnnnnnnnnnnnnnnn."); - MSG(" n###z x####` :x##########W+` ,###" + msg(" n###z x####` :x##########W+` ,###" "##########M; W################."); - MSG(" n####; x####` `z##############W: ,###" + msg(" n####; x####` `z##############W: ,###" "############# W################."); - MSG(" n####W. x####` ,W#################+ ,###" + msg(" n####W. x####` ,W#################+ ,###" "############## W################."); - MSG(" n#####n x####` @################### ,###" + msg(" n#####n x####` @################### ,###" "##############i W################."); - MSG(" n######i x####` .#########@W@########* ,###" + msg(" n######i x####` .#########@W@########* ,###" "##############W`W################."); - MSG(" n######@. x####` x######W*. `;n#######: ,###" + msg(" n######@. x####` x######W*. `;n#######: ,###" "#x,,,,:*M######iW###@:,,,,,,,,,,,`"); - MSG(" n#######n x####` *######+` :M#####M ,###" + msg(" n#######n x####` *######+` :M#####M ,###" "#n `x#####xW###@`"); - MSG(" n########* x####``@####@; `x#####i ,###" + msg(" n########* x####``@####@; `x#####i ,###" "#n ,#####@W###@`"); - MSG(" n########@ x####`*#####i `M####M ,###" + msg(" n########@ x####`*#####i `M####M ,###" "#n x#########@`"); - MSG(" n######### x####`M####z :#####:,###" + msg(" n######### x####`M####z :#####:,###" "#n z#########@`"); - MSG(" n#########* x####,#####. n####+,###" + msg(" n#########* x####,#####. n####+,###" "#n n#########@`"); - MSG(" n####@####@, x####i####x ;####x,###" + msg(" n####@####@, x####i####x ;####x,###" "#n `W#####@####+++++++++++i"); - MSG(" n####*#####M` x#########* `####@,###" + msg(" n####*#####M` x#########* `####@,###" "#n i#####MW###############W"); - MSG(" n####.######+ x####z####; W####,###" + msg(" n####.######+ x####z####; W####,###" "#n i@######W###############W"); - MSG(" n####.`W#####: x####n####: M####:###" + msg(" n####.`W#####: x####n####: M####:###" "#@nnnnnW#######,W###############W"); - MSG(" n####. :#####M`x####z####; W####,###" + msg(" n####. :#####M`x####z####; W####,###" "##############z W###############W"); - MSG(" n####. #######x#########* `####W,###" + msg(" n####. #######x#########* `####W,###" "#############W` W###############W"); - MSG(" n####. `M#####W####i####x ;####x,###" + msg(" n####. `M#####W####i####x ;####x,###" "############W, W####+**********i"); - MSG(" n####. ,##########,#####. n####+,###" + msg(" n####. ,##########,#####. n####+,###" "###########n. W###@`"); - MSG(" n####. ##########`M####z :#####:,###" + msg(" n####. ##########`M####z :#####:,###" "########Wz: W###@`"); - MSG(" n####. x#########`*#####i `M####M ,###" + msg(" n####. x#########`*#####i `M####M ,###" "#x.....` W###@`"); - MSG(" n####. ,@########``@####@; `x#####i ,###" + msg(" n####. ,@########``@####@; `x#####i ,###" "#n W###@`"); - MSG(" n####. *########` *#####@+` ,M#####M ,###" + msg(" n####. *########` *#####@+` ,M#####M ,###" "#n W###@`"); - MSG(" n####. x#######` x######W*. `;n######@: ,###" + msg(" n####. x#######` x######W*. `;n######@: ,###" "#n W###@,,,,,,,,,,,,`"); - MSG(" n####. .@######` .#########@W@########* ,###" + msg(" n####. .@######` .#########@W@########* ,###" "#n W################,"); - MSG(" n####. i######` @################### ,###" + msg(" n####. i######` @################### ,###" "#n W################,"); - MSG(" n####. n#####` ,W#################+ ,###" + msg(" n####. n#####` ,W#################+ ,###" "#n W################,"); - MSG(" n####. .@####` .n##############W; ,###" + msg(" n####. .@####` .n##############W; ,###" "#n W################,"); - MSG(" n####. i####` :x##########W+` ,###" + msg(" n####. i####` :x##########W+` ,###" "#n W################,"); - MSG(" +nnnn` +nnn` ,+x@##@Mz;` .nnn" + msg(" +nnnn` +nnn` ,+x@##@Mz;` .nnn" "n+ zxxxxxxxxxxxxxxxx."); - MSG(" "); - MSG(" " + msg(" "); + msg(" " " ,+M@#Mi"); - MSG(" " + msg(" " " .z########"); - MSG(" " + msg(" " " i@#########i"); - MSG(" " + msg(" " " `############W`"); - MSG(" " + msg(" " " `n#############i"); - MSG(" " + msg(" " " `n##############n"); - MSG(" `` " + msg(" `` " " z###############@`"); - MSG(" `W@z, " + msg(" `W@z, " " ##################,"); - MSG(" *#####` " + msg(" *#####` " " i############@x@###i"); - MSG(" ######M. " + msg(" ######M. " " :#############n`,W##+"); - MSG(" +######@: " + msg(" +######@: " " .W#########M@##+ *##z"); - MSG(" :#######@: " + msg(" :#######@: " " `x########@#x###* ,##n"); - MSG(" `@#######@; " + msg(" `@#######@; " " z#########M*@nW#i .##x"); - MSG(" z########@i " + msg(" z########@i " " *###########WM#@#, `##x"); - MSG(" i##########+ " + msg(" i##########+ " " ;###########*n###@ `##x"); - MSG(" `@#MM#######x, " + msg(" `@#MM#######x, " " ,@#########zM,`z##M `@#x"); - MSG(" n##M#W#######n. " + msg(" n##M#W#######n. " " `.:i*+#zzzz##+i:.` ,W#########Wii,`n@#@` n@##n"); - MSG(" ;###@#x#######n `,i" + msg(" ;###@#x#######n `,i" "#nW@#####@@WWW@@####@Mzi. ,W##########@z.. ;zM#+i####z"); - MSG(" x####nz######## .;#x@##" + msg(" x####nz######## .;#x@##" "@Wn#*;,.` ``,:*#x@##M+, ;@########xz@WM+#` `n@#######"); - MSG(" ,@####M########xi#@##@Mzi," + msg(" ,@####M########xi#@##@Mzi," "` .+x###Mi:n##########Mz```.:i *@######*"); - MSG(" *#####W#########ix+:` " + msg(" *#####W#########ix+:` " " :n#############z: `*.`M######i"); - MSG(" i#W##nW@+@##@#M@; " + msg(" i#W##nW@+@##@#M@; " " ;W@@##########W, i`x@#####,"); - MSG(" `@@n@Wn#@iMW*#*: " + msg(" `@@n@Wn#@iMW*#*: " " `iz#z@######x. M######`"); - MSG(" z##zM###x`*, .` " + msg(" z##zM###x`*, .` " " `iW#####W;:` +#####M"); - MSG(" ,###nn##n` " + msg(" ,###nn##n` " " ,#####x;` ,;@######"); - MSG(" x###xz#. " + msg(" x###xz#. " " in###+ `:######@."); - MSG(" ;####n+ " + msg(" ;####n+ " " `Mnx##xi` , zM#######"); - MSG(" `W####+ " + msg(" `W####+ " "i. `.+x###@#. :n,z######:"); - MSG(" z####@` ;" + msg(" z####@` ;" "#: .ii@###@;.*M*z####@`"); - MSG(" i####M ` `i@" + msg(" i####M ` `i@" "#, :: +#n##@+@##W####n"); - MSG(" :####x ,i. ##xzM###" + msg(" :####x ,i. ##xzM###" "@` i. .@@, .z####x#######*"); - MSG(" ,###W; i##Wz########" + msg(" ,###W; i##Wz########" "# :## z##n ,@########x###:"); - MSG(" n##n `W###########M" + msg(" n##n `W###########M" "`;n, i#x ,###@i *W########W#@`"); - MSG(" .@##+ `x###########@." + msg(" .@##+ `x###########@." " z#+ .M#W``x#####n` `;#######@z#x"); - MSG(" n###z :W############@ " + msg(" n###z :W############@ " " z#* @##xM#######@n; `########nW+"); - MSG(" ;####nW##############W " + msg(" ;####nW##############W " ":@#* `@#############* :########z@i`"); - MSG(" M##################### " + msg(" M##################### " "M##: @#############@: *W########M#"); - MSG(" ;#####################i." + msg(" ;#####################i." "##x` W#############W, :n########zx"); - MSG(" x####################@.`" + msg(" x####################@.`" "x; @#############z. .@########W#"); - MSG(" ,######################` " + msg(" ,######################` " " W###############x*,` W######zM#i"); - MSG(" #######################: " + msg(" #######################: " " z##################@x+*#zzi `@#########."); - MSG(" W########W#z#M#########; " + msg(" W########W#z#M#########; " " *##########################z :@#######@`"); - MSG(" `@#######x`;#z ,x#######; " + msg(" `@#######x`;#z ,x#######; " " z###########M###xnM@########* :M######@"); - MSG(" i########, x#@` z######; " + msg(" i########, x#@` z######; " " *##########i *#@` `+########+` n######."); - MSG(" n#######@` M##, `W#####. " + msg(" n#######@` M##, `W#####. " " *#########z ###; z########M: :W####n"); - MSG(" M#######M n##. x####x " + msg(" M#######M n##. x####x " " `x########: z##+ M#########@; .n###+"); - MSG(" W#######@` :#W `@####: " + msg(" W#######@` :#W `@####: " " `@######W i### ;###########@. n##n"); - MSG(" W########z` ,, .x####z " + msg(" W########z` ,, .x####z " " @######@` `W#; `W############* *###;"); - MSG(" `@#########Mi,:*n@####W` " + msg(" `@#########Mi,:*n@####W` " " W#######* .. `n#############i i###x"); - MSG(" .#####################z " + msg(" .#####################z " " `@#######@*` .x############n:` ;####."); - MSG(" :####################x`,,` " + msg(" :####################x`,,` " " `W#########@x#+#@#############i ,####:"); - MSG(" ;###################x#@###x" + msg(" ;###################x#@###x" "i` *############################: `####i"); - MSG(" i##################+#######" + msg(" i##################+#######" "#M, x##########################@` W###i"); - MSG(" *################@; @######" + msg(" *################@; @######" "##@, .W#########################@ x###:"); - MSG(" .+M#############z. M######" + msg(" .+M#############z. M######" "###x ,W########################@` ####."); - MSG(" *M*;z@########x: :W#####" + msg(" *M*;z@########x: :W#####" "##i .M########################i i###:"); - MSG(" *##@z;#@####x: :z###" + msg(" *##@z;#@####x: :z###" "@i `########################x .###;"); - MSG(" *#####n;#@## ;##" + msg(" *#####n;#@## ;##" "* ,x#####################@` W##*"); - MSG(" *#######n;* :M##" + msg(" *#######n;* :M##" "W*, *W####################` n##z"); - MSG(" i########@. ,*n####" + msg(" i########@. ,*n####" "###M*` `###################M *##M"); - MSG(" i########n `z#####@@" + msg(" i########n `z#####@@" "#####Wi ,M################; ,##@`"); - MSG(" ;WMWW@###* .x##@ni.``" + msg(" ;WMWW@###* .x##@ni.``" ".:+zW##z` `n##############z @##,"); - MSG(" .*++*i;;;. .M#@+` " + msg(" .*++*i;;;. .M#@+` " " .##n `x############x` n##i"); - MSG(" :########* x#W, " + msg(" :########* x#W, " " *#+ *###########M` +##+"); - MSG(" ,######### :#@: " + msg(" ,######### :#@: " " ##: #nzzzzzzzzzz. :##x"); - MSG(" .#####Wz+` ##+ " + msg(" .#####Wz+` ##+ " " `MM` .znnnnnnnnn. `@#@`"); - MSG(" `@@ni;*nMz` @W` " + msg(" `@@ni;*nMz` @W` " " :#+ .x#######n x##,"); - MSG(" i;z@#####, .#* " + msg(" i;z@#####, .#* " " z#: ;;;*zW##; ###i"); - MSG(" z########: :#; " + msg(" z########: :#; " " `Wx +###Wni;n. ;##z"); - MSG(" n########W: .#* " + msg(" n########W: .#* " " ,#, ;#######@+ `@#M"); - MSG(" .###########n;.MM " + msg(" .###########n;.MM " " n* ;iM#######* x#@`"); - MSG(" :#############@;; " + msg(" :#############@;; " " .n` ,#W*iW#####W` +##,"); - MSG(" ,##############. " + msg(" ,##############. " " ix. `x###M;####### ,##i"); - MSG(" .#############@` " + msg(" .#############@` " " x@n**#W######z;M###@. W##"); - MSG(" .##############W: " + msg(" .##############W: " " .x############@*;zW#; z#x"); - MSG(" ,###############@; " + msg(" ,###############@; " " `##############@n*;. i#@"); - MSG(" ,#################i " + msg(" ,#################i " " :n##############W` .##,"); - MSG(" ,###################` " + msg(" ,###################` " " .+W##########W, `##i"); - MSG(" :###################@zi,` " + msg(" :###################@zi,` " " ;zM@@@WMn*` @#z"); - MSG(" :#######################@x+" + msg(" :#######################@x+" "*i;;:i#M, `` M#W"); - MSG(" ;##########################" + msg(" ;##########################" "######@x. n##,"); - MSG(" i#####################@W@@@" + msg(" i#####################@W@@@" "@Wxz*:` *##+"); - MSG(" *######################+```" + msg(" *######################+```" " :##M"); - MSG(" ########################M; " + msg(" ########################M; " " `@##,"); - MSG(" z#########################x" + msg(" z#########################x" ", z###"); - MSG(" n##########################" + msg(" n##########################" "#n: ;##W`"); - MSG(" x##########################" + msg(" x##########################" "###Mz#++##* `W##i"); - MSG(" M##########################" + msg(" M##########################" "##########@` ###x"); - MSG(" W##########################" + msg(" W##########################" "###########` .###,"); - MSG(" @##########################" + msg(" @##########################" "##########M n##z"); - MSG(" @##################z*i@WMMM" + msg(" @##################z*i@WMMM" "x#x@#####,. :##@."); - MSG(" `#####################@xi` " + msg(" `#####################@xi` " " `::,* x##+"); - MSG(" .#####################@#M. " + msg(" .#####################@#M. " " ;##@`"); - MSG(" ,#####################:. " + msg(" ,#####################:. " " M##i"); - MSG(" ;###################ni` " + msg(" ;###################ni` " " i##M"); - MSG(" *#################W#` " + msg(" *#################W#` " " `W##,"); - MSG(" z#################@Wx+. " + msg(" z#################@Wx+. " " +###"); - MSG(" x######################z. " + msg(" x######################z. " " .@#@`"); - MSG(" `@#######################@; " + msg(" `@#######################@; " " z##;"); - MSG(" :##########################: " + msg(" :##########################: " " :##z"); - MSG(" +#########################W# " + msg(" +#########################W# " " M#W"); - MSG(" W################@n+*i;:,` " + msg(" W################@n+*i;:,` " " +##,"); - MSG(" :##################WMxz+, " + msg(" :##################WMxz+, " " ,##i"); - MSG(" n#######################W.., " + msg(" n#######################W.., " " W##"); - MSG(" +#########################WW@+. .:. " + msg(" +#########################WW@+. .:. " " z#x"); - MSG(" `@#############################@@###: " + msg(" `@#############################@@###: " " *#W"); - MSG(" #################################Wz: " + msg(" #################################Wz: " " :#@"); - MSG(",@###############################i " + msg(",@###############################i " " .##"); - MSG("n@@@@@@@#########################+ " + msg("n@@@@@@@#########################+ " " `##"); - MSG("` `.:.`.,:iii;;;;;;;;iii;;;:` `.`` " + msg("` `.:.`.,:iii;;;;;;;;iii;;;:` `.`` " " `nW"); } diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c index 3deb09241c..cfc8eb7316 100644 --- a/src/nvim/ex_eval.c +++ b/src/nvim/ex_eval.c @@ -254,12 +254,12 @@ bool cause_errthrow(const char_u *mesg, bool severe, bool *ignore) } elem = xmalloc(sizeof(struct msglist)); - elem->msg = vim_strsave(mesg); + elem->msg = (char *)vim_strsave(mesg); elem->next = NULL; elem->throw_msg = NULL; *plist = elem; if (plist == msg_list || severe) { - char_u *tmsg; + char *tmsg; // Skip the extra "Vim " prefix for message "E458". tmsg = elem->msg; @@ -387,22 +387,22 @@ int do_intthrow(cstack_T *cstack) } // Get an exception message that is to be stored in current_exception->value. -char_u *get_exception_string(void *value, except_type_T type, char_u *cmdname, int *should_free) +char *get_exception_string(void *value, except_type_T type, char_u *cmdname, int *should_free) { - char_u *ret, *mesg; - char_u *p, *val; + char *ret, *mesg; + char *p, *val; if (type == ET_ERROR) { *should_free = true; mesg = ((struct msglist *)value)->throw_msg; if (cmdname != NULL && *cmdname != NUL) { size_t cmdlen = STRLEN(cmdname); - ret = vim_strnsave((char_u *)"Vim(", 4 + cmdlen + 2 + STRLEN(mesg)); + ret = (char *)vim_strnsave((char_u *)"Vim(", 4 + cmdlen + 2 + STRLEN(mesg)); STRCPY(&ret[4], cmdname); STRCPY(&ret[4 + cmdlen], "):"); val = ret + 4 + cmdlen + 2; } else { - ret = vim_strnsave((char_u *)"Vim:", 4 + STRLEN(mesg)); + ret = (char *)vim_strnsave((char_u *)"Vim:", 4 + STRLEN(mesg)); val = ret + 4; } @@ -438,7 +438,7 @@ char_u *get_exception_string(void *value, except_type_T type, char_u *cmdname, i } } else { *should_free = FALSE; - ret = (char_u *)value; + ret = value; } return ret; @@ -463,7 +463,7 @@ static int throw_exception(void *value, except_type_T type, char_u *cmdname) if (STRNCMP((char_u *)value, "Vim", 3) == 0 && (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':' || ((char_u *)value)[3] == '(')) { - EMSG(_("E608: Cannot :throw exceptions with 'Vim' prefix")); + emsg(_("E608: Cannot :throw exceptions with 'Vim' prefix")); goto fail; } } @@ -518,7 +518,7 @@ static int throw_exception(void *value, except_type_T type, char_u *cmdname) nomem: xfree(excp); suppress_errthrow = true; - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); fail: current_exception = NULL; return FAIL; @@ -835,7 +835,7 @@ void ex_if(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) { - eap->errmsg = (char_u *)N_("E579: :if nesting too deep"); + eap->errmsg = N_("E579: :if nesting too deep"); } else { ++cstack->cs_idx; cstack->cs_flags[cstack->cs_idx] = 0; @@ -865,7 +865,7 @@ void ex_endif(exarg_T *eap) if (eap->cstack->cs_idx < 0 || (eap->cstack->cs_flags[eap->cstack->cs_idx] & (CSF_WHILE | CSF_FOR | CSF_TRY))) { - eap->errmsg = (char_u *)N_("E580: :endif without :if"); + eap->errmsg = N_("E580: :endif without :if"); } else { // When debugging or a breakpoint was encountered, display the debug // prompt (if not already done). This shows the user that an ":endif" @@ -898,17 +898,17 @@ void ex_else(exarg_T *eap) || (cstack->cs_flags[cstack->cs_idx] & (CSF_WHILE | CSF_FOR | CSF_TRY))) { if (eap->cmdidx == CMD_else) { - eap->errmsg = (char_u *)N_("E581: :else without :if"); + eap->errmsg = N_("E581: :else without :if"); return; } - eap->errmsg = (char_u *)N_("E582: :elseif without :if"); + eap->errmsg = N_("E582: :elseif without :if"); skip = TRUE; } else if (cstack->cs_flags[cstack->cs_idx] & CSF_ELSE) { if (eap->cmdidx == CMD_else) { - eap->errmsg = (char_u *)N_("E583: multiple :else"); + eap->errmsg = N_("E583: multiple :else"); return; } - eap->errmsg = (char_u *)N_("E584: :elseif after :else"); + eap->errmsg = N_("E584: :elseif after :else"); skip = TRUE; } @@ -970,7 +970,7 @@ void ex_while(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) { - eap->errmsg = (char_u *)N_("E585: :while/:for nesting too deep"); + eap->errmsg = N_("E585: :while/:for nesting too deep"); } else { /* * The loop flag is set when we have jumped back from the matching @@ -1051,7 +1051,7 @@ void ex_continue(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0) { - eap->errmsg = (char_u *)N_("E586: :continue without :while or :for"); + eap->errmsg = N_("E586: :continue without :while or :for"); } else { // Try to find the matching ":while". This might stop at a try // conditional not in its finally clause (which is then to be executed @@ -1085,7 +1085,7 @@ void ex_break(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0) { - eap->errmsg = (char_u *)N_("E587: :break without :while or :for"); + eap->errmsg = N_("E587: :break without :while or :for"); } else { // Deactivate conditionals until the matching ":while" or a try // conditional not in its finally clause (which is then to be @@ -1106,7 +1106,7 @@ void ex_endwhile(exarg_T *eap) { cstack_T *const cstack = eap->cstack; int idx; - char_u *err; + char *err; int csf; int fl; @@ -1126,9 +1126,9 @@ void ex_endwhile(exarg_T *eap) // If we are in a ":while" or ":for" but used the wrong endloop // command, do not rewind to the next enclosing ":for"/":while". if (fl & CSF_WHILE) { - eap->errmsg = (char_u *)_("E732: Using :endfor with :while"); + eap->errmsg = _("E732: Using :endfor with :while"); } else if (fl & CSF_FOR) { - eap->errmsg = (char_u *)_("E733: Using :endwhile with :for"); + eap->errmsg = _("E733: Using :endwhile with :for"); } } if (!(fl & (CSF_WHILE | CSF_FOR))) { @@ -1188,7 +1188,7 @@ void ex_throw(exarg_T *eap) value = eval_to_string_skip(arg, (const char **)&eap->nextcmd, (bool)eap->skip); } else { - EMSG(_(e_argreq)); + emsg(_(e_argreq)); value = NULL; } @@ -1273,7 +1273,7 @@ void ex_try(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_idx == CSTACK_LEN - 1) { - eap->errmsg = (char_u *)N_("E601: :try nesting too deep"); + eap->errmsg = N_("E601: :try nesting too deep"); } else { ++cstack->cs_idx; ++cstack->cs_trylevel; @@ -1334,7 +1334,7 @@ void ex_catch(exarg_T *eap) char_u *pat; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) { - eap->errmsg = (char_u *)N_("E603: :catch without :try"); + eap->errmsg = N_("E603: :catch without :try"); give_up = TRUE; } else { if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { @@ -1351,7 +1351,7 @@ void ex_catch(exarg_T *eap) if (cstack->cs_flags[idx] & CSF_FINALLY) { // Give up for a ":catch" after ":finally" and ignore it. // Just parse. - eap->errmsg = (char_u *)N_("E604: :catch after :finally"); + eap->errmsg = N_("E604: :catch after :finally"); give_up = TRUE; } else { rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, @@ -1386,7 +1386,7 @@ void ex_catch(exarg_T *eap) if (!skip && (cstack->cs_flags[idx] & CSF_THROWN) && !(cstack->cs_flags[idx] & CSF_CAUGHT)) { if (end != NULL && *end != NUL && !ends_excmd(*skipwhite(end + 1))) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return; } @@ -1417,7 +1417,7 @@ void ex_catch(exarg_T *eap) } p_cpo = save_cpo; if (regmatch.regprog == NULL) { - EMSG2(_(e_invarg2), pat); + semsg(_(e_invarg2), pat); } else { // // Save the value of got_int and reset it. We don't want @@ -1426,7 +1426,7 @@ void ex_catch(exarg_T *eap) // prev_got_int = got_int; got_int = FALSE; - caught = vim_regexec_nl(®match, current_exception->value, + caught = vim_regexec_nl(®match, (char_u *)current_exception->value, (colnr_T)0); got_int |= prev_got_int; vim_regfree(regmatch.regprog); @@ -1483,7 +1483,7 @@ void ex_finally(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) { - eap->errmsg = (char_u *)N_("E606: :finally without :try"); + eap->errmsg = N_("E606: :finally without :try"); } else { if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { eap->errmsg = get_end_emsg(cstack); @@ -1502,7 +1502,7 @@ void ex_finally(exarg_T *eap) if (cstack->cs_flags[idx] & CSF_FINALLY) { // Give up for a multiple ":finally" and ignore it. - eap->errmsg = (char_u *)N_("E607: multiple :finally"); + eap->errmsg = N_("E607: multiple :finally"); return; } rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, @@ -1609,7 +1609,7 @@ void ex_endtry(exarg_T *eap) cstack_T *const cstack = eap->cstack; if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0) { - eap->errmsg = (char_u *)N_("E602: :endtry without :try"); + eap->errmsg = N_("E602: :endtry without :try"); } else { // Don't do something after an error, interrupt or throw in the try // block, catch clause, or finally clause preceding this ":endtry" or @@ -1628,8 +1628,9 @@ void ex_endtry(exarg_T *eap) eap->errmsg = get_end_emsg(cstack); // Find the matching ":try" and report what's missing. idx = cstack->cs_idx; - do + do{ --idx; + } while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY)); rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, &cstack->cs_looplevel); @@ -2042,7 +2043,7 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive) /* * Return an appropriate error message for a missing endwhile/endfor/endif. */ -static char_u *get_end_emsg(cstack_T *cstack) +static char *get_end_emsg(cstack_T *cstack) { if (cstack->cs_flags[cstack->cs_idx] & CSF_WHILE) { return e_endwhile; @@ -2079,7 +2080,7 @@ void rewind_conditionals(cstack_T *cstack, int idx, int cond_type, int *cond_lev */ void ex_endfunction(exarg_T *eap) { - EMSG(_("E193: :endfunction not inside a function")); + emsg(_("E193: :endfunction not inside a function")); } /* diff --git a/src/nvim/ex_eval.h b/src/nvim/ex_eval.h index d3ba43a469..25b30b2805 100644 --- a/src/nvim/ex_eval.h +++ b/src/nvim/ex_eval.h @@ -40,8 +40,8 @@ * message in the list. See cause_errthrow() below. */ struct msglist { - char_u *msg; // original message - char_u *throw_msg; // msg to throw: usually original one + char *msg; // original message + char *throw_msg; // msg to throw: usually original one struct msglist *next; // next of several messages in a row }; @@ -60,7 +60,7 @@ typedef enum typedef struct vim_exception except_T; struct vim_exception { except_type_T type; // exception type - char_u *value; // exception value + char *value; // exception value struct msglist *messages; // message(s) causing error exception char_u *throw_name; // name of the throw point linenr_T throw_lnum; // line number of the throw point diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 79c36576d5..165bfd1677 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -362,7 +362,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s bool delim_optional = false; int delim; char_u *end; - char_u *dummy; + char *dummy; exarg_T ea; pos_T save_cursor; bool use_last_pat; @@ -2036,7 +2036,6 @@ static int command_line_handle_key(CommandLineState *s) return command_line_not_changed(s); - case K_SELECT: // end of Select mode mapping - ignore return command_line_not_changed(s); @@ -2373,7 +2372,7 @@ static void abandon_cmdline(void) if (msg_scrolled == 0) { compute_cmdrow(); } - MSG(""); + msg(""); redraw_cmdline = true; } @@ -2462,7 +2461,8 @@ char *getcmdline_prompt(const char firstc, const char *const prompt, const int a * Return TRUE when the text must not be changed and we can't switch to * another window or buffer. Used when editing the command line etc. */ -int text_locked(void) { +int text_locked(void) +{ if (cmdwin_type != 0) { return TRUE; } @@ -2475,10 +2475,11 @@ int text_locked(void) { */ void text_locked_msg(void) { - EMSG(_(get_text_locked_msg())); + emsg(_(get_text_locked_msg())); } -char_u *get_text_locked_msg(void) { +char *get_text_locked_msg(void) +{ if (cmdwin_type != 0) { return e_cmdwin; } else { @@ -2491,7 +2492,7 @@ char_u *get_text_locked_msg(void) { int curbuf_locked(void) { if (curbuf->b_ro_locked > 0) { - EMSG(_("E788: Not allowed to edit another buffer now")); + emsg(_("E788: Not allowed to edit another buffer now")); return TRUE; } return allbuf_locked(); @@ -2504,7 +2505,7 @@ int curbuf_locked(void) int allbuf_locked(void) { if (allbuf_lock > 0) { - EMSG(_("E811: Not allowed to change buffer information now")); + emsg(_("E811: Not allowed to change buffer information now")); return TRUE; } return FALSE; @@ -2655,7 +2656,7 @@ void free_arshape_buf(void) #endif -enum { MAX_CB_ERRORS = 1 }; +enum { MAX_CB_ERRORS = 1, }; /// Color expression cmdline using built-in expressions parser /// @@ -3763,7 +3764,7 @@ static int nextwild(expand_T *xp, int type, int options, int escape) } if (!(ui_has(kUICmdline) || ui_has(kUIWildmenu))) { - MSG_PUTS("..."); // show that we are busy + msg_puts("..."); // show that we are busy ui_flush(); } @@ -3968,12 +3969,12 @@ char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode * causing the pattern to be added, which has illegal characters. */ if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND)) { - EMSG2(_(e_nomatch2), str); + semsg(_(e_nomatch2), str); } #endif } else if (xp->xp_numfiles == 0) { if (!(options & WILD_SILENT)) { - EMSG2(_(e_nomatch2), str); + semsg(_(e_nomatch2), str); } } else { // Escape the matches for use on the command line. @@ -4011,7 +4012,7 @@ char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode * (and possibly have to hit return to continue!). */ if (!(options & WILD_SILENT)) { - EMSG(_(e_toomany)); + emsg(_(e_toomany)); } else if (!(options & WILD_NO_BEEP)) { beep_flush(); } @@ -4366,10 +4367,10 @@ static int showmatches(expand_T *xp, int wildmenu) attr = HL_ATTR(HLF_D); // find out highlighting for directories if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - MSG_PUTS_ATTR(_("tagname"), HL_ATTR(HLF_T)); + msg_puts_attr(_("tagname"), HL_ATTR(HLF_T)); msg_clr_eos(); msg_advance(maxlen - 3); - MSG_PUTS_ATTR(_(" kind file\n"), HL_ATTR(HLF_T)); + msg_puts_attr(_(" kind file\n"), HL_ATTR(HLF_T)); } // list the files line by line @@ -4382,7 +4383,7 @@ static int showmatches(expand_T *xp, int wildmenu) msg_advance(maxlen + 1); msg_puts((const char *)p); msg_advance(maxlen + 3); - msg_puts_long_attr(p + 2, HL_ATTR(HLF_D)); + msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); break; } for (j = maxlen - lastlen; --j >= 0; ) { @@ -5606,7 +5607,6 @@ void globpath(char_u *path, char_u *file, garray_T *ga, int expand_options) } - /********************************* * Command line history stuff * *********************************/ @@ -6222,7 +6222,7 @@ void ex_history(exarg_T *eap) char_u *arg = eap->arg; if (hislen == 0) { - MSG(_("'history' option is zero")); + msg(_("'history' option is zero")); return; } @@ -6238,7 +6238,7 @@ void ex_history(exarg_T *eap) histype1 = 0; histype2 = HIST_COUNT-1; } else { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return; } } else { @@ -6248,7 +6248,7 @@ void ex_history(exarg_T *eap) end = arg; } if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return; } @@ -6256,7 +6256,7 @@ void ex_history(exarg_T *eap) STRCPY(IObuff, "\n # "); assert(history_names[histype1] != NULL); STRCAT(STRCAT(IObuff, history_names[histype1]), " history"); - MSG_PUTS_TITLE(IObuff); + msg_puts_title((char *)IObuff); idx = hisidx[histype1]; hist = history[histype1]; j = hisidx1; @@ -6475,7 +6475,7 @@ static int open_cmdwin(void) // this happens! if (!win_valid(old_curwin) || !bufref_valid(&old_curbuf)) { cmdwin_result = Ctrl_C; - EMSG(_("E199: Active window or buffer deleted")); + emsg(_("E199: Active window or buffer deleted")); } else { // autocmds may abort script processing if (aborting() && cmdwin_result != K_IGNORE) { diff --git a/src/nvim/ex_session.c b/src/nvim/ex_session.c index 0dfd7e1edd..9aa8cc0107 100644 --- a/src/nvim/ex_session.c +++ b/src/nvim/ex_session.c @@ -860,7 +860,7 @@ void ex_loadview(exarg_T *eap) char *fname = get_view_file(*eap->arg); if (fname != NULL) { if (do_source(fname, false, DOSO_NONE) == FAIL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); } xfree(fname); } @@ -980,7 +980,7 @@ void ex_mkrc(exarg_T *eap) || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL))) { if (os_chdir((char *)dirnow) != 0) { - EMSG(_(e_prev_dir)); + emsg(_(e_prev_dir)); } shorten_fnames(true); // restore original dir @@ -988,7 +988,7 @@ void ex_mkrc(exarg_T *eap) || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL))) { if (os_chdir((char *)dirnow) != 0) { - EMSG(_(e_prev_dir)); + emsg(_(e_prev_dir)); } shorten_fnames(true); } @@ -1025,7 +1025,7 @@ void ex_mkrc(exarg_T *eap) failed |= fclose(fd); if (failed) { - EMSG(_(e_write)); + emsg(_(e_write)); } else if (eap->cmdidx == CMD_mksession) { // successful session write - set v:this_session char *const tbuf = xmalloc(MAXPATHL); @@ -1043,7 +1043,7 @@ void ex_mkrc(exarg_T *eap) static char *get_view_file(int c) { if (curbuf->b_ffname == NULL) { - EMSG(_(e_noname)); + emsg(_(e_noname)); return NULL; } char *sname = (char *)home_replace_save(NULL, curbuf->b_ffname); diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index a3a7791d21..c4d8f75a21 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -48,7 +48,8 @@ # include "extmark.c.generated.h" #endif -static ExtmarkNs *buf_ns_ref(buf_T *buf, uint64_t ns_id, bool put) { +static ExtmarkNs *buf_ns_ref(buf_T *buf, uint64_t ns_id, bool put) +{ return map_ref(uint64_t, ExtmarkNs)(buf->b_extmark_ns, ns_id, put); } @@ -67,6 +68,14 @@ uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T uint64_t mark = 0; uint64_t id = idp ? *idp : 0; + uint8_t decor_level = kDecorLevelNone; // no decor + if (decor) { + decor_level = kDecorLevelVisible; // decor affects redraw + if (kv_size(decor->virt_lines)) { + decor_level = kDecorLevelVirtLine; // decor affects horizontal size + } + } + if (id == 0) { id = ns->free_id++; } else { @@ -75,7 +84,6 @@ uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T if (old_mark & MARKTREE_PAIRED_FLAG || end_row > -1) { extmark_del(buf, ns_id, id); } else { - // TODO(bfredl): we need to do more if "revising" a decoration mark. MarkTreeIter itr[1] = { 0 }; old_pos = marktree_lookup(buf->b_marktree, old_mark, itr); assert(itr->node); @@ -85,7 +93,7 @@ uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T if (it.decor) { decor_remove(buf, row, row, it.decor); } - mark = marktree_revise(buf->b_marktree, itr); + mark = marktree_revise(buf->b_marktree, itr, decor_level); goto revised; } marktree_del_itr(buf->b_marktree, itr, false); @@ -95,14 +103,6 @@ uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T } } - uint8_t decor_level = kDecorLevelNone; // no decor - if (decor) { - decor_level = kDecorLevelVisible; // decor affects redraw - if (kv_size(decor->virt_lines)) { - decor_level = kDecorLevelVirtLine; // decor affects horizontal size - } - } - if (end_row > -1) { mark = marktree_put_pair(buf->b_marktree, row, col, right_gravity, diff --git a/src/nvim/extmark.h b/src/nvim/extmark.h index aee679a9c7..c70db9f7aa 100644 --- a/src/nvim/extmark.h +++ b/src/nvim/extmark.h @@ -8,8 +8,7 @@ EXTERN int extmark_splice_pending INIT(= 0); -typedef struct -{ +typedef struct { uint64_t ns_id; uint64_t mark_id; int row; diff --git a/src/nvim/extmark_defs.h b/src/nvim/extmark_defs.h index 4d4d9aefb5..bbe8504ebf 100644 --- a/src/nvim/extmark_defs.h +++ b/src/nvim/extmark_defs.h @@ -12,8 +12,7 @@ typedef struct { } VirtTextChunk; -typedef struct -{ +typedef struct { uint64_t ns_id; uint64_t mark_id; // TODO(bfredl): a lot of small allocations. Should probably use diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index fca62353d5..9b0caa8da0 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -419,7 +419,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le len = 0; while (*wc_part != NUL) { if (len + 5 >= MAXPATHL) { - EMSG(_(e_pathtoolong)); + emsg(_(e_pathtoolong)); break; } if (STRNCMP(wc_part, "**", 2) == 0) { @@ -437,7 +437,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le } wc_part = (char_u *)errpt; if (*wc_part != NUL && !vim_ispathsep(*wc_part)) { - EMSG2(_( + semsg(_( "E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR); goto error_return; @@ -463,7 +463,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le // create an absolute path if (STRLEN(search_ctx->ffsc_start_dir) + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL) { - EMSG(_(e_pathtoolong)); + emsg(_(e_pathtoolong)); goto error_return; } STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir); @@ -1570,18 +1570,18 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first if (file_name == NULL && (options & FNAME_MESS)) { if (first == TRUE) { if (find_what == FINDFILE_DIR) { - EMSG2(_("E344: Can't find directory \"%s\" in cdpath"), + semsg(_("E344: Can't find directory \"%s\" in cdpath"), ff_file_to_find); } else { - EMSG2(_("E345: Can't find file \"%s\" in path"), + semsg(_("E345: Can't find file \"%s\" in path"), ff_file_to_find); } } else { if (find_what == FINDFILE_DIR) { - EMSG2(_("E346: No more directory \"%s\" found in cdpath"), + semsg(_("E346: No more directory \"%s\" found in cdpath"), ff_file_to_find); } else { - EMSG2(_("E347: No more file \"%s\" found in path"), + semsg(_("E347: No more file \"%s\" found in path"), ff_file_to_find); } } diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index dfe264b08c..cf4037308b 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -465,7 +465,7 @@ int readfile(char_u *fname, char_u *sfname, linenr_T from, linenr_T lines_to_ski && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname))) { - EMSG(_(e_auchangedbuf)); + emsg(_(e_auchangedbuf)); return FAIL; } } @@ -533,7 +533,7 @@ int readfile(char_u *fname, char_u *sfname, linenr_T from, linenr_T lines_to_ski && (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname)))) { - EMSG(_(e_auchangedbuf)); + emsg(_(e_auchangedbuf)); if (!read_buffer) { close(fd); } @@ -643,9 +643,9 @@ int readfile(char_u *fname, char_u *sfname, linenr_T from, linenr_T lines_to_ski --no_wait_return; msg_scroll = msg_save; if (fd < 0) { - EMSG(_("E200: *ReadPre autocommands made the file unreadable")); + emsg(_("E200: *ReadPre autocommands made the file unreadable")); } else { - EMSG(_("E201: *ReadPre autocommands must not change current buffer")); + emsg(_("E201: *ReadPre autocommands must not change current buffer")); } curbuf->b_p_ro = TRUE; // must use "w!" now return FAIL; @@ -832,7 +832,6 @@ retry: } - #ifdef HAVE_ICONV // Try using iconv() if we can't convert internally. if (fio_flags == 0 @@ -863,7 +862,7 @@ retry: advance_fenc = true; if (fd < 0) { // Re-opening the original file failed! - EMSG(_("E202: Conversion made file unreadable!")); + emsg(_("E202: Conversion made file unreadable!")); error = true; goto failed; } @@ -1519,7 +1518,6 @@ rewind_retry: try_mac = 1; try_unix = 1; for (; p >= ptr && *p != CAR; p--) { - ; } if (p >= ptr) { for (p = ptr; p < ptr + size; ++p) { @@ -1849,7 +1847,7 @@ failed: msg_scrolled_ign = true; if (!read_stdin && !read_buffer) { - p = msg_trunc_attr(IObuff, FALSE, 0); + p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0); } if (read_stdin || read_buffer || restart_edit != 0 @@ -2111,27 +2109,27 @@ static char_u *next_fenc(char_u **pp, bool *alloced) static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp) { char_u *tmpname; - char_u *errmsg = NULL; + char *errmsg = NULL; tmpname = vim_tempname(); if (tmpname == NULL) { - errmsg = (char_u *)_("Can't find temp file for conversion"); + errmsg = _("Can't find temp file for conversion"); } else { close(*fdp); // close the input file, ignore errors *fdp = -1; if (eval_charconvert((char *)fenc, "utf-8", (char *)fname, (char *)tmpname) == FAIL) { - errmsg = (char_u *)_("Conversion with 'charconvert' failed"); + errmsg = _("Conversion with 'charconvert' failed"); } if (errmsg == NULL && (*fdp = os_open((char *)tmpname, O_RDONLY, 0)) < 0) { - errmsg = (char_u *)_("can't read output of 'charconvert'"); + errmsg = _("can't read output of 'charconvert'"); } } if (errmsg != NULL) { // Don't use emsg(), it breaks mappings, the retry with // another type of conversion might still work. - MSG(errmsg); + msg(errmsg); if (tmpname != NULL) { os_remove((char *)tmpname); // delete converted file XFREE_CLEAR(tmpname); @@ -2257,7 +2255,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ if (buf->b_ml.ml_mfp == NULL) { /* This can happen during startup when there is a stray "w" in the * vimrc file. */ - EMSG(_(e_emptybuf)); + emsg(_(e_emptybuf)); return FAIL; } @@ -2271,7 +2269,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ // Avoid a crash for a long name. if (STRLEN(fname) >= MAXPATHL) { - EMSG(_(e_longname)); + emsg(_(e_longname)); return FAIL; } @@ -2433,7 +2431,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ --no_wait_return; msg_scroll = msg_save; if (nofile_err) { - EMSG(_("E676: No matching autocommands for acwrite buffer")); + emsg(_("E676: No matching autocommands for acwrite buffer")); } if (nofile_err @@ -2466,7 +2464,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ return OK; } if (!aborting()) { - EMSG(_("E203: Autocommands deleted or unloaded buffer to be written")); + emsg(_("E203: Autocommands deleted or unloaded buffer to be written")); } return FAIL; } @@ -2487,7 +2485,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ if (end < start) { --no_wait_return; msg_scroll = msg_save; - EMSG(_("E204: Autocommand changed number of lines in unexpected way")); + emsg(_("E204: Autocommand changed number of lines in unexpected way")); return FAIL; } } @@ -2772,7 +2770,7 @@ int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_ int ret; char *failed_dir; if ((ret = os_mkdir_recurse((char *)IObuff, 0755, &failed_dir)) != 0) { - EMSG3(_("E303: Unable to create directory \"%s\" for backup file: %s"), + semsg(_("E303: Unable to create directory \"%s\" for backup file: %s"), failed_dir, os_strerror(ret)); xfree(failed_dir); } @@ -2936,7 +2934,7 @@ nobackup: int ret; char *failed_dir; if ((ret = os_mkdir_recurse((char *)IObuff, 0755, &failed_dir)) != 0) { - EMSG3(_("E303: Unable to create directory \"%s\" for backup file: %s"), + semsg(_("E303: Unable to create directory \"%s\" for backup file: %s"), failed_dir, os_strerror(ret)); xfree(failed_dir); } @@ -3083,7 +3081,6 @@ nobackup: } - if (converted && wb_flags == 0) { #ifdef HAVE_ICONV // Use iconv() conversion when conversion is needed and it's not done @@ -3474,7 +3471,7 @@ restore_backup: // This may take a while, if we were interrupted let the user // know we got the message. if (got_int) { - MSG(_(e_interr)); + msg(_(e_interr)); ui_flush(); } @@ -3539,7 +3536,7 @@ restore_backup: } } - set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0); + set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0); } /* When written everything correctly: reset 'modified'. Unless not @@ -3584,7 +3581,7 @@ restore_backup: * the current backup file becomes the original file */ if (org == NULL) { - EMSG(_("E205: Patchmode: can't save original file")); + emsg(_("E205: Patchmode: can't save original file")); } else if (!os_path_exists((char_u *)org)) { vim_rename(backup, (char_u *)org); XFREE_CLEAR(backup); // don't delete the file @@ -3606,7 +3603,7 @@ restore_backup: || (empty_fd = os_open(org, O_CREAT | O_EXCL | O_NOFOLLOW, perm < 0 ? 0666 : (perm & 0777))) < 0) { - EMSG(_("E206: patchmode: can't touch empty original file")); + emsg(_("E206: patchmode: can't touch empty original file")); } else { close(empty_fd); } @@ -3623,7 +3620,7 @@ restore_backup: if (!p_bk && backup != NULL && !write_info.bw_conv_error && os_remove((char *)backup) != 0) { - EMSG(_("E207: Can't delete backup file")); + emsg(_("E207: Can't delete backup file")); } goto nofail; @@ -3663,14 +3660,14 @@ nofail: #endif if (errnum != NULL) { if (errmsgarg != 0) { - emsgf("%s: %s%s: %s", errnum, IObuff, errmsg, os_strerror(errmsgarg)); + semsg("%s: %s%s: %s", errnum, IObuff, errmsg, os_strerror(errmsgarg)); } else { - emsgf("%s: %s%s", errnum, IObuff, errmsg); + semsg("%s: %s%s", errnum, IObuff, errmsg); } } else if (errmsgarg != 0) { - emsgf(errmsg, os_strerror(errmsgarg)); + semsg(errmsg, os_strerror(errmsgarg)); } else { - EMSG(errmsg); + emsg(errmsg); } if (errmsg_allocated) { xfree(errmsg); @@ -3679,9 +3676,9 @@ nofail: retval = FAIL; if (end == 0) { const int attr = HL_ATTR(HLF_E); // Set highlight for error messages. - MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"), + msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"), attr | MSG_HIST); - MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"), + msg_puts_attr(_("don't quit the editor until the file is successfully written!"), attr | MSG_HIST); /* Update the timestamp to avoid an "overwrite changed file" @@ -3764,7 +3761,7 @@ static int set_rw_fname(char_u *fname, char_u *sfname) } if (curbuf != buf) { // We are in another buffer now, don't do the renaming. - EMSG(_(e_auchangedbuf)); + emsg(_(e_auchangedbuf)); return FAIL; } @@ -3852,20 +3849,16 @@ void msg_add_lines(int insert_space, long lnum, off_T nchars) *p++ = ' '; } if (shortmess(SHM_LINES)) { - sprintf((char *)p, "%" PRId64 "L, %" PRId64 "C", - (int64_t)lnum, (int64_t)nchars); + vim_snprintf((char *)p, IOSIZE - (p - IObuff), "%" PRId64 "L, %" PRId64 "C", + (int64_t)lnum, (int64_t)nchars); } else { - if (lnum == 1) { - STRCPY(p, _("1 line, ")); - } else { - sprintf((char *)p, _("%" PRId64 " lines, "), (int64_t)lnum); - } + vim_snprintf((char *)p, IOSIZE - (p - IObuff), + NGETTEXT("%" PRId64 " line, ", "%" PRId64 " lines, ", lnum), + (int64_t)lnum); p += STRLEN(p); - if (nchars == 1) { - STRCPY(p, _("1 character")); - } else { - sprintf((char *)p, _("%" PRId64 " characters"), (int64_t)nchars); - } + vim_snprintf((char *)p, IOSIZE - (p - IObuff), + NGETTEXT("%" PRId64 " character", "%" PRId64 " characters", nchars), + (int64_t)nchars); } } @@ -4250,7 +4243,6 @@ static int get_fio_flags(const char_u *name) } - /* * Check for a Unicode BOM (Byte Order Mark) at the start of p[size]. * "size" must be at least 2. @@ -4783,7 +4775,7 @@ int vim_rename(const char_u *from, const char_u *to) mch_free_acl(acl); #endif if (errmsg != NULL) { - EMSG2(errmsg, to); + semsg(errmsg, to); return -1; } os_remove((char *)from); @@ -4989,7 +4981,7 @@ int buf_check_timestamp(buf_T *buf) busy = false; if (n) { if (!bufref_valid(&bufref)) { - EMSG(_("E246: FileChangedShell autocommand deleted buffer")); + emsg(_("E246: FileChangedShell autocommand deleted buffer")); } s = get_vim_var_str(VV_FCS_CHOICE); if (STRCMP(s, "reload") == 0 && *reason != 'd') { @@ -5065,7 +5057,7 @@ int buf_check_timestamp(buf_T *buf) xstrlcat(tbuf, "; ", tbuf_len - 1); xstrlcat(tbuf, mesg2, tbuf_len - 1); } - EMSG(tbuf); + emsg(tbuf); retval = 2; } else { if (!autocmd_busy) { @@ -5170,7 +5162,7 @@ void buf_reload(buf_T *buf, int orig_mode) } if (savebuf == NULL || saved == FAIL || buf != curbuf || move_lines(buf, savebuf) == FAIL) { - EMSG2(_("E462: Could not prepare for reloading \"%s\""), + semsg(_("E462: Could not prepare for reloading \"%s\""), buf->b_fname); saved = FAIL; } @@ -5182,7 +5174,7 @@ void buf_reload(buf_T *buf, int orig_mode) if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, &ea, flags) != OK) { if (!aborting()) { - EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname); + semsg(_("E321: Could not reload \"%s\""), buf->b_fname); } if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf) { // Put the text back from the save buffer. First @@ -5436,7 +5428,6 @@ char_u *vim_tempname(void) } - /// Tries matching a filename with a "pattern" ("prog" is NULL), or use the /// precompiled regprog "prog" ("pattern" is NULL). That avoids calling /// vim_regcomp() often. @@ -5718,9 +5709,9 @@ char_u *file_pat_to_reg_pat(const char_u *pat, const char_u *pat_end, char *allo reg_pat[i] = NUL; if (nested != 0) { if (nested < 0) { - EMSG(_("E219: Missing {.")); + emsg(_("E219: Missing {.")); } else { - EMSG(_("E220: Missing }.")); + emsg(_("E220: Missing }.")); } XFREE_CLEAR(reg_pat); } diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 8d86dca4d8..daf0df9326 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -418,7 +418,7 @@ void opFoldRange(pos_T firstpos, pos_T lastpos, int opening, int recurse, int ha } } if (done == DONE_NOTHING) { - EMSG(_(e_nofold)); + emsg(_(e_nofold)); } // Force a redraw to remove the Visual highlighting. if (had_visual) { @@ -551,9 +551,9 @@ int foldManualAllowed(bool create) return TRUE; } if (create) { - EMSG(_("E350: Cannot create fold with current 'foldmethod'")); + emsg(_("E350: Cannot create fold with current 'foldmethod'")); } else { - EMSG(_("E351: Cannot delete fold with current 'foldmethod'")); + emsg(_("E351: Cannot delete fold with current 'foldmethod'")); } return FALSE; } @@ -764,7 +764,7 @@ void deleteFold(win_T *const wp, const linenr_T start, const linenr_T end, const } } if (!did_one) { - EMSG(_(e_nofold)); + emsg(_(e_nofold)); // Force a redraw to remove the Visual highlighting. if (had_visual) { redraw_buf_later(wp->w_buffer, INVERTED); @@ -1196,7 +1196,7 @@ static void setFoldRepeat(pos_T pos, long count, int do_open) if (!(done & DONE_ACTION)) { // Only give an error message when no fold could be opened. if (n == 0 && !(done & DONE_FOLD)) { - EMSG(_(e_nofold)); + emsg(_(e_nofold)); } break; } @@ -1333,7 +1333,7 @@ static linenr_T setManualFoldWin(win_T *wp, linenr_T lnum, int opening, int recu } done |= DONE_FOLD; } else if (donep == NULL && wp == curwin) { - EMSG(_(e_nofold)); + emsg(_(e_nofold)); } if (donep != NULL) { @@ -1651,7 +1651,7 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end) { buf_T *buf = wp->w_buffer; if (!MODIFIABLE(buf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); return; } parseMarker(wp); diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index f8cf630411..a04914efd5 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -264,7 +264,7 @@ static void add_buff(buffheader_T *const buf, const char *const s, ptrdiff_t sle buf->bh_space = 0; buf->bh_curr = &(buf->bh_first); } else if (buf->bh_curr == NULL) { // buffer has already been read - IEMSG(_("E222: Add to read buffer")); + iemsg(_("E222: Add to read buffer")); return; } else if (buf->bh_index != 0) { memmove(buf->bh_first.b_next->b_str, @@ -899,7 +899,7 @@ int ins_typebuf(char_u *str, int noremap, int offset, bool nottyped, bool silent newoff = MAXMAPLEN + 4; newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4); if (newlen < 0) { // string is getting too long - EMSG(_(e_toocompl)); // also calls flush_buffers + emsg(_(e_toocompl)); // also calls flush_buffers setcursor(); return FAIL; } @@ -1286,7 +1286,7 @@ void restore_typeahead(tasave_T *tp) void openscript(char_u *name, bool directly) { if (curscript + 1 == NSCRIPT) { - EMSG(_(e_nesting)); + emsg(_(e_nesting)); return; } @@ -1309,7 +1309,7 @@ void openscript(char_u *name, bool directly) int error; if ((scriptin[curscript] = file_open_new(&error, (char *)NameBuff, kFileReadOnly, 0)) == NULL) { - emsgf(_(e_notopen_2), name, os_strerror(error)); + semsg(_(e_notopen_2), name, os_strerror(error)); if (curscript) { curscript--; } @@ -1560,8 +1560,7 @@ int vgetc(void) buf[0] = (char_u)c; for (i = 1; i < n; i++) { buf[i] = (char_u)vgetorpeek(true); - if (buf[i] == K_SPECIAL - ) { + if (buf[i] == K_SPECIAL) { // Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence, // which represents a K_SPECIAL (0x80), // or a CSI - KS_EXTRA - KE_CSI sequence, which represents @@ -1580,7 +1579,8 @@ int vgetc(void) // If mappings are enabled (i.e., not Ctrl-v) and the user directly typed // something with a meta- or alt- modifier that was not mapped, interpret // <M-x> as <Esc>x rather than as an unbound meta keypress. #8213 - if (!no_mapping && KeyTyped + // In Terminal mode, however, this is not desirable. #16220 + if (!no_mapping && KeyTyped && !(State & TERM_FOCUS) && (mod_mask == MOD_MASK_ALT || mod_mask == MOD_MASK_META)) { mod_mask = 0; ins_char_typebuf(c); @@ -1690,7 +1690,7 @@ void vungetc(int c) old_mouse_col = mouse_col; } -/// Gets a character: +/// Gets a byte: /// 1. from the stuffbuffer /// This is used for abbreviated commands like "D" -> "d$". /// Also used to redo a command for ".". @@ -2075,7 +2075,7 @@ static int vgetorpeek(bool advance) * The depth check catches ":map x y" and ":map y x". */ if (++mapdepth >= p_mmd) { - EMSG(_("E223: recursive mapping")); + emsg(_("E223: recursive mapping")); if (State & CMDLINE) { redrawcmdline(); } else { @@ -2931,10 +2931,10 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T && args->unique && STRNCMP(mp->m_keys, lhs, (size_t)len) == 0) { if (is_abbrev) { - EMSG2(_("E224: global abbreviation already exists for %s"), + semsg(_("E224: global abbreviation already exists for %s"), mp->m_keys); } else { - EMSG2(_("E225: global mapping already exists for %s"), mp->m_keys); + semsg(_("E225: global mapping already exists for %s"), mp->m_keys); } retval = 5; goto theend; @@ -3030,9 +3030,9 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T continue; } else if (args->unique) { if (is_abbrev) { - EMSG2(_("E226: abbreviation already exists for %s"), p); + semsg(_("E226: abbreviation already exists for %s"), p); } else { - EMSG2(_("E227: mapping already exists for %s"), p); + semsg(_("E227: mapping already exists for %s"), p); } retval = 5; goto theend; @@ -3091,9 +3091,9 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T if (!has_lhs || !has_rhs) { // print entries if (!did_it && !did_local) { if (is_abbrev) { - MSG(_("No abbreviation found")); + msg(_("No abbreviation found")); } else { - MSG(_("No mapping found")); + msg(_("No mapping found")); } } goto theend; // listing finished @@ -3292,7 +3292,7 @@ void map_clear_mode(char_u *cmdp, char_u *arg, int forceit, int abbr) local = (STRCMP(arg, "<buffer>") == 0); if (!local && *arg != NUL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -4168,7 +4168,7 @@ int makemap(FILE *fd, buf_T *buf) c1 = 't'; break; default: - IEMSG(_("E228: makemap: Illegal mode")); + iemsg(_("E228: makemap: Illegal mode")); return FAIL; } do { @@ -4531,7 +4531,7 @@ char_u *getcmdkeycmd(int promptc, void *cookie, int indent, bool do_concat) if (vgetorpeek(false) == NUL) { // incomplete <Cmd> is an error, because there is not much the user // could do in this state. - EMSG(e_cmdmap_err); + emsg(e_cmdmap_err); aborted = true; break; } @@ -4558,13 +4558,13 @@ char_u *getcmdkeycmd(int promptc, void *cookie, int indent, bool do_concat) aborted = true; } else if (c1 == K_COMMAND) { // special case to give nicer error message - EMSG(e_cmdmap_repeated); + emsg(e_cmdmap_repeated); aborted = true; } else if (IS_SPECIAL(c1)) { if (c1 == K_SNR) { ga_concat(&line_ga, "<SNR>"); } else { - EMSG2(e_cmdmap_key, get_special_key_name(c1, cmod)); + semsg(e_cmdmap_key, get_special_key_name(c1, cmod)); aborted = true; } } else { diff --git a/src/nvim/getchar.h b/src/nvim/getchar.h index 4e9dd2eab7..5950611d3f 100644 --- a/src/nvim/getchar.h +++ b/src/nvim/getchar.h @@ -21,7 +21,7 @@ enum RemapValues { typedef enum { FLUSH_MINIMAL, FLUSH_TYPEAHEAD, // flush current typebuf contents - FLUSH_INPUT // flush typebuf and inchar() input + FLUSH_INPUT, // flush typebuf and inchar() input } flush_buffers_T; /// All possible |:map-arguments| usable in a |:map| command. @@ -63,7 +63,7 @@ typedef struct map_arguments MapArguments; #define KEYLEN_PART_MAP -2 // keylen value for incomplete mapping /// Maximum number of streams to read script from -enum { NSCRIPT = 15 }; +enum { NSCRIPT = 15, }; /// Streams to read script from extern FileDescriptor *scriptin[NSCRIPT]; diff --git a/src/nvim/gettext.h b/src/nvim/gettext.h index 629301e8fe..6d2a55124e 100644 --- a/src/nvim/gettext.h +++ b/src/nvim/gettext.h @@ -10,7 +10,7 @@ # else # define N_(x) x # endif -# define NGETTEXT(x, xs, n) ngettext(x, xs, n) +# define NGETTEXT(x, xs, n) ngettext(x, xs, (unsigned long)n) // On a Mac, gettext's libintl.h defines "setlocale" to be replaced by // "libintl_setlocal" which leads to wrong return values. #9789 # if defined(__APPLE__) && defined(setlocale) diff --git a/src/nvim/globals.h b/src/nvim/globals.h index d1f6e2dbd9..e2d3378402 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -845,154 +845,156 @@ EXTERN linenr_T spell_redraw_lnum INIT(= 0); // The error messages that can be shared are included here. // Excluded are errors that are only used once and debugging messages. -EXTERN char_u e_abort[] INIT(= N_("E470: Command aborted")); -EXTERN char_u e_afterinit[] INIT(= N_("E905: Cannot set this option after startup")); -EXTERN char_u e_api_spawn_failed[] INIT(= N_("E903: Could not spawn API job")); -EXTERN char_u e_argreq[] INIT(= N_("E471: Argument required")); -EXTERN char_u e_backslash[] INIT(= N_("E10: \\ should be followed by /, ? or &")); -EXTERN char_u e_cmdwin[] INIT(= - N_( - "E11: Invalid in command-line window; <CR> executes, CTRL-C quits")); -EXTERN char_u e_curdir[] INIT(= - N_( - "E12: Command not allowed from exrc/vimrc in current dir or tag search")); -EXTERN char_u e_endif[] INIT(= N_("E171: Missing :endif")); -EXTERN char_u e_endtry[] INIT(= N_("E600: Missing :endtry")); -EXTERN char_u e_endwhile[] INIT(= N_("E170: Missing :endwhile")); -EXTERN char_u e_endfor[] INIT(= N_("E170: Missing :endfor")); -EXTERN char_u e_while[] INIT(= N_("E588: :endwhile without :while")); -EXTERN char_u e_for[] INIT(= N_("E588: :endfor without :for")); -EXTERN char_u e_exists[] INIT(= N_("E13: File exists (add ! to override)")); -EXTERN char_u e_failed[] INIT(= N_("E472: Command failed")); -EXTERN char_u e_internal[] INIT(= N_("E473: Internal error")); -EXTERN char_u e_intern2[] INIT(= N_("E685: Internal error: %s")); -EXTERN char_u e_interr[] INIT(= N_("Interrupted")); -EXTERN char_u e_invarg[] INIT(= N_("E474: Invalid argument")); -EXTERN char_u e_invarg2[] INIT(= N_("E475: Invalid argument: %s")); -EXTERN char_u e_invargval[] INIT(= N_("E475: Invalid value for argument %s")); -EXTERN char_u e_invargNval[] INIT(= N_("E475: Invalid value for argument %s: %s")); -EXTERN char_u e_duparg2[] INIT(= N_("E983: Duplicate argument: %s")); -EXTERN char_u e_invexpr2[] INIT(= N_("E15: Invalid expression: %s")); -EXTERN char_u e_invrange[] INIT(= N_("E16: Invalid range")); -EXTERN char_u e_invcmd[] INIT(= N_("E476: Invalid command")); -EXTERN char_u e_isadir2[] INIT(= N_("E17: \"%s\" is a directory")); -EXTERN char_u e_no_spell[] INIT(= N_("E756: Spell checking is not possible")); -EXTERN char_u e_invchan[] INIT(= N_("E900: Invalid channel id")); -EXTERN char_u e_invchanjob[] INIT(= N_("E900: Invalid channel id: not a job")); -EXTERN char_u e_jobtblfull[] INIT(= N_("E901: Job table is full")); -EXTERN char_u e_jobspawn[] INIT(= N_("E903: Process failed to start: %s: \"%s\"")); -EXTERN char_u e_channotpty[] INIT(= N_("E904: channel is not a pty")); -EXTERN char_u e_stdiochan2[] INIT(= N_("E905: Couldn't open stdio channel: %s")); -EXTERN char_u e_invstream[] INIT(= N_("E906: invalid stream for channel")); -EXTERN char_u e_invstreamrpc[] INIT(= N_("E906: invalid stream for rpc channel, use 'rpc'")); -EXTERN char_u e_streamkey[] INIT(= - N_( - "E5210: dict key '%s' already set for buffered stream in channel %" - PRIu64)); -EXTERN char_u e_libcall[] INIT(= N_("E364: Library call failed for \"%s()\"")); +EXTERN char e_abort[] INIT(= N_("E470: Command aborted")); +EXTERN char e_afterinit[] INIT(= N_("E905: Cannot set this option after startup")); +EXTERN char e_api_spawn_failed[] INIT(= N_("E903: Could not spawn API job")); +EXTERN char e_argreq[] INIT(= N_("E471: Argument required")); +EXTERN char e_backslash[] INIT(= N_("E10: \\ should be followed by /, ? or &")); +EXTERN char e_cmdwin[] INIT(= + N_( + "E11: Invalid in command-line window; <CR> executes, CTRL-C quits")); +EXTERN char e_curdir[] INIT(= + N_( + "E12: Command not allowed from exrc/vimrc in current dir or tag search")); +EXTERN char e_endif[] INIT(= N_("E171: Missing :endif")); +EXTERN char e_endtry[] INIT(= N_("E600: Missing :endtry")); +EXTERN char e_endwhile[] INIT(= N_("E170: Missing :endwhile")); +EXTERN char e_endfor[] INIT(= N_("E170: Missing :endfor")); +EXTERN char e_while[] INIT(= N_("E588: :endwhile without :while")); +EXTERN char e_for[] INIT(= N_("E588: :endfor without :for")); +EXTERN char e_exists[] INIT(= N_("E13: File exists (add ! to override)")); +EXTERN char e_failed[] INIT(= N_("E472: Command failed")); +EXTERN char e_internal[] INIT(= N_("E473: Internal error")); +EXTERN char e_intern2[] INIT(= N_("E685: Internal error: %s")); +EXTERN char e_interr[] INIT(= N_("Interrupted")); +EXTERN char e_invarg[] INIT(= N_("E474: Invalid argument")); +EXTERN char e_invarg2[] INIT(= N_("E475: Invalid argument: %s")); +EXTERN char e_invargval[] INIT(= N_("E475: Invalid value for argument %s")); +EXTERN char e_invargNval[] INIT(= N_("E475: Invalid value for argument %s: %s")); +EXTERN char e_duparg2[] INIT(= N_("E983: Duplicate argument: %s")); +EXTERN char e_invexpr2[] INIT(= N_("E15: Invalid expression: %s")); +EXTERN char e_invrange[] INIT(= N_("E16: Invalid range")); +EXTERN char e_invcmd[] INIT(= N_("E476: Invalid command")); +EXTERN char e_isadir2[] INIT(= N_("E17: \"%s\" is a directory")); +EXTERN char e_no_spell[] INIT(= N_("E756: Spell checking is not possible")); +EXTERN char e_invchan[] INIT(= N_("E900: Invalid channel id")); +EXTERN char e_invchanjob[] INIT(= N_("E900: Invalid channel id: not a job")); +EXTERN char e_jobtblfull[] INIT(= N_("E901: Job table is full")); +EXTERN char e_jobspawn[] INIT(= N_("E903: Process failed to start: %s: \"%s\"")); +EXTERN char e_channotpty[] INIT(= N_("E904: channel is not a pty")); +EXTERN char e_stdiochan2[] INIT(= N_("E905: Couldn't open stdio channel: %s")); +EXTERN char e_invstream[] INIT(= N_("E906: invalid stream for channel")); +EXTERN char e_invstreamrpc[] INIT(= N_("E906: invalid stream for rpc channel, use 'rpc'")); +EXTERN char e_streamkey[] INIT(= + N_( + "E5210: dict key '%s' already set for buffered stream in channel %" + PRIu64)); +EXTERN char e_libcall[] INIT(= N_("E364: Library call failed for \"%s()\"")); EXTERN char e_fsync[] INIT(= N_("E667: Fsync failed: %s")); -EXTERN char_u e_mkdir[] INIT(= N_("E739: Cannot create directory %s: %s")); -EXTERN char_u e_markinval[] INIT(= N_("E19: Mark has invalid line number")); -EXTERN char_u e_marknotset[] INIT(= N_("E20: Mark not set")); -EXTERN char_u e_modifiable[] INIT(= N_("E21: Cannot make changes, 'modifiable' is off")); -EXTERN char_u e_nesting[] INIT(= N_("E22: Scripts nested too deep")); -EXTERN char_u e_noalt[] INIT(= N_("E23: No alternate file")); -EXTERN char_u e_noabbr[] INIT(= N_("E24: No such abbreviation")); -EXTERN char_u e_nobang[] INIT(= N_("E477: No ! allowed")); -EXTERN char_u e_nogroup[] INIT(= N_("E28: No such highlight group name: %s")); -EXTERN char_u e_noinstext[] INIT(= N_("E29: No inserted text yet")); -EXTERN char_u e_nolastcmd[] INIT(= N_("E30: No previous command line")); -EXTERN char_u e_nomap[] INIT(= N_("E31: No such mapping")); -EXTERN char_u e_nomatch[] INIT(= N_("E479: No match")); -EXTERN char_u e_nomatch2[] INIT(= N_("E480: No match: %s")); -EXTERN char_u e_noname[] INIT(= N_("E32: No file name")); -EXTERN char_u e_nopresub[] INIT(= N_("E33: No previous substitute regular expression")); -EXTERN char_u e_noprev[] INIT(= N_("E34: No previous command")); -EXTERN char_u e_noprevre[] INIT(= N_("E35: No previous regular expression")); -EXTERN char_u e_norange[] INIT(= N_("E481: No range allowed")); -EXTERN char_u e_noroom[] INIT(= N_("E36: Not enough room")); -EXTERN char_u e_notmp[] INIT(= N_("E483: Can't get temp file name")); -EXTERN char_u e_notopen[] INIT(= N_("E484: Can't open file %s")); -EXTERN char_u e_notopen_2[] INIT(= N_("E484: Can't open file %s: %s")); -EXTERN char_u e_notread[] INIT(= N_("E485: Can't read file %s")); -EXTERN char_u e_null[] INIT(= N_("E38: Null argument")); -EXTERN char_u e_number_exp[] INIT(= N_("E39: Number expected")); -EXTERN char_u e_openerrf[] INIT(= N_("E40: Can't open errorfile %s")); -EXTERN char_u e_outofmem[] INIT(= N_("E41: Out of memory!")); -EXTERN char_u e_patnotf[] INIT(= N_("Pattern not found")); -EXTERN char_u e_patnotf2[] INIT(= N_("E486: Pattern not found: %s")); -EXTERN char_u e_positive[] INIT(= N_("E487: Argument must be positive")); -EXTERN char_u e_prev_dir[] INIT(= N_("E459: Cannot go back to previous directory")); - -EXTERN char_u e_quickfix[] INIT(= N_("E42: No Errors")); -EXTERN char_u e_loclist[] INIT(= N_("E776: No location list")); -EXTERN char_u e_re_damg[] INIT(= N_("E43: Damaged match string")); -EXTERN char_u e_re_corr[] INIT(= N_("E44: Corrupted regexp program")); -EXTERN char_u e_readonly[] INIT(= N_("E45: 'readonly' option is set (add ! to override)")); -EXTERN char_u e_readonlyvar[] INIT(= N_("E46: Cannot change read-only variable \"%.*s\"")); -EXTERN char_u e_stringreq[] INIT(= N_("E928: String required")); -EXTERN char_u e_dictreq[] INIT(= N_("E715: Dictionary required")); -EXTERN char_u e_blobidx[] INIT(= N_("E979: Blob index out of range: %" PRId64)); -EXTERN char_u e_invalblob[] INIT(= N_("E978: Invalid operation for Blob")); -EXTERN char_u e_toomanyarg[] INIT(= N_("E118: Too many arguments for function: %s")); -EXTERN char_u e_dictkey[] INIT(= N_("E716: Key not present in Dictionary: \"%s\"")); -EXTERN char_u e_listreq[] INIT(= N_("E714: List required")); -EXTERN char_u e_listblobreq[] INIT(= N_("E897: List or Blob required")); -EXTERN char_u e_listdictarg[] INIT(= N_("E712: Argument of %s must be a List or Dictionary")); -EXTERN char_u e_listdictblobarg[] INIT(= - N_( - "E896: Argument of %s must be a List, Dictionary or Blob")); -EXTERN char_u e_readerrf[] INIT(= N_("E47: Error while reading errorfile")); -EXTERN char_u e_sandbox[] INIT(= N_("E48: Not allowed in sandbox")); -EXTERN char_u e_secure[] INIT(= N_("E523: Not allowed here")); -EXTERN char_u e_screenmode[] INIT(= N_("E359: Screen mode setting not supported")); -EXTERN char_u e_scroll[] INIT(= N_("E49: Invalid scroll size")); -EXTERN char_u e_shellempty[] INIT(= N_("E91: 'shell' option is empty")); -EXTERN char_u e_signdata[] INIT(= N_("E255: Couldn't read in sign data!")); -EXTERN char_u e_swapclose[] INIT(= N_("E72: Close error on swap file")); -EXTERN char_u e_tagstack[] INIT(= N_("E73: tag stack empty")); -EXTERN char_u e_toocompl[] INIT(= N_("E74: Command too complex")); -EXTERN char_u e_longname[] INIT(= N_("E75: Name too long")); -EXTERN char_u e_toomsbra[] INIT(= N_("E76: Too many [")); -EXTERN char_u e_toomany[] INIT(= N_("E77: Too many file names")); -EXTERN char_u e_trailing[] INIT(= N_("E488: Trailing characters")); -EXTERN char_u e_trailing2[] INIT(= N_("E488: Trailing characters: %s")); -EXTERN char_u e_umark[] INIT(= N_("E78: Unknown mark")); -EXTERN char_u e_wildexpand[] INIT(= N_("E79: Cannot expand wildcards")); -EXTERN char_u e_winheight[] INIT(= N_("E591: 'winheight' cannot be smaller than 'winminheight'")); -EXTERN char_u e_winwidth[] INIT(= N_("E592: 'winwidth' cannot be smaller than 'winminwidth'")); -EXTERN char_u e_write[] INIT(= N_("E80: Error while writing")); -EXTERN char_u e_zerocount[] INIT(= N_("E939: Positive count required")); -EXTERN char_u e_usingsid[] INIT(= N_("E81: Using <SID> not in a script context")); -EXTERN char_u e_missingparen[] INIT(= N_("E107: Missing parentheses: %s")); -EXTERN char_u e_maxmempat[] INIT(= N_("E363: pattern uses more memory than 'maxmempattern'")); -EXTERN char_u e_emptybuf[] INIT(= N_("E749: empty buffer")); -EXTERN char_u e_nobufnr[] INIT(= N_("E86: Buffer %" PRId64 " does not exist")); - -EXTERN char_u e_invalpat[] INIT(= N_("E682: Invalid search pattern or delimiter")); -EXTERN char_u e_bufloaded[] INIT(= N_("E139: File is loaded in another buffer")); -EXTERN char_u e_notset[] INIT(= N_("E764: Option '%s' is not set")); -EXTERN char_u e_invalidreg[] INIT(= N_("E850: Invalid register name")); -EXTERN char_u e_dirnotf[] INIT(= N_("E919: Directory not found in '%s': \"%s\"")); -EXTERN char_u e_au_recursive[] INIT(= N_("E952: Autocommand caused recursive behavior")); -EXTERN char_u e_autocmd_close[] INIT(= N_("E813: Cannot close autocmd window")); -EXTERN char_u e_unsupportedoption[] INIT(= N_("E519: Option not supported")); -EXTERN char_u e_fnametoolong[] INIT(= N_("E856: Filename too long")); -EXTERN char_u e_float_as_string[] INIT(= N_("E806: using Float as a String")); - -EXTERN char_u e_autocmd_err[] INIT(=N_("E5500: autocmd has thrown an exception: %s")); -EXTERN char_u e_cmdmap_err[] INIT(=N_("E5520: <Cmd> mapping must end with <CR>")); -EXTERN char_u +EXTERN char e_mkdir[] INIT(= N_("E739: Cannot create directory %s: %s")); +EXTERN char e_markinval[] INIT(= N_("E19: Mark has invalid line number")); +EXTERN char e_marknotset[] INIT(= N_("E20: Mark not set")); +EXTERN char e_modifiable[] INIT(= N_("E21: Cannot make changes, 'modifiable' is off")); +EXTERN char e_nesting[] INIT(= N_("E22: Scripts nested too deep")); +EXTERN char e_noalt[] INIT(= N_("E23: No alternate file")); +EXTERN char e_noabbr[] INIT(= N_("E24: No such abbreviation")); +EXTERN char e_nobang[] INIT(= N_("E477: No ! allowed")); +EXTERN char e_nogroup[] INIT(= N_("E28: No such highlight group name: %s")); +EXTERN char e_noinstext[] INIT(= N_("E29: No inserted text yet")); +EXTERN char e_nolastcmd[] INIT(= N_("E30: No previous command line")); +EXTERN char e_nomap[] INIT(= N_("E31: No such mapping")); +EXTERN char e_nomatch[] INIT(= N_("E479: No match")); +EXTERN char e_nomatch2[] INIT(= N_("E480: No match: %s")); +EXTERN char e_noname[] INIT(= N_("E32: No file name")); +EXTERN char e_nopresub[] INIT(= N_("E33: No previous substitute regular expression")); +EXTERN char e_noprev[] INIT(= N_("E34: No previous command")); +EXTERN char e_noprevre[] INIT(= N_("E35: No previous regular expression")); +EXTERN char e_norange[] INIT(= N_("E481: No range allowed")); +EXTERN char e_noroom[] INIT(= N_("E36: Not enough room")); +EXTERN char e_notmp[] INIT(= N_("E483: Can't get temp file name")); +EXTERN char e_notopen[] INIT(= N_("E484: Can't open file %s")); +EXTERN char e_notopen_2[] INIT(= N_("E484: Can't open file %s: %s")); +EXTERN char e_notread[] INIT(= N_("E485: Can't read file %s")); +EXTERN char e_null[] INIT(= N_("E38: Null argument")); +EXTERN char e_number_exp[] INIT(= N_("E39: Number expected")); +EXTERN char e_openerrf[] INIT(= N_("E40: Can't open errorfile %s")); +EXTERN char e_outofmem[] INIT(= N_("E41: Out of memory!")); +EXTERN char e_patnotf[] INIT(= N_("Pattern not found")); +EXTERN char e_patnotf2[] INIT(= N_("E486: Pattern not found: %s")); +EXTERN char e_positive[] INIT(= N_("E487: Argument must be positive")); +EXTERN char e_prev_dir[] INIT(= N_("E459: Cannot go back to previous directory")); + +EXTERN char e_quickfix[] INIT(= N_("E42: No Errors")); +EXTERN char e_loclist[] INIT(= N_("E776: No location list")); +EXTERN char e_re_damg[] INIT(= N_("E43: Damaged match string")); +EXTERN char e_re_corr[] INIT(= N_("E44: Corrupted regexp program")); +EXTERN char e_readonly[] INIT(= N_("E45: 'readonly' option is set (add ! to override)")); +EXTERN char e_readonlyvar[] INIT(= N_("E46: Cannot change read-only variable \"%.*s\"")); +EXTERN char e_stringreq[] INIT(= N_("E928: String required")); +EXTERN char e_dictreq[] INIT(= N_("E715: Dictionary required")); +EXTERN char e_blobidx[] INIT(= N_("E979: Blob index out of range: %" PRId64)); +EXTERN char e_invalblob[] INIT(= N_("E978: Invalid operation for Blob")); +EXTERN char e_toomanyarg[] INIT(= N_("E118: Too many arguments for function: %s")); +EXTERN char e_dictkey[] INIT(= N_("E716: Key not present in Dictionary: \"%s\"")); +EXTERN char e_listreq[] INIT(= N_("E714: List required")); +EXTERN char e_listblobreq[] INIT(= N_("E897: List or Blob required")); +EXTERN char e_listdictarg[] INIT(= N_("E712: Argument of %s must be a List or Dictionary")); +EXTERN char e_listdictblobarg[] INIT(= + N_( + "E896: Argument of %s must be a List, Dictionary or Blob")); +EXTERN char e_readerrf[] INIT(= N_("E47: Error while reading errorfile")); +EXTERN char e_sandbox[] INIT(= N_("E48: Not allowed in sandbox")); +EXTERN char e_secure[] INIT(= N_("E523: Not allowed here")); +EXTERN char e_screenmode[] INIT(= N_("E359: Screen mode setting not supported")); +EXTERN char e_scroll[] INIT(= N_("E49: Invalid scroll size")); +EXTERN char e_shellempty[] INIT(= N_("E91: 'shell' option is empty")); +EXTERN char e_signdata[] INIT(= N_("E255: Couldn't read in sign data!")); +EXTERN char e_swapclose[] INIT(= N_("E72: Close error on swap file")); +EXTERN char e_tagstack[] INIT(= N_("E73: tag stack empty")); +EXTERN char e_toocompl[] INIT(= N_("E74: Command too complex")); +EXTERN char e_longname[] INIT(= N_("E75: Name too long")); +EXTERN char e_toomsbra[] INIT(= N_("E76: Too many [")); +EXTERN char e_toomany[] INIT(= N_("E77: Too many file names")); +EXTERN char e_trailing[] INIT(= N_("E488: Trailing characters")); +EXTERN char e_trailing2[] INIT(= N_("E488: Trailing characters: %s")); +EXTERN char e_umark[] INIT(= N_("E78: Unknown mark")); +EXTERN char e_wildexpand[] INIT(= N_("E79: Cannot expand wildcards")); +EXTERN char e_winheight[] INIT(= N_("E591: 'winheight' cannot be smaller than 'winminheight'")); +EXTERN char e_winwidth[] INIT(= N_("E592: 'winwidth' cannot be smaller than 'winminwidth'")); +EXTERN char e_write[] INIT(= N_("E80: Error while writing")); +EXTERN char e_zerocount[] INIT(= N_("E939: Positive count required")); +EXTERN char e_usingsid[] INIT(= N_("E81: Using <SID> not in a script context")); +EXTERN char e_missingparen[] INIT(= N_("E107: Missing parentheses: %s")); +EXTERN char e_maxmempat[] INIT(= N_("E363: pattern uses more memory than 'maxmempattern'")); +EXTERN char e_emptybuf[] INIT(= N_("E749: empty buffer")); +EXTERN char e_nobufnr[] INIT(= N_("E86: Buffer %" PRId64 " does not exist")); + +EXTERN char e_invalpat[] INIT(= N_("E682: Invalid search pattern or delimiter")); +EXTERN char e_bufloaded[] INIT(= N_("E139: File is loaded in another buffer")); +EXTERN char e_notset[] INIT(= N_("E764: Option '%s' is not set")); +EXTERN char e_invalidreg[] INIT(= N_("E850: Invalid register name")); +EXTERN char e_dirnotf[] INIT(= N_("E919: Directory not found in '%s': \"%s\"")); +EXTERN char e_au_recursive[] INIT(= N_("E952: Autocommand caused recursive behavior")); +EXTERN char e_autocmd_close[] INIT(= N_("E813: Cannot close autocmd window")); +EXTERN char e_unsupportedoption[] INIT(= N_("E519: Option not supported")); +EXTERN char e_fnametoolong[] INIT(= N_("E856: Filename too long")); +EXTERN char e_float_as_string[] INIT(= N_("E806: using Float as a String")); + +EXTERN char e_autocmd_err[] INIT(=N_("E5500: autocmd has thrown an exception: %s")); +EXTERN char e_cmdmap_err[] INIT(=N_("E5520: <Cmd> mapping must end with <CR>")); +EXTERN char e_cmdmap_repeated[] INIT(=N_("E5521: <Cmd> mapping must end with <CR> before second <Cmd>")); -EXTERN char_u e_cmdmap_key[] INIT(=N_("E5522: <Cmd> mapping must not include %s key")); +EXTERN char e_cmdmap_key[] INIT(=N_("E5522: <Cmd> mapping must not include %s key")); -EXTERN char_u e_api_error[] INIT(=N_("E5555: API call: %s")); +EXTERN char e_api_error[] INIT(=N_("E5555: API call: %s")); EXTERN char e_luv_api_disabled[] INIT(=N_("E5560: %s must not be called in a lua loop callback")); -EXTERN char_u e_floatonly[] INIT(=N_( - "E5601: Cannot close window, only floating window would remain")); -EXTERN char_u e_floatexchange[] INIT(=N_("E5602: Cannot exchange or rotate float")); +EXTERN char e_floatonly[] INIT(=N_( + "E5601: Cannot close window, only floating window would remain")); +EXTERN char e_floatexchange[] INIT(=N_("E5602: Cannot exchange or rotate float")); + +EXTERN char e_non_empty_string_required[] INIT(= N_("E1142: Non-empty string required")); EXTERN char e_cannot_define_autocommands_for_all_events[] INIT(= N_( @@ -1023,7 +1025,7 @@ EXTERN bool headless_mode INIT(= false); typedef enum { kUnknown, kWorking, - kBroken + kBroken, } WorkingStatus; /// The scope of a working-directory command like `:cd`. diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index d9830de2b5..a6cbfa7a72 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -263,7 +263,7 @@ struct prt_resfile_buffer_S { * Parse 'printoptions' and set the flags in "printer_opts". * Returns an error message or NULL; */ -char_u *parse_printoptions(void) +char *parse_printoptions(void) { return parse_list_options(p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS); } @@ -272,7 +272,7 @@ char_u *parse_printoptions(void) * Parse 'printoptions' and set the flags in "printer_opts". * Returns an error message or NULL; */ -char_u *parse_printmbfont(void) +char *parse_printmbfont(void) { return parse_list_options(p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS); } @@ -286,10 +286,10 @@ char_u *parse_printmbfont(void) * Returns an error message for an illegal option, NULL otherwise. * Only used for the printer at the moment... */ -static char_u *parse_list_options(char_u *option_str, option_table_T *table, size_t table_size) +static char *parse_list_options(char_u *option_str, option_table_T *table, size_t table_size) { option_table_T *old_opts; - char_u *ret = NULL; + char *ret = NULL; char_u *stringp; char_u *colonp; char_u *commap; @@ -312,7 +312,7 @@ static char_u *parse_list_options(char_u *option_str, option_table_T *table, siz while (*stringp) { colonp = vim_strchr(stringp, ':'); if (colonp == NULL) { - ret = (char_u *)N_("E550: Missing colon"); + ret = N_("E550: Missing colon"); break; } commap = vim_strchr(stringp, ','); @@ -329,7 +329,7 @@ static char_u *parse_list_options(char_u *option_str, option_table_T *table, siz } if (idx == table_size) { - ret = (char_u *)N_("E551: Illegal component"); + ret = N_("E551: Illegal component"); break; } @@ -338,7 +338,7 @@ static char_u *parse_list_options(char_u *option_str, option_table_T *table, siz if (table[idx].hasnum) { if (!ascii_isdigit(*p)) { - ret = (char_u *)N_("E552: digit expected"); + ret = N_("E552: digit expected"); break; } @@ -621,12 +621,12 @@ void ex_hardcopy(exarg_T *eap) settings.has_color = TRUE; if (*eap->arg == '>') { - char_u *errormsg = NULL; + char *errormsg = NULL; // Expand things like "%.ps". if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL) { if (errormsg != NULL) { - EMSG(errormsg); + emsg(errormsg); } return; } @@ -684,7 +684,7 @@ void ex_hardcopy(exarg_T *eap) bytes_to_print += STRLEN(skipwhite(ml_get(lnum))); } if (bytes_to_print == 0) { - MSG(_("No text to be printed")); + msg(_("No text to be printed")); goto print_fail_no_begin; } @@ -1329,7 +1329,7 @@ static void prt_write_file_raw_len(char_u *buffer, size_t bytes) { if (!prt_file_error && fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd) != bytes) { - EMSG(_("E455: Error writing to PostScript output file")); + emsg(_("E455: Error writing to PostScript output file")); prt_file_error = TRUE; } } @@ -1704,7 +1704,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) FILE *fd_resource = os_fopen((char *)resource->filename, READBIN); if (fd_resource == NULL) { - EMSG2(_("E624: Can't open file \"%s\""), resource->filename); + semsg(_("E624: Can't open file \"%s\""), resource->filename); return false; } memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN); @@ -1713,7 +1713,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) prt_resfile.len = (int)fread((char *)prt_resfile.buffer, sizeof(char_u), PRT_FILE_BUFFER_LEN, fd_resource); if (ferror(fd_resource)) { - EMSG2(_("E457: Can't read PostScript resource file \"%s\""), + semsg(_("E457: Can't read PostScript resource file \"%s\""), resource->filename); fclose(fd_resource); return false; @@ -1729,7 +1729,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) if (prt_resfile_strncmp(offset, PRT_RESOURCE_HEADER, (int)STRLEN(PRT_RESOURCE_HEADER)) != 0) { - EMSG2(_("E618: file \"%s\" is not a PostScript resource file"), + semsg(_("E618: file \"%s\" is not a PostScript resource file"), resource->filename); return false; } @@ -1746,7 +1746,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) } if (prt_resfile_strncmp(offset, PRT_RESOURCE_RESOURCE, (int)STRLEN(PRT_RESOURCE_RESOURCE)) != 0) { - EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), + semsg(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } @@ -1763,7 +1763,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) (int)STRLEN(PRT_RESOURCE_CMAP)) == 0) { resource->type = PRT_RESOURCE_TYPE_CMAP; } else { - EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), + semsg(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } @@ -1804,7 +1804,7 @@ static bool prt_open_resource(struct prt_ps_resource_S *resource) } if (!seen_title || !seen_version) { - EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), + semsg(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } @@ -1817,7 +1817,7 @@ static bool prt_check_resource(const struct prt_ps_resource_S *resource, const c { // Version number m.n should match, the revision number does not matter if (STRNCMP(resource->version, version, STRLEN(version))) { - EMSG2(_("E621: \"%s\" resource file has wrong version"), + semsg(_("E621: \"%s\" resource file has wrong version"), resource->name); return false; } @@ -2203,7 +2203,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) if (!prt_custom_cmap) { // Check encoding and character set are compatible if ((p_mbenc->needs_charset & p_mbchar->has_charset) == 0) { - EMSG(_("E673: Incompatible multi-byte encoding and character set.")); + emsg(_("E673: Incompatible multi-byte encoding and character set.")); return FALSE; } @@ -2215,7 +2215,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) } else { // Add custom CMap character set name if (*p_pmcs == NUL) { - EMSG(_("E674: printmbcharset cannot be empty with multi-byte encoding.")); + emsg(_("E674: printmbcharset cannot be empty with multi-byte encoding.")); return FALSE; } STRLCPY(prt_cmap, p_pmcs, sizeof(prt_cmap) - 2); @@ -2231,7 +2231,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) STRCAT(prt_cmap, "H"); if (!mbfont_opts[OPT_MBFONT_REGULAR].present) { - EMSG(_("E675: No default font specified for multi-byte printing.")); + emsg(_("E675: No default font specified for multi-byte printing.")); return FALSE; } @@ -2394,7 +2394,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) if (psettings->outfile == NULL) { prt_ps_file_name = vim_tempname(); if (prt_ps_file_name == NULL) { - EMSG(_(e_notmp)); + emsg(_(e_notmp)); return FAIL; } prt_ps_fd = os_fopen((char *)prt_ps_file_name, WRITEBIN); @@ -2406,7 +2406,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) } } if (prt_ps_fd == NULL) { - EMSG(_("E324: Can't open PostScript output file")); + emsg(_("E324: Can't open PostScript output file")); mch_print_cleanup(); return FAIL; } @@ -2439,7 +2439,7 @@ static int prt_add_resource(struct prt_ps_resource_S *resource) fd_resource = os_fopen((char *)resource->filename, READBIN); if (fd_resource == NULL) { - EMSG2(_("E456: Can't open file \"%s\""), resource->filename); + semsg(_("E456: Can't open file \"%s\""), resource->filename); return FALSE; } switch (resource->type) { @@ -2459,7 +2459,7 @@ static int prt_add_resource(struct prt_ps_resource_S *resource) bytes_read = fread((char *)resource_buffer, sizeof(char_u), sizeof(resource_buffer), fd_resource); if (ferror(fd_resource)) { - EMSG2(_("E457: Can't read PostScript resource file \"%s\""), + semsg(_("E457: Can't read PostScript resource file \"%s\""), resource->filename); fclose(fd_resource); return FALSE; @@ -2567,7 +2567,7 @@ int mch_print_begin(prt_settings_T *psettings) // Search for external resources VIM supplies if (!prt_find_resource("prolog", &res_prolog)) { - EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\"")); + emsg(_("E456: Can't find PostScript resource file \"prolog.ps\"")); return FALSE; } if (!prt_open_resource(&res_prolog)) { @@ -2579,7 +2579,7 @@ int mch_print_begin(prt_settings_T *psettings) if (prt_out_mbyte) { // Look for required version of multi-byte printing procset if (!prt_find_resource("cidfont", &res_cidfont)) { - EMSG(_("E456: Can't find PostScript resource file \"cidfont.ps\"")); + emsg(_("E456: Can't find PostScript resource file \"cidfont.ps\"")); return FALSE; } if (!prt_open_resource(&res_cidfont)) { @@ -2609,7 +2609,7 @@ int mch_print_begin(prt_settings_T *psettings) // Use latin1 as default printing encoding p_encoding = (char_u *)"latin1"; if (!prt_find_resource((char *)p_encoding, &res_encoding)) { - EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), + semsg(_("E456: Can't find PostScript resource file \"%s.ps\""), p_encoding); return FALSE; } @@ -2628,7 +2628,7 @@ int mch_print_begin(prt_settings_T *psettings) if (prt_use_courier) { // Include ASCII range encoding vector if (!prt_find_resource(prt_ascii_encoding, &res_encoding)) { - EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), + semsg(_("E456: Can't find PostScript resource file \"%s.ps\""), prt_ascii_encoding); return FALSE; } @@ -2644,7 +2644,7 @@ int mch_print_begin(prt_settings_T *psettings) if (!(enc_canon_props(p_enc) & enc_canon_props(p_encoding) & ENC_8BIT)) { // Set up encoding conversion if required if (convert_setup(&prt_conv, p_enc, p_encoding) == FAIL) { - emsgf(_("E620: Unable to convert to print encoding \"%s\""), + semsg(_("E620: Unable to convert to print encoding \"%s\""), p_encoding); return false; } @@ -2654,7 +2654,7 @@ int mch_print_begin(prt_settings_T *psettings) if (prt_out_mbyte && prt_custom_cmap) { // Find user supplied CMap if (!prt_find_resource(prt_cmap, &res_cmap)) { - EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), + semsg(_("E456: Can't find PostScript resource file \"%s.ps\""), prt_cmap); return FALSE; } @@ -2879,7 +2879,7 @@ void mch_print_end(prt_settings_T *psettings) // Not printing to a file: use 'printexpr' to print the file. if (eval_printexpr((char *)prt_ps_file_name, (char *)psettings->arguments) == FAIL) { - EMSG(_("E365: Failed to print PostScript file")); + emsg(_("E365: Failed to print PostScript file")); } else { prt_message((char_u *)_("Print job sent.")); } diff --git a/src/nvim/hashtab.c b/src/nvim/hashtab.c index a8e5de839a..ca6f033c47 100644 --- a/src/nvim/hashtab.c +++ b/src/nvim/hashtab.c @@ -281,11 +281,11 @@ static void hash_may_resize(hashtab_T *ht, size_t minitems) #ifdef HT_DEBUG if (ht->ht_used > ht->ht_filled) { - EMSG("hash_may_resize(): more used than filled"); + emsg("hash_may_resize(): more used than filled"); } if (ht->ht_filled >= ht->ht_mask + 1) { - EMSG("hash_may_resize(): table completely filled"); + emsg("hash_may_resize(): table completely filled"); } #endif // ifdef HT_DEBUG diff --git a/src/nvim/highlight.c b/src/nvim/highlight.c index 737e668e81..3050ca02de 100644 --- a/src/nvim/highlight.c +++ b/src/nvim/highlight.c @@ -76,7 +76,7 @@ static int get_attr_entry(HlEntry entry) // compute new ones for all groups. // When called recursively, we are really out of numbers. if (recursive) { - EMSG(_("E424: Too many different highlighting attributes in use")); + emsg(_("E424: Too many different highlighting attributes in use")); return 0; } recursive = true; diff --git a/src/nvim/highlight_defs.h b/src/nvim/highlight_defs.h index 12f2b62313..d4d53c4126 100644 --- a/src/nvim/highlight_defs.h +++ b/src/nvim/highlight_defs.h @@ -103,7 +103,7 @@ typedef enum { HLF_NFLOAT, // Floating window HLF_MSG, // Message area HLF_BORDER, // Floating window border - HLF_COUNT // MUST be the last one + HLF_COUNT, // MUST be the last one } hlf_T; EXTERN const char *hlf_names[] INIT(= { diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index d731e79473..5b5f056164 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -64,7 +64,7 @@ static cscmd_T cs_cmds[] = static void cs_usage_msg(csid_e x) { - (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage); + (void)semsg(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage); } @@ -72,7 +72,7 @@ static enum { EXP_CSCOPE_SUBCMD, // expand ":cscope" sub-commands EXP_SCSCOPE_SUBCMD, // expand ":scscope" sub-commands EXP_CSCOPE_FIND, // expand ":cscope find" arguments - EXP_CSCOPE_KILL // expand ":cscope kill" arguments + EXP_CSCOPE_KILL, // expand ":cscope kill" arguments } expand_what; /* @@ -184,7 +184,7 @@ static void do_cscope_general(exarg_T *eap, int make_split) if (make_split) { if (!cmdp->cansplit) { - (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n")); + (void)msg_puts(_("This cscope command does not support splitting the window.\n")); return; } postponed_split = -1; @@ -216,7 +216,7 @@ void ex_cstag(exarg_T *eap) int ret = FALSE; if (*eap->arg == NUL) { - (void)EMSG(_("E562: Usage: cstag <ident>")); + (void)emsg(_("E562: Usage: cstag <ident>")); return; } @@ -268,7 +268,7 @@ void ex_cstag(exarg_T *eap) } if (!ret) { - (void)EMSG(_("E257: cstag: tag not found")); + (void)emsg(_("E257: cstag: tag not found")); g_do_tagpreview = 0; } } @@ -403,12 +403,8 @@ static int cs_add(exarg_T *eap) static void cs_stat_emsg(char *fname) { - char *stat_emsg = _("E563: stat(%s) error: %d"); - char *buf = xmalloc(strlen(stat_emsg) + MAXPATHL + 10); - - (void)sprintf(buf, stat_emsg, fname, errno); - (void)EMSG(buf); - xfree(buf); + int err = errno; + (void)semsg(_("E563: stat(%s) error: %d"), fname, err); } @@ -489,7 +485,7 @@ staterr: i = cs_insert_filelist(fname, ppath, flags, &file_info); } else { if (p_csverbose) { - (void)EMSG2(_("E564: %s is not a directory or a valid cscope database"), + (void)semsg(_("E564: %s is not a directory or a valid cscope database"), fname); } goto add_err; @@ -550,7 +546,7 @@ static size_t cs_cnt_connections(void) /// @param idx connection index static void cs_reading_emsg(size_t idx) { - EMSGU(_("E262: error reading cscope connection %" PRIu64), idx); + semsg(_("E262: error reading cscope connection %" PRIu64), (uint64_t)idx); } #define CSREAD_BUFSIZE 2048 @@ -662,7 +658,7 @@ static char *cs_create_cmd(char *csoption, char *pattern) search = 9; break; default: - (void)EMSG(_("E561: unknown cscope search type")); + (void)emsg(_("E561: unknown cscope search type")); cs_usage_msg(Find); return NULL; } @@ -700,7 +696,7 @@ static int cs_create_connection(size_t i) */ to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1; if (pipe(to_cs) < 0 || pipe(from_cs) < 0) { - (void)EMSG(_("E566: Could not create cscope pipes")); + (void)emsg(_("E566: Could not create cscope pipes")); err_closing: if (to_cs[0] != -1) { (void)close(to_cs[0]); @@ -719,7 +715,7 @@ err_closing: switch (csinfo[i].pid = fork()) { case -1: - (void)EMSG(_("E622: Could not fork for cscope")); + (void)emsg(_("E622: Could not fork for cscope")); goto err_closing; case 0: // child: run cscope. if (dup2(to_cs[0], STDIN_FILENO) == -1) { @@ -752,7 +748,7 @@ err_closing: if (!(pipe_stdin = CreatePipe(&stdin_rd, &stdin_wr, &sa, 0)) || !(pipe_stdout = CreatePipe(&stdout_rd, &stdout_wr, &sa, 0))) { - (void)EMSG(_("E566: Could not create cscope pipes")); + (void)emsg(_("E566: Could not create cscope pipes")); err_closing: if (pipe_stdin) { CloseHandle(stdin_rd); @@ -856,7 +852,7 @@ err_closing: if (!created) { PERROR(_("cs_create_connection exec failed")); - (void)EMSG(_("E623: Could not spawn cscope process")); + (void)emsg(_("E623: Could not spawn cscope process")); goto err_closing; } // else @@ -892,7 +888,7 @@ static int cs_find(exarg_T *eap) char *opt, *pat; if (cs_check_for_connections() == FALSE) { - (void)EMSG(_("E567: no cscope connections")); + (void)emsg(_("E567: no cscope connections")); return FALSE; } @@ -970,13 +966,7 @@ static int cs_find_common(char *opt, char *pat, int forceit, int verbose, int us qfpos++; // next symbol must be + or - if (strchr(CSQF_FLAGS, *qfpos) == NULL) { - char *nf = _("E469: invalid cscopequickfix flag %c for %c"); - // strlen will be enough because we use chars - char *buf = xmalloc(strlen(nf)); - - sprintf(buf, nf, *qfpos, *(qfpos-1)); - (void)EMSG(buf); - xfree(buf); + (void)semsg(_("E469: invalid cscopequickfix flag %c for %c"), *qfpos, *(qfpos - 1));; return FALSE; } @@ -1025,18 +1015,9 @@ static int cs_find_common(char *opt, char *pat, int forceit, int verbose, int us xfree(cmd); if (totmatches == 0) { - char *nf = _("E259: no matches found for cscope query %s of %s"); - char *buf; - - if (!verbose) { - xfree(nummatches); - return FALSE; + if (verbose) { + (void)semsg(_("E259: no matches found for cscope query %s of %s"), opt, pat); } - - buf = xmalloc(strlen(opt) + strlen(pat) + strlen(nf)); - sprintf(buf, nf, opt, pat); - (void)EMSG(buf); - xfree(buf); xfree(nummatches); return FALSE; } @@ -1050,7 +1031,7 @@ static int cs_find_common(char *opt, char *pat, int forceit, int verbose, int us f = os_fopen((char *)tmp, "w"); if (f == NULL) { - EMSG2(_(e_notopen), tmp); + semsg(_(e_notopen), tmp); } else { cs_file_results(f, nummatches); fclose(f); @@ -1106,7 +1087,7 @@ static int cs_help(exarg_T *eap) { cscmd_T *cmdp = cs_cmds; - (void)MSG_PUTS(_("cscope commands:\n")); + (void)msg_puts(_("cscope commands:\n")); while (cmdp->name != NULL) { char *help = _(cmdp->help); int space_cnt = 30 - vim_strsize((char_u *)help); @@ -1120,7 +1101,7 @@ static int cs_help(exarg_T *eap) help, space_cnt, " ", cmdp->usage); if (strcmp(cmdp->name, "find") == 0) { - MSG_PUTS(_("\n" + msg_puts(_("\n" " a: Find assignments to this symbol\n" " c: Find functions calling this function\n" " d: Find functions called by this function\n" @@ -1161,7 +1142,7 @@ static int cs_insert_filelist(char *fname, char *ppath, char *flags, FileInfo *f if (csinfo[j].fname != NULL && os_fileid_equal_fileinfo(&(csinfo[j].file_id), file_info)) { if (p_csverbose) { - (void)EMSG(_("E568: duplicate cscope database not added")); + (void)emsg(_("E568: duplicate cscope database not added")); } return CSCOPE_FAILURE; } @@ -1267,7 +1248,7 @@ static int cs_kill(exarg_T *eap) i = (size_t)num; } else { // All negative values besides -1 are invalid. if (p_csverbose) { - (void)EMSG2(_("E261: cscope connection %s not found"), stok); + (void)semsg(_("E261: cscope connection %s not found"), stok); } return CSCOPE_FAILURE; } @@ -1283,7 +1264,7 @@ static int cs_kill(exarg_T *eap) if (!killall && (i >= csinfo_size || csinfo[i].fname == NULL)) { if (p_csverbose) { - (void)EMSG2(_("E261: cscope connection %s not found"), stok); + (void)semsg(_("E261: cscope connection %s not found"), stok); } return CSCOPE_FAILURE; } else { @@ -1428,7 +1409,7 @@ static char *cs_manage_matches(char **matches, char **contexts, size_t totmatche cs_print_tags_priv(mp, cp, cnt); break; default: // should not reach here - IEMSG(_("E570: fatal error in cs_manage_matches")); + iemsg(_("E570: fatal error in cs_manage_matches")); return NULL; } @@ -1463,7 +1444,6 @@ retry: // If the line's too long for the buffer, discard it. if ((p = strchr(buf, '\n')) == NULL) { while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n') { - ; } return NULL; } @@ -1521,7 +1501,7 @@ static void cs_file_results(FILE *f, int *nummatches_a) context = xmalloc(strlen(cntx) + 5); - if (strcmp(cntx, "<global>")==0) { + if (strcmp(cntx, "<global>") == 0) { strcpy(context, "<<global>>"); } else { sprintf(context, "<<%s>>", cntx); @@ -1654,16 +1634,16 @@ static void cs_print_tags_priv(char **matches, char **cntxts, char *buf = xmalloc(newsize); size_t bufsize = newsize; // Track available bufsize (void)snprintf(buf, bufsize, cstag_msg, ptag); - MSG_PUTS_ATTR(buf, HL_ATTR(HLF_T)); + msg_puts_attr(buf, HL_ATTR(HLF_T)); msg_clr_eos(); // restore matches[0] *ptag_end = '\t'; // Column headers for match number, line number and filename. - MSG_PUTS_ATTR(_("\n # line"), HL_ATTR(HLF_T)); + msg_puts_attr(_("\n # line"), HL_ATTR(HLF_T)); msg_advance(msg_col + 2); - MSG_PUTS_ATTR(_("filename / context / line\n"), HL_ATTR(HLF_T)); + msg_puts_attr(_("filename / context / line\n"), HL_ATTR(HLF_T)); for (size_t i = 0; i < num_matches; i++) { assert(strcnt(matches[i], '\t') >= 2); @@ -1690,8 +1670,8 @@ static void cs_print_tags_priv(char **matches, char **cntxts, bufsize = newsize; } (void)snprintf(buf, bufsize, csfmt_str, i + 1, lno); - MSG_PUTS_ATTR(buf, HL_ATTR(HLF_CM)); - MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), HL_ATTR(HLF_CM)); + msg_puts_attr(buf, HL_ATTR(HLF_CM)); + msg_outtrans_long_attr((char_u *)cs_pathcomponents(fname), HL_ATTR(HLF_CM)); // compute the required space for the context char *context = cntxts[i] ? cntxts[i] : globalcntx; @@ -1713,11 +1693,11 @@ static void cs_print_tags_priv(char **matches, char **cntxts, msg_putchar('\n'); } msg_advance(12); - MSG_PUTS_LONG(buf); + msg_outtrans_long_attr((char_u *)buf, 0); msg_putchar('\n'); if (extra != NULL) { msg_advance(13); - MSG_PUTS_LONG(extra); + msg_outtrans_long_attr((char_u *)extra, 0); } // restore matches[i] @@ -1777,7 +1757,7 @@ static int cs_read_prompt(size_t i) buf[bufpos - epromptlen] = NUL; // print message to user - (void)EMSG2(cs_emsg, buf); + (void)semsg(cs_emsg, buf); // send RETURN to cscope (void)putc('\n', csinfo[i].to_fp); @@ -1800,7 +1780,7 @@ static int cs_read_prompt(size_t i) if (ch == EOF) { PERROR("cs_read_prompt EOF"); if (buf != NULL && buf[0] != NUL) { - (void)EMSG2(cs_emsg, buf); + (void)semsg(cs_emsg, buf); } else if (p_csverbose) { cs_reading_emsg(i); // don't have additional information } @@ -1987,7 +1967,7 @@ static int cs_reset(exarg_T *eap) // connection number in the same line as // "Added cscope database..." snprintf(buf, ARRAY_SIZE(buf), " (#%zu)", i); - MSG_PUTS_ATTR(buf, HL_ATTR(HLF_R)); + msg_puts_attr(buf, HL_ATTR(HLF_R)); } } xfree(dblist[i]); @@ -2060,9 +2040,9 @@ static char *cs_resolve_file(size_t i, char *name) static int cs_show(exarg_T *eap) { if (cs_cnt_connections() == 0) { - MSG_PUTS(_("no cscope connections\n")); + msg_puts(_("no cscope connections\n")); } else { - MSG_PUTS_ATTR(_(" # pid database name prepend path\n"), + msg_puts_attr(_(" # pid database name prepend path\n"), HL_ATTR(HLF_T)); for (size_t i = 0; i < csinfo_size; i++) { if (csinfo[i].fname == NULL) { diff --git a/src/nvim/if_cscope_defs.h b/src/nvim/if_cscope_defs.h index 182cbc28e1..6ded89fa0b 100644 --- a/src/nvim/if_cscope_defs.h +++ b/src/nvim/if_cscope_defs.h @@ -52,13 +52,13 @@ typedef struct csi { FILE *to_fp; // to cscope: FILE. } csinfo_T; -typedef enum { Add, Find, Help, Kill, Reset, Show } csid_e; +typedef enum { Add, Find, Help, Kill, Reset, Show, } csid_e; typedef enum { Store, Get, Free, - Print + Print, } mcmd_e; #endif // NVIM_IF_CSCOPE_DEFS_H diff --git a/src/nvim/keymap.c b/src/nvim/keymap.c index b724d82f7c..fc2f9b04f5 100644 --- a/src/nvim/keymap.c +++ b/src/nvim/keymap.c @@ -647,7 +647,7 @@ int find_special_key(const char_u **srcp, const size_t src_len, int *const modp, } else if (end - bp > 4 && STRNICMP(bp, "char-", 5) == 0) { vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true); if (l == 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return 0; } bp += l + 5; @@ -677,7 +677,7 @@ int find_special_key(const char_u **srcp, const size_t src_len, int *const modp, // <Char-123> or <Char-033> or <Char-0x33> vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true); if (l == 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return 0; } key = (int)n; @@ -891,7 +891,7 @@ char_u *replace_termcodes(const char_u *from, const size_t from_len, char_u **bu // (room: 5 * 6 = 30 bytes; needed: 3 + <nr> + 1 <= 14) if (end - src >= 4 && STRNICMP(src, "<SID>", 5) == 0) { if (current_sctx.sc_sid <= 0) { - EMSG(_(e_usingsid)); + emsg(_(e_usingsid)); } else { src += 5; result[dlen++] = K_SPECIAL; diff --git a/src/nvim/keymap.h b/src/nvim/keymap.h index 663a7a12ec..5ff5a38614 100644 --- a/src/nvim/keymap.h +++ b/src/nvim/keymap.h @@ -245,7 +245,7 @@ enum key_extra { KE_MOUSEMOVE = 100, // mouse moved with no button down // , KE_CANCEL = 101 // return from vgetc KE_EVENT = 102, // event - KE_COMMAND = 104 // <Cmd> special key + KE_COMMAND = 104, // <Cmd> special key }; /* diff --git a/src/nvim/lib/kbtree.h b/src/nvim/lib/kbtree.h index e2a4e9edea..5d9c1095bc 100644 --- a/src/nvim/lib/kbtree.h +++ b/src/nvim/lib/kbtree.h @@ -46,20 +46,18 @@ #define __KB_KEY(type, x) (x->key) #define __KB_PTR(btr, x) (x->ptr) -#define __KB_TREE_T(name, key_t, T) \ - typedef struct kbnode_##name##_s kbnode_##name##_t; \ - struct kbnode_##name##_s { \ +#define __KB_TREE_T(name, key_t, T) \ + typedef struct kbnode_##name##_s kbnode_##name##_t; \ + struct kbnode_##name##_s { \ int32_t n; \ bool is_internal; \ key_t key[2*T-1]; \ kbnode_##name##_t *ptr[]; \ } ; \ - \ typedef struct { \ kbnode_##name##_t *root; \ int n_keys, n_nodes; \ } kbtree_##name##_t; \ - \ typedef struct { \ kbnode_##name##_t *x; \ int i; \ @@ -69,231 +67,231 @@ } kbitr_##name##_t; \ -#define __kb_destroy(kbnode_t, b) do { \ - int i; \ - unsigned int max = 8; \ - kbnode_t *x, **top, **stack = 0; \ - if (b->root) { \ - top = stack = (kbnode_t **)xcalloc(max, sizeof(kbnode_t *)); \ - *top++ = (b)->root; \ - while (top != stack) { \ - x = *--top; \ - if (x->is_internal == 0) { XFREE_CLEAR(x); continue; } \ - for (i = 0; i <= x->n; ++i) \ - if (__KB_PTR(b, x)[i]) { \ - if (top - stack == (int)max) { \ - max <<= 1; \ +#define __kb_destroy(kbnode_t, b) do { \ + int i; \ + unsigned int max = 8; \ + kbnode_t *x, **top, **stack = 0; \ + if (b->root) { \ + top = stack = (kbnode_t **)xcalloc(max, sizeof(kbnode_t *)); \ + *top++ = (b)->root; \ + while (top != stack) { \ + x = *--top; \ + if (x->is_internal == 0) { XFREE_CLEAR(x); continue; } \ + for (i = 0; i <= x->n; ++i) \ + if (__KB_PTR(b, x)[i]) { \ + if (top - stack == (int)max) { \ + max <<= 1; \ stack = (kbnode_t **)xrealloc(stack, max * sizeof(kbnode_t *)); \ - top = stack + (max>>1); \ - } \ - *top++ = __KB_PTR(b, x)[i]; \ - } \ - XFREE_CLEAR(x); \ - } \ - } \ - XFREE_CLEAR(stack); \ + top = stack + (max>>1); \ + } \ + *top++ = __KB_PTR(b, x)[i]; \ + } \ + XFREE_CLEAR(x); \ + } \ + } \ + XFREE_CLEAR(stack); \ } while (0) -#define __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ +#define __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ static inline int __kb_getp_aux_##name(const kbnode_t * __restrict x, key_t * __restrict k, \ int *r) \ - { \ - int tr, *rr, begin = 0, end = x->n; \ - if (x->n == 0) return -1; \ - rr = r? r : &tr; \ - while (begin < end) { \ - int mid = (begin + end) >> 1; \ + { \ + int tr, *rr, begin = 0, end = x->n; \ + if (x->n == 0) return -1; \ + rr = r? r : &tr; \ + while (begin < end) { \ + int mid = (begin + end) >> 1; \ if (__cmp(__KB_KEY(key_t, x)[mid], *k) < 0) begin = mid + 1; \ - else end = mid; \ - } \ - if (begin == x->n) { *rr = 1; return x->n - 1; } \ - if ((*rr = __cmp(*k, __KB_KEY(key_t, x)[begin])) < 0) --begin; \ - return begin; \ + else end = mid; \ + } \ + if (begin == x->n) { *rr = 1; return x->n - 1; } \ + if ((*rr = __cmp(*k, __KB_KEY(key_t, x)[begin])) < 0) --begin; \ + return begin; \ } -#define __KB_GET(name, key_t, kbnode_t) \ +#define __KB_GET(name, key_t, kbnode_t) \ static key_t *kb_getp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ + { \ if (!b->root) { \ return 0; \ } \ - int i, r = 0; \ - kbnode_t *x = b->root; \ - while (x) { \ - i = __kb_getp_aux_##name(x, k, &r); \ - if (i >= 0 && r == 0) return &__KB_KEY(key_t, x)[i]; \ - if (x->is_internal == 0) return 0; \ - x = __KB_PTR(b, x)[i + 1]; \ - } \ - return 0; \ - } \ + int i, r = 0; \ + kbnode_t *x = b->root; \ + while (x) { \ + i = __kb_getp_aux_##name(x, k, &r); \ + if (i >= 0 && r == 0) return &__KB_KEY(key_t, x)[i]; \ + if (x->is_internal == 0) return 0; \ + x = __KB_PTR(b, x)[i + 1]; \ + } \ + return 0; \ + } \ static inline key_t *kb_get_##name(kbtree_##name##_t *b, key_t k) \ - { \ - return kb_getp_##name(b, &k); \ + { \ + return kb_getp_##name(b, &k); \ } -#define __KB_INTERVAL(name, key_t, kbnode_t) \ +#define __KB_INTERVAL(name, key_t, kbnode_t) \ static inline void kb_intervalp_##name(kbtree_##name##_t *b, key_t * __restrict k, key_t **lower, \ - key_t **upper) \ - { \ + key_t **upper) \ + { \ if (!b->root) { \ return; \ } \ - int i, r = 0; \ - kbnode_t *x = b->root; \ - *lower = *upper = 0; \ - while (x) { \ - i = __kb_getp_aux_##name(x, k, &r); \ - if (i >= 0 && r == 0) { \ - *lower = *upper = &__KB_KEY(key_t, x)[i]; \ - return; \ - } \ - if (i >= 0) *lower = &__KB_KEY(key_t, x)[i]; \ - if (i < x->n - 1) *upper = &__KB_KEY(key_t, x)[i + 1]; \ - if (x->is_internal == 0) return; \ - x = __KB_PTR(b, x)[i + 1]; \ - } \ - } \ + int i, r = 0; \ + kbnode_t *x = b->root; \ + *lower = *upper = 0; \ + while (x) { \ + i = __kb_getp_aux_##name(x, k, &r); \ + if (i >= 0 && r == 0) { \ + *lower = *upper = &__KB_KEY(key_t, x)[i]; \ + return; \ + } \ + if (i >= 0) *lower = &__KB_KEY(key_t, x)[i]; \ + if (i < x->n - 1) *upper = &__KB_KEY(key_t, x)[i + 1]; \ + if (x->is_internal == 0) return; \ + x = __KB_PTR(b, x)[i + 1]; \ + } \ + } \ static inline void kb_interval_##name(kbtree_##name##_t *b, key_t k, key_t **lower, key_t **upper) \ - { \ - kb_intervalp_##name(b, &k, lower, upper); \ + { \ + kb_intervalp_##name(b, &k, lower, upper); \ } -#define __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ - /* x must be an internal node */ \ +#define __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ + /* x must be an internal node */ \ static inline void __kb_split_##name(kbtree_##name##_t *b, kbnode_t *x, int i, kbnode_t *y) \ - { \ - kbnode_t *z; \ - z = (kbnode_t *)xcalloc(1, y->is_internal? ILEN : sizeof(kbnode_##name##_t)); \ - ++b->n_nodes; \ - z->is_internal = y->is_internal; \ - z->n = T - 1; \ + { \ + kbnode_t *z; \ + z = (kbnode_t *)xcalloc(1, y->is_internal? ILEN : sizeof(kbnode_##name##_t)); \ + ++b->n_nodes; \ + z->is_internal = y->is_internal; \ + z->n = T - 1; \ memcpy(__KB_KEY(key_t, z), &__KB_KEY(key_t, y)[T], sizeof(key_t) * (T - 1)); \ if (y->is_internal) memcpy(__KB_PTR(b, z), &__KB_PTR(b, y)[T], sizeof(void *) * T); \ - y->n = T - 1; \ + y->n = T - 1; \ memmove(&__KB_PTR(b, x)[i + 2], &__KB_PTR(b, \ x)[i + 1], sizeof(void *) * (unsigned int)(x->n - i)); \ - __KB_PTR(b, x)[i + 1] = z; \ + __KB_PTR(b, x)[i + 1] = z; \ memmove(&__KB_KEY(key_t, x)[i + 1], &__KB_KEY(key_t, x)[i], \ sizeof(key_t) * (unsigned int)(x->n - i)); \ - __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[T - 1]; \ - ++x->n; \ - } \ + __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[T - 1]; \ + ++x->n; \ + } \ static inline key_t *__kb_putp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k) \ - { \ - int i = x->n - 1; \ - key_t *ret; \ - if (x->is_internal == 0) { \ - i = __kb_getp_aux_##name(x, k, 0); \ - if (i != x->n - 1) \ + { \ + int i = x->n - 1; \ + key_t *ret; \ + if (x->is_internal == 0) { \ + i = __kb_getp_aux_##name(x, k, 0); \ + if (i != x->n - 1) \ memmove(&__KB_KEY(key_t, x)[i + 2], &__KB_KEY(key_t, \ x)[i + 1], \ (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - ret = &__KB_KEY(key_t, x)[i + 1]; \ - *ret = *k; \ - ++x->n; \ - } else { \ - i = __kb_getp_aux_##name(x, k, 0) + 1; \ - if (__KB_PTR(b, x)[i]->n == 2 * T - 1) { \ - __kb_split_##name(b, x, i, __KB_PTR(b, x)[i]); \ - if (__cmp(*k, __KB_KEY(key_t, x)[i]) > 0) ++i; \ - } \ - ret = __kb_putp_aux_##name(b, __KB_PTR(b, x)[i], k); \ - } \ - return ret; \ - } \ + ret = &__KB_KEY(key_t, x)[i + 1]; \ + *ret = *k; \ + ++x->n; \ + } else { \ + i = __kb_getp_aux_##name(x, k, 0) + 1; \ + if (__KB_PTR(b, x)[i]->n == 2 * T - 1) { \ + __kb_split_##name(b, x, i, __KB_PTR(b, x)[i]); \ + if (__cmp(*k, __KB_KEY(key_t, x)[i]) > 0) ++i; \ + } \ + ret = __kb_putp_aux_##name(b, __KB_PTR(b, x)[i], k); \ + } \ + return ret; \ + } \ static inline key_t *kb_putp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ + { \ if (!b->root) { \ - b->root = (kbnode_t *)xcalloc(1, ILEN); \ - ++b->n_nodes; \ + b->root = (kbnode_t *)xcalloc(1, ILEN); \ + ++b->n_nodes; \ } \ - kbnode_t *r, *s; \ - ++b->n_keys; \ - r = b->root; \ - if (r->n == 2 * T - 1) { \ - ++b->n_nodes; \ - s = (kbnode_t *)xcalloc(1, ILEN); \ - b->root = s; s->is_internal = 1; s->n = 0; \ - __KB_PTR(b, s)[0] = r; \ - __kb_split_##name(b, s, 0, r); \ - r = s; \ - } \ - return __kb_putp_aux_##name(b, r, k); \ - } \ + kbnode_t *r, *s; \ + ++b->n_keys; \ + r = b->root; \ + if (r->n == 2 * T - 1) { \ + ++b->n_nodes; \ + s = (kbnode_t *)xcalloc(1, ILEN); \ + b->root = s; s->is_internal = 1; s->n = 0; \ + __KB_PTR(b, s)[0] = r; \ + __kb_split_##name(b, s, 0, r); \ + r = s; \ + } \ + return __kb_putp_aux_##name(b, r, k); \ + } \ static inline void kb_put_##name(kbtree_##name##_t *b, key_t k) \ - { \ - kb_putp_##name(b, &k); \ + { \ + kb_putp_##name(b, &k); \ } -#define __KB_DEL(name, key_t, kbnode_t, T) \ +#define __KB_DEL(name, key_t, kbnode_t, T) \ static inline key_t __kb_delp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k, \ int s) \ - { \ - int yn, zn, i, r = 0; \ - kbnode_t *xp, *y, *z; \ - key_t kp; \ - if (x == 0) return *k; \ - if (s) { /* s can only be 0, 1 or 2 */ \ - r = x->is_internal == 0? 0 : s == 1? 1 : -1; \ - i = s == 1? x->n - 1 : -1; \ - } else i = __kb_getp_aux_##name(x, k, &r); \ - if (x->is_internal == 0) { \ - if (s == 2) ++i; \ - kp = __KB_KEY(key_t, x)[i]; \ + { \ + int yn, zn, i, r = 0; \ + kbnode_t *xp, *y, *z; \ + key_t kp; \ + if (x == 0) return *k; \ + if (s) { /* s can only be 0, 1 or 2 */ \ + r = x->is_internal == 0? 0 : s == 1? 1 : -1; \ + i = s == 1? x->n - 1 : -1; \ + } else i = __kb_getp_aux_##name(x, k, &r); \ + if (x->is_internal == 0) { \ + if (s == 2) ++i; \ + kp = __KB_KEY(key_t, x)[i]; \ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ x)[i + 1], \ (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - --x->n; \ - return kp; \ - } \ - if (r == 0) { \ - if ((yn = __KB_PTR(b, x)[i]->n) >= T) { \ - xp = __KB_PTR(b, x)[i]; \ - kp = __KB_KEY(key_t, x)[i]; \ + --x->n; \ + return kp; \ + } \ + if (r == 0) { \ + if ((yn = __KB_PTR(b, x)[i]->n) >= T) { \ + xp = __KB_PTR(b, x)[i]; \ + kp = __KB_KEY(key_t, x)[i]; \ __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 1); \ - return kp; \ - } else if ((zn = __KB_PTR(b, x)[i + 1]->n) >= T) { \ - xp = __KB_PTR(b, x)[i + 1]; \ - kp = __KB_KEY(key_t, x)[i]; \ + return kp; \ + } else if ((zn = __KB_PTR(b, x)[i + 1]->n) >= T) { \ + xp = __KB_PTR(b, x)[i + 1]; \ + kp = __KB_KEY(key_t, x)[i]; \ __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 2); \ - return kp; \ - } else if (yn == T - 1 && zn == T - 1) { \ - y = __KB_PTR(b, x)[i]; z = __KB_PTR(b, x)[i + 1]; \ - __KB_KEY(key_t, y)[y->n++] = *k; \ + return kp; \ + } else if (yn == T - 1 && zn == T - 1) { \ + y = __KB_PTR(b, x)[i]; z = __KB_PTR(b, x)[i + 1]; \ + __KB_KEY(key_t, y)[y->n++] = *k; \ memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, z), (unsigned int)z->n * sizeof(key_t)); \ if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ z), \ (unsigned int)(z->n + 1) * sizeof(void *)); \ - y->n += z->n; \ + y->n += z->n; \ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ x)[i + 1], \ (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ x)[i + 2], \ (unsigned int)(x->n - i - 1) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(z); \ - return __kb_delp_aux_##name(b, y, k, s); \ - } \ - } \ - ++i; \ - if ((xp = __KB_PTR(b, x)[i])->n == T - 1) { \ - if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n >= T) { \ + --x->n; \ + XFREE_CLEAR(z); \ + return __kb_delp_aux_##name(b, y, k, s); \ + } \ + } \ + ++i; \ + if ((xp = __KB_PTR(b, x)[i])->n == T - 1) { \ + if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n >= T) { \ memmove(&__KB_KEY(key_t, xp)[1], __KB_KEY(key_t, xp), (unsigned int)xp->n * sizeof(key_t)); \ if (xp->is_internal) memmove(&__KB_PTR(b, xp)[1], __KB_PTR(b, \ xp), \ (unsigned int)(xp->n + 1) * sizeof(void *)); \ - __KB_KEY(key_t, xp)[0] = __KB_KEY(key_t, x)[i - 1]; \ + __KB_KEY(key_t, xp)[0] = __KB_KEY(key_t, x)[i - 1]; \ __KB_KEY(key_t, x)[i - 1] = __KB_KEY(key_t, y)[y->n - 1]; \ if (xp->is_internal) __KB_PTR(b, xp)[0] = __KB_PTR(b, y)[y->n]; \ - --y->n; ++xp->n; \ + --y->n; ++xp->n; \ } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n >= T) { \ - __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ - __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[0]; \ + __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ + __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[0]; \ if (xp->is_internal) __KB_PTR(b, xp)[xp->n] = __KB_PTR(b, y)[0]; \ - --y->n; \ + --y->n; \ memmove(__KB_KEY(key_t, y), &__KB_KEY(key_t, y)[1], (unsigned int)y->n * sizeof(key_t)); \ if (y->is_internal) memmove(__KB_PTR(b, y), &__KB_PTR(b, \ y)[1], \ @@ -301,55 +299,55 @@ } else if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n == T - 1) { \ __KB_KEY(key_t, y)[y->n++] = __KB_KEY(key_t, x)[i - 1]; \ memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, xp), \ - (unsigned int)xp->n * sizeof(key_t)); \ + (unsigned int)xp->n * sizeof(key_t)); \ if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ xp), \ (unsigned int)(xp->n + 1) * sizeof(void *)); \ - y->n += xp->n; \ + y->n += xp->n; \ memmove(&__KB_KEY(key_t, x)[i - 1], &__KB_KEY(key_t, \ x)[i], \ (unsigned int)(x->n - i) * sizeof(key_t)); \ memmove(&__KB_PTR(b, x)[i], &__KB_PTR(b, \ x)[i + 1], (unsigned int)(x->n - i) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(xp); \ - xp = y; \ + --x->n; \ + XFREE_CLEAR(xp); \ + xp = y; \ } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n == T - 1) { \ - __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ + __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ memmove(&__KB_KEY(key_t, xp)[xp->n], __KB_KEY(key_t, y), \ - (unsigned int)y->n * sizeof(key_t)); \ + (unsigned int)y->n * sizeof(key_t)); \ if (xp->is_internal) memmove(&__KB_PTR(b, xp)[xp->n], __KB_PTR(b, y), \ (unsigned int)(y->n + 1) * sizeof(void *)); \ - xp->n += y->n; \ + xp->n += y->n; \ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ x)[i + 1], \ (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ x)[i + 2], \ (unsigned int)(x->n - i - 1) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(y); \ - } \ - } \ - return __kb_delp_aux_##name(b, xp, k, s); \ - } \ + --x->n; \ + XFREE_CLEAR(y); \ + } \ + } \ + return __kb_delp_aux_##name(b, xp, k, s); \ + } \ static inline key_t kb_delp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ - kbnode_t *x; \ - key_t ret; \ - ret = __kb_delp_aux_##name(b, b->root, k, 0); \ - --b->n_keys; \ - if (b->root->n == 0 && b->root->is_internal) { \ - --b->n_nodes; \ - x = b->root; \ - b->root = __KB_PTR(b, x)[0]; \ - XFREE_CLEAR(x); \ - } \ - return ret; \ - } \ + { \ + kbnode_t *x; \ + key_t ret; \ + ret = __kb_delp_aux_##name(b, b->root, k, 0); \ + --b->n_keys; \ + if (b->root->n == 0 && b->root->is_internal) { \ + --b->n_nodes; \ + x = b->root; \ + b->root = __KB_PTR(b, x)[0]; \ + XFREE_CLEAR(x); \ + } \ + return ret; \ + } \ static inline key_t kb_del_##name(kbtree_##name##_t *b, key_t k) \ - { \ - return kb_delp_##name(b, &k); \ + { \ + return kb_delp_##name(b, &k); \ } #define __KB_ITR(name, key_t, kbnode_t) \ @@ -425,7 +423,7 @@ return 0; \ } \ static inline int kb_itr_get_##name(kbtree_##name##_t *b, key_t k, kbitr_##name##_t *itr) \ - { \ + { \ return kb_itr_getp_##name(b, &k, itr); \ } \ static inline void kb_del_itr_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ @@ -439,12 +437,12 @@ KBTREE_INIT_IMPL(name, key_t, kbnode_##name##_t, __cmp, T, \ (sizeof(kbnode_##name##_t)+(2*T)*sizeof(void *))) -#define KBTREE_INIT_IMPL(name, key_t, kbnode_t, __cmp, T, ILEN) \ - __KB_TREE_T(name, key_t, T) \ - __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ - __KB_GET(name, key_t, kbnode_t) \ - __KB_INTERVAL(name, key_t, kbnode_t) \ - __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ +#define KBTREE_INIT_IMPL(name, key_t, kbnode_t, __cmp, T, ILEN) \ + __KB_TREE_T(name, key_t, T) \ + __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ + __KB_GET(name, key_t, kbnode_t) \ + __KB_INTERVAL(name, key_t, kbnode_t) \ + __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ __KB_DEL(name, key_t, kbnode_t, T) \ __KB_ITR(name, key_t, kbnode_t) diff --git a/src/nvim/lib/khash.h b/src/nvim/lib/khash.h index dd87415144..e0faf94db9 100644 --- a/src/nvim/lib/khash.h +++ b/src/nvim/lib/khash.h @@ -417,12 +417,12 @@ typedef khint_t khiter_t; } \ } -#define KHASH_DECLARE(name, khkey_t, khval_t) \ - __KHASH_TYPE(name, khkey_t, khval_t) \ +#define KHASH_DECLARE(name, khkey_t, khval_t) \ + __KHASH_TYPE(name, khkey_t, khval_t) \ __KHASH_PROTOTYPES(name, khkey_t, khval_t) #define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ - __KHASH_TYPE(name, khkey_t, khval_t) \ + __KHASH_TYPE(name, khkey_t, khval_t) \ __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) #define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ @@ -627,12 +627,12 @@ static kh_inline khint_t __ac_Wang_hash(khint_t key) @param vvar Variable to which value will be assigned @param code Block of code to execute */ -#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \ - for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ - if (!kh_exist(h, __i)) continue; \ - (kvar) = kh_key(h, __i); \ - (vvar) = kh_val(h, __i); \ - code; \ +#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \ + for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ + if (!kh_exist(h, __i)) continue; \ + (kvar) = kh_key(h, __i); \ + (vvar) = kh_val(h, __i); \ + code; \ } } /*! @function @@ -641,11 +641,11 @@ static kh_inline khint_t __ac_Wang_hash(khint_t key) @param vvar Variable to which value will be assigned @param code Block of code to execute */ -#define kh_foreach_value(h, vvar, code) { khint_t __i; \ - for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ - if (!kh_exist(h, __i)) continue; \ - (vvar) = kh_val(h, __i); \ - code; \ +#define kh_foreach_value(h, vvar, code) { khint_t __i; \ + for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ + if (!kh_exist(h, __i)) continue; \ + (vvar) = kh_val(h, __i); \ + code; \ } } /*! @function @@ -672,7 +672,7 @@ static kh_inline khint_t __ac_Wang_hash(khint_t key) @abstract Instantiate a hash set containing integer keys @param name Name of the hash table [symbol] */ -#define KHASH_SET_INIT_INT(name) \ +#define KHASH_SET_INIT_INT(name) \ KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal) /*! @function @@ -680,14 +680,14 @@ static kh_inline khint_t __ac_Wang_hash(khint_t key) @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ -#define KHASH_MAP_INIT_INT(name, khval_t) \ +#define KHASH_MAP_INIT_INT(name, khval_t) \ KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) /*! @function @abstract Instantiate a hash map containing 64-bit integer keys @param name Name of the hash table [symbol] */ -#define KHASH_SET_INIT_INT64(name) \ +#define KHASH_SET_INIT_INT64(name) \ KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) /*! @function @@ -695,7 +695,7 @@ static kh_inline khint_t __ac_Wang_hash(khint_t key) @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ -#define KHASH_MAP_INIT_INT64(name, khval_t) \ +#define KHASH_MAP_INIT_INT64(name, khval_t) \ KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) typedef const char *kh_cstr_t; @@ -703,7 +703,7 @@ typedef const char *kh_cstr_t; @abstract Instantiate a hash map containing const char* keys @param name Name of the hash table [symbol] */ -#define KHASH_SET_INIT_STR(name) \ +#define KHASH_SET_INIT_STR(name) \ KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal) /*! @function diff --git a/src/nvim/lib/kvec.h b/src/nvim/lib/kvec.h index ff0a8bcb7c..34332ba34b 100644 --- a/src/nvim/lib/kvec.h +++ b/src/nvim/lib/kvec.h @@ -95,15 +95,15 @@ } while (0) #define kv_splice(v1, v0) \ - do { \ - if ((v1).capacity < (v1).size + (v0).size) { \ - (v1).capacity = (v1).size + (v0).size; \ - kv_roundup32((v1).capacity); \ - kv_resize((v1), (v1).capacity); \ - } \ - memcpy((v1).items + (v1).size, (v0).items, sizeof((v1).items[0]) * (v0).size); \ - (v1).size = (v1).size + (v0).size; \ - } while (0) + do { \ + if ((v1).capacity < (v1).size + (v0).size) { \ + (v1).capacity = (v1).size + (v0).size; \ + kv_roundup32((v1).capacity); \ + kv_resize((v1), (v1).capacity); \ + } \ + memcpy((v1).items + (v1).size, (v0).items, sizeof((v1).items[0]) * (v0).size); \ + (v1).size = (v1).size + (v0).size; \ + } while (0) #define kv_pushp(v) \ ((((v).size == (v).capacity) ? (kv_resize_full(v), 0) : 0), \ diff --git a/src/nvim/lib/queue.h b/src/nvim/lib/queue.h index 871f49c863..e5574094bc 100644 --- a/src/nvim/lib/queue.h +++ b/src/nvim/lib/queue.h @@ -38,7 +38,7 @@ typedef struct _queue { // elements results in undefined behavior. #define QUEUE_FOREACH(q, h, code) \ (q) = (h)->next; \ - while((q) != (h)) { \ + while ((q) != (h)) { \ QUEUE *next = q->next; \ code \ (q) = next; \ diff --git a/src/nvim/lib/ringbuf.h b/src/nvim/lib/ringbuf.h index 06f7830bd1..4fd110a531 100644 --- a/src/nvim/lib/ringbuf.h +++ b/src/nvim/lib/ringbuf.h @@ -29,7 +29,7 @@ : ((rb)->next > \ (rb)->first) ? (size_t)((rb)->next - \ (rb)->first) \ - : (size_t)((rb)->\ + : (size_t)((rb)-> \ next - (rb)->buf + \ (rb)->buf_end - \ (rb)->first + 1)) @@ -130,7 +130,6 @@ .buf_end = buf + size - 1, \ }; \ } \ -\ static inline void funcprefix##_rb_free(TypeName##RingBuffer *const rb) \ REAL_FATTR_UNUSED; \ static inline void funcprefix##_rb_free(TypeName##RingBuffer *const rb) \ @@ -143,14 +142,12 @@ } \ XFREE_CLEAR(rb->buf); \ } \ -\ static inline void funcprefix##_rb_dealloc(TypeName##RingBuffer *const rb) \ REAL_FATTR_UNUSED; \ static inline void funcprefix##_rb_dealloc(TypeName##RingBuffer *const rb) \ { \ XFREE_CLEAR(rb->buf); \ } \ -\ static inline void funcprefix##_rb_push(TypeName##RingBuffer *const rb, \ RBType item) \ REAL_FATTR_NONNULL_ARG(1); \ @@ -166,7 +163,6 @@ *rb->next = item; \ rb->next = _RINGBUF_NEXT(rb, rb->next); \ } \ -\ static inline ptrdiff_t funcprefix##_rb_find_idx(const TypeName##RingBuffer *const rb, \ const RBType *const item_p) \ REAL_FATTR_NONNULL_ALL REAL_FATTR_PURE REAL_FATTR_UNUSED; \ @@ -183,21 +179,18 @@ return item_p - rb->buf + rb->buf_end - rb->first + 1; \ } \ } \ -\ static inline size_t funcprefix##_rb_size(const TypeName##RingBuffer *const rb) \ REAL_FATTR_NONNULL_ALL REAL_FATTR_PURE; \ static inline size_t funcprefix##_rb_size(const TypeName##RingBuffer *const rb) \ { \ return (size_t)(rb->buf_end - rb->buf) + 1; \ } \ -\ static inline size_t funcprefix##_rb_length(const TypeName##RingBuffer *const rb) \ REAL_FATTR_NONNULL_ALL REAL_FATTR_PURE; \ static inline size_t funcprefix##_rb_length(const TypeName##RingBuffer *const rb) \ { \ return _RINGBUF_LENGTH(rb); \ } \ -\ static inline RBType *funcprefix##_rb_idx_p(const TypeName##RingBuffer *const rb, \ const size_t idx) \ REAL_FATTR_NONNULL_ALL REAL_FATTR_PURE; \ @@ -212,7 +205,6 @@ return rb->first + idx; \ } \ } \ -\ static inline RBType funcprefix##_rb_idx(const TypeName##RingBuffer *const rb, \ const size_t idx) \ REAL_FATTR_NONNULL_ALL REAL_FATTR_PURE REAL_FATTR_UNUSED; \ @@ -221,7 +213,6 @@ { \ return *funcprefix##_rb_idx_p(rb, idx); \ } \ -\ static inline void funcprefix##_rb_insert(TypeName##RingBuffer *const rb, \ const size_t idx, \ RBType item) \ @@ -263,7 +254,6 @@ } \ rb->next = _RINGBUF_NEXT(rb, rb->next); \ } \ -\ static inline void funcprefix##_rb_remove(TypeName##RingBuffer *const rb, \ const size_t idx) \ REAL_FATTR_NONNULL_ARG(1) REAL_FATTR_UNUSED; \ diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c index ca3c4f604a..9f2372f831 100644 --- a/src/nvim/lua/converter.c +++ b/src/nvim/lua/converter.c @@ -62,7 +62,7 @@ static LuaTableProps nlua_traverse_table(lua_State *const lstate) LuaTableProps ret; memset(&ret, 0, sizeof(ret)); if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { - emsgf(_("E1502: Lua failed to grow stack to %i"), lua_gettop(lstate) + 2); + semsg(_("E1502: Lua failed to grow stack to %i"), lua_gettop(lstate) + 2); ret.type = kObjectTypeNil; return ret; } @@ -198,7 +198,7 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv) kvi_push(stack, ((TVPopStackItem) { ret_tv, false, false, 0 })); while (ret && kv_size(stack)) { if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { - emsgf(_("E1502: Lua failed to grow stack to %i"), lua_gettop(lstate) + 3); + semsg(_("E1502: Lua failed to grow stack to %i"), lua_gettop(lstate) + 3); ret = false; break; } @@ -376,7 +376,7 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv) cur.tv->vval.v_float = (float_T)table_props.val; break; case kObjectTypeNil: - EMSG(_("E5100: Cannot convert given lua table: table " + emsg(_("E5100: Cannot convert given lua table: table " "should either have a sequence of positive integer keys " "or contain only string keys")); ret = false; @@ -408,13 +408,13 @@ nlua_pop_typval_table_processing_end: cur.tv->v_type = VAR_SPECIAL; cur.tv->vval.v_special = kSpecialVarNull; } else { - EMSG(_("E5101: Cannot convert given lua type")); + emsg(_("E5101: Cannot convert given lua type")); ret = false; } break; } default: - EMSG(_("E5101: Cannot convert given lua type")); + emsg(_("E5101: Cannot convert given lua type")); ret = false; break; } @@ -503,7 +503,7 @@ static bool typval_conv_special = false; #define TYPVAL_ENCODE_CONV_LIST_START(tv, len) \ do { \ if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { \ - emsgf(_("E5102: Lua failed to grow stack to %i"), \ + semsg(_("E5102: Lua failed to grow stack to %i"), \ lua_gettop(lstate) + 3); \ return false; \ } \ @@ -526,7 +526,7 @@ static bool typval_conv_special = false; #define TYPVAL_ENCODE_CONV_DICT_START(tv, dict, len) \ do { \ if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { \ - emsgf(_("E5102: Lua failed to grow stack to %i"), \ + semsg(_("E5102: Lua failed to grow stack to %i"), \ lua_gettop(lstate) + 3); \ return false; \ } \ @@ -614,7 +614,7 @@ bool nlua_push_typval(lua_State *lstate, typval_T *const tv, bool special) const int initial_size = lua_gettop(lstate); if (!lua_checkstack(lstate, initial_size + 2)) { - emsgf(_("E1502: Lua failed to grow stack to %i"), initial_size + 4); + semsg(_("E1502: Lua failed to grow stack to %i"), initial_size + 4); return false; } if (encode_vim_to_lua(lstate, tv, "nlua_push_typval argument") == FAIL) { diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 05c33d7918..b27b1ae7a8 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -80,11 +80,32 @@ static void nlua_error(lua_State *const lstate, const char *const msg) const char *const str = lua_tolstring(lstate, -1, &len); msg_ext_set_kind("lua_error"); - emsgf_multiline(msg, (int)len, str); + semsg_multiline(msg, (int)len, str); lua_pop(lstate, 1); } +/// Like lua_pcall, but use debug.traceback as errfunc. +/// +/// @param lstate Lua interpreter state +/// @param[in] nargs Number of arguments expected by the function being called. +/// @param[in] nresults Number of results the function returns. +static int nlua_pcall(lua_State *lstate, int nargs, int nresults) +{ + lua_getglobal(lstate, "debug"); + lua_getfield(lstate, -1, "traceback"); + lua_remove(lstate, -2); + lua_insert(lstate, -2 - nargs); + int status = lua_pcall(lstate, nargs, nresults, -2 - nargs); + if (status) { + lua_remove(lstate, -2); + } else { + lua_remove(lstate, -1 - nresults); + } + return status; +} + + /// Gets the version of the current Nvim build. /// /// @param lstate Lua interpreter state. @@ -101,7 +122,7 @@ static void nlua_luv_error_event(void **argv) { char *error = (char *)argv[0]; msg_ext_set_kind("lua_error"); - emsgf_multiline("Error executing luv callback:\n%s", error); + semsg_multiline("Error executing luv callback:\n%s", error); xfree(error); } @@ -115,7 +136,7 @@ static int nlua_luv_cfpcall(lua_State *lstate, int nargs, int nresult, int flags in_fast_callback++; int top = lua_gettop(lstate); - int status = lua_pcall(lstate, nargs, nresult, 0); + int status = nlua_pcall(lstate, nargs, nresult); if (status) { if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT)) { // consider out of memory errors unrecoverable, just like xmalloc() @@ -146,7 +167,7 @@ static void nlua_schedule_event(void **argv) lua_State *const lstate = global_lstate; nlua_pushref(lstate, cb); nlua_unref(lstate, cb); - if (lua_pcall(lstate, 0, 0, 0)) { + if (nlua_pcall(lstate, 0, 0)) { nlua_error(lstate, _("Error executing vim.schedule lua callback: %.*s")); } } @@ -183,7 +204,7 @@ static void dummy_timer_close_cb(TimeWatcher *tw, void *data) static bool nlua_wait_condition(lua_State *lstate, int *status, bool *callback_result) { lua_pushvalue(lstate, 2); - *status = lua_pcall(lstate, 0, 1, 0); + *status = nlua_pcall(lstate, 0, 1); if (*status) { return true; // break on error, but keep error on stack } @@ -385,7 +406,7 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL { const char *code = (char *)&shared_module[0]; if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/shared.lua") - || lua_pcall(lstate, 0, 0, 0)) { + || nlua_pcall(lstate, 0, 0)) { nlua_error(lstate, _("E5106: Error while creating shared module: %.*s")); return 1; } @@ -397,7 +418,7 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL const char *code = (char *)&inspect_module[0]; if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/inspect.lua") - || lua_pcall(lstate, 0, 1, 0)) { + || nlua_pcall(lstate, 0, 1)) { nlua_error(lstate, _("E5106: Error while creating inspect module: %.*s")); return 1; } @@ -406,7 +427,7 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL code = (char *)&lua_F_module[0]; if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/F.lua") - || lua_pcall(lstate, 0, 1, 0)) { + || nlua_pcall(lstate, 0, 1)) { nlua_error(lstate, _("E5106: Error while creating vim.F module: %.*s")); return 1; } @@ -419,7 +440,7 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL { const char *code = (char *)&vim_module[0]; if (luaL_loadbuffer(lstate, code, strlen(code), "@vim.lua") - || lua_pcall(lstate, 0, 0, 0)) { + || nlua_pcall(lstate, 0, 0)) { nlua_error(lstate, _("E5106: Error while creating vim module: %.*s")); return 1; } @@ -431,7 +452,7 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL const char *code = (char *)&lua_meta_module[0]; if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/_meta.lua") - || lua_pcall(lstate, 0, 1, 0)) { + || nlua_pcall(lstate, 0, 1)) { nlua_error(lstate, _("E5106: Error while creating vim._meta module: %.*s")); return 1; } @@ -458,7 +479,7 @@ void nlua_init(void) lua_State *lstate = luaL_newstate(); if (lstate == NULL) { - EMSG(_("E970: Failed to initialize lua interpreter")); + emsg(_("E970: Failed to initialize lua interpreter")); preserve_exit(); } luaL_openlibs(lstate); @@ -519,10 +540,10 @@ static void nlua_print_event(void **argv) } break; } - msg((char_u *)str + start); + msg(str + start); } if (len && str[len - 1] == NUL) { // Last was newline - msg((char_u *)""); + msg(""); } xfree(str); } @@ -549,6 +570,7 @@ static int nlua_print(lua_State *const lstate) for (; curargidx <= nargs; curargidx++) { lua_pushvalue(lstate, -1); // tostring lua_pushvalue(lstate, curargidx); // arg + // Do not use nlua_pcall here to avoid duplicate stack trace information if (lua_pcall(lstate, 1, 1, 0)) { errmsg = lua_tolstring(lstate, -1, &errmsg_len); goto nlua_print_error; @@ -616,7 +638,7 @@ static int nlua_debug(lua_State *lstate) if (luaL_loadbuffer(lstate, (const char *)input.vval.v_string, STRLEN(input.vval.v_string), "=(debug command)")) { nlua_error(lstate, _("E5115: Error while loading debug string: %.*s")); - } else if (lua_pcall(lstate, 0, 0, 0)) { + } else if (nlua_pcall(lstate, 0, 0)) { nlua_error(lstate, _("E5116: Error while calling debug string: %.*s")); } tv_clear(&input); @@ -909,7 +931,7 @@ static void nlua_typval_exec(const char *lcmd, size_t lcmd_len, const char *name PUSH_ALL_TYPVALS(lstate, args, argcount, special); - if (lua_pcall(lstate, argcount, ret_tv ? 1 : 0, 0)) { + if (nlua_pcall(lstate, argcount, ret_tv ? 1 : 0)) { nlua_error(lstate, _("E5108: Error executing lua %.*s")); return; } @@ -964,7 +986,7 @@ int typval_exec_lua_callable(lua_State *lstate, LuaCallable lua_cb, int argcount PUSH_ALL_TYPVALS(lstate, argvars, argcount, false); - if (lua_pcall(lstate, argcount, 1, 0)) { + if (nlua_pcall(lstate, argcount, 1)) { nlua_print(lstate); return ERROR_OTHER; } @@ -999,7 +1021,7 @@ Object nlua_exec(const String str, const Array args, Error *err) nlua_push_Object(lstate, args.items[i], false); } - if (lua_pcall(lstate, (int)args.size, 1, 0)) { + if (nlua_pcall(lstate, (int)args.size, 1)) { size_t len; const char *errstr = lua_tolstring(lstate, -1, &len); api_set_error(err, kErrorTypeException, @@ -1032,7 +1054,7 @@ Object nlua_call_ref(LuaRef ref, const char *name, Array args, bool retval, Erro nlua_push_Object(lstate, args.items[i], false); } - if (lua_pcall(lstate, nargs, retval ? 1 : 0, 0)) { + if (nlua_pcall(lstate, nargs, retval ? 1 : 0)) { // if err is passed, the caller will deal with the error. if (err) { size_t len; @@ -1091,7 +1113,7 @@ void ex_luado(exarg_T *const eap) FUNC_ATTR_NONNULL_ALL { if (u_save(eap->line1 - 1, eap->line2 + 1) == FAIL) { - EMSG(_("cannot save undo information")); + emsg(_("cannot save undo information")); return; } const char *const cmd = (const char *)eap->arg; @@ -1126,7 +1148,7 @@ void ex_luado(exarg_T *const eap) if (lcmd_len >= IOSIZE) { xfree(lcmd); } - if (lua_pcall(lstate, 0, 1, 0)) { + if (nlua_pcall(lstate, 0, 1)) { nlua_error(lstate, _("E5110: Error executing lua: %.*s")); return; } @@ -1138,7 +1160,7 @@ void ex_luado(exarg_T *const eap) const char *old_line = (const char *)ml_get_buf(curbuf, l, false); lua_pushstring(lstate, old_line); lua_pushnumber(lstate, (lua_Number)l); - if (lua_pcall(lstate, 2, 1, 0)) { + if (nlua_pcall(lstate, 2, 1)) { nlua_error(lstate, _("E5111: Error calling lua: %.*s")); break; } @@ -1189,7 +1211,7 @@ bool nlua_exec_file(const char *path) return false; } - if (lua_pcall(lstate, 0, 0, 0)) { + if (nlua_pcall(lstate, 0, 0)) { nlua_error(lstate, _("E5113: Error while calling lua chunk: %.*s")); return false; } @@ -1241,7 +1263,7 @@ int nlua_expand_pat(expand_T *xp, char_u *pat, int *num_results, char_u ***resul // [ vim, vim._on_key, buf ] lua_pushlstring(lstate, (const char *)pat, STRLEN(pat)); - if (lua_pcall(lstate, 1, 2, 0) != 0) { + if (nlua_pcall(lstate, 1, 2) != 0) { nlua_error(lstate, _("Error executing vim._expand_pat: %.*s")); return FAIL; @@ -1394,7 +1416,7 @@ void nlua_execute_on_key(int c) // [ vim, vim._on_key, buf ] lua_pushlstring(lstate, (const char *)buf, buf_len); - if (lua_pcall(lstate, 1, 0, 0)) { + if (nlua_pcall(lstate, 1, 0)) { nlua_error(lstate, _("Error executing vim.on_key Lua callback: %.*s")); } diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 2d969357b4..db79e9e7e9 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -216,6 +216,45 @@ static int nlua_str_utf_pos(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL return 1; } +/// Return the offset from the 1-indexed byte position to the first byte of the +/// current character. +/// +/// Expects a string and an int. +/// +/// Returns the byte offset to the first byte of the current character +/// pointed into by the offset. +static int nlua_str_utf_start(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL +{ + size_t s1_len; + const char *s1 = luaL_checklstring(lstate, 1, &s1_len); + long offset = luaL_checkinteger(lstate, 2); + if (offset < 0 || offset > (intptr_t)s1_len) { + return luaL_error(lstate, "index out of range"); + } + int tail_offset = mb_head_off((char_u *)s1, (char_u *)s1 + (char_u)offset - 1); + lua_pushinteger(lstate, tail_offset); + return 1; +} + +/// Return the offset from the 1-indexed byte position to the last +/// byte of the current character. +/// +/// Expects a string and an int. +/// +/// Returns the byte offset to the last byte of the current character +/// pointed into by the offset. +static int nlua_str_utf_end(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL +{ + size_t s1_len; + const char *s1 = luaL_checklstring(lstate, 1, &s1_len); + long offset = luaL_checkinteger(lstate, 2); + if (offset < 0 || offset > (intptr_t)s1_len) { + return luaL_error(lstate, "index out of range"); + } + int tail_offset = mb_tail_off((char_u *)s1, (char_u *)s1 + (char_u)offset - 1); + lua_pushinteger(lstate, tail_offset); + return 1; +} /// convert UTF-32 or UTF-16 indices to byte index. /// @@ -272,7 +311,8 @@ int nlua_regex(lua_State *lstate) return 1; } -static dict_T *nlua_get_var_scope(lua_State *lstate) { +static dict_T *nlua_get_var_scope(lua_State *lstate) +{ const char *scope = luaL_checkstring(lstate, 1); handle_T handle = (handle_T)luaL_checkinteger(lstate, 2); dict_T *dict = NULL; @@ -424,7 +464,6 @@ static int nlua_stricmp(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL } - void nlua_state_add_stdlib(lua_State *const lstate) { // stricmp @@ -439,6 +478,12 @@ void nlua_state_add_stdlib(lua_State *const lstate) // str_utf_pos lua_pushcfunction(lstate, &nlua_str_utf_pos); lua_setfield(lstate, -2, "str_utf_pos"); + // str_utf_start + lua_pushcfunction(lstate, &nlua_str_utf_start); + lua_setfield(lstate, -2, "str_utf_start"); + // str_utf_end + lua_pushcfunction(lstate, &nlua_str_utf_end); + lua_setfield(lstate, -2, "str_utf_end"); // regex lua_pushcfunction(lstate, &nlua_regex); lua_setfield(lstate, -2, "regex"); diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c index 02bd612149..60a000843f 100644 --- a/src/nvim/lua/treesitter.c +++ b/src/nvim/lua/treesitter.c @@ -1195,7 +1195,8 @@ int tslua_parse_query(lua_State *L) } -static const char *query_err_string(TSQueryError err) { +static const char *query_err_string(TSQueryError err) +{ switch (err) { case TSQueryErrorSyntax: return "invalid syntax"; diff --git a/src/nvim/macros.h b/src/nvim/macros.h index 50ee91dc36..fd23ab8270 100644 --- a/src/nvim/macros.h +++ b/src/nvim/macros.h @@ -204,11 +204,11 @@ /// #if defined(__clang__) && __clang__ == 1 # define PRAGMA_DIAG_PUSH_IGNORE_MISSING_PROTOTYPES \ - _Pragma("clang diagnostic push")\ + _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wmissing-prototypes\"") # ifdef HAVE_WIMPLICIT_FALLTHROUGH_FLAG # define PRAGMA_DIAG_PUSH_IGNORE_IMPLICIT_FALLTHROUGH \ - _Pragma("clang diagnostic push")\ + _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wimplicit-fallthrough\"") # else # define PRAGMA_DIAG_PUSH_IGNORE_IMPLICIT_FALLTHROUGH \ @@ -218,11 +218,11 @@ _Pragma("clang diagnostic pop") #elif defined(__GNUC__) # define PRAGMA_DIAG_PUSH_IGNORE_MISSING_PROTOTYPES \ - _Pragma("GCC diagnostic push")\ + _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"") # ifdef HAVE_WIMPLICIT_FALLTHROUGH_FLAG # define PRAGMA_DIAG_PUSH_IGNORE_IMPLICIT_FALLTHROUGH \ - _Pragma("GCC diagnostic push")\ + _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") # else # define PRAGMA_DIAG_PUSH_IGNORE_IMPLICIT_FALLTHROUGH \ diff --git a/src/nvim/main.c b/src/nvim/main.c index c329c9a8f4..921bc883cf 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -674,8 +674,7 @@ void getout(int exitval) profile_dump(); - if (did_emsg - ) { + if (did_emsg) { // give the user a chance to read the (error) message no_wait_return = FALSE; wait_return(FALSE); @@ -824,11 +823,11 @@ static void command_line_scan(mparm_T *parmp) msgpack_packer *p = msgpack_packer_new(&fp, msgpack_file_write); if (fof_ret != 0) { - emsgf(_("E5421: Failed to open stdin: %s"), os_strerror(fof_ret)); + semsg(_("E5421: Failed to open stdin: %s"), os_strerror(fof_ret)); } if (p == NULL) { - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); } Object md = DICTIONARY_OBJ(api_metadata()); @@ -1698,8 +1697,11 @@ static void do_system_initialization(void) } char *vimrc = xmalloc(dir_len + sizeof(path_tail) + 1); memcpy(vimrc, dir, dir_len); - vimrc[dir_len] = PATHSEP; - memcpy(vimrc + dir_len + 1, path_tail, sizeof(path_tail)); + if (vimrc[dir_len - 1] != PATHSEP) { + vimrc[dir_len] = PATHSEP; + dir_len += 1; + } + memcpy(vimrc + dir_len, path_tail, sizeof(path_tail)); if (do_source(vimrc, false, DOSO_NONE) != FAIL) { xfree(vimrc); xfree(config_dirs); @@ -1743,7 +1745,7 @@ static bool do_user_initialization(void) if (os_path_exists(init_lua_path) && do_source((char *)init_lua_path, true, DOSO_VIMRC)) { if (os_path_exists(user_vimrc)) { - EMSG3(_("E5422: Conflicting configs: \"%s\" \"%s\""), init_lua_path, + semsg(_("E5422: Conflicting configs: \"%s\" \"%s\""), init_lua_path, user_vimrc); } @@ -1815,7 +1817,7 @@ static void source_startup_scripts(const mparm_T *const parmp) // Do nothing. } else { if (do_source(parmp->use_vimrc, false, DOSO_NONE) != OK) { - EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc); + semsg(_("E282: Cannot read from \"%s\""), parmp->use_vimrc); } } } else if (!silent_mode) { diff --git a/src/nvim/map.c b/src/nvim/map.c index 20d5570e8c..1d9abe3ef2 100644 --- a/src/nvim/map.c +++ b/src/nvim/map.c @@ -51,36 +51,28 @@ #define MAP_IMPL(T, U, ...) \ INITIALIZER_DECLARE(T, U, __VA_ARGS__); \ __KHASH_IMPL(T##_##U##_map, , T, U, 1, T##_hash, T##_eq) \ - \ void map_##T##_##U##_destroy(Map(T, U) *map) \ { \ kh_dealloc(T##_##U##_map, &map->table); \ } \ - \ U map_##T##_##U##_get(Map(T, U) *map, T key) \ { \ khiter_t k; \ - \ if ((k = kh_get(T##_##U##_map, &map->table, key)) == kh_end(&map->table)) { \ return INITIALIZER(T, U); \ } \ - \ return kh_val(&map->table, k); \ } \ - \ bool map_##T##_##U##_has(Map(T, U) *map, T key) \ { \ return kh_get(T##_##U##_map, &map->table, key) != kh_end(&map->table); \ } \ - \ T map_##T##_##U##_key(Map(T, U) *map, T key) \ { \ khiter_t k; \ - \ if ((k = kh_get(T##_##U##_map, &map->table, key)) == kh_end(&map->table)) { \ abort(); /* Caller must check map_has(). */ \ } \ - \ return kh_key(&map->table, k); \ } \ U map_##T##_##U##_put(Map(T, U) *map, T key, U value) \ @@ -88,15 +80,12 @@ int ret; \ U rv = INITIALIZER(T, U); \ khiter_t k = kh_put(T##_##U##_map, &map->table, key, &ret); \ - \ if (!ret) { \ rv = kh_val(&map->table, k); \ } \ - \ kh_val(&map->table, k) = value; \ return rv; \ } \ - \ U *map_##T##_##U##_ref(Map(T, U) *map, T key, bool put) \ { \ int ret; \ @@ -112,23 +101,18 @@ return NULL; \ } \ } \ - \ return &kh_val(&map->table, k); \ } \ - \ U map_##T##_##U##_del(Map(T, U) *map, T key) \ { \ U rv = INITIALIZER(T, U); \ khiter_t k; \ - \ if ((k = kh_get(T##_##U##_map, &map->table, key)) != kh_end(&map->table)) { \ rv = kh_val(&map->table, k); \ kh_del(T##_##U##_map, &map->table, k); \ } \ - \ return rv; \ } \ - \ void map_##T##_##U##_clear(Map(T, U) *map) \ { \ kh_clear(T##_##U##_map, &map->table); \ diff --git a/src/nvim/map.h b/src/nvim/map.h index 6ed341ac76..dbd85a4e1f 100644 --- a/src/nvim/map.h +++ b/src/nvim/map.h @@ -16,11 +16,9 @@ #define MAP_DECLS(T, U) \ KHASH_DECLARE(T##_##U##_map, T, U) \ - \ typedef struct { \ khash_t(T##_##U##_map) table; \ } Map(T, U); \ - \ Map(T, U) *map_##T##_##U##_new(void); \ void map_##T##_##U##_free(Map(T, U) *map); \ void map_##T##_##U##_destroy(Map(T, U) *map); \ diff --git a/src/nvim/mark.c b/src/nvim/mark.c index ea9acdf31a..51f4ba635f 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -564,19 +564,19 @@ static void fmarks_check_one(xfmark_T *fm, char_u *name, buf_T *buf) int check_mark(pos_T *pos) { if (pos == NULL) { - EMSG(_(e_umark)); + emsg(_(e_umark)); return FAIL; } if (pos->lnum <= 0) { // lnum is negative if mark is in another file can can't get that // file, error message already give then. if (pos->lnum == 0) { - EMSG(_(e_marknotset)); + emsg(_(e_marknotset)); } return FAIL; } if (pos->lnum > curbuf->b_ml.ml_line_count) { - EMSG(_(e_markinval)); + emsg(_(e_markinval)); return FAIL; } return OK; @@ -711,9 +711,9 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu did_title = false; } else { if (arg == NULL) { - MSG(_("No marks set")); + msg(_("No marks set")); } else { - EMSG2(_("E283: No marks matching \"%s\""), arg); + semsg(_("E283: No marks matching \"%s\""), arg); } } } else if (!got_int @@ -762,9 +762,9 @@ void ex_delmarks(exarg_T *eap) // clear all marks clrallmarks(curbuf); } else if (eap->forceit) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else if (*eap->arg == NUL) { - EMSG(_(e_argreq)); + emsg(_(e_argreq)); } else { // clear specified marks only for (p = eap->arg; *p != NUL; ++p) { @@ -779,7 +779,7 @@ void ex_delmarks(exarg_T *eap) : (digit ? ascii_isdigit(p[2]) : ASCII_ISUPPER(p[2]))) || to < from) { - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return; } p += 2; @@ -821,7 +821,7 @@ void ex_delmarks(exarg_T *eap) case ' ': break; default: - EMSG2(_(e_invarg2), p); + semsg(_(e_invarg2), p); return; } } @@ -839,7 +839,7 @@ void ex_jumps(exarg_T *eap) cleanup_jumplist(curwin, true); // Highlight title - MSG_PUTS_TITLE(_("\n jump line col file/text")); + 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 = fm_getname(&curwin->w_jumplist[i].fmark, 16); @@ -871,7 +871,7 @@ void ex_jumps(exarg_T *eap) ui_flush(); } if (curwin->w_jumplistidx == curwin->w_jumplistlen) { - MSG_PUTS("\n>"); + msg_puts("\n>"); } } @@ -891,7 +891,7 @@ void ex_changes(exarg_T *eap) char_u *name; // Highlight title - MSG_PUTS_TITLE(_("\nchange line col text")); + msg_puts_title(_("\nchange line col text")); for (i = 0; i < curbuf->b_changelistlen && !got_int; ++i) { if (curbuf->b_changelist[i].mark.lnum != 0) { @@ -914,7 +914,7 @@ void ex_changes(exarg_T *eap) ui_flush(); } if (curwin->w_changelistidx == curbuf->b_changelistlen) { - MSG_PUTS("\n>"); + msg_puts("\n>"); } } diff --git a/src/nvim/marktree.c b/src/nvim/marktree.c index a7f540c748..38014ab375 100644 --- a/src/nvim/marktree.c +++ b/src/nvim/marktree.c @@ -570,11 +570,11 @@ void marktree_free_node(mtnode_t *x) } /// NB: caller must check not pair! -uint64_t marktree_revise(MarkTree *b, MarkTreeIter *itr) +uint64_t marktree_revise(MarkTree *b, MarkTreeIter *itr, uint8_t decor_level) { uint64_t old_id = rawkey(itr).id; pmap_del(uint64_t)(b->id2node, ANTIGRAVITY(old_id)); - uint64_t new_id = (b->next_id += ID_INCR); + uint64_t new_id = (b->next_id += ID_INCR) + ((uint64_t)decor_level << DECOR_OFFSET); rawkey(itr).id = new_id + (RIGHT_GRAVITY&old_id); refkey(b, itr->node, itr->i); return new_id; diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index bd680330ca..cc488d486f 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -346,7 +346,6 @@ static int enc_canon_search(const char_u *name) } - /* * Find canonical encoding "name" in the list and return its properties. * Returns 0 if not found. @@ -1587,7 +1586,7 @@ void show_utf8(void) line = get_cursor_pos_ptr(); len = utfc_ptr2len(line); if (len == 0) { - MSG("NUL"); + msg("NUL"); return; } @@ -1610,7 +1609,7 @@ void show_utf8(void) } } - msg(IObuff); + msg((char *)IObuff); } /// Return offset from "p" to the first byte of the character it points into. @@ -1883,6 +1882,40 @@ int mb_tail_off(char_u *base, char_u *p) return i; } + +/// Return the offset from "p" to the first byte of the character it points +/// into. Can start anywhere in a stream of bytes. +/// +/// @param[in] base Pointer to start of string +/// @param[in] p Pointer to byte for which to return the offset to the previous codepoint +// +/// @return 0 if invalid sequence, else offset to previous codepoint +int mb_head_off(char_u *base, char_u *p) +{ + int i; + int j; + + if (*p == NUL) { + return 0; + } + + // Find the first character that is not 10xx.xxxx + for (i = 0; p - i > base; i--) { + if ((p[i] & 0xc0) != 0x80) { + break; + } + } + + // Find the last character that is 10xx.xxxx + for (j = 0; (p[j + 1] & 0xc0) == 0x80; j++) {} + + // Check for illegal sequence. + if (utf8len_tab[p[i]] == 1) { + return 0; + } + return i; +} + /* * Find the next illegal byte sequence. */ @@ -2398,8 +2431,6 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen #endif // HAVE_ICONV - - /* * Setup "vcp" for conversion from "from" to "to". * The names must have been made canonical with enc_canonize(). diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c index 438340e0c4..2a0ea9a269 100644 --- a/src/nvim/memfile.c +++ b/src/nvim/memfile.c @@ -168,7 +168,7 @@ void mf_close(memfile_T *mfp, bool del_file) return; } if (mfp->mf_fd >= 0 && close(mfp->mf_fd) < 0) { - EMSG(_(e_swapclose)); + emsg(_(e_swapclose)); } if (del_file && mfp->mf_fname != NULL) { os_remove((char *)mfp->mf_fname); @@ -206,7 +206,7 @@ void mf_close_file(buf_T *buf, bool getlines) } if (close(mfp->mf_fd) < 0) { // close the file - EMSG(_(e_swapclose)); + emsg(_(e_swapclose)); } mfp->mf_fd = -1; @@ -325,7 +325,7 @@ void mf_put(memfile_T *mfp, bhdr_T *hp, bool dirty, bool infile) unsigned flags = hp->bh_flags; if ((flags & BH_LOCKED) == 0) { - IEMSG(_("E293: block was not locked")); + iemsg(_("E293: block was not locked")); } flags &= ~BH_LOCKED; if (dirty) { @@ -648,7 +648,7 @@ static int mf_write(memfile_T *mfp, bhdr_T *hp) /// write or when hitting a key. We keep on trying, in case some /// space becomes available. if (!did_swapwrite_msg) { - EMSG(_("E297: Write error in swap file")); + emsg(_("E297: Write error in swap file")); } did_swapwrite_msg = true; return FAIL; @@ -792,7 +792,7 @@ static bool mf_do_open(memfile_T *mfp, char_u *fname, int flags) if ((flags & O_CREAT) && os_fileinfo_link((char *)mfp->mf_fname, &file_info)) { mfp->mf_fd = -1; - EMSG(_("E300: Swap file already exists (symlink attack?)")); + emsg(_("E300: Swap file already exists (symlink attack?)")); } else { // try to open the file mfp->mf_fd = mch_open_rw((char *)mfp->mf_fname, flags | O_NOFOLLOW); diff --git a/src/nvim/memline.c b/src/nvim/memline.c index b4e9869b17..456b1013c1 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -2,7 +2,7 @@ // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // for debugging -// #define CHECK(c, s) do { if (c) EMSG(s); } while (0) +// #define CHECK(c, s) do { if (c) emsg(s); } while (0) #define CHECK(c, s) do { } while (0) /* @@ -235,7 +235,7 @@ static linenr_T lowest_marked = 0; // argument for ml_upd_block0() typedef enum { UB_FNAME = 0, // update timestamp and filename - UB_SAME_DIR // update the B0_SAME_DIR flag + UB_SAME_DIR, // update the B0_SAME_DIR flag } upd_block0_T; #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -296,7 +296,7 @@ int ml_open(buf_T *buf) */ hp = mf_new(mfp, false, 1); if (hp->bh_bnum != 0) { - IEMSG(_("E298: Didn't get block nr 0?")); + iemsg(_("E298: Didn't get block nr 0?")); goto error; } b0p = hp->bh_data; @@ -340,7 +340,7 @@ int ml_open(buf_T *buf) goto error; } if (hp->bh_bnum != 1) { - IEMSG(_("E298: Didn't get block nr 1?")); + iemsg(_("E298: Didn't get block nr 1?")); goto error; } pp = hp->bh_data; @@ -356,7 +356,7 @@ int ml_open(buf_T *buf) */ hp = ml_new_data(mfp, false, 1); if (hp->bh_bnum != 2) { - IEMSG(_("E298: Didn't get block nr 2?")); + iemsg(_("E298: Didn't get block nr 2?")); goto error; } @@ -448,13 +448,13 @@ void ml_setname(buf_T *buf) mfp->mf_fd = os_open((char *)mfp->mf_fname, O_RDWR, 0); if (mfp->mf_fd < 0) { // could not (re)open the swap file, what can we do???? - EMSG(_("E301: Oops, lost the swap file!!!")); + emsg(_("E301: Oops, lost the swap file!!!")); return; } (void)os_set_cloexec(mfp->mf_fd); } if (!success) { - EMSG(_("E302: Could not rename swap file")); + emsg(_("E302: Could not rename swap file")); } } @@ -538,7 +538,7 @@ void ml_open_file(buf_T *buf) if (*p_dir != NUL && mfp->mf_fname == NULL) { need_wait_return = true; // call wait_return later no_wait_return++; - (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"), + (void)semsg(_("E303: Unable to open swap file for \"%s\", recovery impossible"), buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname); --no_wait_return; } @@ -654,7 +654,7 @@ static void ml_upd_block0(buf_T *buf, upd_block0_T what) } b0p = hp->bh_data; if (ml_check_b0_id(b0p) == FAIL) { - IEMSG(_("E304: ml_upd_block0(): Didn't get block 0??")); + iemsg(_("E304: ml_upd_block0(): Didn't get block 0??")); } else { if (what == UB_FNAME) { set_b0_fname(b0p, buf); @@ -814,7 +814,7 @@ void ml_recover(bool checkext) // count the number of matching swap files len = recover_names(fname, FALSE, 0, NULL); if (len == 0) { // no swap files found - EMSG2(_("E305: No swap file found for %s"), fname); + semsg(_("E305: No swap file found for %s"), fname); goto theend; } if (len == 1) { // one swap file found, use it @@ -823,7 +823,7 @@ void ml_recover(bool checkext) // list the names of the swap files (void)recover_names(fname, TRUE, 0, NULL); msg_putchar('\n'); - MSG_PUTS(_("Enter number of swap file to use (0 to quit): ")); + msg_puts(_("Enter number of swap file to use (0 to quit): ")); i = get_number(FALSE, NULL); if (i < 1 || i > len) { goto theend; @@ -865,7 +865,7 @@ void ml_recover(bool checkext) mfp = mf_open(fname_used, O_RDONLY); fname_used = p; if (mfp == NULL || mfp->mf_fd < 0) { - EMSG2(_("E306: Cannot open %s"), fname_used); + semsg(_("E306: Cannot open %s"), fname_used); goto theend; } buf->b_ml.ml_mfp = mfp; @@ -883,9 +883,9 @@ void ml_recover(bool checkext) */ if ((hp = mf_get(mfp, 0, 1)) == NULL) { msg_start(); - MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST); + msg_puts_attr(_("Unable to read block 0 from "), attr | MSG_HIST); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); - MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."), + msg_puts_attr(_("\nMaybe no changes were made or Vim did not update the swap file."), attr | MSG_HIST); msg_end(); goto theend; @@ -894,26 +894,26 @@ void ml_recover(bool checkext) if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0) { msg_start(); msg_outtrans_attr(mfp->mf_fname, MSG_HIST); - MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"), + msg_puts_attr(_(" cannot be used with this version of Vim.\n"), MSG_HIST); - MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST); + msg_puts_attr(_("Use Vim version 3.0.\n"), MSG_HIST); msg_end(); goto theend; } if (ml_check_b0_id(b0p) == FAIL) { - EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname); + semsg(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname); goto theend; } if (b0_magic_wrong(b0p)) { msg_start(); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); - MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"), + msg_puts_attr(_(" cannot be used on this computer.\n"), attr | MSG_HIST); - MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST); + msg_puts_attr(_("The file was created on "), attr | MSG_HIST); // avoid going past the end of a corrupted hostname b0p->b0_fname[0] = NUL; - MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST); - MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST); + msg_puts_attr((char *)b0p->b0_hname, attr | MSG_HIST); + msg_puts_attr(_(",\nor the file has been damaged."), attr | MSG_HIST); msg_end(); goto theend; } @@ -929,7 +929,7 @@ void ml_recover(bool checkext) if (mfp->mf_page_size < previous_page_size) { msg_start(); msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); - MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"), + msg_puts_attr(_(" has been damaged (page size is smaller than minimum value).\n"), attr | MSG_HIST); msg_end(); goto theend; @@ -982,7 +982,7 @@ void ml_recover(bool checkext) && org_file_info.stat.st_mtim.tv_sec > swp_file_info.stat.st_mtim.tv_sec) || org_file_info.stat.st_mtim.tv_sec != mtime)) { - EMSG(_("E308: Warning: Original file may have been changed")); + emsg(_("E308: Warning: Original file may have been changed")); } ui_flush(); @@ -1052,7 +1052,7 @@ void ml_recover(bool checkext) */ if ((hp = mf_get(mfp, bnum, page_count)) == NULL) { if (bnum == 1) { - EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname); + semsg(_("E309: Unable to read block 1 from %s"), mfp->mf_fname); goto theend; } ++error; @@ -1121,7 +1121,7 @@ void ml_recover(bool checkext) dp = hp->bh_data; if (dp->db_id != DATA_ID) { // block id wrong if (bnum == 1) { - EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"), + semsg(_("E310: Block 1 ID wrong (%s not a .swp file?)"), mfp->mf_fname); goto theend; } @@ -1232,23 +1232,23 @@ void ml_recover(bool checkext) recoverymode = FALSE; if (got_int) { - EMSG(_("E311: Recovery Interrupted")); + emsg(_("E311: Recovery Interrupted")); } else if (error) { ++no_wait_return; - MSG(">>>>>>>>>>>>>"); - EMSG(_( "E312: Errors detected while recovering; look for lines starting with ???")); + msg(">>>>>>>>>>>>>"); + emsg(_( "E312: Errors detected while recovering; look for lines starting with ???")); --no_wait_return; - MSG(_("See \":help E312\" for more information.")); - MSG(">>>>>>>>>>>>>"); + msg(_("See \":help E312\" for more information.")); + msg(">>>>>>>>>>>>>"); } else { if (curbuf->b_changed) { - MSG(_("Recovery completed. You should check if everything is OK.")); - MSG_PUTS(_("\n(You might want to write out this file under another name\n")); - MSG_PUTS(_("and run diff with the original file to check for changes)")); + msg(_("Recovery completed. You should check if everything is OK.")); + msg_puts(_("\n(You might want to write out this file under another name\n")); + msg_puts(_("and run diff with the original file to check for changes)")); } else { - MSG(_("Recovery completed. Buffer contents equals file contents.")); + msg(_("Recovery completed. Buffer contents equals file contents.")); } - MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n")); + msg_puts(_("\nYou may want to delete the .swp file now.\n\n")); cmdline_row = msg_row; } redraw_curbuf_later(NOT_VALID); @@ -1316,7 +1316,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) if (list) { // use msg() to start the scrolling properly - msg((char_u *)_("Swap files found:")); + msg(_("Swap files found:")); msg_putchar('\n'); } @@ -1424,14 +1424,14 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) } else if (list) { if (dir_name[0] == '.' && dir_name[1] == NUL) { if (fname == NULL) { - MSG_PUTS(_(" In current directory:\n")); + msg_puts(_(" In current directory:\n")); } else { - MSG_PUTS(_(" Using specified name:\n")); + msg_puts(_(" Using specified name:\n")); } } else { - MSG_PUTS(_(" In directory ")); + msg_puts(_(" In directory ")); msg_home_replace(dir_name); - MSG_PUTS(":\n"); + msg_puts(":\n"); } if (num_files) { @@ -1444,7 +1444,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) (void)swapfile_info(files[i]); } } else { - MSG_PUTS(_(" -- none --\n")); + msg_puts(_(" -- none --\n")); } ui_flush(); } else { @@ -1542,15 +1542,15 @@ static time_t swapfile_info(char_u *fname) #ifdef UNIX // print name of owner of the file if (os_get_uname(file_info.stat.st_uid, uname, B0_UNAME_SIZE) == OK) { - MSG_PUTS(_(" owned by: ")); + msg_puts(_(" owned by: ")); msg_outtrans((char_u *)uname); - MSG_PUTS(_(" dated: ")); + msg_puts(_(" dated: ")); } else #endif - MSG_PUTS(_(" dated: ")); + msg_puts(_(" dated: ")); x = file_info.stat.st_mtim.tv_sec; char ctime_buf[50]; - MSG_PUTS(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf))); + msg_puts(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf))); } /* @@ -1560,55 +1560,55 @@ static time_t swapfile_info(char_u *fname) if (fd >= 0) { if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) { if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0) { - MSG_PUTS(_(" [from Vim version 3.0]")); + msg_puts(_(" [from Vim version 3.0]")); } else if (ml_check_b0_id(&b0) == FAIL) { - MSG_PUTS(_(" [does not look like a Vim swap file]")); + msg_puts(_(" [does not look like a Vim swap file]")); } else if (!ml_check_b0_strings(&b0)) { - MSG_PUTS(_(" [garbled strings (not nul terminated)]")); + msg_puts(_(" [garbled strings (not nul terminated)]")); } else { - MSG_PUTS(_(" file name: ")); + msg_puts(_(" file name: ")); if (b0.b0_fname[0] == NUL) { - MSG_PUTS(_("[No Name]")); + msg_puts(_("[No Name]")); } else { msg_outtrans(b0.b0_fname); } - MSG_PUTS(_("\n modified: ")); - MSG_PUTS(b0.b0_dirty ? _("YES") : _("no")); + msg_puts(_("\n modified: ")); + msg_puts(b0.b0_dirty ? _("YES") : _("no")); if (*(b0.b0_uname) != NUL) { - MSG_PUTS(_("\n user name: ")); + msg_puts(_("\n user name: ")); msg_outtrans(b0.b0_uname); } if (*(b0.b0_hname) != NUL) { if (*(b0.b0_uname) != NUL) { - MSG_PUTS(_(" host name: ")); + msg_puts(_(" host name: ")); } else { - MSG_PUTS(_("\n host name: ")); + msg_puts(_("\n host name: ")); } msg_outtrans(b0.b0_hname); } if (char_to_long(b0.b0_pid) != 0L) { - MSG_PUTS(_("\n process ID: ")); + msg_puts(_("\n process ID: ")); msg_outnum(char_to_long(b0.b0_pid)); if (os_proc_running((int)char_to_long(b0.b0_pid))) { - MSG_PUTS(_(" (STILL RUNNING)")); + msg_puts(_(" (STILL RUNNING)")); process_still_running = true; } } if (b0_magic_wrong(&b0)) { - MSG_PUTS(_("\n [not usable on this computer]")); + msg_puts(_("\n [not usable on this computer]")); } } } else { - MSG_PUTS(_(" [cannot be read]")); + msg_puts(_(" [cannot be read]")); } close(fd); } else { - MSG_PUTS(_(" [cannot be opened]")); + msg_puts(_(" [cannot be opened]")); } msg_putchar('\n'); @@ -1638,7 +1638,7 @@ static time_t swapfile_unchanged(char *fname) } // the ID and magic number must be correct - if (ml_check_b0_id(&b0) == FAIL|| b0_magic_wrong(&b0)) { + if (ml_check_b0_id(&b0) == FAIL || b0_magic_wrong(&b0)) { ret = false; } @@ -1756,7 +1756,7 @@ void ml_preserve(buf_T *buf, int message, bool do_fsync) if (mfp == NULL || mfp->mf_fname == NULL) { if (message) { - EMSG(_("E313: Cannot preserve, there is no swap file")); + emsg(_("E313: Cannot preserve, there is no swap file")); } return; } @@ -1807,9 +1807,9 @@ theend: if (message) { if (status == OK) { - MSG(_("File preserved")); + msg(_("File preserved")); } else { - EMSG(_("E314: Preserve failed")); + emsg(_("E314: Preserve failed")); } } } @@ -1857,7 +1857,7 @@ char_u *ml_get_buf(buf_T *buf, linenr_T lnum, bool will_change) // Avoid giving this message for a recursive call, may happen when // the GUI redraws part of the text. recursive++; - IEMSGN(_("E315: ml_get: invalid lnum: %" PRId64), lnum); + siemsg(_("E315: ml_get: invalid lnum: %" PRId64), (int64_t)lnum); recursive--; } errorret: @@ -1893,8 +1893,8 @@ errorret: recursive++; get_trans_bufname(buf); shorten_dir(NameBuff); - iemsgf(_("E316: ml_get: cannot find line %" PRId64 " in buffer %d %s"), - lnum, buf->b_fnum, NameBuff); + siemsg(_("E316: ml_get: cannot find line %" PRId64 " in buffer %d %s"), + (int64_t)lnum, buf->b_fnum, NameBuff); recursive--; } goto errorret; @@ -2295,7 +2295,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b } pp = hp->bh_data; // must be pointer block if (pp->pb_id != PTR_ID) { - IEMSG(_("E317: pointer block id wrong 3")); + iemsg(_("E317: pointer block id wrong 3")); mf_put(mfp, hp, false, false); return FAIL; } @@ -2437,7 +2437,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b * Safety check: fallen out of for loop? */ if (stack_idx < 0) { - IEMSG(_("E318: Updated too many blocks?")); + iemsg(_("E318: Updated too many blocks?")); buf->b_ml.ml_stack_top = 0; // invalidate stack } } @@ -2563,8 +2563,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) * If the file becomes empty the last line is replaced by an empty line. */ if (buf->b_ml.ml_line_count == 1) { // file becomes empty - if (message - ) { + if (message) { set_keep_msg((char_u *)_(no_lines_msg), 0); } @@ -2630,7 +2629,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) } pp = hp->bh_data; // must be pointer block if (pp->pb_id != PTR_ID) { - IEMSG(_("E317: pointer block id wrong 4")); + iemsg(_("E317: pointer block id wrong 4")); mf_put(mfp, hp, false, false); return FAIL; } @@ -2846,7 +2845,7 @@ static void ml_flush_line(buf_T *buf) hp = ml_find_line(buf, lnum, ML_FIND); if (hp == NULL) { - IEMSGN(_("E320: Cannot find line %" PRId64), lnum); + siemsg(_("E320: Cannot find line %" PRId64), (int64_t)lnum); } else { dp = hp->bh_data; idx = lnum - buf->b_ml.ml_locked_low; @@ -3061,7 +3060,7 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) pp = (PTR_BL *)(dp); // must be pointer block if (pp->pb_id != PTR_ID) { - IEMSG(_("E317: pointer block id wrong")); + iemsg(_("E317: pointer block id wrong")); goto error_block; } @@ -3100,10 +3099,10 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) } if (idx >= (int)pp->pb_count) { // past the end: something wrong! if (lnum > buf->b_ml.ml_line_count) { - IEMSGN(_("E322: line number out of range: %" PRId64 " past the end"), - lnum - buf->b_ml.ml_line_count); + siemsg(_("E322: line number out of range: %" PRId64 " past the end"), + (int64_t)lnum - buf->b_ml.ml_line_count); } else { - IEMSGN(_("E323: line count wrong in block %" PRId64), bnum); + siemsg(_("E323: line count wrong in block %" PRId64), bnum); } goto error_block; } @@ -3182,7 +3181,7 @@ static void ml_lineadd(buf_T *buf, int count) pp = hp->bh_data; // must be pointer block if (pp->pb_id != PTR_ID) { mf_put(mfp, hp, false, false); - IEMSG(_("E317: pointer block id wrong 2")); + iemsg(_("E317: pointer block id wrong 2")); break; } pp->pb_pointer[ip->ip_index].pe_line_count += count; @@ -3215,7 +3214,7 @@ int resolve_symlink(const char_u *fname, char_u *buf) for (;; ) { // Limit symlink depth to 100, catch recursive loops. if (++depth == 100) { - EMSG2(_("E773: Symlink loop for \"%s\""), fname); + semsg(_("E773: Symlink loop for \"%s\""), fname); return FAIL; } @@ -3357,39 +3356,39 @@ static void attention_message(buf_T *buf, char_u *fname) assert(buf->b_fname != NULL); ++no_wait_return; - (void)EMSG(_("E325: ATTENTION")); - MSG_PUTS(_("\nFound a swap file by the name \"")); + (void)emsg(_("E325: ATTENTION")); + msg_puts(_("\nFound a swap file by the name \"")); msg_home_replace(fname); - MSG_PUTS("\"\n"); + msg_puts("\"\n"); const time_t swap_mtime = swapfile_info(fname); - MSG_PUTS(_("While opening file \"")); + msg_puts(_("While opening file \"")); msg_outtrans(buf->b_fname); - MSG_PUTS("\"\n"); + msg_puts("\"\n"); FileInfo file_info; if (!os_fileinfo((char *)buf->b_fname, &file_info)) { - MSG_PUTS(_(" CANNOT BE FOUND")); + msg_puts(_(" CANNOT BE FOUND")); } else { - MSG_PUTS(_(" dated: ")); + msg_puts(_(" dated: ")); time_t x = file_info.stat.st_mtim.tv_sec; char ctime_buf[50]; - MSG_PUTS(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf))); + msg_puts(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf))); if (swap_mtime != 0 && x > swap_mtime) { - MSG_PUTS(_(" NEWER than swap file!\n")); + msg_puts(_(" NEWER than swap file!\n")); } } // Some of these messages are long to allow translation to // other languages. - MSG_PUTS(_("\n(1) Another program may be editing the same file. If this is" + msg_puts(_("\n(1) Another program may be editing the same file. If this is" " the case,\n be careful not to end up with two different" " instances of the same\n file when making changes." " Quit, or continue with caution.\n")); - MSG_PUTS(_("(2) An edit session for this file crashed.\n")); - MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r ")); + msg_puts(_("(2) An edit session for this file crashed.\n")); + msg_puts(_(" If this is the case, use \":recover\" or \"vim -r ")); 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_puts(_("\"\n to recover the changes (see \":help recovery\").\n")); + msg_puts(_(" If you did this already, delete the swap file \"")); msg_outtrans(fname); - MSG_PUTS(_("\"\n to avoid this message.\n")); + msg_puts(_("\"\n to avoid this message.\n")); cmdline_row = msg_row; --no_wait_return; } @@ -3648,7 +3647,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ break; } } else { - MSG_PUTS("\n"); + msg_puts("\n"); if (msg_silent == 0) { // call wait_return() later need_wait_return = true; @@ -3666,7 +3665,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ */ if (fname[n - 1] == 'a') { // ".s?a" if (fname[n - 2] == 'a') { // ".saa": tried enough, give up - EMSG(_("E326: Too many swap files found")); + emsg(_("E326: Too many swap files found")); XFREE_CLEAR(fname); break; } @@ -3682,7 +3681,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ int ret; char *failed_dir; if ((ret = os_mkdir_recurse(dir_name, 0755, &failed_dir)) != 0) { - EMSG3(_("E303: Unable to create directory \"%s\" for swap file, " + semsg(_("E303: Unable to create directory \"%s\" for swap file, " "recovery impossible: %s"), failed_dir, os_strerror(ret)); xfree(failed_dir); diff --git a/src/nvim/memory.c b/src/nvim/memory.c index 5345580b93..547a9015b7 100644 --- a/src/nvim/memory.c +++ b/src/nvim/memory.c @@ -510,7 +510,7 @@ void do_outofmem_msg(size_t size) * message fails, e.g. when setting v:errmsg. */ did_outofmem_msg = true; - EMSGU(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), size); + semsg(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), (uint64_t)size); } } diff --git a/src/nvim/menu.c b/src/nvim/menu.c index f1ae8740bb..c2b6a5e402 100644 --- a/src/nvim/menu.c +++ b/src/nvim/menu.c @@ -38,8 +38,6 @@ #endif - - /// The character for each menu mode static char_u menu_mode_chars[] = { 'n', 'v', 's', 'o', 'i', 'c', 't' }; @@ -168,7 +166,7 @@ void ex_menu(exarg_T *eap) menu_path = (char *)arg; if (*menu_path == '.') { - EMSG2(_(e_invarg2), menu_path); + semsg(_(e_invarg2), menu_path); goto theend; } @@ -181,7 +179,7 @@ void ex_menu(exarg_T *eap) show_menus((char_u *)menu_path, modes); goto theend; } else if (*map_to != NUL && (unmenu || enable != kNone)) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); goto theend; } @@ -318,7 +316,7 @@ static int add_menu_path(const char_u *const menu_path, vimmenu_T *menuarg, dname = menu_text(name, NULL, NULL); if (*dname == NUL) { // Only a mnemonic or accelerator is not valid. - EMSG(_("E792: Empty menu name")); + emsg(_("E792: Empty menu name")); goto erret; } @@ -329,13 +327,13 @@ static int add_menu_path(const char_u *const menu_path, vimmenu_T *menuarg, if (menu_name_equal(name, menu) || menu_name_equal(dname, menu)) { if (*next_name == NUL && menu->children != NULL) { if (!sys_menu) { - EMSG(_("E330: Menu path must not lead to a sub-menu")); + emsg(_("E330: Menu path must not lead to a sub-menu")); } goto erret; } if (*next_name != NUL && menu->children == NULL) { if (!sys_menu) { - EMSG(_(e_notsubmenu)); + emsg(_(e_notsubmenu)); } goto erret; } @@ -355,12 +353,12 @@ static int add_menu_path(const char_u *const menu_path, vimmenu_T *menuarg, if (menu == NULL) { if (*next_name == NUL && parent == NULL) { - EMSG(_("E331: Must not add menu items directly to menu bar")); + emsg(_("E331: Must not add menu items directly to menu bar")); goto erret; } if (menu_is_separator(dname) && *next_name != NUL) { - EMSG(_("E332: Separator cannot be part of a menu path")); + emsg(_("E332: Separator cannot be part of a menu path")); goto erret; } @@ -519,7 +517,7 @@ static int menu_enable_recurse(vimmenu_T *menu, char_u *name, int modes, int ena if (*name == NUL || *name == '*' || menu_name_equal(name, menu)) { if (*p != NUL) { if (menu->children == NULL) { - EMSG(_(e_notsubmenu)); + emsg(_(e_notsubmenu)); return FAIL; } if (menu_enable_recurse(menu->children, p, modes, enable) == FAIL) { @@ -543,7 +541,7 @@ static int menu_enable_recurse(vimmenu_T *menu, char_u *name, int modes, int ena menu = menu->next; } if (*name != NUL && *name != '*' && menu == NULL) { - EMSG2(_(e_nomenu), name); + semsg(_(e_nomenu), name); return FAIL; } @@ -572,7 +570,7 @@ static int remove_menu(vimmenu_T **menup, char_u *name, int modes, bool silent) if (*name == NUL || menu_name_equal(name, menu)) { if (*p != NUL && menu->children == NULL) { if (!silent) { - EMSG(_(e_notsubmenu)); + emsg(_(e_notsubmenu)); } return FAIL; } @@ -582,7 +580,7 @@ static int remove_menu(vimmenu_T **menup, char_u *name, int modes, bool silent) } } else if (*name != NUL) { if (!silent) { - EMSG(_(e_othermode)); + emsg(_(e_othermode)); } return FAIL; } @@ -614,7 +612,7 @@ static int remove_menu(vimmenu_T **menup, char_u *name, int modes, bool silent) if (*name != NUL) { if (menu == NULL) { if (!silent) { - EMSG2(_(e_nomenu), name); + semsg(_(e_nomenu), name); } return FAIL; } @@ -797,10 +795,10 @@ static vimmenu_T *find_menu(vimmenu_T *menu, char_u *name, int modes) if (menu_name_equal(name, menu)) { // Found menu if (*p != NUL && menu->children == NULL) { - EMSG(_(e_notsubmenu)); + emsg(_(e_notsubmenu)); return NULL; } else if ((menu->modes & modes) == 0x0) { - EMSG(_(e_othermode)); + emsg(_(e_othermode)); return NULL; } else if (*p == NUL) { // found a full match return menu; @@ -811,7 +809,7 @@ static vimmenu_T *find_menu(vimmenu_T *menu, char_u *name, int modes) } if (menu == NULL) { - EMSG2(_(e_nomenu), name); + semsg(_(e_nomenu), name); return NULL; } // Found a match, search the sub-menu. @@ -832,7 +830,7 @@ static int show_menus(char_u *const path_name, int modes) // Now we have found the matching menu, and we list the mappings // Highlight title - MSG_PUTS_TITLE(_("\n--- Menus ---")); + msg_puts_title(_("\n--- Menus ---")); show_menus_recursive(menu->parent, modes, 0); return OK; @@ -854,11 +852,11 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) return; } for (i = 0; i < depth; i++) { - MSG_PUTS(" "); + msg_puts(" "); } if (menu->priority) { msg_outnum(menu->priority); - MSG_PUTS(" "); + msg_puts(" "); } // Same highlighting as for directories!? msg_outtrans_attr(menu->name, HL_ATTR(HLF_D)); @@ -872,7 +870,7 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) return; } for (i = 0; i < depth + 2; i++) { - MSG_PUTS(" "); + msg_puts(" "); } msg_putchar(menu_mode_chars[bit]); if (menu->noremap[bit] == REMAP_NONE) { @@ -892,7 +890,7 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) } else { msg_putchar(' '); } - MSG_PUTS(" "); + msg_puts(" "); if (*menu->strings[bit] == NUL) { msg_puts_attr("<Nop>", HL_ATTR(HLF_8)); } else { @@ -951,7 +949,7 @@ char_u *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char_u *arg, bool if (!ascii_iswhite(*p)) { if (STRNCMP(arg, "enable", 6) == 0 - && (arg[6] == NUL || ascii_iswhite(arg[6]))) { + && (arg[6] == NUL || ascii_iswhite(arg[6]))) { p = arg + 6; } else if (STRNCMP(arg, "disable", 7) == 0 && (arg[7] == NUL || ascii_iswhite(arg[7]))) { @@ -1466,7 +1464,7 @@ static void execute_menu(const exarg_T *eap, vimmenu_T *menu) menu->silent[idx]); } } else if (eap != NULL) { - EMSG2(_("E335: Menu not defined for %s mode"), mode); + semsg(_("E335: Menu not defined for %s mode"), mode); } } @@ -1484,10 +1482,10 @@ void ex_emenu(exarg_T *eap) while (menu != NULL) { if (menu_name_equal(name, menu)) { if (*p == NUL && menu->children != NULL) { - EMSG(_("E333: Menu path must lead to a menu item")); + emsg(_("E333: Menu path must lead to a menu item")); menu = NULL; } else if (*p != NUL && menu->children == NULL) { - EMSG(_(e_notsubmenu)); + emsg(_(e_notsubmenu)); menu = NULL; } break; @@ -1502,7 +1500,7 @@ void ex_emenu(exarg_T *eap) } xfree(saved_name); if (menu == NULL) { - EMSG2(_("E334: Menu not found: %s"), eap->arg); + semsg(_("E334: Menu not found: %s"), eap->arg); return; } @@ -1558,7 +1556,7 @@ void ex_menutranslate(exarg_T *eap) *arg = NUL; arg = menu_skip_part(to); if (arg == to) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { from = vim_strsave(from); from_noamp = menu_text(from, NULL, NULL); diff --git a/src/nvim/message.c b/src/nvim/message.c index 75f0dd6bb7..80cc655c11 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -209,7 +209,7 @@ void msg_grid_validate(void) * When terminal not initialized (yet) mch_errmsg(..) is used. * return TRUE if wait_return not called */ -int msg(char_u *s) +int msg(char *s) { return msg_attr_keep(s, 0, false, false); } @@ -218,7 +218,7 @@ int msg(char_u *s) int verb_msg(char *s) { verbose_enter(); - int n = msg_attr_keep((char_u *)s, 0, false, false); + int n = msg_attr_keep(s, 0, false, false); verbose_leave(); return n; @@ -227,7 +227,7 @@ int verb_msg(char *s) int msg_attr(const char *s, const int attr) FUNC_ATTR_NONNULL_ARG(1) { - return msg_attr_keep((char_u *)s, attr, false, false); + return msg_attr_keep(s, attr, false, false); } /// similar to msg_outtrans_attr, but support newlines and tabs. @@ -265,7 +265,7 @@ void msg_multiline_attr(const char *s, int attr, bool check_int, bool *need_clea /// @param keep set keep_msg if it doesn't scroll -bool msg_attr_keep(char_u *s, int attr, bool keep, bool multiline) +bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) FUNC_ATTR_NONNULL_ALL { static int entered = 0; @@ -281,12 +281,12 @@ bool msg_attr_keep(char_u *s, int attr, bool keep, bool multiline) // Skip messages not match ":filter pattern". // Don't filter when there is an error. - if (!emsg_on_display && message_filtered(s)) { + if (!emsg_on_display && message_filtered((char_u *)s)) { return true; } if (attr == 0) { - set_vim_var_string(VV_STATUSMSG, (char *)s, -1); + set_vim_var_string(VV_STATUSMSG, s, -1); } /* @@ -301,35 +301,35 @@ bool msg_attr_keep(char_u *s, int attr, bool keep, bool multiline) // Add message to history (unless it's a repeated kept message or a // truncated message) - if (s != keep_msg + if ((const char_u *)s != keep_msg || (*s != '<' && last_msg_hist != NULL && last_msg_hist->msg != NULL && STRCMP(s, last_msg_hist->msg))) { - add_msg_hist((const char *)s, -1, attr, multiline); + add_msg_hist(s, -1, attr, multiline); } // Truncate the message if needed. msg_start(); - buf = msg_strtrunc(s, FALSE); + buf = msg_strtrunc((char_u *)s, FALSE); if (buf != NULL) { - s = buf; + s = (const char *)buf; } bool need_clear = true; if (multiline) { - msg_multiline_attr((char *)s, attr, false, &need_clear); + msg_multiline_attr(s, attr, false, &need_clear); } else { - msg_outtrans_attr(s, attr); + msg_outtrans_attr((char_u *)s, attr); } if (need_clear) { msg_clr_eos(); } retval = msg_end(); - if (keep && retval && vim_strsize(s) < (int)(Rows - cmdline_row - 1) + if (keep && retval && vim_strsize((char_u *)s) < (int)(Rows - cmdline_row - 1) * Columns + sc_col) { - set_keep_msg(s, 0); + set_keep_msg((char_u *)s, 0); } xfree(buf); @@ -453,11 +453,11 @@ void trunc_string(char_u *s, char_u *buf, int room_in, int buflen) } /* - * Note: Caller of smgs() and smsg_attr() must check the resulting string is + * Note: Caller of smsg() and smsg_attr() must check the resulting string is * shorter than IOSIZE!!! */ -int smsg(char *s, ...) +int smsg(const char *s, ...) FUNC_ATTR_PRINTF(1, 2) { va_list arglist; @@ -465,10 +465,10 @@ int smsg(char *s, ...) va_start(arglist, s); vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist); va_end(arglist); - return msg(IObuff); + return msg((char *)IObuff); } -int smsg_attr(int attr, char *s, ...) +int smsg_attr(int attr, const char *s, ...) FUNC_ATTR_PRINTF(2, 3) { va_list arglist; @@ -479,7 +479,7 @@ int smsg_attr(int attr, char *s, ...) return msg_attr((const char *)IObuff, attr); } -int smsg_attr_keep(int attr, char *s, ...) +int smsg_attr_keep(int attr, const char *s, ...) FUNC_ATTR_PRINTF(2, 3) { va_list arglist; @@ -487,7 +487,7 @@ int smsg_attr_keep(int attr, char *s, ...) va_start(arglist, s); vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist); va_end(arglist); - return msg_attr_keep(IObuff, attr, true, false); + return msg_attr_keep((const char *)IObuff, attr, true, false); } /* @@ -721,7 +721,7 @@ static bool emsg_multiline(const char *s, bool multiline) // Display the error message itself. msg_nowait = false; // Wait for this msg. - return msg_attr_keep((char_u *)s, attr, false, multiline); + return msg_attr_keep(s, attr, false, multiline); } /// emsg() - display an error message @@ -730,25 +730,25 @@ static bool emsg_multiline(const char *s, bool multiline) /// When terminal not initialized (yet) mch_errmsg(..) is used. /// /// @return true if wait_return not called -bool emsg(const char_u *s) +bool emsg(const char *s) { return emsg_multiline((const char *)s, false); } void emsg_invreg(int name) { - EMSG2(_("E354: Invalid register name: '%s'"), transchar(name)); + semsg(_("E354: Invalid register name: '%s'"), transchar(name)); } /// Print an error message with unknown number of arguments -bool emsgf(const char *const fmt, ...) +bool semsg(const char *const fmt, ...) FUNC_ATTR_PRINTF(1, 2) { bool ret; va_list ap; va_start(ap, fmt); - ret = emsgfv(fmt, ap); + ret = semsgv(fmt, ap); va_end(ap); return ret; @@ -756,7 +756,7 @@ bool emsgf(const char *const fmt, ...) #define MULTILINE_BUFSIZE 8192 -bool emsgf_multiline(const char *const fmt, ...) +bool semsg_multiline(const char *const fmt, ...) { bool ret; va_list ap; @@ -777,7 +777,7 @@ bool emsgf_multiline(const char *const fmt, ...) } /// Print an error message with unknown number of arguments -static bool emsgfv(const char *fmt, va_list ap) +static bool semsgv(const char *fmt, va_list ap) { static char errbuf[IOSIZE]; if (emsg_not_now()) { @@ -786,7 +786,7 @@ static bool emsgfv(const char *fmt, va_list ap) vim_vsnprintf(errbuf, sizeof(errbuf), fmt, ap); - return emsg((const char_u *)errbuf); + return emsg(errbuf); } /// Same as emsg(...), but abort on error when ABORT_ON_INTERNAL_ERROR is @@ -794,20 +794,20 @@ static bool emsgfv(const char *fmt, va_list ap) /// detected when fuzzing vim. void iemsg(const char *s) { - emsg((char_u *)s); + emsg(s); #ifdef ABORT_ON_INTERNAL_ERROR abort(); #endif } -/// Same as emsgf(...) but abort on error when ABORT_ON_INTERNAL_ERROR is +/// Same as semsg(...) but abort on error when ABORT_ON_INTERNAL_ERROR is /// defined. It is used for internal errors only, so that they can be /// detected when fuzzing vim. -void iemsgf(const char *s, ...) +void siemsg(const char *s, ...) { va_list ap; va_start(ap, s); - (void)emsgfv(s, ap); + (void)semsgv(s, ap); va_end(ap); #ifdef ABORT_ON_INTERNAL_ERROR abort(); @@ -817,17 +817,17 @@ void iemsgf(const char *s, ...) /// Give an "Internal error" message. void internal_error(char *where) { - IEMSG2(_(e_intern2), where); + siemsg(_(e_intern2), where); } -static void msg_emsgf_event(void **argv) +static void msg_semsg_event(void **argv) { char *s = argv[0]; - (void)emsg((char_u *)s); + (void)emsg(s); xfree(s); } -void msg_schedule_emsgf(const char *const fmt, ...) +void msg_schedule_semsg(const char *const fmt, ...) FUNC_ATTR_PRINTF(1, 2) { va_list ap; @@ -836,7 +836,7 @@ void msg_schedule_emsgf(const char *const fmt, ...) va_end(ap); char *s = xstrdup((char *)IObuff); - multiqueue_put(main_loop.events, msg_emsgf_event, 1, s); + multiqueue_put(main_loop.events, msg_semsg_event, 1, s); } /* @@ -845,21 +845,21 @@ void msg_schedule_emsgf(const char *const fmt, ...) * Careful: The string may be changed by msg_may_trunc()! * Returns a pointer to the printed message, if wait_return() not called. */ -char_u *msg_trunc_attr(char_u *s, int force, int attr) +char *msg_trunc_attr(char *s, int force, int attr) { int n; // Add message to history before truncating. - add_msg_hist((const char *)s, -1, attr, false); + add_msg_hist(s, -1, attr, false); - s = msg_may_trunc(force, s); + char *ts = (char *)msg_may_trunc(force, (char_u *)s); msg_hist_off = true; - n = msg_attr((const char *)s, attr); + n = msg_attr(ts, attr); msg_hist_off = false; if (n) { - return s; + return ts; } return NULL; } @@ -1009,7 +1009,7 @@ void ex_messages(void *const eap_p) } if (*eap->arg != NUL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1050,7 +1050,7 @@ void ex_messages(void *const eap_p) msg_hist_off = true; for (; p != NULL && !got_int; p = p->next) { if (p->msg != NULL) { - msg_attr_keep(p->msg, p->attr, false, p->multiline); + msg_attr_keep((char *)p->msg, p->attr, false, p->multiline); } } msg_hist_off = false; @@ -1072,11 +1072,11 @@ void msg_end_prompt(void) lines_left = -1; } -/// wait for the user to hit a key (normally a return) +/// Wait for the user to hit a key (normally Enter) /// -/// if 'redraw' is true, redraw the entire screen NOT_VALID -/// if 'redraw' is false, do a normal redraw -/// if 'redraw' is -1, don't redraw at all +/// If 'redraw' is true, redraw the entire screen NOT_VALID +/// If 'redraw' is false, do a normal redraw +/// If 'redraw' is -1, don't redraw at all void wait_return(int redraw) { int c; @@ -1119,7 +1119,7 @@ void wait_return(int redraw) quit_more = FALSE; got_int = FALSE; } else if (exmode_active) { - MSG_PUTS(" "); // make sure the cursor is on the right line + msg_puts(" "); // make sure the cursor is on the right line c = CAR; // no need for a return in ex mode got_int = FALSE; } else { @@ -1199,11 +1199,11 @@ void wait_return(int redraw) } } while ((had_got_int && c == Ctrl_C) || c == K_IGNORE - || c == K_LEFTDRAG || c == K_LEFTRELEASE + || c == K_LEFTDRAG || c == K_LEFTRELEASE || c == K_MIDDLEDRAG || c == K_MIDDLERELEASE - || c == K_RIGHTDRAG || c == K_RIGHTRELEASE - || c == K_MOUSELEFT || c == K_MOUSERIGHT - || c == K_MOUSEDOWN || c == K_MOUSEUP + || c == K_RIGHTDRAG || c == K_RIGHTRELEASE + || c == K_MOUSELEFT || c == K_MOUSERIGHT + || c == K_MOUSEDOWN || c == K_MOUSEUP || c == K_MOUSEMOVE); os_breakcheck(); /* @@ -1275,10 +1275,10 @@ static void hit_return_msg(void) } msg_ext_set_kind("return_prompt"); if (got_int) { - MSG_PUTS(_("Interrupt: ")); + msg_puts(_("Interrupt: ")); } - MSG_PUTS_ATTR(_("Press ENTER or type command to continue"), HL_ATTR(HLF_R)); + msg_puts_attr(_("Press ENTER or type command to continue"), HL_ATTR(HLF_R)); if (!msg_use_printf()) { msg_clr_eos(); } @@ -1376,7 +1376,7 @@ void msg_putchar(int c) void msg_putchar_attr(int c, int attr) { - char buf[MB_MAXBYTES + 1]; + char_u buf[MB_MAXBYTES + 1]; if (IS_SPECIAL(c)) { buf[0] = (char)K_SPECIAL; @@ -1384,9 +1384,9 @@ void msg_putchar_attr(int c, int attr) buf[2] = (char)K_THIRD(c); buf[3] = NUL; } else { - buf[utf_char2bytes(c, (char_u *)buf)] = NUL; + buf[utf_char2bytes(c, buf)] = NUL; } - msg_puts_attr(buf, attr); + msg_puts_attr((const char *)buf, attr); } void msg_outnum(long n) @@ -1569,22 +1569,22 @@ int msg_outtrans_special(const char_u *strstart, bool from, int maxlen) int attr = HL_ATTR(HLF_8); while (*str != NUL) { - const char *string; + const char *text; // Leading and trailing spaces need to be displayed in <> form. if ((str == strstart || str[1] == NUL) && *str == ' ') { - string = "<Space>"; + text = "<Space>"; str++; } else { - string = str2special((const char **)&str, from, false); + text = str2special((const char **)&str, from, false); } - const int len = vim_strsize((char_u *)string); + const int len = vim_strsize((char_u *)text); if (maxlen > 0 && retval + len >= maxlen) { break; } // Highlight special keys - msg_puts_attr(string, (len > 1 - && (*mb_ptr2len)((char_u *)string) <= 1 - ? attr : 0)); + msg_puts_attr(text, (len > 1 + && (*mb_ptr2len)((char_u *)text) <= 1 + ? attr : 0)); retval += len; } return retval; @@ -1909,12 +1909,12 @@ void msg_puts_title(const char *s) * part in the middle and replace it with "..." when necessary. * Does not handle multi-byte characters! */ -void msg_puts_long_attr(char_u *longstr, int attr) +void msg_outtrans_long_attr(char_u *longstr, int attr) { - msg_puts_long_len_attr(longstr, (int)STRLEN(longstr), attr); + msg_outtrans_long_len_attr(longstr, (int)STRLEN(longstr), attr); } -void msg_puts_long_len_attr(char_u *longstr, int len, int attr) +void msg_outtrans_long_len_attr(char_u *longstr, int len, int attr) { int slen = len; int room; @@ -2408,7 +2408,7 @@ typedef enum { SB_CLEAR_NONE = 0, SB_CLEAR_ALL, SB_CLEAR_CMDLINE_BUSY, - SB_CLEAR_CMDLINE_DONE + SB_CLEAR_CMDLINE_DONE, } sb_clear_T; // When to clear text on next msg. @@ -3308,7 +3308,7 @@ int verbose_open(void) verbose_fd = os_fopen((char *)p_vfile, "a"); if (verbose_fd == NULL) { - EMSG2(_(e_notopen), p_vfile); + semsg(_(e_notopen), p_vfile); return FAIL; } } diff --git a/src/nvim/message.h b/src/nvim/message.h index 6d4d030500..316b2df7a4 100644 --- a/src/nvim/message.h +++ b/src/nvim/message.h @@ -30,53 +30,6 @@ #define VIM_ALL 5 #define VIM_DISCARDALL 6 -/// Show plain message -#define MSG(s) msg((char_u *)(s)) - -/// Show message highlighted according to the attr -#define MSG_ATTR(s, attr) msg_attr((const char *)(s), (attr)) - -/// Display error message -/// -/// Sets error flag in process, can be transformed into an exception. -#define EMSG(s) emsg((char_u *)(s)) - -/// Like #EMSG, but for messages with one "%s" inside -#define EMSG2(s, p) emsgf((const char *)(s), (p)) - -/// Like #EMSG, but for messages with two "%s" inside -#define EMSG3(s, p, q) emsgf((const char *)(s), (p), (q)) - -/// Like #EMSG, but for messages with one "%" PRId64 inside -#define EMSGN(s, n) emsgf((const char *)(s), (int64_t)(n)) - -/// Like #EMSG, but for messages with one "%" PRIu64 inside -#define EMSGU(s, n) emsgf((const char *)(s), (uint64_t)(n)) - -/// Like #EMSG, but for internal messages -#define IEMSG(s) iemsg((const char *)(s)) - -/// Like #EMSG2, but for internal messages -#define IEMSG2(s, p) iemsgf((const char *)(s), (p)) - -/// Like #EMSGN, but for internal messages -#define IEMSGN(s, n) iemsgf((const char *)(s), (int64_t)(n)) - -/// Display message at the recorded position -#define MSG_PUTS(s) msg_puts((const char *)(s)) - -/// Display message at the recorded position, highlighted -#define MSG_PUTS_ATTR(s, a) msg_puts_attr((const char *)(s), (a)) - -/// Like #MSG_PUTS, but highlight like title -#define MSG_PUTS_TITLE(s) msg_puts_title((const char *)(s)) - -/// Like #MSG_PUTS, but if middle part of too long messages it will be replaced -#define MSG_PUTS_LONG(s) msg_puts_long_attr((char_u *)(s), 0) - -/// Like #MSG_PUTS_ATTR, but if middle part of long messages will be replaced -#define MSG_PUTS_LONG_ATTR(s, a) msg_puts_long_attr((char_u *)(s), (a)) - typedef struct { String text; int attr; diff --git a/src/nvim/misc1.c b/src/nvim/misc1.c index ffc930ac1e..faf0b0f633 100644 --- a/src/nvim/misc1.c +++ b/src/nvim/misc1.c @@ -145,7 +145,6 @@ int get_leader_len(char_u *line, char_u **flags, bool backward, bool include_spa } } for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j) { - ; } if (string[j] != NUL) { continue; // string doesn't match @@ -276,7 +275,7 @@ int get_last_leader_offset(char_u *line, char_u **flags) } } for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j) { - /* do nothing */; + // do nothing } if (string[j] != NUL) { continue; @@ -590,7 +589,7 @@ int get_number(int colon, int *mouse_used) ++typed; } else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H) { if (typed > 0) { - MSG_PUTS("\b \b"); + msg_puts("\b \b"); --typed; } n /= 10; @@ -630,10 +629,10 @@ int prompt_for_number(int *mouse_used) // When using ":silent" assume that <CR> was entered. if (mouse_used != NULL) { - MSG_PUTS(_("Type number and <Enter> or click with the mouse " + msg_puts(_("Type number and <Enter> or click with the mouse " "(q or empty cancels): ")); } else { - MSG_PUTS(_("Type number and <Enter> (q or empty cancels): ")); + msg_puts(_("Type number and <Enter> (q or empty cancels): ")); } /* Set the state such that text can be selected/copied/pasted and we still @@ -687,25 +686,19 @@ void msgmore(long n) } if (pn > p_report) { - if (pn == 1) { - if (n > 0) { - STRLCPY(msg_buf, _("1 more line"), MSG_BUF_LEN); - } else { - STRLCPY(msg_buf, _("1 line less"), MSG_BUF_LEN); - } + if (n > 0) { + vim_snprintf(msg_buf, MSG_BUF_LEN, + NGETTEXT("%ld more line", "%ld more lines", pn), + pn); } else { - if (n > 0) { - vim_snprintf(msg_buf, MSG_BUF_LEN, - _("%" PRId64 " more lines"), (int64_t)pn); - } else { - vim_snprintf(msg_buf, MSG_BUF_LEN, - _("%" PRId64 " fewer lines"), (int64_t)pn); - } + vim_snprintf(msg_buf, MSG_BUF_LEN, + NGETTEXT("%ld line less", "%ld fewer lines", pn), + pn); } if (got_int) { xstrlcat(msg_buf, _(" (Interrupted)"), MSG_BUF_LEN); } - if (msg((char_u *)msg_buf)) { + if (msg(msg_buf)) { set_keep_msg((char_u *)msg_buf, 0); keep_msg_more = true; } @@ -927,7 +920,7 @@ int call_shell(char_u *cmd, ShellOpts opts, char_u *extra_shell_arg) } if (*p_sh == NUL) { - EMSG(_(e_shellempty)); + emsg(_(e_shellempty)); retval = -1; } else { // The external command may update a tags file, clear cached tags. @@ -965,7 +958,7 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret // get a name for the temp file char_u *tempname = vim_tempname(); if (tempname == NULL) { - EMSG(_(e_notmp)); + emsg(_(e_notmp)); return NULL; } @@ -986,7 +979,7 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret FILE *fd = os_fopen((char *)tempname, READBIN); if (fd == NULL) { - EMSG2(_(e_notopen), tempname); + semsg(_(e_notopen), tempname); goto done; } @@ -999,7 +992,7 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret fclose(fd); os_remove((char *)tempname); if (i != len) { - EMSG2(_(e_notread), tempname); + semsg(_(e_notread), tempname); XFREE_CLEAR(buffer); } else if (ret_len == NULL) { // Change NUL into SOH, otherwise the string is truncated. diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 438ddd6fd3..6f1cc494b2 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -2170,7 +2170,7 @@ static void op_function(const oparg_T *oap) const bool save_finish_op = finish_op; if (*p_opfunc == NUL) { - EMSG(_("E774: 'operatorfunc' is empty")); + emsg(_("E774: 'operatorfunc' is empty")); } else { // Set '[ and '] marks to text to be operated on. curbuf->b_op_start = oap->start; @@ -3225,9 +3225,9 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char_u **te if (ptr[col] == NUL || (i == 0 && this_class != 2)) { // Didn't find an identifier or text. if (find_type & FIND_STRING) { - EMSG(_("E348: No string under cursor")); + emsg(_("E348: No string under cursor")); } else { - EMSG(_(e_noident)); + emsg(_(e_noident)); } return 0; } @@ -4546,7 +4546,7 @@ dozet: } else if (foldmethodIsMarker(curwin)) { deleteFold(curwin, (linenr_T)1, curbuf->b_ml.ml_line_count, true, false); } else { - EMSG(_("E352: Cannot erase folds with current 'foldmethod'")); + emsg(_("E352: Cannot erase folds with current 'foldmethod'")); } break; @@ -4772,7 +4772,6 @@ dozet: } - /* * "Q" command. */ @@ -5011,7 +5010,7 @@ static void nv_ident(cmdarg_T *cap) bool kp_ex = (*kp == ':'); // 'keywordprg' is an ex command bool kp_help = (STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0); if (kp_help && *skipwhite(ptr) == NUL) { - EMSG(_(e_noident)); // found white space only + emsg(_(e_noident)); // found white space only return; } size_t buf_size = n * 2 + 30 + STRLEN(kp); @@ -5053,7 +5052,7 @@ static void nv_ident(cmdarg_T *cap) --n; } if (n == 0) { - EMSG(_(e_noident)); // found dashes only + emsg(_(e_noident)); // found dashes only xfree(buf); return; } @@ -5780,10 +5779,10 @@ static void nv_brackets(cmdarg_T *cap) * "[m" or "]m" search for prev/next start of (Java) method. * "[M" or "]M" search for prev/next end of (Java) method. */ - if ( (cap->cmdchar == '[' - && vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL) - || (cap->cmdchar == ']' - && vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL)) { + if ((cap->cmdchar == '[' + && vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL) + || (cap->cmdchar == ']' + && vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL)) { if (cap->nchar == '*') { cap->nchar = '/'; } @@ -6349,7 +6348,7 @@ static void nv_Replace(cmdarg_T *cap) nv_operator(cap); } else if (!checkclearopq(cap->oap)) { if (!MODIFIABLE(curbuf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); } else { if (virtual_active()) { coladvance(getviscol()); @@ -6370,7 +6369,7 @@ static void nv_vreplace(cmdarg_T *cap) nv_replace(cap); // Do same as "r" in Visual mode for now } else if (!checkclearopq(cap->oap)) { if (!MODIFIABLE(curbuf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); } else { if (cap->extra_char == Ctrl_V) { // get another character cap->extra_char = get_literal(); @@ -6615,11 +6614,11 @@ static void nv_pcmark(cmdarg_T *cap) nv_cursormark(cap, false, pos); } else if (cap->cmdchar == 'g') { if (curbuf->b_changelistlen == 0) { - EMSG(_("E664: changelist is empty")); + emsg(_("E664: changelist is empty")); } else if (cap->count1 < 0) { - EMSG(_("E662: At start of changelist")); + emsg(_("E662: At start of changelist")); } else { - EMSG(_("E663: At end of changelist")); + emsg(_("E663: At end of changelist")); } } else { clearopbeep(cap->oap); @@ -7849,10 +7848,10 @@ static void nv_esc(cmdarg_T *cap) && !VIsual_active && no_reason) { if (anyBufIsChanged()) { - MSG(_("Type :qa! and press <Enter> to abandon all changes" + msg(_("Type :qa! and press <Enter> to abandon all changes" " and exit Nvim")); } else { - MSG(_("Type :qa and press <Enter> to exit Nvim")); + msg(_("Type :qa and press <Enter> to exit Nvim")); } } @@ -7926,7 +7925,7 @@ static void nv_edit(cmdarg_T *cap) nv_object(cap); } else if (!curbuf->b_p_ma && !p_im && !curbuf->terminal) { // Only give this error when 'insertmode' is off. - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); clearop(cap->oap); } else if (!checkclearopq(cap->oap)) { switch (cap->cmdchar) { diff --git a/src/nvim/normal.h b/src/nvim/normal.h index fbcc6da75b..0c2b8b4d8a 100644 --- a/src/nvim/normal.h +++ b/src/nvim/normal.h @@ -19,7 +19,7 @@ typedef enum { kMTCharWise = 0, ///< character-wise movement/register kMTLineWise = 1, ///< line-wise movement/register kMTBlockWise = 2, ///< block-wise movement/register - kMTUnknown = -1 ///< Unknown or invalid motion type + kMTUnknown = -1, ///< Unknown or invalid motion type } MotionType; /* diff --git a/src/nvim/ops.c b/src/nvim/ops.c index eb37213f1a..a4b554601e 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -210,7 +210,6 @@ void op_shift(oparg_T *oap, int curs_top, int amount) { long i; int first_char; - char_u *s; int block_col = 0; if (u_save((linenr_T)(oap->start.lnum - 1), @@ -249,27 +248,21 @@ void op_shift(oparg_T *oap, int curs_top, int amount) foldOpenCursor(); if (oap->line_count > p_report) { + char *op; if (oap->op_type == OP_RSHIFT) { - s = (char_u *)">"; + op = ">"; } else { - s = (char_u *)"<"; + op = "<"; } - if (oap->line_count == 1) { - if (amount == 1) { - sprintf((char *)IObuff, _("1 line %sed 1 time"), s); - } else { - sprintf((char *)IObuff, _("1 line %sed %d times"), s, amount); - } - } else { - if (amount == 1) { - sprintf((char *)IObuff, _("%" PRId64 " lines %sed 1 time"), - (int64_t)oap->line_count, s); - } else { - sprintf((char *)IObuff, _("%" PRId64 " lines %sed %d times"), - (int64_t)oap->line_count, s, amount); - } - } - msg_attr_keep(IObuff, 0, true, false); + + char *msg_line_single = NGETTEXT("%" PRId64 " line %sed %d time", + "%" PRId64 " line %sed %d times", amount); + char *msg_line_plural = NGETTEXT("%" PRId64 " lines %sed %d time", + "%" PRId64 " lines %sed %d times", amount); + vim_snprintf((char *)IObuff, IOSIZE, + NGETTEXT(msg_line_single, msg_line_plural, oap->line_count), + (int64_t)oap->line_count, op, amount); + msg_attr_keep((char *)IObuff, 0, true, false); } /* @@ -640,7 +633,7 @@ void op_reindent(oparg_T *oap, Indenter how) // Don't even try when 'modifiable' is off. if (!MODIFIABLE(curbuf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); return; } @@ -695,11 +688,9 @@ void op_reindent(oparg_T *oap, Indenter how) if (oap->line_count > p_report) { i = oap->line_count - (i + 1); - if (i == 1) { - MSG(_("1 line indented ")); - } else { - smsg(_("%" PRId64 " lines indented "), (int64_t)i); - } + smsg(NGETTEXT("%" PRId64 " line indented ", + "%" PRId64 " lines indented ", i), + (int64_t)i); } // set '[ and '] marks curbuf->b_op_start = oap->start; @@ -930,7 +921,7 @@ int do_record(int c) if (ui_has(kUIMessages)) { showmode(); } else { - MSG(""); + msg(""); } p = get_recorded(); if (p == NULL) { @@ -1018,7 +1009,7 @@ int do_execreg(int regname, int colon, int addcr, int silent) if (regname == '@') { // repeat previous one if (execreg_lastc == NUL) { - EMSG(_("E748: No previously used register")); + emsg(_("E748: No previously used register")); return FAIL; } regname = execreg_lastc; @@ -1036,7 +1027,7 @@ int do_execreg(int regname, int colon, int addcr, int silent) if (regname == ':') { // use last command line if (last_cmdline == NULL) { - EMSG(_(e_nolastcmd)); + emsg(_(e_nolastcmd)); return FAIL; } // don't keep the cmdline containing @: @@ -1066,7 +1057,7 @@ int do_execreg(int regname, int colon, int addcr, int silent) } else if (regname == '.') { // use last inserted text p = get_last_insert_save(); if (p == NULL) { - EMSG(_(e_noinstext)); + emsg(_(e_noinstext)); return FAIL; } retval = put_in_typebuf(p, false, colon, silent); @@ -1291,14 +1282,14 @@ bool get_spec_reg(int regname, char_u **argp, bool *allocated, bool errmsg) case ':': // last command line if (last_cmdline == NULL && errmsg) { - EMSG(_(e_nolastcmd)); + emsg(_(e_nolastcmd)); } *argp = last_cmdline; return true; case '/': // last search-pattern if (last_search_pat() == NULL && errmsg) { - EMSG(_(e_noprevre)); + emsg(_(e_noprevre)); } *argp = last_search_pat(); return true; @@ -1307,7 +1298,7 @@ bool get_spec_reg(int regname, char_u **argp, bool *allocated, bool errmsg) *argp = get_last_insert_save(); *allocated = true; if (*argp == NULL && errmsg) { - EMSG(_(e_noinstext)); + emsg(_(e_noinstext)); } return true; @@ -1424,7 +1415,7 @@ int op_delete(oparg_T *oap) } if (!MODIFIABLE(curbuf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); return FAIL; } @@ -1787,7 +1778,7 @@ int op_replace(oparg_T *oap, int c) char_u *after_p = NULL; int had_ctrl_v_cr = false; - if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty) { + if ((curbuf->b_ml.ml_flags & ML_EMPTY) || oap->empty) { return OK; // nothing to do } if (c == REPLACE_CR_NCHAR) { @@ -2073,11 +2064,9 @@ void op_tilde(oparg_T *oap) curbuf->b_op_end = oap->end; if (oap->line_count > p_report) { - if (oap->line_count == 1) { - MSG(_("1 line changed")); - } else { - smsg(_("%" PRId64 " lines changed"), (int64_t)oap->line_count); - } + smsg(NGETTEXT("%" PRId64 " line changed", + "%" PRId64 " lines changed", oap->line_count), + (int64_t)oap->line_count); } } @@ -2732,17 +2721,14 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) // redisplay now, so message is not deleted update_topline_redraw(); - if (yanklines == 1) { - if (yank_type == kMTBlockWise) { - smsg(_("block of 1 line yanked%s"), namebuf); - } else { - smsg(_("1 line yanked%s"), namebuf); - } - } else if (yank_type == kMTBlockWise) { - smsg(_("block of %" PRId64 " lines yanked%s"), + if (yank_type == kMTBlockWise) { + smsg(NGETTEXT("block of %" PRId64 " line yanked%s", + "block of %" PRId64 " lines yanked%s", yanklines), (int64_t)yanklines, namebuf); } else { - smsg(_("%" PRId64 " lines yanked%s"), (int64_t)yanklines, namebuf); + smsg(NGETTEXT("%" PRId64 " line yanked%s", + "%" PRId64 " lines yanked%s", yanklines), + (int64_t)yanklines, namebuf); } } } @@ -3089,7 +3075,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) } if (y_size == 0 || y_array == NULL) { - EMSG2(_("E353: Nothing in register %s"), + semsg(_("E353: Nothing in register %s"), regname == 0 ? (char_u *)"\"" : transchar(regname)); goto end; } @@ -3708,12 +3694,12 @@ void ex_display(exarg_T *eap) msg_puts(" "); msg_putchar('"'); msg_putchar(name); - MSG_PUTS(" "); + msg_puts(" "); int n = Columns - 11; for (size_t j = 0; j < yb->y_size && n > 1; j++) { if (j) { - MSG_PUTS_ATTR("^J", attr); + msg_puts_attr("^J", attr); n -= 2; } for (p = yb->y_array[j]; *p && (n -= ptr2cells(p)) >= 0; p++) { // -V1019 NOLINT(whitespace/line_length) @@ -3723,7 +3709,7 @@ void ex_display(exarg_T *eap) } } if (n > 1 && yb->y_type == kMTLineWise) { - MSG_PUTS_ATTR("^J", attr); + msg_puts_attr("^J", attr); } ui_flush(); // show one line at a time } @@ -4141,7 +4127,6 @@ static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, in */ line1 = vim_strsave(ml_get(lnum)); for (idx1 = 0; ascii_iswhite(line1[idx1]); ++idx1) { - ; } line2 = ml_get(lnum + 1); for (idx2 = 0; idx2 < leader2_len; ++idx2) { @@ -4809,11 +4794,9 @@ void op_addsub(oparg_T *oap, linenr_T Prenum1, bool g_cmd) } if (change_cnt > p_report) { - if (change_cnt == 1) { - MSG(_("1 line changed")); - } else { - smsg(_("%" PRId64 " lines changed"), (int64_t)change_cnt); - } + smsg(NGETTEXT("%" PRId64 " lines changed", + "%" PRId64 " lines changed", change_cnt), + (int64_t)change_cnt); } } } @@ -5400,7 +5383,7 @@ void write_reg_contents_lst(int name, char_u **strings, bool must_append, Motion if (strings[0] == NULL) { s = (char_u *)""; } else if (strings[1] != NULL) { - EMSG(_("E883: search pattern and expression register may not " + emsg(_("E883: search pattern and expression register may not " "contain two or more lines")); return; } @@ -5462,7 +5445,7 @@ void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_a buf = buflist_findnr(num); if (buf == NULL) { - EMSGN(_(e_nobufnr), (long)num); + semsg(_(e_nobufnr), (int64_t)num); } } else { buf = buflist_findnr(buflist_findpat(str, str + STRLEN(str), @@ -5704,7 +5687,7 @@ void cursor_pos_info(dict_T *dict) // Compute the length of the file in characters. if (curbuf->b_ml.ml_flags & ML_EMPTY) { if (dict == NULL) { - MSG(_(no_lines_msg)); + msg(_(no_lines_msg)); return; } } else { @@ -5902,7 +5885,7 @@ void cursor_pos_info(dict_T *dict) // Don't shorten this message, the user asked for it. p = p_shm; p_shm = (char_u *)""; - msg(IObuff); + msg((char *)IObuff); p_shm = p; } } @@ -5964,7 +5947,7 @@ static yankreg_T *adjust_clipboard_name(int *name, bool quiet, bool writing) clipboard_didwarn = true; // Do NOT error (emsg()) here--if it interrupts :redir we get into // a weird state, stuck in "redirect mode". - msg((char_u *)MSG_NO_CLIP); + msg(MSG_NO_CLIP); } // ... else, be silent (don't flood during :while, :redir, etc.). goto end; @@ -6202,7 +6185,7 @@ err: reg->additional_data = NULL; reg->timestamp = 0; if (errmsg) { - EMSG("clipboard: provider returned invalid data"); + emsg("clipboard: provider returned invalid data"); } *target = reg; return false; diff --git a/src/nvim/ops.h b/src/nvim/ops.h index 11049b72c0..efde7290cf 100644 --- a/src/nvim/ops.h +++ b/src/nvim/ops.h @@ -77,7 +77,7 @@ typedef int (*Indenter)(void); enum GRegFlags { kGRegNoExpr = 1, ///< Do not allow expression register. kGRegExprSrc = 2, ///< Return expression itself for "=" register. - kGRegList = 4 ///< Return list. + kGRegList = 4, ///< Return list. }; /// Definition of one register diff --git a/src/nvim/option.c b/src/nvim/option.c index 05dcf737b2..064a0f33ad 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -105,7 +105,7 @@ // WV_ and BV_ values get typecasted to this for the "indir" field typedef enum { PV_NONE = 0, - PV_MAXVAL = 0xffff // to avoid warnings for value out of range + PV_MAXVAL = 0xffff, // to avoid warnings for value out of range } idopt_T; /* @@ -419,7 +419,7 @@ void set_init_1(bool clean_arg) } xfree(item); } - if(mustfree) { + if (mustfree) { xfree(p); } } @@ -949,8 +949,8 @@ void set_title_defaults(void) int do_set(char_u *arg, int opt_flags) { int opt_idx; - char_u *errmsg; - char_u errbuf[80]; + char *errmsg; + char errbuf[80]; char_u *startarg; int prefix; // 1: nothing, 0: "no", 2: "inv" in front of name char_u nextchar; // next non-white char after option name @@ -1071,7 +1071,7 @@ int do_set(char_u *arg, int opt_flags) nextchar = arg[len]; if (opt_idx == -1 && key == 0) { // found a mismatch: skip - errmsg = (char_u *)N_("E518: Unknown option"); + errmsg = N_("E518: Unknown option"); goto skip; } @@ -1082,7 +1082,7 @@ int do_set(char_u *arg, int opt_flags) if (vim_strchr((char_u *)"=:!&<", nextchar) == NULL && (!(options[opt_idx].flags & P_BOOL) || nextchar == '?')) { - errmsg = (char_u *)_(e_unsupportedoption); + errmsg = _(e_unsupportedoption); } goto skip; } @@ -1109,11 +1109,11 @@ int do_set(char_u *arg, int opt_flags) // Disallow changing some options from modelines. if (opt_flags & OPT_MODELINE) { if (flags & (P_SECURE | P_NO_ML)) { - errmsg = (char_u *)N_("E520: Not allowed in a modeline"); + errmsg = N_("E520: Not allowed in a modeline"); goto skip; } if ((flags & P_MLE) && !p_mle) { - errmsg = (char_u *)N_("E992: Not allowed in a modeline when 'modelineexpr' is off"); + errmsg = N_("E992: Not allowed in a modeline when 'modelineexpr' is off"); goto skip; } // In diff mode some options are overruled. This avoids that @@ -1181,7 +1181,7 @@ int do_set(char_u *arg, int opt_flags) } } } else { - errmsg = (char_u *)N_("E846: Key code not set"); + errmsg = N_("E846: Key code not set"); goto skip; } if (nextchar != '?' @@ -1232,7 +1232,7 @@ int do_set(char_u *arg, int opt_flags) } } - errmsg = (char_u *)set_bool_option(opt_idx, varp, (int)value, + errmsg = set_bool_option(opt_idx, varp, (int)value, opt_flags); } else { // Numeric or string. if (vim_strchr((const char_u *)"=:&<", nextchar) == NULL @@ -1275,11 +1275,11 @@ int do_set(char_u *arg, int opt_flags) // Allow negative, octal and hex numbers. vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true); if (i == 0 || (arg[i] != NUL && !ascii_iswhite(arg[i]))) { - errmsg = (char_u *)N_("E521: Number required after ="); + errmsg = N_("E521: Number required after ="); goto skip; } } else { - errmsg = (char_u *)N_("E521: Number required after ="); + errmsg = N_("E521: Number required after ="); goto skip; } @@ -1292,9 +1292,9 @@ int do_set(char_u *arg, int opt_flags) if (removing) { value = *(long *)varp - value; } - errmsg = (char_u *)set_num_option(opt_idx, varp, (long)value, - errbuf, sizeof(errbuf), - opt_flags); + errmsg = set_num_option(opt_idx, varp, (long)value, + errbuf, sizeof(errbuf), + opt_flags); } else if (opt_idx >= 0) { // String. char_u *save_arg = NULL; char_u *s = NULL; @@ -1361,7 +1361,7 @@ int do_set(char_u *arg, int opt_flags) && (*arg == NUL || *arg == ' ')) { STRCPY(errbuf, ":help"); save_arg = arg; - arg = errbuf; + arg = (char_u *)errbuf; } /* * Convert 'backspace' number to string, for @@ -1415,7 +1415,7 @@ int do_set(char_u *arg, int opt_flags) STRLCAT(errbuf, "[,],", sizeof(errbuf)); } save_arg = arg; - arg = errbuf; + arg = (char_u *)errbuf; } /* * Remove '>' before 'dir' and 'bdir', for @@ -1690,7 +1690,7 @@ skip: trans_characters(IObuff, IOSIZE); no_wait_return++; // wait_return done later - emsg(IObuff); // show error highlighted + emsg((char *)IObuff); // show error highlighted no_wait_return--; return FAIL; @@ -1736,10 +1736,10 @@ static void did_set_option(int opt_idx, int opt_flags, int new_value, int value_ } } -static char_u *illegal_char(char_u *errbuf, size_t errbuflen, int c) +static char *illegal_char(char *errbuf, size_t errbuflen, int c) { if (errbuf == NULL) { - return (char_u *)""; + return ""; } vim_snprintf((char *)errbuf, errbuflen, _("E539: Illegal character <%s>"), (char *)transchar(c)); @@ -1761,7 +1761,7 @@ static int string_to_key(char_u *arg) /// Check value of 'cedit' and set cedit_key. /// Returns NULL if value is OK, error message otherwise. -static char_u *check_cedit(void) +static char *check_cedit(void) { int n; @@ -2141,7 +2141,7 @@ void set_string_option_direct(const char *name, int opt_idx, const char_u *val, idx = findoption(name); if (idx < 0) { // Not found (should not happen). internal_error("set_string_option_direct()"); - IEMSG2(_("For option %s"), name); + siemsg(_("For option %s"), name); return; } } @@ -2238,9 +2238,9 @@ static char *set_string_option(const int opt_idx, const char *const value, const char *const saved_newval = xstrdup(s); int value_checked = false; - char *const r = (char *)did_set_string_option(opt_idx, (char_u **)varp, (int)true, - (char_u *)oldval, - NULL, 0, opt_flags, &value_checked); + char *const r = did_set_string_option(opt_idx, (char_u **)varp, (int)true, + (char_u *)oldval, + NULL, 0, opt_flags, &value_checked); if (r == NULL) { did_set_option(opt_idx, opt_flags, true, value_checked); } @@ -2313,11 +2313,11 @@ static bool valid_spellfile(const char_u *val) /// @param errbuflen length of errors buffer /// @param opt_flags OPT_LOCAL and/or OPT_GLOBAL /// @param value_checked value was checked to be safe, no need to set P_INSECURE -static char_u *did_set_string_option(int opt_idx, char_u **varp, bool new_value_alloced, - char_u *oldval, char_u *errbuf, size_t errbuflen, - int opt_flags, int *value_checked) +static char *did_set_string_option(int opt_idx, char_u **varp, bool new_value_alloced, + char_u *oldval, char *errbuf, size_t errbuflen, + int opt_flags, int *value_checked) { - char_u *errmsg = NULL; + char *errmsg = NULL; char_u *s, *p; int did_chartab = false; char_u **gvarp; @@ -2369,7 +2369,7 @@ static char_u *did_set_string_option(int opt_idx, char_u **varp, bool new_value_ } else if (varp == &p_bex || varp == &p_pm) { // 'backupext' and 'patchmode' if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex, *p_pm == '.' ? p_pm + 1 : p_pm) == 0) { - errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal"); + errmsg = N_("E589: 'backupext' and 'patchmode' are equal"); } } else if (varp == &curwin->w_p_briopt) { // 'breakindentopt' if (briopt_check(curwin) == FAIL) { @@ -2457,11 +2457,11 @@ static char_u *did_set_string_option(int opt_idx, char_u **varp, bool new_value_ } else { FOR_ALL_TAB_WINDOWS(tp, wp) { if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { - errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'"); + errmsg = _("E834: Conflicts with value of 'listchars'"); goto ambw_end; } if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { - errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'"); + errmsg = _("E835: Conflicts with value of 'fillchars'"); goto ambw_end; } } @@ -2634,9 +2634,9 @@ ambw_end: s++; } if (*s++ == NUL) { - errmsg = (char_u *)N_("E524: Missing colon"); + errmsg = N_("E524: Missing colon"); } else if (*s == ',' || *s == NUL) { - errmsg = (char_u *)N_("E525: Zero length string"); + errmsg = N_("E525: Zero length string"); } if (errmsg != NULL) { break; @@ -2714,7 +2714,7 @@ ambw_end: transchar_byte(*(s - 1))); errmsg = errbuf; } else { - errmsg = (char_u *)""; + errmsg = ""; } break; } @@ -2723,20 +2723,20 @@ ambw_end: s++; } else if (*s) { if (errbuf != NULL) { - errmsg = (char_u *)N_("E527: Missing comma"); + errmsg = N_("E527: Missing comma"); } else { - errmsg = (char_u *)""; + errmsg = ""; } break; } } if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0) { - errmsg = (char_u *)N_("E528: Must specify a ' value"); + errmsg = N_("E528: Must specify a ' value"); } } else if (gvarp == &p_sbr) { // 'showbreak' for (s = *varp; *s; ) { if (ptr2cells(s) != 1) { - errmsg = (char_u *)N_("E595: 'showbreak' contains unprintable or wide character"); + errmsg = N_("E595: 'showbreak' contains unprintable or wide character"); } MB_PTR_ADV(s); } @@ -2905,7 +2905,7 @@ ambw_end: *--s); errmsg = errbuf; } else { - errmsg = (char_u *)""; + errmsg = ""; } break; } @@ -2932,7 +2932,7 @@ ambw_end: // When changing the 'signcolumn' to or from 'number', recompute the // width of the number column if 'number' or 'relativenumber' is set. if (((*oldval == 'n' && *(oldval + 1) == 'u') - || (*curwin->w_p_scl == 'n' && *(curwin->w_p_scl + 1) =='u')) + || (*curwin->w_p_scl == 'n' && *(curwin->w_p_scl + 1) == 'u')) && (curwin->w_p_nu || curwin->w_p_rnu)) { curwin->w_nrwidth_line_count = 0; } @@ -3009,7 +3009,7 @@ ambw_end: } else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) { // 'foldmarker' p = vim_strchr(*varp, ','); if (p == NULL) { - errmsg = (char_u *)N_("E536: comma required"); + errmsg = N_("E536: comma required"); } else if (p == *varp || p[1] == NUL) { errmsg = e_invarg; } else if (foldmethodIsMarker(curwin)) { @@ -3017,7 +3017,7 @@ ambw_end: } } else if (gvarp == &p_cms) { // 'commentstring' if (**varp != NUL && strstr((char *)(*varp), "%s") == NULL) { - errmsg = (char_u *)N_("E537: 'commentstring' must be empty or contain %s"); + errmsg = N_("E537: 'commentstring' must be empty or contain %s"); } } else if (varp == &p_fdo) { // 'foldopen' if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true) != OK) { @@ -3342,7 +3342,7 @@ int check_signcolumn(char_u *val) /// Handle setting 'colorcolumn' or 'textwidth' in window "wp". /// /// @return error message, NULL if it's OK. -char_u *check_colorcolumn(win_T *wp) +char *check_colorcolumn(win_T *wp) { char_u *s; int col; @@ -3427,7 +3427,7 @@ void check_blending(win_T *wp) /// /// @param varp either &curwin->w_p_lcs or &curwin->w_p_fcs /// @return error message, NULL if it's OK. -static char_u *set_chars_option(win_T *wp, char_u **varp, bool set) +static char *set_chars_option(win_T *wp, char_u **varp, bool set) { int round, i, len, entries; char_u *p, *s; @@ -3614,10 +3614,10 @@ static char_u *set_chars_option(win_T *wp, char_u **varp, bool set) /// Check validity of options with the 'statusline' format. /// Return error message or NULL. -char_u *check_stl_option(char_u *s) +char *check_stl_option(char_u *s) { int groupdepth = 0; - static char_u errbuf[80]; + static char errbuf[80]; while (*s) { // Check for valid keys after % sequences @@ -3668,19 +3668,19 @@ char_u *check_stl_option(char_u *s) s++; } if (*s != '}') { - return (char_u *)N_("E540: Unclosed expression sequence"); + return N_("E540: Unclosed expression sequence"); } } } if (groupdepth != 0) { - return (char_u *)N_("E542: unbalanced groups"); + return N_("E542: unbalanced groups"); } return NULL; } -static char_u *did_set_spell_option(bool is_spellfile) +static char *did_set_spell_option(bool is_spellfile) { - char_u *errmsg = NULL; + char *errmsg = NULL; if (is_spellfile) { int l = (int)STRLEN(curwin->w_s->b_p_spf); @@ -3704,7 +3704,7 @@ static char_u *did_set_spell_option(bool is_spellfile) /// Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'. /// Return error message when failed, NULL when OK. -static char_u *compile_cap_prog(synblock_T *synblock) +static char *compile_cap_prog(synblock_T *synblock) FUNC_ATTR_NONNULL_ALL { regprog_T *rp = synblock->b_cap_prog; @@ -3831,7 +3831,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va // Ensure that options set to p_force_on cannot be disabled. if ((int *)varp == &p_force_on && p_force_on == false) { p_force_on = true; - return (char *)e_unsupportedoption; + return e_unsupportedoption; // Ensure that options set to p_force_off cannot be enabled. } else if ((int *)varp == &p_force_off && p_force_off == true) { p_force_off = false; @@ -4017,9 +4017,9 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va } } else if ((int *)varp == &curwin->w_p_spell) { // 'spell' if (curwin->w_p_spell) { - char_u *errmsg = did_set_spelllang(curwin); + char *errmsg = did_set_spelllang(curwin); if (errmsg != NULL) { - EMSG(_(errmsg)); + emsg(_(errmsg)); } } } @@ -4136,10 +4136,10 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va /// @param[in] opt_flags OPT_LOCAL, OPT_GLOBAL or OPT_MODELINE. /// /// @return NULL on success, error message on error. -static char *set_num_option(int opt_idx, char_u *varp, long value, char_u *errbuf, size_t errbuflen, +static char *set_num_option(int opt_idx, char_u *varp, long value, char *errbuf, size_t errbuflen, int opt_flags) { - char_u *errmsg = NULL; + char *errmsg = NULL; long old_value = *(long *)varp; long old_Rows = Rows; // remember old Rows long *pp = (long *)varp; @@ -4147,12 +4147,12 @@ static char *set_num_option(int opt_idx, char_u *varp, long value, char_u *errbu // Disallow changing some options from secure mode. if ((secure || sandbox != 0) && (options[opt_idx].flags & P_SECURE)) { - return (char *)e_secure; + return e_secure; } // Many number options assume their value is in the signed int range. if (value < INT_MIN || value > INT_MAX) { - return (char *)e_invarg; + return e_invarg; } // Options that need some validation. @@ -4921,12 +4921,12 @@ char *set_option_value(const char *const name, const long number, const char *co opt_idx = findoption(name); if (opt_idx < 0) { - EMSG2(_("E355: Unknown option: %s"), name); + semsg(_("E355: Unknown option: %s"), name); } else { uint32_t flags = options[opt_idx].flags; // Disallow changing some options in the sandbox if (sandbox > 0 && (flags & P_SECURE)) { - EMSG(_(e_sandbox)); + emsg(_(e_sandbox)); return NULL; } if (flags & P_STRING) { @@ -4948,7 +4948,7 @@ char *set_option_value(const char *const name, const long number, const char *co // There's another character after zeros or the string // is empty. In both cases, we are trying to set a // num option using a string. - EMSG3(_("E521: Number required: &%s = '%s'"), + semsg(_("E521: Number required: &%s = '%s'"), name, string); return NULL; // do nothing as we hit an error } @@ -5016,11 +5016,11 @@ static void showoptions(int all, int opt_flags) // Highlight title if (opt_flags & OPT_GLOBAL) { - MSG_PUTS_TITLE(_("\n--- Global option values ---")); + msg_puts_title(_("\n--- Global option values ---")); } else if (opt_flags & OPT_LOCAL) { - MSG_PUTS_TITLE(_("\n--- Local option values ---")); + msg_puts_title(_("\n--- Local option values ---")); } else { - MSG_PUTS_TITLE(_("\n--- Options ---")); + msg_puts_title(_("\n--- Options ---")); } // Do the loop two times: @@ -5151,13 +5151,13 @@ static void showoneopt(vimoption_T *p, int opt_flags) // for 'modified' we also need to check if 'ff' or 'fenc' changed. if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed ? !curbufIsChanged() : !*(int *)varp)) { - MSG_PUTS("no"); + msg_puts("no"); } else if ((p->flags & P_BOOL) && *(int *)varp < 0) { - MSG_PUTS("--"); + msg_puts("--"); } else { - MSG_PUTS(" "); + msg_puts(" "); } - MSG_PUTS(p->fullname); + msg_puts(p->fullname); if (!(p->flags & P_BOOL)) { msg_putchar('='); // put value string in NameBuff @@ -5487,7 +5487,7 @@ void unset_global_local_option(char *name, void *from) int opt_idx = findoption(name); if (opt_idx < 0) { - EMSG2(_("E355: Unknown option: %s"), name); + semsg(_("E355: Unknown option: %s"), name); return; } p = &(options[opt_idx]); @@ -5935,7 +5935,7 @@ static char_u *get_varp(vimoption_T *p) case PV_WINBL: return (char_u *)&(curwin->w_p_winbl); default: - IEMSG(_("E356: get_varp ERROR")); + iemsg(_("E356: get_varp ERROR")); } // always return a valid pointer to avoid a crash! return (char_u *)&(curbuf->b_p_wm); @@ -6808,7 +6808,7 @@ static void langmap_set(void) } } if (to == NUL) { - EMSG2(_("E357: 'langmap': Matching character missing for %s"), + semsg(_("E357: 'langmap': Matching character missing for %s"), transchar(from)); return; } @@ -6828,7 +6828,7 @@ static void langmap_set(void) p = p2; if (p[0] != NUL) { if (p[0] != ',') { - EMSG2(_("E358: 'langmap': Extra characters after semicolon: %s"), + semsg(_("E358: 'langmap': Extra characters after semicolon: %s"), p); return; } @@ -7305,9 +7305,9 @@ bool tabstop_set(char_u *var, long **array) if (strtol((char *)cp, (char **)&end, 10) <= 0) { if (cp != end) { - EMSG(_(e_positive)); + emsg(_(e_positive)); } else { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } return false; } @@ -7320,7 +7320,7 @@ bool tabstop_set(char_u *var, long **array) valcount++; continue; } - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return false; } @@ -7330,7 +7330,7 @@ bool tabstop_set(char_u *var, long **array) t = 1; for (cp = var; *cp != NUL;) { (*array)[t++] = atoi((char *)cp); - while (*cp != NUL && *cp != ',') { + while (*cp != NUL && *cp != ',') { cp++; } if (*cp != NUL) { diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index 441d29cd9f..6edc15be57 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -836,7 +836,7 @@ enum { BV_WM, BV_VSTS, BV_VTS, - BV_COUNT // must be the last one + BV_COUNT, // must be the last one }; /* @@ -889,7 +889,7 @@ enum { WV_FCS, WV_LCS, WV_WINBL, - WV_COUNT // must be the last one + WV_COUNT, // must be the last one }; // Value for b_p_ul indicating the global value must be used. diff --git a/src/nvim/os/dl.c b/src/nvim/os/dl.c index b2e3994d10..7d095d31e3 100644 --- a/src/nvim/os/dl.c +++ b/src/nvim/os/dl.c @@ -49,7 +49,7 @@ bool os_libcall(const char *libname, const char *funcname, const char *argv, int // open the dynamic loadable library if (uv_dlopen(libname, &lib)) { - EMSG2(_("dlerror = \"%s\""), uv_dlerror(&lib)); + semsg(_("dlerror = \"%s\""), uv_dlerror(&lib)); uv_dlclose(&lib); return false; } @@ -57,7 +57,7 @@ bool os_libcall(const char *libname, const char *funcname, const char *argv, int // find and load the requested function in the library gen_fn fn; if (uv_dlsym(&lib, funcname, (void **)&fn)) { - EMSG2(_("dlerror = \"%s\""), uv_dlerror(&lib)); + semsg(_("dlerror = \"%s\""), uv_dlerror(&lib)); uv_dlclose(&lib); return false; } diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index 0f363ecfc3..727b10f7a7 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -250,7 +250,7 @@ void os_copy_fullenv(char **env, size_t env_size) char *utf8_str; int conversion_result = utf16_to_utf8(p, -1, &utf8_str); if (conversion_result != 0) { - EMSG2("utf16_to_utf8 failed: %d", conversion_result); + semsg("utf16_to_utf8 failed: %d", conversion_result); break; } p += l + 1; @@ -297,7 +297,7 @@ char *os_getenvname_at_index(size_t index) char *utf8_str; int conversion_result = utf16_to_utf8(p, -1, &utf8_str); if (conversion_result != 0) { - EMSG2("utf16_to_utf8 failed: %d", conversion_result); + semsg("utf16_to_utf8 failed: %d", conversion_result); break; } @@ -375,7 +375,7 @@ void os_get_hostname(char *hostname, size_t size) if (GetComputerNameW(host_utf16, &host_wsize) == 0) { *hostname = '\0'; DWORD err = GetLastError(); - EMSG2("GetComputerNameW failed: %d", err); + semsg("GetComputerNameW failed: %d", err); return; } host_utf16[host_wsize] = '\0'; @@ -383,13 +383,13 @@ void os_get_hostname(char *hostname, size_t size) char *host_utf8; int conversion_result = utf16_to_utf8(host_utf16, -1, &host_utf8); if (conversion_result != 0) { - EMSG2("utf16_to_utf8 failed: %d", conversion_result); + semsg("utf16_to_utf8 failed: %d", conversion_result); return; } xstrlcpy(hostname, host_utf8, size); xfree(host_utf8); #else - EMSG("os_get_hostname failed: missing uname()"); + emsg("os_get_hostname failed: missing uname()"); *hostname = '\0'; #endif } @@ -481,7 +481,7 @@ void init_homedir(void) var = (char *)IObuff; } if (os_chdir(os_buf) != 0) { - EMSG(_(e_prev_dir)); + emsg(_(e_prev_dir)); } } } diff --git a/src/nvim/os/fileio.c b/src/nvim/os/fileio.c index 1ae6ca4244..b1710737d0 100644 --- a/src/nvim/os/fileio.c +++ b/src/nvim/os/fileio.c @@ -426,6 +426,6 @@ int msgpack_file_write(void *data, const char *buf, size_t len) /// @return -1 (error return for msgpack_packer callbacks). int msgpack_file_write_error(const int error) { - emsgf(_("E5420: Failed to write to file: %s"), os_strerror(error)); + semsg(_("E5420: Failed to write to file: %s"), os_strerror(error)); return -1; } diff --git a/src/nvim/os/fileio.h b/src/nvim/os/fileio.h index 7c53cd4f07..426dc422c2 100644 --- a/src/nvim/os/fileio.h +++ b/src/nvim/os/fileio.h @@ -68,7 +68,7 @@ enum { /// Read or write buffer size /// /// Currently equal to (IOSIZE - 1), but they do not need to be connected. - kRWBufferSize = 1024 + kRWBufferSize = 1024, }; #ifdef INCLUDE_GENERATED_DECLARATIONS diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c index 9675cfbb0f..3ff13c2b3f 100644 --- a/src/nvim/os/fs.c +++ b/src/nvim/os/fs.c @@ -1212,7 +1212,7 @@ char *os_resolve_shortcut(const char *fname) wchar_t *p; const int r = utf8_to_utf16(fname, -1, &p); if (r != 0) { - EMSG2("utf8_to_utf16 failed: %d", r); + semsg("utf8_to_utf16 failed: %d", r); } else if (p != NULL) { // Get a pointer to the IPersistFile interface. hr = pslw->lpVtbl->QueryInterface(pslw, &IID_IPersistFile, (void **)&ppf); @@ -1239,7 +1239,7 @@ char *os_resolve_shortcut(const char *fname) if (hr == S_OK && wsz[0] != NUL) { const int r2 = utf16_to_utf8(wsz, -1, &rfname); if (r2 != 0) { - EMSG2("utf16_to_utf8 failed: %d", r2); + semsg("utf16_to_utf8 failed: %d", r2); } } @@ -1274,7 +1274,7 @@ bool os_is_reparse_point_include(const char *path) const int r = utf8_to_utf16(path, -1, &utf16_path); if (r != 0) { - EMSG2("utf8_to_utf16 failed: %d", r); + semsg("utf8_to_utf16 failed: %d", r); return false; } diff --git a/src/nvim/os/input.c b/src/nvim/os/input.c index 4c6e9ee4d3..5b231f205b 100644 --- a/src/nvim/os/input.c +++ b/src/nvim/os/input.c @@ -30,7 +30,7 @@ typedef enum { kInputNone, kInputAvail, - kInputEof + kInputEof, } InbufPollResult; static Stream read_stream = { .closed = true }; // Input before UI starts. @@ -401,7 +401,7 @@ static InbufPollResult inbuf_poll(int ms, MultiQueue *events) prof_inchar_enter(); } - if ((ms == - 1 || ms > 0) && events != main_loop.events && !input_eof) { + if ((ms == -1 || ms > 0) && events != main_loop.events && !input_eof) { // The pending input provoked a blocking wait. Do special events now. #6247 blocking = true; multiqueue_process_events(ch_before_blocking_events); diff --git a/src/nvim/os/pty_conpty_win.c b/src/nvim/os/pty_conpty_win.c index 0625d6994e..f9478d951f 100644 --- a/src/nvim/os/pty_conpty_win.c +++ b/src/nvim/os/pty_conpty_win.c @@ -96,7 +96,7 @@ conpty_t *os_conpty_init(char **in_name, char **out_name, uint16_t width, uint16 goto failed; } assert(width <= SHRT_MAX); - assert(height <= SHRT_MAX); + assert(height <= SHRT_MAX); COORD size = { (int16_t)width, (int16_t)height }; HRESULT hr; hr = pCreatePseudoConsole(size, in_read, out_write, 0, &conpty_object->pty); @@ -107,7 +107,7 @@ conpty_t *os_conpty_init(char **in_name, char **out_name, uint16_t width, uint16 conpty_object->si_ex.StartupInfo.cb = sizeof(conpty_object->si_ex); size_t bytes_required; - InitializeProcThreadAttributeList(NULL, 1, 0, & bytes_required); + InitializeProcThreadAttributeList(NULL, 1, 0, &bytes_required); conpty_object->si_ex.lpAttributeList = (PPROC_THREAD_ATTRIBUTE_LIST)xmalloc(bytes_required); if (!InitializeProcThreadAttributeList(conpty_object->si_ex.lpAttributeList, diff --git a/src/nvim/os/pty_process_win.h b/src/nvim/os/pty_process_win.h index 3f6cc58e3e..d1737fd63a 100644 --- a/src/nvim/os/pty_process_win.h +++ b/src/nvim/os/pty_process_win.h @@ -10,7 +10,7 @@ typedef enum { kWinpty, - kConpty + kConpty, } PtyType; typedef struct pty_process { diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index 2bff65b241..6ef0aa1091 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -159,7 +159,7 @@ int os_expand_wildcards(int num_pat, char_u **pat, int *num_file, char_u ***file // get a name for the temp file if ((tempname = vim_tempname()) == NULL) { - EMSG(_(e_notmp)); + emsg(_(e_notmp)); return FAIL; } @@ -341,7 +341,7 @@ int os_expand_wildcards(int num_pat, char_u **pat, int *num_file, char_u ***file if (!(flags & EW_SILENT)) { msg_putchar('\n'); // clear bottom line quickly cmdline_row = Rows - 1; // continue on last line - MSG(_(e_wildexpand)); + msg(_(e_wildexpand)); msg_start(); // don't overwrite this message } @@ -358,7 +358,7 @@ int os_expand_wildcards(int num_pat, char_u **pat, int *num_file, char_u ***file if (fd == NULL) { // Something went wrong, perhaps a file name with a special char. if (!(flags & EW_SILENT)) { - MSG(_(e_wildexpand)); + msg(_(e_wildexpand)); msg_start(); // don't overwrite this message } xfree(tempname); @@ -389,7 +389,7 @@ int os_expand_wildcards(int num_pat, char_u **pat, int *num_file, char_u ***file os_remove((char *)tempname); if (readlen != len) { // unexpected read error - EMSG2(_(e_notread), tempname); + semsg(_(e_notread), tempname); xfree(tempname); xfree(buffer); return FAIL; @@ -670,7 +670,7 @@ int os_call_shell(char_u *cmd, ShellOpts opts, char_u *extra_args) } if (!emsg_silent && exitcode != 0 && !(opts & kShellOptSilent)) { - MSG_PUTS(_("\nshell returned ")); + msg_puts(_("\nshell returned ")); msg_outnum(exitcode); msg_putchar('\n'); } @@ -742,9 +742,9 @@ static int do_os_system(char **argv, const char *input, size_t len, char **outpu loop_poll_events(&main_loop, 0); // Failed, probably 'shell' is not executable. if (!silent) { - MSG_PUTS(_("\nshell failed to start: ")); + msg_puts(_("\nshell failed to start: ")); msg_outtrans((char_u *)os_strerror(status)); - MSG_PUTS(": "); + msg_puts(": "); msg_outtrans((char_u *)prog); msg_putchar('\n'); } @@ -1180,7 +1180,7 @@ static void shell_write_cb(Stream *stream, void *data, int status) if (status) { // Can happen if system() tries to send input to a shell command that was // backgrounded (:call system("cat - &", "foo")). #3529 #5241 - msg_schedule_emsgf(_("E5677: Error writing input to shell-command: %s"), + msg_schedule_semsg(_("E5677: Error writing input to shell-command: %s"), uv_err_name(status)); } stream_close(stream, NULL, NULL); diff --git a/src/nvim/os/users.c b/src/nvim/os/users.c index fd7ead68da..9952e2b387 100644 --- a/src/nvim/os/users.c +++ b/src/nvim/os/users.c @@ -64,7 +64,7 @@ int os_get_usernames(garray_T *users) char *user; int conversion_result = utf16_to_utf8(uinfo[i].usri0_name, -1, &user); if (conversion_result != 0) { - EMSG2("utf16_to_utf8 failed: %d", conversion_result); + semsg("utf16_to_utf8 failed: %d", conversion_result); break; } add_user(users, user, false); diff --git a/src/nvim/path.c b/src/nvim/path.c index 5b1793b111..6f0f715a25 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -1011,8 +1011,7 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern) // /file.txt / /file.txt // c:\file.txt c:\ .\file.txt short_name = path_shorten_fname(path, curdir); - if (short_name != NULL && short_name > path + 1 - ) { + if (short_name != NULL && short_name > path + 1) { STRCPY(path, "."); add_pathsep((char *)path); STRMOVE(path + STRLEN(path), short_name); @@ -1506,8 +1505,9 @@ void simplify_filename(char_u *filename) if (vim_ispathsep(*p)) { relative = false; - do + do{ ++p; + } while (vim_ispathsep(*p)); } start = p; // remember start after "c:/" or "/" or "///" @@ -1701,7 +1701,7 @@ char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, if (file_name == NULL && (options & FNAME_MESS)) { char_u c = ptr[len]; ptr[len] = NUL; - EMSG2(_("E447: Can't find file \"%s\" in path"), ptr); + semsg(_("E447: Can't find file \"%s\" in path"), ptr); ptr[len] = c; } @@ -2081,7 +2081,7 @@ int expand_wildcards_eval(char_u **pat, int *num_file, char_u ***file, int flags int ret = FAIL; char_u *eval_pat = NULL; char_u *exp_pat = *pat; - char_u *ignored_msg; + char *ignored_msg; size_t usedlen; if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<') { @@ -2257,7 +2257,7 @@ int path_full_dir_name(char *directory, char *buffer, size_t len) if (os_chdir(old_dir) != SUCCESS) { // That shouldn't happen, since we've tested if it works. retval = FAIL; - EMSG(_(e_prev_dir)); + emsg(_(e_prev_dir)); } return retval; diff --git a/src/nvim/path.h b/src/nvim/path.h index 5d81e68caa..1006ef9ffb 100644 --- a/src/nvim/path.h +++ b/src/nvim/path.h @@ -33,7 +33,7 @@ typedef enum file_comparison { kDifferentFiles = 2, ///< Both exist and are different files. kBothFilesMissing = 4, ///< Both don't exist. kOneFileMissing = 6, ///< One of them doesn't exist. - kEqualFileNames = 7 ///< Both don't exist and file names are same. + kEqualFileNames = 7, ///< Both don't exist and file names are same. } FileComparison; #ifdef INCLUDE_GENERATED_DECLARATIONS diff --git a/src/nvim/pos.h b/src/nvim/pos.h index 2fbd049aa0..d17e27906e 100644 --- a/src/nvim/pos.h +++ b/src/nvim/pos.h @@ -14,13 +14,13 @@ typedef int colnr_T; #define PRIdCOLNR "d" /// Maximal (invalid) line number -enum { MAXLNUM = 0x7fffffff }; +enum { MAXLNUM = 0x7fffffff, }; /// Maximal column number -enum { MAXCOL = INT_MAX }; +enum { MAXCOL = INT_MAX, }; // Minimum line number -enum { MINLNUM = 1 }; +enum { MINLNUM = 1, }; // minimum column number -enum { MINCOL = 1 }; +enum { MINCOL = 1, }; /* * position in file or buffer diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 570bb5e7ae..950d187ad5 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -82,7 +82,7 @@ typedef enum { QFLT_QUICKFIX, ///< Quickfix list - global list QFLT_LOCATION, ///< Location list - per window list - QFLT_INTERNAL ///< Internal - Temporary list used by + QFLT_INTERNAL, ///< Internal - Temporary list used by // getqflist()/getloclist() } qfltype_T; @@ -322,8 +322,7 @@ int qf_init(win_T *wp, const char_u *restrict efile, char_u *restrict errorforma // Maximum number of bytes allowed per line while reading an errorfile. static const size_t LINE_MAXLEN = 4096; -static struct fmtpattern -{ +static struct fmtpattern { char_u convchar; char *pattern; } fmt_pat[FMT_PATTERNS] = @@ -346,23 +345,19 @@ static struct fmtpattern /// pattern specifier is supplied in "efmpat". The converted pattern is stored /// in "regpat". Returns a pointer to the location after the pattern. static char_u *efmpat_to_regpat(const char_u *efmpat, char_u *regpat, efm_T *efminfo, int idx, - int round, char_u *errmsg, size_t errmsglen) + int round) FUNC_ATTR_NONNULL_ALL { if (efminfo->addr[idx]) { // Each errorformat pattern can occur only once - snprintf((char *)errmsg, errmsglen, - _("E372: Too many %%%c in format string"), *efmpat); - EMSG(errmsg); + semsg(_("E372: Too many %%%c in format string"), *efmpat); return NULL; } if ((idx && idx < 6 && vim_strchr((char_u *)"DXOPQ", efminfo->prefix) != NULL) || (idx == 6 && vim_strchr((char_u *)"OPQ", efminfo->prefix) == NULL)) { - snprintf((char *)errmsg, errmsglen, - _("E373: Unexpected %%%c in format string"), *efmpat); - EMSG(errmsg); + semsg(_("E373: Unexpected %%%c in format string"), *efmpat); return NULL; } efminfo->addr[idx] = (char_u)++ round; @@ -406,8 +401,7 @@ static char_u *efmpat_to_regpat(const char_u *efmpat, char_u *regpat, efm_T *efm /// Convert a scanf like format in 'errorformat' to a regular expression. /// Returns a pointer to the location after the pattern. -static char_u *scanf_fmt_to_regpat(const char_u **pefmp, const char_u *efm, int len, char_u *regpat, - char_u *errmsg, size_t errmsglen) +static char_u *scanf_fmt_to_regpat(const char_u **pefmp, const char_u *efm, int len, char_u *regpat) FUNC_ATTR_NONNULL_ALL { const char_u *efmp = *pefmp; @@ -422,7 +416,7 @@ static char_u *scanf_fmt_to_regpat(const char_u **pefmp, const char_u *efm, int while (efmp < efm + len && (*regpat++ = *++efmp) != ']') { } if (efmp == efm + len) { - EMSG(_("E374: Missing ] in format string")); + emsg(_("E374: Missing ] in format string")); return NULL; } } @@ -432,10 +426,7 @@ static char_u *scanf_fmt_to_regpat(const char_u **pefmp, const char_u *efm, int *regpat++ = '\\'; *regpat++ = '+'; } else { - // TODO(vim): scanf()-like: %*ud, %*3c, %*f, ... ? - snprintf((char *)errmsg, errmsglen, - _("E375: Unsupported %%%c in format string"), *efmp); - EMSG(errmsg); + semsg(_("E375: Unsupported %%%c in format string"), *efmp); return NULL; } @@ -445,8 +436,7 @@ static char_u *scanf_fmt_to_regpat(const char_u **pefmp, const char_u *efm, int } /// Analyze/parse an errorformat prefix. -static const char_u *efm_analyze_prefix(const char_u *efmp, efm_T *efminfo, char_u *errmsg, - size_t errmsglen) +static const char_u *efm_analyze_prefix(const char_u *efmp, efm_T *efminfo) FUNC_ATTR_NONNULL_ALL { if (vim_strchr((char_u *)"+-", *efmp) != NULL) { @@ -455,9 +445,7 @@ static const char_u *efm_analyze_prefix(const char_u *efmp, efm_T *efminfo, char if (vim_strchr((char_u *)"DXAEWINCZGOPQ", *efmp) != NULL) { efminfo->prefix = *efmp; } else { - snprintf((char *)errmsg, errmsglen, - _("E376: Invalid %%%c in format string prefix"), *efmp); - EMSG(errmsg); + semsg(_("E376: Invalid %%%c in format string prefix"), *efmp); return NULL; } @@ -466,8 +454,7 @@ static const char_u *efm_analyze_prefix(const char_u *efmp, efm_T *efminfo, char // Converts a 'errorformat' string to regular expression pattern -static int efm_to_regpat(const char_u *efm, int len, efm_T *fmt_ptr, char_u *regpat, char_u *errmsg, - size_t errmsglen) +static int efm_to_regpat(const char_u *efm, int len, efm_T *fmt_ptr, char_u *regpat) FUNC_ATTR_NONNULL_ALL { // Build regexp pattern from current 'errorformat' option @@ -484,15 +471,14 @@ static int efm_to_regpat(const char_u *efm, int len, efm_T *fmt_ptr, char_u *reg } } if (idx < FMT_PATTERNS) { - ptr = efmpat_to_regpat(efmp, ptr, fmt_ptr, idx, round, errmsg, - errmsglen); + ptr = efmpat_to_regpat(efmp, ptr, fmt_ptr, idx, round); if (ptr == NULL) { return FAIL; } round++; } else if (*efmp == '*') { efmp++; - ptr = scanf_fmt_to_regpat(&efmp, efm, len, ptr, errmsg, errmsglen); + ptr = scanf_fmt_to_regpat(&efmp, efm, len, ptr); if (ptr == NULL) { return FAIL; } @@ -505,14 +491,12 @@ static int efm_to_regpat(const char_u *efm, int len, efm_T *fmt_ptr, char_u *reg } else if (efmp == efm + 1) { // analyse prefix // prefix is allowed only at the beginning of the errorformat // option part - efmp = efm_analyze_prefix(efmp, fmt_ptr, errmsg, errmsglen); + efmp = efm_analyze_prefix(efmp, fmt_ptr); if (efmp == NULL) { return FAIL; } } else { - snprintf((char *)errmsg, CMDBUFFSIZE + 1, - _("E377: Invalid %%%c in format string"), *efmp); - EMSG(errmsg); + semsg(_("E377: Invalid %%%c in format string"), *efmp); return FAIL; } } else { // copy normal character @@ -591,9 +575,6 @@ static efm_T *parse_efm_option(char_u *efm) efm_T *fmt_last = NULL; int len; - size_t errmsglen = CMDBUFFSIZE + 1; - char_u *errmsg = xmalloc(errmsglen); - // Get some space to modify the format string into. size_t sz = efm_regpat_bufsz(efm); char_u *fmtstr = xmalloc(sz); @@ -611,7 +592,7 @@ static efm_T *parse_efm_option(char_u *efm) // Isolate one part in the 'errorformat' option len = efm_option_part_len(efm); - if (efm_to_regpat(efm, len, fmt_ptr, fmtstr, errmsg, errmsglen) == FAIL) { + if (efm_to_regpat(efm, len, fmt_ptr, fmtstr) == FAIL) { goto parse_efm_error; } if ((fmt_ptr->prog = vim_regcomp(fmtstr, RE_MAGIC + RE_STRING)) == NULL) { @@ -622,7 +603,7 @@ static efm_T *parse_efm_option(char_u *efm) } if (fmt_first == NULL) { // nothing found - EMSG(_("E378: 'errorformat' contains no pattern")); + emsg(_("E378: 'errorformat' contains no pattern")); } goto parse_efm_end; @@ -632,7 +613,6 @@ parse_efm_error: parse_efm_end: xfree(fmtstr); - xfree(errmsg); return fmt_first; } @@ -1027,7 +1007,7 @@ static int qf_setup_state(qfstate_T *pstate, char_u *restrict enc, const char_u if (efile != NULL && (pstate->fd = os_fopen((const char *)efile, "r")) == NULL) { - EMSG2(_(e_openerrf), efile); + semsg(_(e_openerrf), efile); return FAIL; } @@ -1171,7 +1151,7 @@ static int qf_init_ext(qf_info_T *qi, int qf_idx, const char_u *restrict efile, retval = qfl->qf_count; goto qf_init_end; } - EMSG(_(e_readerrf)); + emsg(_(e_readerrf)); error2: if (!adding) { // Error when creating a new list. Free the new list @@ -1564,7 +1544,7 @@ static int qf_parse_dir_pfx(int idx, qffields_T *fields, qf_list_T *qfl) { if (idx == 'D') { // enter directory if (*fields->namebuf == NUL) { - EMSG(_("E379: Missing or empty directory name")); + emsg(_("E379: Missing or empty directory name")); return QF_FAIL; } qfl->qf_directory = qf_push_dir(fields->namebuf, &qfl->qf_dir_stack, false); @@ -1748,7 +1728,7 @@ static void decr_quickfix_busy(void) } #ifdef ABORT_ON_INTERNAL_ERROR if (quickfix_busy < 0) { - EMSG("quickfix_busy has become negative"); + emsg("quickfix_busy has become negative"); abort(); } #endif @@ -1758,7 +1738,7 @@ static void decr_quickfix_busy(void) void check_quickfix_busy(void) { if (quickfix_busy != 0) { - EMSGN("quickfix_busy not zero on exit: %" PRId64, (int64_t)quickfix_busy); + semsg("quickfix_busy not zero on exit: %" PRId64, (int64_t)quickfix_busy); # ifdef ABORT_ON_INTERNAL_ERROR abort(); # endif @@ -1894,7 +1874,7 @@ static qf_info_T *qf_cmd_get_stack(exarg_T *eap, int print_emsg) qi = GET_LOC_LIST(curwin); if (qi == NULL) { if (print_emsg) { - EMSG(_(e_loclist)); + emsg(_(e_loclist)); } return NULL; } @@ -2361,7 +2341,7 @@ static qfline_T *get_nth_valid_entry(qf_list_T *qfl, int errornr, int dir, int * qf_ptr = prev_qf_ptr; qf_idx = prev_index; if (err != NULL) { - EMSG(_(err)); + emsg(_(err)); return NULL; } break; @@ -2379,7 +2359,7 @@ static qfline_T *get_nth_valid_entry(qf_list_T *qfl, int errornr, int dir, int * static qfline_T *get_nth_entry(qf_list_T *qfl, int errornr, int *new_qfidx) { qfline_T *qf_ptr = qfl->qf_ptr; - int qf_idx = qfl->qf_index;; + int qf_idx = qfl->qf_index; // New error number is less than the current error number while (errornr < qf_idx && qf_idx > 1 && qf_ptr->qf_prev != NULL) { @@ -2722,13 +2702,13 @@ static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, win // If a location list, check whether the associated window is still // present. if (qfl_type == QFLT_LOCATION && !win_valid_any_tab(oldwin)) { - EMSG(_("E924: Current window was closed")); + emsg(_("E924: Current window was closed")); *opened_window = false; return NOTDONE; } if (qfl_type == QFLT_QUICKFIX && !qflist_valid(NULL, save_qfid)) { - EMSG(_(e_current_quickfix_list_was_changed)); + emsg(_(e_current_quickfix_list_was_changed)); return NOTDONE; } @@ -2736,9 +2716,9 @@ static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, win || old_changetick != qfl->qf_changedtick || !is_qf_entry_present(qfl, qf_ptr)) { if (qfl_type == QFLT_QUICKFIX) { - EMSG(_(e_current_quickfix_list_was_changed)); + emsg(_(e_current_quickfix_list_was_changed)); } else { - EMSG(_(e_current_location_list_was_changed)); + emsg(_(e_current_location_list_was_changed)); } return NOTDONE; } @@ -2810,7 +2790,7 @@ static void qf_jump_print_msg(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, buf msg_scroll = false; } msg_ext_set_kind("quickfix"); - msg_attr_keep(IObuff, 0, true, false); + msg_attr_keep((char *)IObuff, 0, true, false); msg_scroll = (int)i; } @@ -2837,9 +2817,9 @@ static int qf_jump_open_window(qf_info_T *qi, qfline_T *qf_ptr, bool newwin, int || old_changetick != qfl->qf_changedtick || !is_qf_entry_present(qfl, qf_ptr)) { if (qfl_type == QFLT_QUICKFIX) { - EMSG(_(e_current_quickfix_list_was_changed)); + emsg(_(e_current_quickfix_list_was_changed)); } else { - EMSG(_(e_current_location_list_was_changed)); + emsg(_(e_current_location_list_was_changed)); } return FAIL; } @@ -2862,9 +2842,9 @@ static int qf_jump_open_window(qf_info_T *qi, qfline_T *qf_ptr, bool newwin, int || old_changetick != qfl->qf_changedtick || !is_qf_entry_present(qfl, qf_ptr)) { if (qfl_type == QFLT_QUICKFIX) { - EMSG(_(e_current_quickfix_list_was_changed)); + emsg(_(e_current_quickfix_list_was_changed)); } else { - EMSG(_(e_current_location_list_was_changed)); + emsg(_(e_current_location_list_was_changed)); } return FAIL; } @@ -2951,7 +2931,7 @@ static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, boo } if (qf_stack_empty(qi) || qf_list_empty(qf_get_curlist(qi))) { - EMSG(_(e_quickfix)); + emsg(_(e_quickfix)); return; } @@ -3124,7 +3104,7 @@ void qf_list(exarg_T *eap) } if (qf_stack_empty(qi) || qf_list_empty(qf_get_curlist(qi))) { - EMSG(_(e_quickfix)); + emsg(_(e_quickfix)); return; } @@ -3134,7 +3114,7 @@ void qf_list(exarg_T *eap) plus = true; } if (!get_list_range(&arg, &idx1, &idx2) || *arg != NUL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); return; } qfl = qf_get_curlist(qi); @@ -3254,7 +3234,7 @@ static void qf_msg(qf_info_T *qi, int which, char *lead) xstrlcat((char *)buf, title, IOSIZE); } trunc_string(buf, buf, Columns - 1, IOSIZE); - msg(buf); + msg((char *)buf); } /// ":colder [count]": Up in the quickfix stack. @@ -3279,13 +3259,13 @@ void qf_age(exarg_T *eap) while (count--) { if (eap->cmdidx == CMD_colder || eap->cmdidx == CMD_lolder) { if (qi->qf_curlist == 0) { - EMSG(_("E380: At bottom of quickfix stack")); + emsg(_("E380: At bottom of quickfix stack")); break; } --qi->qf_curlist; } else { if (qi->qf_curlist >= qi->qf_listcount - 1) { - EMSG(_("E381: At top of quickfix stack")); + emsg(_("E381: At top of quickfix stack")); break; } ++qi->qf_curlist; @@ -3303,7 +3283,7 @@ void qf_history(exarg_T *eap) if (eap->addr_count > 0) { if (qi == NULL) { - EMSG(_(e_loclist)); + emsg(_(e_loclist)); return; } @@ -3313,14 +3293,14 @@ void qf_history(exarg_T *eap) qf_msg(qi, qi->qf_curlist, ""); qf_update_buffer(qi, NULL); } else { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); } return; } if (qf_stack_empty(qi)) { - MSG(_("No entries")); + msg(_("No entries")); } else { for (i = 0; i < qi->qf_listcount; i++) { qf_msg(qi, i, i == qi->qf_curlist ? "> " : " "); @@ -3489,7 +3469,7 @@ void qf_view_result(bool split) qi = GET_LOC_LIST(curwin); } if (qf_list_empty(qf_get_curlist(qi))) { - EMSG(_(e_quickfix)); + emsg(_(e_quickfix)); return; } @@ -4293,7 +4273,7 @@ static char *make_get_fullcmd(const char_u *makecmd, const char_u *fname) msg_didout = false; } msg_start(); - MSG_PUTS(":!"); + msg_puts(":!"); msg_outtrans((char_u *)cmd); // show what we are doing return cmd; @@ -4384,7 +4364,7 @@ static char_u *get_mef_name(void) if (*p_mef == NUL) { name = vim_tempname(); if (name == NULL) { - EMSG(_(e_notmp)); + emsg(_(e_notmp)); } return name; } @@ -4958,7 +4938,7 @@ void ex_cbelow(exarg_T *eap) int buf_has_flag; if (eap->addr_count > 0 && eap->line2 <= 0) { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); return; } @@ -4970,7 +4950,7 @@ void ex_cbelow(exarg_T *eap) buf_has_flag = BUF_HAS_LL_ENTRY; } if (!(curbuf->b_has_qf_entry & buf_has_flag)) { - EMSG(_(e_quickfix)); + emsg(_(e_quickfix)); return; } @@ -4981,7 +4961,7 @@ void ex_cbelow(exarg_T *eap) qfl = qf_get_curlist(qi); // check if the list has valid errors if (!qf_list_has_valid_entries(qfl)) { - EMSG(_(e_quickfix)); + emsg(_(e_quickfix)); return; } @@ -5012,7 +4992,7 @@ void ex_cbelow(exarg_T *eap) if (errornr > 0) { qf_jump(qi, 0, errornr, false); } else { - EMSG(_(e_no_more_items)); + emsg(_(e_no_more_items)); } } @@ -5136,7 +5116,7 @@ static void vgr_init_regmatch(regmmatch_T *regmatch, char_u *s) if (s == NULL || *s == NUL) { // Pattern is empty, use last search pattern. if (last_search_pat() == NULL) { - EMSG(_(e_noprevre)); + emsg(_(e_noprevre)); return; } regmatch->regprog = vim_regcomp(last_search_pat(), RE_MAGIC); @@ -5196,7 +5176,7 @@ static bool vgr_qflist_valid(win_T *wp, qf_info_T *qi, unsigned qfid, char_u *ti if (!qflist_valid(wp, qfid)) { if (wp != NULL) { // An autocmd has freed the location list - EMSG(_(e_current_location_list_was_changed)); + emsg(_(e_current_location_list_was_changed)); return false; } else { // Quickfix list is not found, create a new one. @@ -5355,7 +5335,7 @@ void ex_vimgrep(exarg_T *eap) char_u *title = vim_strsave(qf_cmdtitle(*eap->cmdlinep)); p = skip_vimgrep_pat(eap->arg, &s, &flags); if (p == NULL) { - EMSG(_(e_invalpat)); + emsg(_(e_invalpat)); goto theend; } @@ -5366,7 +5346,7 @@ void ex_vimgrep(exarg_T *eap) p = skipwhite(p); if (*p == NUL) { - EMSG(_("E683: File name missing or invalid pattern")); + emsg(_("E683: File name missing or invalid pattern")); goto theend; } @@ -5382,7 +5362,7 @@ void ex_vimgrep(exarg_T *eap) goto theend; } if (fcount == 0) { - EMSG(_(e_nomatch)); + emsg(_(e_nomatch)); goto theend; } @@ -5528,7 +5508,7 @@ void ex_vimgrep(exarg_T *eap) target_dir); } } else { - EMSG2(_(e_nomatch2), s); + semsg(_(e_nomatch2), s); } decr_quickfix_busy(); @@ -6252,7 +6232,7 @@ static int qf_add_entry_from_dict(qf_list_T *qfl, const dict_T *d, bool first_en if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) { if (!did_bufnr_emsg) { did_bufnr_emsg = true; - EMSGN(_("E92: Buffer %" PRId64 " not found"), bufnum); + semsg(_("E92: Buffer %" PRId64 " not found"), (int64_t)bufnum); } valid = false; bufnum = 0; @@ -6660,7 +6640,7 @@ int set_errorlist(win_T *wp, list_T *list, int action, char_u *title, dict_T *wh // A dict argument cannot be specified with a non-empty list argument if (list != NULL && tv_list_len(list) != 0 && what != NULL) { - EMSG2(_(e_invarg2), _("cannot have both a list and a \"what\" argument")); + semsg(_(e_invarg2), _("cannot have both a list and a \"what\" argument")); return FAIL; } @@ -6761,12 +6741,12 @@ static int cbuffer_process_args(exarg_T *eap, buf_T **bufp, linenr_T *line1, lin } if (buf == NULL) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return FAIL; } if (buf->b_ml.ml_mfp == NULL) { - EMSG(_("E681: Buffer is not loaded")); + emsg(_("E681: Buffer is not loaded")); return FAIL; } @@ -6777,7 +6757,7 @@ static int cbuffer_process_args(exarg_T *eap, buf_T **bufp, linenr_T *line1, lin if (eap->line1 < 1 || eap->line1 > buf->b_ml.ml_line_count || eap->line2 < 1 || eap->line2 > buf->b_ml.ml_line_count) { - EMSG(_(e_invrange)); + emsg(_(e_invrange)); return FAIL; } @@ -6937,7 +6917,7 @@ void ex_cexpr(exarg_T *eap) } decr_quickfix_busy(); } else { - EMSG(_("E777: String or List expected")); + emsg(_("E777: String or List expected")); } cleanup: tv_clear(&tv); @@ -7150,7 +7130,7 @@ void ex_helpgrep(exarg_T *eap) if (!qf_list_empty(qf_get_curlist(qi))) { qf_jump(qi, 0, 0, false); } else { - EMSG2(_(e_nomatch2), eap->arg); + semsg(_(e_nomatch2), eap->arg); } decr_quickfix_busy(); @@ -7168,4 +7148,3 @@ void ex_helpgrep(exarg_T *eap) } } - diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index d39d6c69f1..7bc1af9004 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -463,13 +463,13 @@ static int toggle_Magic(int x) // Used for an error (down from) vim_regcomp(): give the error message, set // rc_did_emsg and return NULL -#define EMSG_RET_NULL(m) return (EMSG(m), rc_did_emsg = true, (void *)NULL) -#define IEMSG_RET_NULL(m) return (IEMSG(m), rc_did_emsg = true, (void *)NULL) -#define EMSG_RET_FAIL(m) return (EMSG(m), rc_did_emsg = true, FAIL) +#define EMSG_RET_NULL(m) return (emsg(m), rc_did_emsg = true, (void *)NULL) +#define IEMSG_RET_NULL(m) return (iemsg(m), rc_did_emsg = true, (void *)NULL) +#define EMSG_RET_FAIL(m) return (emsg(m), rc_did_emsg = true, FAIL) #define EMSG2_RET_NULL(m, c) \ - return (EMSG2((m), (c) ? "" : "\\"), rc_did_emsg = true, (void *)NULL) + return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, (void *)NULL) #define EMSG2_RET_FAIL(m, c) \ - return (EMSG2((m), (c) ? "" : "\\"), rc_did_emsg = true, FAIL) + return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, FAIL) #define EMSG_ONE_RET_NULL EMSG2_RET_NULL(_( \ "E369: invalid item in %s%%[]"), reg_magic == MAGIC_ALL) @@ -1237,7 +1237,7 @@ static int seen_endbrace(int refnum) } if (*p == NUL) { - EMSG(_("E65: Illegal back reference")); + emsg(_("E65: Illegal back reference")); rc_did_emsg = true; return false; } @@ -1767,7 +1767,7 @@ static char_u *regpiece(int *flagp) else sprintf((char *)IObuff, _("E62: Nested %s%c"), reg_magic == MAGIC_ALL ? "" : "\\", no_Magic(peekchr())); - EMSG_RET_NULL(IObuff); + EMSG_RET_NULL((char *)IObuff); } return ret; @@ -1929,7 +1929,7 @@ static char_u *regatom(int *flagp) sprintf((char *)IObuff, _("E64: %s%c follows nothing"), (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL) ? "" : "\\", c); - EMSG_RET_NULL(IObuff); + EMSG_RET_NULL((char *)IObuff); /* NOTREACHED */ case Magic('~'): /* previous substitute pattern */ @@ -3153,7 +3153,7 @@ static int read_limits(long *minval, long *maxval) if (*regparse != '}') { sprintf((char *)IObuff, _("E554: Syntax error in %s{...}"), reg_magic == MAGIC_ALL ? "" : "\\"); - EMSG_RET_FAIL(IObuff); + EMSG_RET_FAIL((char *)IObuff); } /* @@ -3483,7 +3483,7 @@ static long bt_regexec_both(char_u *line, /* Be paranoid... */ if (prog == NULL || line == NULL) { - IEMSG(_(e_null)); + iemsg(_(e_null)); goto theend; } @@ -4730,7 +4730,7 @@ static bool regmatch( * follows. The code is below. Parameters are stored in * a regstar_T on the regstack. */ if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { - EMSG(_(e_maxmempat)); + emsg(_(e_maxmempat)); status = RA_FAIL; } else { ga_grow(®stack, sizeof(regstar_T)); @@ -4768,7 +4768,7 @@ static bool regmatch( case NOBEHIND: /* Need a bit of room to store extra positions. */ if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { - EMSG(_(e_maxmempat)); + emsg(_(e_maxmempat)); status = RA_FAIL; } else { ga_grow(®stack, sizeof(regbehind_T)); @@ -4816,7 +4816,7 @@ static bool regmatch( break; default: - IEMSG(_(e_re_corr)); + iemsg(_(e_re_corr)); #ifdef REGEXP_DEBUG printf("Illegal op code %d\n", op); #endif @@ -5174,7 +5174,7 @@ static bool regmatch( * We get here only if there's trouble -- normally "case END" is * the terminating point. */ - IEMSG(_(e_re_corr)); + iemsg(_(e_re_corr)); #ifdef REGEXP_DEBUG printf("Premature EOL\n"); #endif @@ -5196,7 +5196,7 @@ static regitem_T *regstack_push(regstate_T state, char_u *scan) regitem_T *rp; if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) { - EMSG(_(e_maxmempat)); + emsg(_(e_maxmempat)); return NULL; } ga_grow(®stack, sizeof(regitem_T)); @@ -5581,7 +5581,7 @@ do_class: break; default: // Oh dear. Called inappropriately. - IEMSG(_(e_re_corr)); + iemsg(_(e_re_corr)); #ifdef REGEXP_DEBUG printf("Called regrepeat with op code %d\n", OP(p)); #endif @@ -5631,7 +5631,7 @@ static int prog_magic_wrong(void) } if (UCHARAT(((bt_regprog_T *)prog)->program) != REGMAGIC) { - EMSG(_(e_re_corr)); + emsg(_(e_re_corr)); return true; } return false; @@ -6689,7 +6689,7 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest, // Be paranoid... if ((source == NULL && expr == NULL) || dest == NULL) { - EMSG(_(e_null)); + emsg(_(e_null)); return 0; } if (prog_magic_wrong()) @@ -6943,7 +6943,7 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest, } } else if (*s == NUL) { // we hit NUL. if (copy) { - IEMSG(_(e_re_damg)); + iemsg(_(e_re_damg)); } goto exit; } else { @@ -7229,7 +7229,7 @@ regprog_T *vim_regcomp(char_u *expr_arg, int re_flags) regname[newengine]); #endif } else { - EMSG(_( + emsg(_( "E864: \\%#= can only be followed by 0, 1, or 2. The automatic engine will be used ")); regexp_engine = AUTOMATIC_ENGINE; } @@ -7263,7 +7263,7 @@ regprog_T *vim_regcomp(char_u *expr_arg, int re_flags) fprintf(f, "Syntax error in \"%s\"\n", expr); fclose(f); } else - EMSG2("(NFA) Could not open \"%s\" to write !!!", + semsg("(NFA) Could not open \"%s\" to write !!!", BT_REGEXP_DEBUG_LOG_NAME); } #endif @@ -7302,8 +7302,8 @@ static void report_re_switch(char_u *pat) { if (p_verbose > 0) { verbose_enter(); - MSG_PUTS(_("Switching to backtracking RE engine for pattern: ")); - MSG_PUTS(pat); + msg_puts(_("Switching to backtracking RE engine for pattern: ")); + msg_puts((char *)pat); verbose_leave(); } } @@ -7328,7 +7328,7 @@ static bool vim_regexec_string(regmatch_T *rmp, char_u *line, colnr_T col, // Cannot use the same prog recursively, it contains state. if (rmp->regprog->re_in_use) { - EMSG(_(e_recursive)); + emsg(_(e_recursive)); return false; } rmp->regprog->re_in_use = true; @@ -7425,7 +7425,7 @@ long vim_regexec_multi( // Cannot use the same prog recursively, it contains state. if (rmp->regprog->re_in_use) { - EMSG(_(e_recursive)); + emsg(_(e_recursive)); return false; } rmp->regprog->re_in_use = true; diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index 0eb061034f..04fb77e6b3 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -1244,11 +1244,11 @@ static int nfa_regatom(void) p = vim_strchr(classchars, no_Magic(c)); if (p == NULL) { if (extra == NFA_ADD_NL) { - EMSGN(_(e_ill_char_class), c); + semsg(_(e_ill_char_class), (int64_t)c); rc_did_emsg = true; return FAIL; } - IEMSGN("INTERNAL: Unknown character class char: %" PRId64, c); + siemsg("INTERNAL: Unknown character class char: %" PRId64, (int64_t)c); return FAIL; } // When '.' is followed by a composing char ignore the dot, so that @@ -1286,7 +1286,7 @@ static int nfa_regatom(void) case Magic('|'): case Magic('&'): case Magic(')'): - EMSGN(_(e_misplaced), no_Magic(c)); // -V1037 + semsg(_(e_misplaced), (int64_t)no_Magic(c)); // -V1037 return FAIL; case Magic('='): @@ -1296,7 +1296,7 @@ static int nfa_regatom(void) case Magic('*'): case Magic('{'): // these should follow an atom, not form an atom - EMSGN(_(e_misplaced), no_Magic(c)); + semsg(_(e_misplaced), (int64_t)no_Magic(c)); return FAIL; case Magic('~'): @@ -1306,7 +1306,7 @@ static int nfa_regatom(void) // Previous substitute pattern. // Generated as "\%(pattern\)". if (reg_prev_sub == NULL) { - EMSG(_(e_nopresub)); + emsg(_(e_nopresub)); return FAIL; } for (lp = reg_prev_sub; *lp != NUL; MB_CPTR_ADV(lp)) { @@ -1383,7 +1383,7 @@ static int nfa_regatom(void) re_has_z = REX_SET; break; default: - emsgf(_("E867: (NFA) Unknown operator '\\z%c'"), + semsg(_("E867: (NFA) Unknown operator '\\z%c'"), no_Magic(c)); return FAIL; } @@ -1489,7 +1489,7 @@ static int nfa_regatom(void) while (ascii_isdigit(c)) { if (n > (INT32_MAX - (c - '0')) / 10) { // overflow. - EMSG(_(e_value_too_large)); + emsg(_(e_value_too_large)); return FAIL; } n = n * 10 + (c - '0'); @@ -1516,7 +1516,7 @@ static int nfa_regatom(void) limit = INT32_MAX / MB_MAXBYTES; } if (n >= limit) { - EMSG(_(e_value_too_large)); + emsg(_(e_value_too_large)); return FAIL; } EMIT((int)n); @@ -1529,7 +1529,7 @@ static int nfa_regatom(void) break; } } - emsgf(_("E867: (NFA) Unknown operator '\\%%%c'"), + semsg(_("E867: (NFA) Unknown operator '\\%%%c'"), no_Magic(c)); return FAIL; } @@ -1955,7 +1955,7 @@ static int nfa_regpiece(void) break; } if (i == 0) { - emsgf(_("E869: (NFA) Unknown operator '\\@%c'"), op); + semsg(_("E869: (NFA) Unknown operator '\\@%c'"), op); return FAIL; } EMIT(i); @@ -2752,7 +2752,7 @@ static void st_error(int *postfix, int *end, int *p) fclose(df); } #endif - EMSG(_("E874: (NFA) Could not pop the stack!")); + emsg(_("E874: (NFA) Could not pop the stack!")); } /* @@ -4103,7 +4103,7 @@ skip_add: const size_t newsize = newlen * sizeof(nfa_thread_T); if ((long)(newsize >> 10) >= p_mmp) { - EMSG(_(e_maxmempat)); + emsg(_(e_maxmempat)); depth--; return NULL; } @@ -4393,7 +4393,7 @@ static regsubs_T *addstate_here( const size_t newsize = newlen * sizeof(nfa_thread_T); if ((long)(newsize >> 10) >= p_mmp) { - EMSG(_(e_maxmempat)); + emsg(_(e_maxmempat)); return NULL; } nfa_thread_T *const newl = xmalloc(newsize); @@ -4522,7 +4522,7 @@ static int check_char_class(int class, int c) default: // should not be here :P - IEMSGN(_(e_ill_char_class), class); + siemsg(_(e_ill_char_class), (int64_t)class); return FAIL; } return FAIL; @@ -4799,7 +4799,7 @@ static int recursive_regmatch( fprintf(log_fd, "MATCH = %s\n", !result ? "false" : "OK"); fprintf(log_fd, "****************************\n"); } else { - EMSG(_(e_log_open_failed)); + emsg(_(e_log_open_failed)); log_fd = stderr; } #endif @@ -5081,7 +5081,7 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, FILE *debug = fopen(NFA_REGEXP_DEBUG_LOG, "a"); if (debug == NULL) { - EMSG2("(NFA) COULD NOT OPEN %s!", NFA_REGEXP_DEBUG_LOG); + semsg("(NFA) COULD NOT OPEN %s!", NFA_REGEXP_DEBUG_LOG); return false; } #endif @@ -5119,7 +5119,7 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, abs(start->id), code); fprintf(log_fd, "**********************************\n"); } else { - EMSG(_(e_log_open_failed)); + emsg(_(e_log_open_failed)); log_fd = stderr; } #endif @@ -6145,7 +6145,7 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, #ifdef REGEXP_DEBUG if (c < 0) { - IEMSGN("INTERNAL: Negative state char: %" PRId64, c); + siemsg("INTERNAL: Negative state char: %" PRId64, (int64_t)c); } #endif result = (c == curc); @@ -6427,7 +6427,7 @@ static long nfa_regtry(nfa_regprog_T *prog, fprintf(f, "\n\n"); fclose(f); } else { - EMSG("Could not open temporary log file for writing"); + emsg("Could not open temporary log file for writing"); } #endif @@ -6542,7 +6542,7 @@ static long nfa_regexec_both(char_u *line, colnr_T startcol, /* Be paranoid... */ if (prog == NULL || line == NULL) { - IEMSG(_(e_null)); + iemsg(_(e_null)); goto theend; } diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index 5ade6244f9..674d807e96 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -146,7 +146,7 @@ int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback, char *basepath = path == p_rtp ? "runtimepath" : "packpath"; if (flags & DIP_ERR) { - EMSG3(_(e_dirnotf), basepath, name); + semsg(_(e_dirnotf), basepath, name); } else if (p_verbose > 0) { verbose_enter(); smsg(_("not found in '%s': \"%s\""), basepath, name); @@ -268,7 +268,7 @@ int do_in_cached_path(char_u *name, int flags, DoInRuntimepathCB callback, void if (!did_one && name != NULL) { if (flags & DIP_ERR) { - EMSG3(_(e_dirnotf), "runtime path", name); + semsg(_(e_dirnotf), "runtime path", name); } else if (p_verbose > 0) { verbose_enter(); smsg(_("not found in runtime path: \"%s\""), name); @@ -439,16 +439,16 @@ static void expand_rtp_entry(RuntimeSearchPath *search_path, Map(String, handle_ } static void expand_pack_entry(RuntimeSearchPath *search_path, Map(String, handle_T) *rtp_used, - CharVec *after_path, char_u *pack_entry) + CharVec *after_path, char_u *pack_entry, size_t pack_entry_len) { static char buf[MAXPATHL]; char *(start_pat[]) = { "/pack/*/start/*", "/start/*" }; // NOLINT for (int i = 0; i < 2; i++) { - if (STRLEN(pack_entry) + STRLEN(start_pat[i]) + 1 > MAXPATHL) { + if (pack_entry_len + STRLEN(start_pat[i]) + 1 > sizeof buf) { continue; } - STRLCPY(buf, pack_entry, MAXPATHL); - xstrlcat(buf, start_pat[i], sizeof buf); + STRLCPY(buf, pack_entry, sizeof buf); + STRLCPY(buf + pack_entry_len, start_pat[i], sizeof buf - pack_entry_len); expand_rtp_entry(search_path, rtp_used, buf, false); size_t after_size = STRLEN(buf)+7; char *after = xmallocz(after_size); @@ -507,14 +507,15 @@ RuntimeSearchPath runtime_search_path_build(void) handle_T *h = map_ref(String, handle_T)(&pack_used, cstr_as_string((char *)buf), false); if (h) { (*h)++; - expand_pack_entry(&search_path, &rtp_used, &after_path, buf); + expand_pack_entry(&search_path, &rtp_used, &after_path, buf, buflen); } } for (size_t i = 0; i < kv_size(pack_entries); i++) { - handle_T h = map_get(String, handle_T)(&pack_used, kv_A(pack_entries, i)); + String item = kv_A(pack_entries, i); + handle_T h = map_get(String, handle_T)(&pack_used, item); if (h == 0) { - expand_pack_entry(&search_path, &rtp_used, &after_path, (char_u *)kv_A(pack_entries, i).data); + expand_pack_entry(&search_path, &rtp_used, &after_path, (char_u *)item.data, item.size); } } @@ -573,7 +574,6 @@ void runtime_search_path_validate(void) } - /// Just like do_in_path_and_pp(), using 'runtimepath' for "path". int do_in_runtimepath(char_u *name, int flags, DoInRuntimepathCB callback, void *cookie) { diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 2cbd45e922..07cd8549a6 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -65,8 +65,8 @@ #include <stdbool.h> #include <string.h> -#include "nvim/api/private/helpers.h" #include "nvim/api/extmark.h" +#include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/arabic.h" #include "nvim/ascii.h" @@ -1952,7 +1952,7 @@ static size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_ first_level = 1; } - for (i = 0; i < MIN(fdc, level); i++) { + for (i = 0; i < MIN(fdc, level); i++) { if (foldinfo.fi_lnum == lnum && first_level + i >= foldinfo.fi_low_level) { symbol = wp->w_p_fcs_chars.foldopen; @@ -6083,7 +6083,7 @@ static void prepare_search_hl(win_T *wp, linenr_T lnum) || (cur != NULL && pos_inprogress))) { next_search_hl(wp, shl, shl->first_lnum, (colnr_T)n, shl == &search_hl ? NULL : cur); - pos_inprogress = !(cur == NULL || cur->pos.cur == 0); + pos_inprogress = !(cur == NULL || cur->pos.cur == 0); if (shl->lnum != 0) { shl->first_lnum = shl->lnum + shl->rm.endpos[0].lnum @@ -6727,7 +6727,6 @@ bool grid_invalid_row(ScreenGrid *grid, int row) } - /// Copy part of a grid line for vertically split window. static void linecopy(ScreenGrid *grid, int to, int from, int col, int width) { @@ -6964,7 +6963,7 @@ int showmode(void) lines_left = 0; if (do_mode) { - MSG_PUTS_ATTR("--", attr); + msg_puts_attr("--", attr); // CTRL-X in Insert mode if (edit_submode != NULL && !shortmess(SHM_COMPLETIONMENU)) { // These messages can get long, avoid a wrap in a narrow window. @@ -6989,7 +6988,7 @@ int showmode(void) msg_puts_attr((const char *)edit_submode, attr); } if (edit_submode_extra != NULL) { - MSG_PUTS_ATTR(" ", attr); // Add a space in between. + msg_puts_attr(" ", attr); // Add a space in between. if ((int)edit_submode_highl < HLF_COUNT) { sub_attr = win_hl_attr(curwin, edit_submode_highl); } else { @@ -7000,37 +6999,37 @@ int showmode(void) } } else { if (State & TERM_FOCUS) { - MSG_PUTS_ATTR(_(" TERMINAL"), attr); + msg_puts_attr(_(" TERMINAL"), attr); } else if (State & VREPLACE_FLAG) { - MSG_PUTS_ATTR(_(" VREPLACE"), attr); + msg_puts_attr(_(" VREPLACE"), attr); } else if (State & REPLACE_FLAG) { - MSG_PUTS_ATTR(_(" REPLACE"), attr); + msg_puts_attr(_(" REPLACE"), attr); } else if (State & INSERT) { if (p_ri) { - MSG_PUTS_ATTR(_(" REVERSE"), attr); + msg_puts_attr(_(" REVERSE"), attr); } - MSG_PUTS_ATTR(_(" INSERT"), attr); + msg_puts_attr(_(" INSERT"), attr); } else if (restart_edit == 'I' || restart_edit == 'i' || restart_edit == 'a') { - MSG_PUTS_ATTR(_(" (insert)"), attr); + msg_puts_attr(_(" (insert)"), attr); } else if (restart_edit == 'R') { - MSG_PUTS_ATTR(_(" (replace)"), attr); + msg_puts_attr(_(" (replace)"), attr); } else if (restart_edit == 'V') { - MSG_PUTS_ATTR(_(" (vreplace)"), attr); + msg_puts_attr(_(" (vreplace)"), attr); } if (p_hkmap) { - MSG_PUTS_ATTR(_(" Hebrew"), attr); + msg_puts_attr(_(" Hebrew"), attr); } if (State & LANGMAP) { if (curwin->w_p_arab) { - MSG_PUTS_ATTR(_(" Arabic"), attr); + msg_puts_attr(_(" Arabic"), attr); } else if (get_keymap_str(curwin, (char_u *)" (%s)", NameBuff, MAXPATHL)) { - MSG_PUTS_ATTR(NameBuff, attr); + msg_puts_attr((char *)NameBuff, attr); } } if ((State & INSERT) && p_paste) { - MSG_PUTS_ATTR(_(" (paste)"), attr); + msg_puts_attr(_(" (paste)"), attr); } if (VIsual_active) { @@ -7054,9 +7053,9 @@ int showmode(void) default: p = N_(" SELECT BLOCK"); break; } - MSG_PUTS_ATTR(_(p), attr); + msg_puts_attr(_(p), attr); } - MSG_PUTS_ATTR(" --", attr); + msg_puts_attr(" --", attr); } need_clear = TRUE; @@ -7145,11 +7144,11 @@ void clearmode(void) static void recording_mode(int attr) { - MSG_PUTS_ATTR(_("recording"), attr); + msg_puts_attr(_("recording"), attr); if (!shortmess(SHM_RECORDING)) { - char_u s[4]; - snprintf((char *)s, ARRAY_SIZE(s), " @%c", reg_recording); - MSG_PUTS_ATTR(s, attr); + char s[4]; + snprintf(s, ARRAY_SIZE(s), " @%c", reg_recording); + msg_puts_attr(s, attr); } } diff --git a/src/nvim/search.c b/src/nvim/search.c index c3a5f8dbe6..32bb0cb55a 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -144,9 +144,9 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc } if (spats[i].pat == NULL) { // pattern was never defined if (pat_use == RE_SUBST) { - EMSG(_(e_nopresub)); + emsg(_(e_nopresub)); } else { - EMSG(_(e_noprevre)); + emsg(_(e_noprevre)); } rc_did_emsg = true; return FAIL; @@ -577,7 +577,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, if (search_regcomp(pat, RE_SEARCH, pat_use, (options & (SEARCH_HIS + SEARCH_KEEP)), ®match) == FAIL) { if ((options & SEARCH_MSG) && !rc_did_emsg) { - EMSG2(_("E383: Invalid search string: %s"), mr_pattern); + semsg(_("E383: Invalid search string: %s"), mr_pattern); } return FAIL; } @@ -953,15 +953,15 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, if (!found) { // did not find it if (got_int) { - EMSG(_(e_interr)); + emsg(_(e_interr)); } else if ((options & SEARCH_MSG) == SEARCH_MSG) { if (p_ws) { - EMSG2(_(e_patnotf2), mr_pattern); + semsg(_(e_patnotf2), mr_pattern); } else if (lnum == 0) { - EMSG2(_("E384: search hit TOP without match for: %s"), + semsg(_("E384: search hit TOP without match for: %s"), mr_pattern); } else { - EMSG2(_("E385: search hit BOTTOM without match for: %s"), + semsg(_("E385: search hit BOTTOM without match for: %s"), mr_pattern); } } @@ -1115,7 +1115,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, if (spats[RE_SEARCH].pat == NULL) { // no previous pattern searchstr = spats[RE_SUBST].pat; if (searchstr == NULL) { - EMSG(_(e_noprevre)); + emsg(_(e_noprevre)); retval = 0; goto end_do_search; } @@ -1426,7 +1426,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, search_delim = dirc; if (dirc != '?' && dirc != '/') { retval = 0; - EMSG(_("E386: Expected '?' or '/' after ';'")); + emsg(_("E386: Expected '?' or '/' after ';'")); goto end_do_search; } ++pat; @@ -2530,13 +2530,14 @@ int findsent(Direction dir, long count) } if (c == '.' || c == '!' || c == '?') { tpos = pos; - do + do{ if ((c = inc(&tpos)) == -1) { break; } + } while (vim_strchr((char_u *)")]\"'", c = gchar_pos(&tpos)) != NULL); - if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL + if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL || (cpo_J && (c == ' ' && inc(&tpos) >= 0 && gchar_pos(&tpos) == ' '))) { pos = tpos; @@ -2662,12 +2663,12 @@ static int inmacro(char_u *opt, char_u *s) // Accept two characters in the option being equal to two characters // in the line. A space in the option matches with a space in the // line or the line having ended. - if ( (macro[0] == s[0] - || (macro[0] == ' ' - && (s[0] == NUL || s[0] == ' '))) - && (macro[1] == s[1] - || ((macro[1] == NUL || macro[1] == ' ') - && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) { + if ((macro[0] == s[0] + || (macro[0] == ' ' + && (s[0] == NUL || s[0] == ' '))) + && (macro[1] == s[1] + || ((macro[1] == NUL || macro[1] == ' ') + && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) { break; } ++macro; @@ -4250,7 +4251,6 @@ abort_search: } - /// Find next search match under cursor, cursor at end. /// Used while an operator is pending, and in Visual mode. /// @@ -4655,7 +4655,7 @@ void f_searchcount(typval_T *argvars, typval_T *rettv, FunPtr fptr) bool error = false; if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); return; } dict = argvars[0].vval.v_dict; @@ -4690,11 +4690,11 @@ void f_searchcount(typval_T *argvars, typval_T *rettv, FunPtr fptr) di = tv_dict_find(dict, (const char *)"pos", -1); if (di != NULL) { if (di->di_tv.v_type != VAR_LIST) { - EMSG2(_(e_invarg2), "pos"); + semsg(_(e_invarg2), "pos"); return; } if (tv_list_len(di->di_tv.vval.v_list) != 3) { - EMSG2(_(e_invarg2), "List format should be [lnum, col, off]"); + semsg(_(e_invarg2), "List format should be [lnum, col, off]"); return; } li = tv_list_find(di->di_tv.vval.v_list, 0L); @@ -4878,7 +4878,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo if (!got_int) { // don't display if 'q' typed at "--more--" // message msg_home_replace_hl(new_fname); - MSG_PUTS(_(" (includes previously listed match)")); + msg_puts(_(" (includes previously listed match)")); prev_fname = NULL; } } @@ -4895,25 +4895,25 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo msg_putchar('\n'); // cursor below last one } else { gotocmdline(true); // cursor at status line - MSG_PUTS_TITLE(_("--- Included files ")); + msg_puts_title(_("--- Included files ")); if (action != ACTION_SHOW_ALL) { - MSG_PUTS_TITLE(_("not found ")); + msg_puts_title(_("not found ")); } - MSG_PUTS_TITLE(_("in path ---\n")); + msg_puts_title(_("in path ---\n")); } did_show = true; while (depth_displayed < depth && !got_int) { ++depth_displayed; for (i = 0; i < depth_displayed; i++) { - MSG_PUTS(" "); + msg_puts(" "); } msg_home_replace(files[depth_displayed].name); - MSG_PUTS(" -->\n"); + msg_puts(" -->\n"); } if (!got_int) { // don't display if 'q' typed // for "--more--" message for (i = 0; i <= depth_displayed; i++) { - MSG_PUTS(" "); + msg_puts(" "); } if (new_fname != NULL) { // using "new_fname" is more reliable, e.g., when @@ -4934,10 +4934,8 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo // find the file name after the end of the match for (p = incl_regmatch.endp[0]; *p && !vim_isfilec(*p); p++) { - ; } for (i = 0; vim_isfilec(p[i]); i++) { - ; } } @@ -4964,9 +4962,9 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo if (new_fname == NULL && action == ACTION_SHOW_ALL) { if (already_searched) { - MSG_PUTS(_(" (Already listed)")); + msg_puts(_(" (Already listed)")); } else { - MSG_PUTS(_(" NOT FOUND")); + msg_puts(_(" NOT FOUND")); } } } @@ -5011,7 +5009,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo vim_snprintf((char *)IObuff, IOSIZE, _("Scanning included file: %s"), (char *)new_fname); - msg_trunc_attr(IObuff, true, HL_ATTR(HLF_R)); + msg_trunc_attr((char *)IObuff, true, HL_ATTR(HLF_R)); } else if (p_verbose >= 5) { verbose_enter(); smsg(_("Searching included file %s"), @@ -5216,7 +5214,7 @@ search_line: found = true; if (depth == -1 && lnum == curwin->w_cursor.lnum && l_g_do_tagpreview == 0) { - EMSG(_("E387: Match is on current line")); + emsg(_("E387: Match is on current line")); } else if (action == ACTION_SHOW) { show_pat_in_path(line, type, did_show, action, (depth == -1) ? NULL : files[depth].fp, @@ -5341,19 +5339,19 @@ exit_matched: if (type == CHECK_PATH) { if (!did_show) { if (action != ACTION_SHOW_ALL) { - MSG(_("All included files were found")); + msg(_("All included files were found")); } else { - MSG(_("No included files")); + msg(_("No included files")); } } } else if (!found && action != ACTION_EXPAND) { if (got_int || compl_interrupted) { - EMSG(_(e_interr)); + emsg(_(e_interr)); } else if (type == FIND_DEFINE) { - EMSG(_("E388: Couldn't find definition")); + emsg(_("E388: Couldn't find definition")); } else { - EMSG(_("E389: Couldn't find pattern")); + emsg(_("E389: Couldn't find pattern")); } } if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) { diff --git a/src/nvim/search.h b/src/nvim/search.h index 85bcda84a4..15b8d41f39 100644 --- a/src/nvim/search.h +++ b/src/nvim/search.h @@ -84,8 +84,7 @@ typedef struct { int sa_wrapped; ///< search wrapped around } searchit_arg_T; -typedef struct searchstat -{ +typedef struct searchstat { int cur; // current position of found words int cnt; // total count of found words bool exact_match; // true if matched exactly on specified position diff --git a/src/nvim/shada.c b/src/nvim/shada.c index 10f93913ad..89f9d3a719 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -713,11 +713,11 @@ static ShaDaReadResult sd_reader_skip(ShaDaReadDef *const sd_reader, const size_ { if (sd_reader->skip(sd_reader, offset) != OK) { if (sd_reader->error != NULL) { - emsgf(_(SERR "System error while skipping in ShaDa file: %s"), + semsg(_(SERR "System error while skipping in ShaDa file: %s"), sd_reader->error); return kSDReadStatusReadError; } else if (sd_reader->eof) { - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "last entry specified that it occupies %" PRIu64 " bytes, " "but file ended earlier"), (uint64_t)offset); @@ -762,7 +762,7 @@ static void close_file(void *cookie) { const int error = file_free(cookie, !!p_fs); if (error != 0) { - emsgf(_(SERR "System error while closing ShaDa file: %s"), + semsg(_(SERR "System error while closing ShaDa file: %s"), os_strerror(error)); } } @@ -797,7 +797,7 @@ static int msgpack_sd_writer_write(void *data, const char *buf, size_t len) ShaDaWriteDef *const sd_writer = (ShaDaWriteDef *)data; ptrdiff_t written_bytes = sd_writer->write(sd_writer, buf, len); if (written_bytes == -1) { - emsgf(_(SERR "System error while writing ShaDa file: %s"), + semsg(_(SERR "System error while writing ShaDa file: %s"), sd_writer->error); return -1; } @@ -844,7 +844,7 @@ static int shada_read_file(const char *const file, const int flags) if (of_ret != 0) { if (of_ret != UV_ENOENT || (flags & kShaDaMissingError)) { - emsgf(_(SERR "System error while opening ShaDa file %s for reading: %s"), + semsg(_(SERR "System error while opening ShaDa file %s for reading: %s"), fname, os_strerror(of_ret)); } xfree(fname); @@ -1598,7 +1598,7 @@ static ShaDaWriteResult shada_pack_entry(msgpack_packer *const packer, ShadaEntr if (encode_vim_to_msgpack(spacker, &entry.data.global_var.value, vardesc) == FAIL) { ret = kSDWriteIgnError; - EMSG2(_(WERR "Failed to write variable %s"), + semsg(_(WERR "Failed to write variable %s"), entry.data.global_var.name); goto shada_pack_entry_error; } @@ -1899,7 +1899,7 @@ shada_parse_msgpack_read_next: {} } break; case MSGPACK_UNPACK_PARSE_ERROR: - emsgf(_(RCERR "Failed to parse ShaDa file due to a msgpack parser error " + semsg(_(RCERR "Failed to parse ShaDa file due to a msgpack parser error " "at position %" PRIu64), (uint64_t)initial_fpos); ret = kSDReadStatusNotShaDa; @@ -1910,18 +1910,18 @@ shada_parse_msgpack_read_next: {} try_to_free_memory(); goto shada_parse_msgpack_read_next; } - EMSG(_(e_outofmem)); + emsg(_(e_outofmem)); ret = kSDReadStatusReadError; break; case MSGPACK_UNPACK_CONTINUE: - emsgf(_(RCERR "Failed to parse ShaDa file: incomplete msgpack string " + semsg(_(RCERR "Failed to parse ShaDa file: incomplete msgpack string " "at position %" PRIu64), (uint64_t)initial_fpos); ret = kSDReadStatusNotShaDa; break; case MSGPACK_UNPACK_EXTRA_BYTES: shada_parse_msgpack_extra_bytes: - emsgf(_(RCERR "Failed to parse ShaDa file: extra bytes in msgpack string " + semsg(_(RCERR "Failed to parse ShaDa file: extra bytes in msgpack string " "at position %" PRIu64), (uint64_t)initial_fpos); ret = kSDReadStatusNotShaDa; @@ -2949,7 +2949,7 @@ int shada_write_file(const char *const file, bool nomerge) int error; if ((error = open_shada_file_for_reading(fname, &sd_reader)) != 0) { if (error != UV_ENOENT) { - emsgf(_(SERR "System error while opening ShaDa file %s for reading " + semsg(_(SERR "System error while opening ShaDa file %s for reading " "to merge before writing it: %s"), fname, os_strerror(error)); // Try writing the file even if opening it emerged any issues besides @@ -2981,7 +2981,7 @@ shada_write_file_open: {} if (*wp == 'z') { // Tried names from .tmp.a to .tmp.z, all failed. Something must be // wrong then. - EMSG2(_("E138: All %s.tmp.X files exist, cannot write ShaDa file!"), + semsg(_("E138: All %s.tmp.X files exist, cannot write ShaDa file!"), fname); xfree(fname); xfree(tempname); @@ -2993,7 +2993,7 @@ shada_write_file_open: {} goto shada_write_file_open; } } else { - emsgf(_(SERR "System error while opening temporary ShaDa file %s " + semsg(_(SERR "System error while opening temporary ShaDa file %s " "for writing: %s"), tempname, os_strerror(error)); } } @@ -3008,7 +3008,7 @@ shada_write_file_nomerge: {} int ret; char *failed_dir; if ((ret = os_mkdir_recurse(fname, 0700, &failed_dir)) != 0) { - EMSG3(_(SERR "Failed to create directory %s " + semsg(_(SERR "Failed to create directory %s " "for writing ShaDa file: %s"), failed_dir, os_strerror(ret)); xfree(fname); @@ -3022,7 +3022,7 @@ shada_write_file_nomerge: {} sd_writer.cookie = file_open_new(&error, fname, kFileCreate|kFileTruncate, 0600); if (sd_writer.cookie == NULL) { - emsgf(_(SERR "System error while opening ShaDa file %s for writing: %s"), + semsg(_(SERR "System error while opening ShaDa file %s for writing: %s"), fname, os_strerror(error)); } } @@ -3064,7 +3064,7 @@ shada_write_file_nomerge: {} const int fchown_ret = os_fchown(file_fd(sd_writer.cookie), old_uid, old_gid); if (fchown_ret != 0) { - EMSG3(_(RNERR "Failed setting uid and gid for file %s: %s"), + semsg(_(RNERR "Failed setting uid and gid for file %s: %s"), tempname, os_strerror(fchown_ret)); goto shada_write_file_did_not_remove; } @@ -3074,13 +3074,13 @@ shada_write_file_nomerge: {} : (old_info.stat.st_gid == getgid() ? (old_info.stat.st_mode & 0020) : (old_info.stat.st_mode & 0002)))) { - EMSG2(_("E137: ShaDa file is not writable: %s"), fname); + semsg(_("E137: ShaDa file is not writable: %s"), fname); goto shada_write_file_did_not_remove; } } #endif if (vim_rename((char_u *)tempname, (char_u *)fname) == -1) { - EMSG3(_(RNERR "Can't rename ShaDa file from %s to %s!"), + semsg(_(RNERR "Can't rename ShaDa file from %s to %s!"), tempname, fname); } else { did_remove = true; @@ -3088,10 +3088,10 @@ shada_write_file_nomerge: {} } } else { if (sw_ret == kSDWriteReadNotShada) { - EMSG3(_(RNERR "Did not rename %s because %s " + semsg(_(RNERR "Did not rename %s because %s " "does not look like a ShaDa file"), tempname, fname); } else { - EMSG3(_(RNERR "Did not rename %s to %s because there were errors " + semsg(_(RNERR "Did not rename %s to %s because there were errors " "during writing it"), tempname, fname); } } @@ -3099,7 +3099,7 @@ shada_write_file_nomerge: {} #ifdef UNIX shada_write_file_did_not_remove: #endif - EMSG3(_(RNERR "Do not forget to remove %s or rename it manually to %s."), + semsg(_(RNERR "Do not forget to remove %s or rename it manually to %s."), tempname, fname); } xfree(tempname); @@ -3225,11 +3225,11 @@ static ShaDaReadResult fread_len(ShaDaReadDef *const sd_reader, char *const buff if (read_bytes != (ptrdiff_t)length) { if (sd_reader->error != NULL) { - emsgf(_(SERR "System error while reading ShaDa file: %s"), + semsg(_(SERR "System error while reading ShaDa file: %s"), sd_reader->error); return kSDReadStatusReadError; } else { - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "last entry specified that it occupies %" PRIu64 " bytes, " "but file ended earlier"), (uint64_t)length); @@ -3263,11 +3263,11 @@ static ShaDaReadResult msgpack_read_uint64(ShaDaReadDef *const sd_reader, const if (first_char == EOF) { if (sd_reader->error) { - emsgf(_(SERR "System error while reading integer from ShaDa file: %s"), + semsg(_(SERR "System error while reading integer from ShaDa file: %s"), sd_reader->error); return kSDReadStatusReadError; } else if (sd_reader->eof) { - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "expected positive integer at position %" PRIu64 ", but got nothing"), (uint64_t)fpos); @@ -3294,7 +3294,7 @@ static ShaDaReadResult msgpack_read_uint64(ShaDaReadDef *const sd_reader, const length = 8; break; default: - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "expected positive integer at position %" PRIu64), (uint64_t)fpos); return kSDReadStatusNotShaDa; @@ -3334,18 +3334,18 @@ static ShaDaReadResult msgpack_read_uint64(ShaDaReadDef *const sd_reader, const proc) \ do { \ if (!(condition)) { \ - emsgf(_(READERR(entry_name, error_desc)), initial_fpos); \ + semsg(_(READERR(entry_name, error_desc)), initial_fpos); \ CLEAR_GA_AND_ERROR_OUT(ad_ga); \ } \ tgt = proc(obj.via.attr); \ } while (0) #define CHECK_KEY_IS_STR(un, entry_name) \ if (un.data.via.map.ptr[i].key.type != MSGPACK_OBJECT_STR) { \ - emsgf(_(READERR(entry_name, "has key which is not a string")), \ + semsg(_(READERR(entry_name, "has key which is not a string")), \ initial_fpos); \ CLEAR_GA_AND_ERROR_OUT(ad_ga); \ } else if (un.data.via.map.ptr[i].key.via.str.size == 0) { \ - emsgf(_(READERR(entry_name, "has empty key")), initial_fpos); \ + semsg(_(READERR(entry_name, "has empty key")), initial_fpos); \ CLEAR_GA_AND_ERROR_OUT(ad_ga); \ } #define CHECKED_KEY(un, entry_name, name, error_desc, tgt, condition, attr, \ @@ -3403,7 +3403,7 @@ static ShaDaReadResult msgpack_read_uint64(ShaDaReadDef *const sd_reader, const typval_T adtv; \ if (msgpack_to_vim(obj, &adtv) == FAIL \ || adtv.v_type != VAR_DICT) { \ - emsgf(_(READERR(name, \ + semsg(_(READERR(name, \ "cannot be converted to a VimL dictionary")), \ initial_fpos); \ ga_clear(&ad_ga); \ @@ -3428,7 +3428,7 @@ static ShaDaReadResult msgpack_read_uint64(ShaDaReadDef *const sd_reader, const }; \ typval_T aetv; \ if (msgpack_to_vim(obj, &aetv) == FAIL) { \ - emsgf(_(READERR(name, "cannot be converted to a VimL list")), \ + semsg(_(READERR(name, "cannot be converted to a VimL list")), \ initial_fpos); \ tv_clear(&aetv); \ goto shada_read_next_item_error; \ @@ -3488,7 +3488,7 @@ shada_read_next_item_start: } if (length_u64 > PTRDIFF_MAX) { - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "there is an item at position %" PRIu64 " " "that is stated to be too long"), initial_fpos); @@ -3502,7 +3502,7 @@ shada_read_next_item_start: // kSDItemUnknown cannot possibly pass that far because it is -1 and that // will fail in msgpack_read_uint64. But kSDItemMissing may and it will // otherwise be skipped because (1 << 0) will never appear in flags. - emsgf(_(RCERR "Error while reading ShaDa file: " + semsg(_(RCERR "Error while reading ShaDa file: " "there is an item at position %" PRIu64 " " "that must not be there: Missing items are " "for internal uses only"), @@ -3572,13 +3572,13 @@ shada_read_next_item_start: switch ((ShadaEntryType)type_u64) { case kSDItemHeader: if (!msgpack_rpc_to_dictionary(&(unpacked.data), &(entry->data.header))) { - emsgf(_(READERR("header", "is not a dictionary")), initial_fpos); + semsg(_(READERR("header", "is not a dictionary")), initial_fpos); goto shada_read_next_item_error; } break; case kSDItemSearchPattern: { if (unpacked.data.type != MSGPACK_OBJECT_MAP) { - emsgf(_(READERR("search pattern", "is not a dictionary")), + semsg(_(READERR("search pattern", "is not a dictionary")), initial_fpos); goto shada_read_next_item_error; } @@ -3610,7 +3610,7 @@ shada_read_next_item_start: ADDITIONAL_KEY(unpacked) } if (entry->data.search_pattern.pat == NULL) { - emsgf(_(READERR("search pattern", "has no pattern")), initial_fpos); + semsg(_(READERR("search pattern", "has no pattern")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } SET_ADDITIONAL_DATA(entry->data.search_pattern.additional_data, @@ -3622,7 +3622,7 @@ shada_read_next_item_start: case kSDItemGlobalMark: case kSDItemLocalMark: { if (unpacked.data.type != MSGPACK_OBJECT_MAP) { - emsgf(_(READERR("mark", "is not a dictionary")), initial_fpos); + semsg(_(READERR("mark", "is not a dictionary")), initial_fpos); goto shada_read_next_item_error; } garray_T ad_ga; @@ -3631,7 +3631,7 @@ shada_read_next_item_start: CHECK_KEY_IS_STR(unpacked, "mark") if (CHECK_KEY(unpacked.data.via.map.ptr[i].key, KEY_NAME_CHAR)) { if (type_u64 == kSDItemJump || type_u64 == kSDItemChange) { - emsgf(_(READERR("mark", "has n key which is only valid for " + semsg(_(READERR("mark", "has n key which is only valid for " "local and global mark entries")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } @@ -3647,15 +3647,15 @@ shada_read_next_item_start: ADDITIONAL_KEY(unpacked) } if (entry->data.filemark.fname == NULL) { - emsgf(_(READERR("mark", "is missing file name")), initial_fpos); + semsg(_(READERR("mark", "is missing file name")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } if (entry->data.filemark.mark.lnum <= 0) { - emsgf(_(READERR("mark", "has invalid line number")), initial_fpos); + semsg(_(READERR("mark", "has invalid line number")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } if (entry->data.filemark.mark.col < 0) { - emsgf(_(READERR("mark", "has invalid column number")), initial_fpos); + semsg(_(READERR("mark", "has invalid column number")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } SET_ADDITIONAL_DATA(entry->data.filemark.additional_data, "mark"); @@ -3663,7 +3663,7 @@ shada_read_next_item_start: } case kSDItemRegister: { if (unpacked.data.type != MSGPACK_OBJECT_MAP) { - emsgf(_(READERR("register", "is not a dictionary")), initial_fpos); + semsg(_(READERR("register", "is not a dictionary")), initial_fpos); goto shada_read_next_item_error; } garray_T ad_ga; @@ -3673,14 +3673,14 @@ shada_read_next_item_start: if (CHECK_KEY(unpacked.data.via.map.ptr[i].key, REG_KEY_CONTENTS)) { if (unpacked.data.via.map.ptr[i].val.type != MSGPACK_OBJECT_ARRAY) { - emsgf(_(READERR("register", + semsg(_(READERR("register", "has " REG_KEY_CONTENTS " key with non-array value")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } if (unpacked.data.via.map.ptr[i].val.via.array.size == 0) { - emsgf(_(READERR("register", + semsg(_(READERR("register", "has " REG_KEY_CONTENTS " key with empty array")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); @@ -3689,7 +3689,7 @@ shada_read_next_item_start: unpacked.data.via.map.ptr[i].val.via.array; for (size_t j = 0; j < arr.size; j++) { if (arr.ptr[j].type != MSGPACK_OBJECT_BIN) { - emsgf(_(READERR("register", "has " REG_KEY_CONTENTS " array " + semsg(_(READERR("register", "has " REG_KEY_CONTENTS " array " "with non-binary value")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } @@ -3711,7 +3711,7 @@ shada_read_next_item_start: ADDITIONAL_KEY(unpacked) } if (entry->data.reg.contents == NULL) { - emsgf(_(READERR("register", "has missing " REG_KEY_CONTENTS " array")), + semsg(_(READERR("register", "has missing " REG_KEY_CONTENTS " array")), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } @@ -3720,29 +3720,29 @@ shada_read_next_item_start: } case kSDItemHistoryEntry: { if (unpacked.data.type != MSGPACK_OBJECT_ARRAY) { - emsgf(_(READERR("history", "is not an array")), initial_fpos); + semsg(_(READERR("history", "is not an array")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.size < 2) { - emsgf(_(READERR("history", "does not have enough elements")), + semsg(_(READERR("history", "does not have enough elements")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.ptr[0].type != MSGPACK_OBJECT_POSITIVE_INTEGER) { - emsgf(_(READERR("history", "has wrong history type type")), + semsg(_(READERR("history", "has wrong history type type")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.ptr[1].type != MSGPACK_OBJECT_BIN) { - emsgf(_(READERR("history", "has wrong history string type")), + semsg(_(READERR("history", "has wrong history string type")), initial_fpos); goto shada_read_next_item_error; } if (memchr(unpacked.data.via.array.ptr[1].via.bin.ptr, 0, unpacked.data.via.array.ptr[1].via.bin.size) != NULL) { - emsgf(_(READERR("history", "contains string with zero byte inside")), + semsg(_(READERR("history", "contains string with zero byte inside")), initial_fpos); goto shada_read_next_item_error; } @@ -3752,13 +3752,13 @@ shada_read_next_item_start: entry->data.history_item.histtype == HIST_SEARCH; if (is_hist_search) { if (unpacked.data.via.array.size < 3) { - emsgf(_(READERR("search history", + semsg(_(READERR("search history", "does not have separator character")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.ptr[2].type != MSGPACK_OBJECT_POSITIVE_INTEGER) { - emsgf(_(READERR("search history", + semsg(_(READERR("search history", "has wrong history separator type")), initial_fpos); goto shada_read_next_item_error; } @@ -3784,16 +3784,16 @@ shada_read_next_item_start: } case kSDItemVariable: { if (unpacked.data.type != MSGPACK_OBJECT_ARRAY) { - emsgf(_(READERR("variable", "is not an array")), initial_fpos); + semsg(_(READERR("variable", "is not an array")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.size < 2) { - emsgf(_(READERR("variable", "does not have enough elements")), + semsg(_(READERR("variable", "does not have enough elements")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.ptr[0].type != MSGPACK_OBJECT_BIN) { - emsgf(_(READERR("variable", "has wrong variable name type")), + semsg(_(READERR("variable", "has wrong variable name type")), initial_fpos); goto shada_read_next_item_error; } @@ -3813,7 +3813,7 @@ shada_read_next_item_start: const typval_T *type_tv = TV_LIST_ITEM_TV(type_item); if (type_tv->v_type != VAR_NUMBER || type_tv->vval.v_number != VAR_TYPE_BLOB) { - emsgf(_(READERR("variable", "has wrong variable type")), + semsg(_(READERR("variable", "has wrong variable type")), initial_fpos); goto shada_read_next_item_error; } @@ -3828,7 +3828,7 @@ shada_read_next_item_start: tv_blob_set_ret(&entry->data.global_var.value, blob); } else if (msgpack_to_vim(unpacked.data.via.array.ptr[1], &(entry->data.global_var.value)) == FAIL) { - emsgf(_(READERR("variable", "has value that cannot " + semsg(_(READERR("variable", "has value that cannot " "be converted to the VimL value")), initial_fpos); goto shada_read_next_item_error; } @@ -3836,16 +3836,16 @@ shada_read_next_item_start: } case kSDItemSubString: if (unpacked.data.type != MSGPACK_OBJECT_ARRAY) { - emsgf(_(READERR("sub string", "is not an array")), initial_fpos); + semsg(_(READERR("sub string", "is not an array")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.size < 1) { - emsgf(_(READERR("sub string", "does not have enough elements")), + semsg(_(READERR("sub string", "does not have enough elements")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.ptr[0].type != MSGPACK_OBJECT_BIN) { - emsgf(_(READERR("sub string", "has wrong sub string type")), + semsg(_(READERR("sub string", "has wrong sub string type")), initial_fpos); goto shada_read_next_item_error; } @@ -3857,7 +3857,7 @@ shada_read_next_item_start: break; case kSDItemBufferList: if (unpacked.data.type != MSGPACK_OBJECT_ARRAY) { - emsgf(_(READERR("buffer list", "is not an array")), initial_fpos); + semsg(_(READERR("buffer list", "is not an array")), initial_fpos); goto shada_read_next_item_error; } if (unpacked.data.via.array.size == 0) { @@ -3873,7 +3873,7 @@ shada_read_next_item_start: }; { if (unpacked_2.data.type != MSGPACK_OBJECT_MAP) { - emsgf(_(RERR "Error while reading ShaDa file: " + semsg(_(RERR "Error while reading ShaDa file: " "buffer list at position %" PRIu64 " " "contains entry that is not a dictionary"), initial_fpos); @@ -3900,21 +3900,21 @@ shada_read_next_item_start: i = j; // XXX: Restore `i`. } if (entry->data.buffer_list.buffers[i].pos.lnum <= 0) { - emsgf(_(RERR "Error while reading ShaDa file: " + semsg(_(RERR "Error while reading ShaDa file: " "buffer list at position %" PRIu64 " " "contains entry with invalid line number"), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } if (entry->data.buffer_list.buffers[i].pos.col < 0) { - emsgf(_(RERR "Error while reading ShaDa file: " + semsg(_(RERR "Error while reading ShaDa file: " "buffer list at position %" PRIu64 " " "contains entry with invalid column number"), initial_fpos); CLEAR_GA_AND_ERROR_OUT(ad_ga); } if (entry->data.buffer_list.buffers[i].fname == NULL) { - emsgf(_(RERR "Error while reading ShaDa file: " + semsg(_(RERR "Error while reading ShaDa file: " "buffer list at position %" PRIu64 " " "contains entry that does not have a file name"), initial_fpos); @@ -4014,7 +4014,7 @@ static inline size_t shada_init_jumps(PossiblyFreedShadaEntry *jumps, jump_iter = mark_jumplist_iter(jump_iter, curwin, &fm); if (fm.fmark.mark.lnum == 0) { - iemsgf("ShaDa: mark lnum zero (ji:%p, js:%p, len:%i)", + siemsg("ShaDa: mark lnum zero (ji:%p, js:%p, len:%i)", (void *)jump_iter, (void *)&curwin->w_jumplist[0], curwin->w_jumplistlen); continue; diff --git a/src/nvim/sign.c b/src/nvim/sign.c index 1b100161bf..29b608154b 100644 --- a/src/nvim/sign.c +++ b/src/nvim/sign.c @@ -23,8 +23,7 @@ /// Struct to hold the sign properties. typedef struct sign sign_T; -struct sign -{ +struct sign { sign_T *sn_next; // next sign in list int sn_typenr; // type number of sign char_u *sn_name; // name of sign @@ -434,9 +433,9 @@ sign_attrs_T *sign_get_attr(SignType type, sign_attrs_T sattrs[], int idx, int m int nr_matches = 0; for (int i = 0; i < SIGN_SHOW_MAX; i++) { - if ( (type == SIGN_TEXT && sattrs[i].sat_text != NULL) - || (type == SIGN_LINEHL && sattrs[i].sat_linehl != 0) - || (type == SIGN_NUMHL && sattrs[i].sat_numhl != 0)) { + if ((type == SIGN_TEXT && sattrs[i].sat_text != NULL) + || (type == SIGN_LINEHL && sattrs[i].sat_linehl != 0) + || (type == SIGN_NUMHL && sattrs[i].sat_numhl != 0)) { matches[nr_matches] = &sattrs[i]; nr_matches++; // attr list is sorted with most important (priority, id), thus we @@ -681,7 +680,7 @@ void sign_list_placed(buf_T *rbuf, char_u *sign_group) char lbuf[MSG_BUF_LEN]; char group[MSG_BUF_LEN]; - MSG_PUTS_TITLE(_("\n--- Signs ---")); + msg_puts_title(_("\n--- Signs ---")); msg_putchar('\n'); if (rbuf == NULL) { buf = firstbuf; @@ -691,7 +690,7 @@ void sign_list_placed(buf_T *rbuf, char_u *sign_group) while (buf != NULL && !got_int) { if (buf->b_signlist != NULL) { vim_snprintf(lbuf, MSG_BUF_LEN, _("Signs for %s:"), buf->b_fname); - MSG_PUTS_ATTR(lbuf, HL_ATTR(HLF_D)); + msg_puts_attr(lbuf, HL_ATTR(HLF_D)); msg_putchar('\n'); } FOR_ALL_SIGNS_IN_BUF(buf, sign) { @@ -711,7 +710,7 @@ void sign_list_placed(buf_T *rbuf, char_u *sign_group) _(" line=%ld id=%d%s name=%s priority=%d"), (long)sign->se_lnum, sign->se_id, group, sign_typenr2name(sign->se_typenr), sign->se_priority); - MSG_PUTS(lbuf); + msg_puts(lbuf); msg_putchar('\n'); } if (rbuf != NULL) { @@ -825,7 +824,7 @@ static sign_T *alloc_new_sign(char_u *name) } if (next_sign_typenr == start) { xfree(sp); - EMSG(_("E612: Too many signs defined")); + emsg(_("E612: Too many signs defined")); return NULL; } lp = first_sign; // start all over @@ -879,7 +878,7 @@ static int sign_define_init_text(sign_T *sp, char_u *text) } // Currently must be empty, one or two display cells if (s != endp || cells > 2) { - EMSG2(_("E239: Invalid sign text: %s"), text); + semsg(_("E239: Invalid sign text: %s"), text); return FAIL; } if (cells < 1) { @@ -962,7 +961,7 @@ int sign_undefine_by_name(const char_u *name) sp = sign_find(name, &sp_prev); if (sp == NULL) { - EMSG2(_("E155: Unknown sign: %s"), name); + semsg(_("E155: Unknown sign: %s"), name); return FAIL; } sign_undefine(sp, sp_prev); @@ -990,7 +989,7 @@ static void sign_list_by_name(char_u *name) if (sp != NULL) { sign_list_defined(sp); } else { - EMSG2(_("E155: Unknown sign: %s"), name); + semsg(_("E155: Unknown sign: %s"), name); } } @@ -1012,7 +1011,7 @@ int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign_name, } } if (sp == NULL) { - EMSG2(_("E155: Unknown sign: %s"), sign_name); + semsg(_("E155: Unknown sign: %s"), sign_name); return FAIL; } if (*sign_id == 0) { @@ -1041,7 +1040,7 @@ int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign_name, // number column is less than 2, then force recomputing the width. may_force_numberwidth_recompute(buf, false); } else { - EMSG2(_("E885: Not possible to change sign %s"), sign_name); + semsg(_("E885: Not possible to change sign %s"), sign_name); return FAIL; } @@ -1088,7 +1087,7 @@ static void sign_unplace_at_cursor(char_u *groupname) if (id > 0) { sign_unplace(id, groupname, curwin->w_buffer, curwin->w_cursor.lnum); } else { - EMSG(_("E159: Missing sign number")); + emsg(_("E159: Missing sign number")); } } @@ -1098,7 +1097,7 @@ linenr_T sign_jump(int sign_id, char_u *sign_group, buf_T *buf) linenr_T lnum; if ((lnum = buf_findsign(buf, sign_id, sign_group)) <= 0) { - EMSGN(_("E157: Invalid sign ID: %" PRId64), sign_id); + semsg(_("E157: Invalid sign ID: %" PRId64), (int64_t)sign_id); return -1; } @@ -1109,7 +1108,7 @@ linenr_T sign_jump(int sign_id, char_u *sign_group, buf_T *buf) beginline(BL_WHITE); } else { // ... not currently in a window if (buf->b_fname == NULL) { - EMSG(_("E934: Cannot jump to a buffer that does not have a name")); + emsg(_("E934: Cannot jump to a buffer that does not have a name")); return -1; } size_t cmdlen = STRLEN(buf->b_fname) + 24; @@ -1160,7 +1159,7 @@ static void sign_define_cmd(char_u *sign_name, char_u *cmdline) arg += 6; numhl = vim_strnsave(arg, (size_t)(p - arg)); } else { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); failed = true; break; } @@ -1194,7 +1193,7 @@ static void sign_place_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, // :sign place group=* if (lnum >= 0 || sign_name != NULL || (group != NULL && *group == '\0')) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); } else { sign_list_placed(buf, group); } @@ -1202,7 +1201,7 @@ static void sign_place_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, // Place a new sign if (sign_name == NULL || buf == NULL || (group != NULL && *group == '\0')) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1214,7 +1213,7 @@ static void sign_place_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, char_u *group) { if (lnum >= 0 || sign_name != NULL || (group != NULL && *group == '\0')) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1271,7 +1270,7 @@ static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int i static void sign_jump_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, char_u *group) { if (sign_name == NULL && group == NULL && id == -1) { - EMSG(_(e_argreq)); + emsg(_(e_argreq)); return; } @@ -1279,7 +1278,7 @@ static void sign_jump_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, || lnum >= 0 || sign_name != NULL) { // File or buffer is not specified or an empty group is used // or a line number or a sign name is specified. - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return; } @@ -1318,7 +1317,7 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si lnum_arg = true; } else if (STRNCMP(arg, "*", 1) == 0 && cmd == SIGNCMD_UNPLACE) { if (*signid != -1) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return FAIL; } *signid = -2; @@ -1355,18 +1354,18 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si filename = arg; *buf = buflist_findnr(getdigits_int(&arg, true, 0)); if (*skipwhite(arg) != NUL) { - EMSG(_(e_trailing)); + emsg(_(e_trailing)); } break; } else { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return FAIL; } arg = skipwhite(arg); } if (filename != NULL && *buf == NULL) { - EMSG2(_("E158: Invalid buffer name: %s"), filename); + semsg(_("E158: Invalid buffer name: %s"), filename); return FAIL; } @@ -1391,7 +1390,7 @@ void ex_sign(exarg_T *eap) p = skiptowhite(arg); idx = sign_cmd_idx(arg, p); if (idx == SIGNCMD_LAST) { - EMSG2(_("E160: Unknown sign command: %s"), arg); + semsg(_("E160: Unknown sign command: %s"), arg); return; } arg = skipwhite(p); @@ -1404,7 +1403,7 @@ void ex_sign(exarg_T *eap) sign_list_defined(sp); } } else if (*arg == NUL) { - EMSG(_("E156: Missing sign name")); + emsg(_("E156: Missing sign name")); } else { char_u *name; @@ -1898,7 +1897,7 @@ void sign_define_multiple(list_T *l, list_T *retlist) if (TV_LIST_ITEM_TV(li)->v_type == VAR_DICT) { retval = sign_define_from_dict(NULL, TV_LIST_ITEM_TV(li)->vval.v_dict); } else { - EMSG(_(e_dictreq)); + emsg(_(e_dictreq)); } tv_list_append_number(retlist, retval); }); @@ -1934,7 +1933,7 @@ int sign_place_from_dict(typval_T *id_tv, typval_T *group_tv, typval_T *name_tv, return -1; } if (sign_id < 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); return -1; } } @@ -1995,7 +1994,7 @@ int sign_place_from_dict(typval_T *id_tv, typval_T *group_tv, typval_T *name_tv, if (di != NULL) { lnum = tv_get_lnum(&di->di_tv); if (lnum <= 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); goto cleanup; } } @@ -2069,7 +2068,7 @@ int sign_unplace_from_dict(typval_T *group_tv, dict_T *dict) if (tv_dict_find(dict, "id", -1) != NULL) { sign_id = (int)tv_dict_get_number(dict, "id"); if (sign_id <= 0) { - EMSG(_(e_invarg)); + emsg(_(e_invarg)); goto cleanup; } } diff --git a/src/nvim/sign_defs.h b/src/nvim/sign_defs.h index f3ec2c45f6..46436b2c8e 100644 --- a/src/nvim/sign_defs.h +++ b/src/nvim/sign_defs.h @@ -9,8 +9,7 @@ // signs: line annotations // Sign group -typedef struct signgroup_S -{ +typedef struct signgroup_S { uint16_t sg_refcount; // number of signs in this group int sg_next_sign_id; // next sign id for this group char_u sg_name[1]; // sign group name @@ -55,5 +54,4 @@ typedef enum { } SignType; - #endif // NVIM_SIGN_DEFS_H diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 9ed421c8a0..013cc1e594 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -634,7 +634,7 @@ static void find_word(matchinf_T *mip, int mode) if (byts[arridx] == 0) { if (endidxcnt == MAXWLEN) { // Must be a corrupted spell file. - EMSG(_(e_format)); + emsg(_(e_format)); return; } endlen[endidxcnt] = wlen; @@ -1386,7 +1386,7 @@ static bool no_spell_checking(win_T *wp) { if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL || GA_EMPTY(&wp->w_s->b_langp)) { - EMSG(_(e_no_spell)); + emsg(_(e_no_spell)); return true; } return false; @@ -1758,7 +1758,8 @@ void slang_free(slang_T *lp) } /// Frees a salitem_T -static void free_salitem(salitem_T *smp) { +static void free_salitem(salitem_T *smp) +{ xfree(smp->sm_lead); // Don't free sm_oneof and sm_rules, they point into sm_lead. xfree(smp->sm_to); @@ -1768,7 +1769,8 @@ static void free_salitem(salitem_T *smp) { } /// Frees a fromto_T -static void free_fromto(fromto_T *ftp) { +static void free_fromto(fromto_T *ftp) +{ xfree(ftp->ft_from); xfree(ftp->ft_to); } @@ -2036,7 +2038,7 @@ static int count_syllables(slang_T *slang, const char_u *word) // Parse 'spelllang' and set w_s->b_langp accordingly. // Returns NULL if it's OK, an error message otherwise. -char_u *did_set_spelllang(win_T *wp) +char *did_set_spelllang(win_T *wp) { garray_T ga; char_u *splp; @@ -2057,7 +2059,7 @@ char_u *did_set_spelllang(win_T *wp) bool nobreak = false; langp_T *lp, *lp2; static bool recursive = false; - char_u *ret_msg = NULL; + char *ret_msg = NULL; char_u *spl_copy; bufref_T bufref; @@ -2155,8 +2157,7 @@ char_u *did_set_spelllang(win_T *wp) // SpellFileMissing autocommands may do anything, including // destroying the buffer we are using... if (!bufref_valid(&bufref)) { - ret_msg = - (char_u *)N_("E797: SpellFileMissing autocommand deleted buffer"); + ret_msg = N_("E797: SpellFileMissing autocommand deleted buffer"); goto theend; } } @@ -2870,7 +2871,7 @@ void spell_suggest(int count) } if (*curwin->w_s->b_p_spl == NUL) { - EMSG(_(e_no_spell)); + emsg(_(e_no_spell)); return; } @@ -2933,7 +2934,7 @@ void spell_suggest(int count) true, need_cap, true); if (GA_EMPTY(&sug.su_ga)) { - MSG(_("Sorry, no suggestions")); + msg(_("Sorry, no suggestions")); } else if (count > 0) { if (count > sug.su_ga.ga_len) { smsg(_("Sorry, only %" PRId64 " suggestions"), @@ -3149,7 +3150,7 @@ void ex_spellrepall(exarg_T *eap) linenr_T prev_lnum = 0; if (repl_from == NULL || repl_to == NULL) { - EMSG(_("E752: No previous spell replacement")); + emsg(_("E752: No previous spell replacement")); return; } addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from)); @@ -3193,7 +3194,7 @@ void ex_spellrepall(exarg_T *eap) xfree(frompat); if (sub_nsubs == 0) { - EMSG2(_("E753: Not found: %s"), repl_from); + semsg(_("E753: Not found: %s"), repl_from); } else { do_sub_msg(false); } @@ -3404,7 +3405,7 @@ static void spell_suggest_file(suginfo_T *su, char_u *fname) // Open the file. fd = os_fopen((char *)fname, "r"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return; } @@ -3420,7 +3421,6 @@ static void spell_suggest_file(suginfo_T *su, char_u *fname) if (STRICMP(su->su_badword, line) == 0) { // Match! Isolate the good word, until CR or NL. for (len = 0; p[len] >= ' '; ++len) { - ; } p[len] = NUL; @@ -3813,7 +3813,6 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so if (sp->ts_prefixdepth == PFD_PREFIXTREE) { // Skip over the NUL bytes, we use them later. for (n = 0; n < len && byts[arridx + n] == 0; ++n) { - ; } sp->ts_curi += n; @@ -3888,7 +3887,6 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so n = stack[sp->ts_prefixdepth].ts_arridx; len = pbyts[n++]; for (c = 0; c < len && pbyts[n + c] == 0; ++c) { - ; } if (c > 0) { c = valid_word_prefix(c, n, flags, diff --git a/src/nvim/spell_defs.h b/src/nvim/spell_defs.h index 78aa6bf199..220f51cd2f 100644 --- a/src/nvim/spell_defs.h +++ b/src/nvim/spell_defs.h @@ -230,7 +230,7 @@ typedef enum { STATE_REP_INI, // Prepare for using REP items. STATE_REP, // Use matching REP items from the .aff file. STATE_REP_UNDO, // Undo a REP item replacement. - STATE_FINAL // End of this node. + STATE_FINAL, // End of this node. } state_T; // Struct to keep the state at each level in suggest_try_change(). diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index e3a6236ae4..cddf3fe855 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -549,7 +549,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, ; ); if (memcmp(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0) { return SP_FORMERROR; } @@ -584,7 +584,7 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile fd = os_fopen((char *)fname, "r"); if (fd == NULL) { if (!silent) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); } else if (p_verbose > 2) { verbose_enter(); smsg((char *)e_notopen, fname); @@ -619,10 +619,10 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile switch (scms_ret) { case SP_FORMERROR: case SP_TRUNCERROR: - emsgf("%s", _("E757: This does not look like a spell file")); + semsg("%s", _("E757: This does not look like a spell file")); goto endFAIL; case SP_OTHERERROR: - emsgf(_("E5042: Failed to read spell file %s: %s"), + semsg(_("E5042: Failed to read spell file %s: %s"), fname, strerror(ferror(fd))); goto endFAIL; case 0: @@ -630,10 +630,10 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile } c = getc(fd); // <versionnr> if (c < VIMSPELLVERSION) { - EMSG(_("E771: Old spell file, needs to be updated")); + emsg(_("E771: Old spell file, needs to be updated")); goto endFAIL; } else if (c > VIMSPELLVERSION) { - EMSG(_("E772: Spell file is for newer version of Vim")); + emsg(_("E772: Spell file is for newer version of Vim")); goto endFAIL; } @@ -742,7 +742,7 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile // Unsupported section. When it's required give an error // message. When it's not required skip the contents. if (c & SNF_REQUIRED) { - EMSG(_("E770: Unsupported section in spell file")); + emsg(_("E770: Unsupported section in spell file")); goto endFAIL; } while (--len >= 0) { @@ -754,12 +754,12 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile } someerror: if (res == SP_FORMERROR) { - EMSG(_(e_format)); + emsg(_(e_format)); goto endFAIL; } if (res == SP_TRUNCERROR) { truncerr: - EMSG(_(e_spell_trunc)); + emsg(_(e_spell_trunc)); goto endFAIL; } if (res == SP_OTHERERROR) { @@ -907,17 +907,17 @@ void suggest_load_files(void) buf[i] = getc(fd); // <fileID> } if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0) { - EMSG2(_("E778: This does not look like a .sug file: %s"), + semsg(_("E778: This does not look like a .sug file: %s"), slang->sl_fname); goto nextone; } c = getc(fd); // <versionnr> if (c < VIMSUGVERSION) { - EMSG2(_("E779: Old .sug file, needs to be updated: %s"), + semsg(_("E779: Old .sug file, needs to be updated: %s"), slang->sl_fname); goto nextone; } else if (c > VIMSUGVERSION) { - EMSG2(_("E780: .sug file is for newer version of Vim: %s"), + semsg(_("E780: .sug file is for newer version of Vim: %s"), slang->sl_fname); goto nextone; } @@ -926,7 +926,7 @@ void suggest_load_files(void) // the .spl file. Otherwise the word numbers won't match. timestamp = get8ctime(fd); // <timestamp> if (timestamp != slang->sl_sugtime) { - EMSG2(_("E781: .sug file doesn't match .spl file: %s"), + semsg(_("E781: .sug file doesn't match .spl file: %s"), slang->sl_fname); goto nextone; } @@ -936,7 +936,7 @@ void suggest_load_files(void) if (spell_read_tree(fd, &slang->sl_sbyts, NULL, &slang->sl_sidxs, false, 0) != 0) { someerror: - EMSG2(_("E782: error while reading .sug file: %s"), + semsg(_("E782: error while reading .sug file: %s"), slang->sl_fname); slang_clear_sug(slang); goto nextone; @@ -1030,7 +1030,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, ; ); lp->sl_regions[len] = NUL; return 0; } @@ -1097,7 +1097,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, ; ); buf[n + 1] = NUL; lp->sl_prefprog[i] = vim_regcomp((char_u *)buf, RE_MAGIC | RE_STRING); } @@ -2042,7 +2042,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) // Open the file. fd = os_fopen((char *)fname, "r"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return NULL; } @@ -2748,11 +2748,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) // Check that we didn't use too many renumbered flags. if (spin->si_newcompID < spin->si_newprefID) { if (spin->si_newcompID == 127 || spin->si_newcompID == 255) { - MSG(_("Too many postponed prefixes")); + msg(_("Too many postponed prefixes")); } else if (spin->si_newprefID == 0 || spin->si_newprefID == 127) { - MSG(_("Too many compound flags")); + msg(_("Too many compound flags")); } else { - MSG(_("Too many postponed prefixes and/or compound flags")); + msg(_("Too many postponed prefixes and/or compound flags")); } } @@ -3126,7 +3126,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) // Open the file. fd = os_fopen((char *)fname, "r"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return FAIL; } @@ -3142,7 +3142,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) // Read and ignore the first line: word count. if (vim_fgets(line, MAXLINELEN, fd) || !ascii_isdigit(*skipwhite(line))) { - EMSG2(_("E760: No word count in %s"), fname); + semsg(_("E760: No word count in %s"), fname); } // Read all the lines in the file one by one. @@ -3209,7 +3209,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) _("line %6d, word %6ld - %s"), lnum, spin->si_foldwcount + spin->si_keepwcount, w); msg_start(); - msg_puts_long_attr(message, 0); + msg_outtrans_long_attr(message, 0); msg_clr_eos(); msg_didout = false; msg_col = 0; @@ -3684,7 +3684,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) // Open the file. fd = os_fopen((char *)fname, "r"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return FAIL; } @@ -4352,7 +4352,7 @@ static int write_vim_spell(spellinfo_T *spin, char_u *fname) FILE *fd = os_fopen((char *)fname, "w"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return FAIL; } @@ -4723,7 +4723,7 @@ theend: retval = FAIL; } if (retval == FAIL) { - EMSG(_(e_write)); + emsg(_(e_write)); } return retval; @@ -4845,7 +4845,7 @@ static int put_node(FILE *fd, wordnode_T *node, int idx, int regionmask, bool pr if (fd != NULL) { if (putc(np->wn_byte, fd) == EOF) { // <byte> or <xbyte> - EMSG(_(e_write)); + emsg(_(e_write)); return 0; } } @@ -5164,13 +5164,13 @@ static int offset2bytes(int nr, char_u *buf) buf[3] = b1; return 4; } - if (b3 > 1 || b2 > 0x3f ) { // 3 bytes + if (b3 > 1 || b2 > 0x3f) { // 3 bytes buf[0] = 0xc0 + b3; buf[1] = b2; buf[2] = b1; return 3; } - if (b2 > 1 || b1 > 0x7f ) { // 2 bytes + if (b2 > 1 || b1 > 0x7f) { // 2 bytes buf[0] = 0x80 + b2; buf[1] = b1; return 2; @@ -5186,7 +5186,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) // Create the file. Note that an existing file is silently overwritten! FILE *fd = os_fopen((char *)fname, "w"); if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); return; } @@ -5196,7 +5196,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) // <SUGHEADER>: <fileID> <versionnr> <timestamp> if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) { // <fileID> - EMSG(_(e_write)); + emsg(_(e_write)); goto theend; } putc(VIMSUGVERSION, fd); // <versionnr> @@ -5234,7 +5234,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) char_u *line = ml_get_buf(spin->si_spellbuf, lnum, false); size_t len = STRLEN(line) + 1; if (fwrite(line, len, 1, fd) == 0) { - EMSG(_(e_write)); + emsg(_(e_write)); goto theend; } assert((size_t)spin->si_memtot + len <= INT_MAX); @@ -5243,7 +5243,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) // Write another byte to check for errors. if (putc(0, fd) == EOF) { - EMSG(_(e_write)); + emsg(_(e_write)); } vim_snprintf((char *)IObuff, IOSIZE, @@ -5331,20 +5331,20 @@ static void mkspell(int fcount, char_u **fnames, bool ascii, bool over_write, bo } if (incount <= 0) { - EMSG(_(e_invarg)); // need at least output and input names + emsg(_(e_invarg)); // need at least output and input names } else if (vim_strchr(path_tail(wfname), '_') != NULL) { - EMSG(_("E751: Output file name must not have region name")); + emsg(_("E751: Output file name must not have region name")); } else if (incount > MAXREGIONS) { - emsgf(_("E754: Only up to %d regions supported"), MAXREGIONS); + semsg(_("E754: Only up to %d regions supported"), MAXREGIONS); } else { // Check for overwriting before doing things that may take a lot of // time. if (!over_write && os_path_exists(wfname)) { - EMSG(_(e_exists)); + emsg(_(e_exists)); goto theend; } if (os_isdir(wfname)) { - EMSG2(_(e_isadir2), wfname); + semsg(_(e_isadir2), wfname); goto theend; } @@ -5359,7 +5359,7 @@ static void mkspell(int fcount, char_u **fnames, bool ascii, bool over_write, bo len = (int)STRLEN(innames[i]); if (STRLEN(path_tail(innames[i])) < 5 || innames[i][len - 3] != '_') { - EMSG2(_("E755: Invalid region in %s"), innames[i]); + semsg(_("E755: Invalid region in %s"), innames[i]); goto theend; } spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]); @@ -5417,7 +5417,7 @@ static void mkspell(int fcount, char_u **fnames, bool ascii, bool over_write, bo } if (spin.si_compflags != NULL && spin.si_nobreak) { - MSG(_("Warning: both compounding and NOBREAK specified")); + msg(_("Warning: both compounding and NOBREAK specified")); } if (!error && !got_int) { @@ -5487,7 +5487,7 @@ static void spell_message(const spellinfo_T *spin, char_u *str) if (!spin->si_verbose) { verbose_enter(); } - MSG(str); + msg((char *)str); ui_flush(); if (!spin->si_verbose) { verbose_leave(); @@ -5541,7 +5541,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo } if (*curwin->w_s->b_p_spf == NUL) { - EMSG2(_(e_notset), "spellfile"); + semsg(_(e_notset), "spellfile"); return; } fnamebuf = xmalloc(MAXPATHL); @@ -5552,7 +5552,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo break; } if (*spf == NUL) { - EMSGN(_("E765: 'spellfile' does not have %" PRId64 " entries"), idx); + semsg(_("E765: 'spellfile' does not have %" PRId64 " entries"), (int64_t)idx); xfree(fnamebuf); return; } @@ -5564,7 +5564,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo buf = NULL; } if (buf != NULL && bufIsChanged(buf)) { - EMSG(_(e_bufloaded)); + emsg(_(e_bufloaded)); xfree(fnamebuf); return; } @@ -5632,7 +5632,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo } if (fd == NULL) { - EMSG2(_(e_notopen), fname); + semsg(_(e_notopen), fname); } else { if (what == SPELL_ADD_BAD) { fprintf(fd, "%.*s/!\n", len, word); @@ -5778,7 +5778,7 @@ static int set_spell_finish(spelltab_T *new_st) || spelltab.st_isu[i] != new_st->st_isu[i] || spelltab.st_fold[i] != new_st->st_fold[i] || spelltab.st_upper[i] != new_st->st_upper[i]) { - EMSG(_("E763: Word characters differ between spell files")); + emsg(_("E763: Word characters differ between spell files")); return FAIL; } } @@ -5876,7 +5876,7 @@ static void set_map_str(slang_T *lp, char_u *map) } else { // This should have been checked when generating the .spl // file. - EMSG(_("E783: duplicate char in MAP entry")); + emsg(_("E783: duplicate char in MAP entry")); xfree(b); } } else { diff --git a/src/nvim/strings.c b/src/nvim/strings.c index 11c1aa1760..688ac548c0 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -557,7 +557,7 @@ static varnumber_T tv_nr(typval_T *tvs, int *idxp) varnumber_T n = 0; if (tvs[idx].v_type == VAR_UNKNOWN) { - EMSG(_(e_printf)); + emsg(_(e_printf)); } else { (*idxp)++; bool err = false; @@ -590,7 +590,7 @@ static const char *tv_str(typval_T *tvs, int *idxp, char **const tofree) const char *s = NULL; if (tvs[idx].v_type == VAR_UNKNOWN) { - EMSG(_(e_printf)); + emsg(_(e_printf)); } else { (*idxp)++; if (tvs[idx].v_type == VAR_STRING || tvs[idx].v_type == VAR_NUMBER) { @@ -627,7 +627,7 @@ static const void *tv_ptr(const typval_T *const tvs, int *const idxp) #undef OFF const int idx = *idxp - 1; if (tvs[idx].v_type == VAR_UNKNOWN) { - EMSG(_(e_printf)); + emsg(_(e_printf)); return NULL; } else { (*idxp)++; @@ -652,7 +652,7 @@ static float_T tv_float(typval_T *const tvs, int *const idxp) float_T f = 0; if (tvs[idx].v_type == VAR_UNKNOWN) { - EMSG(_(e_printf)); + emsg(_(e_printf)); } else { (*idxp)++; if (tvs[idx].v_type == VAR_FLOAT) { @@ -660,7 +660,7 @@ static float_T tv_float(typval_T *const tvs, int *const idxp) } else if (tvs[idx].v_type == VAR_NUMBER) { f = (float_T)tvs[idx].vval.v_number; } else { - EMSG(_("E807: Expected Float argument for printf()")); + emsg(_("E807: Expected Float argument for printf()")); } } return f; @@ -706,7 +706,7 @@ static float_T tv_float(typval_T *const tvs, int *const idxp) /// Append a formatted value to the string /// /// @see vim_vsnprintf_typval(). -int vim_snprintf_add(char *str, size_t str_m, char *fmt, ...) +int vim_snprintf_add(char *str, size_t str_m, const char *fmt, ...) FUNC_ATTR_PRINTF(3, 4) { const size_t len = strlen(str); @@ -1184,7 +1184,7 @@ int vim_vsnprintf_typval(char *str, size_t str_m, const char *fmt, va_list ap, t zero_padding_insertion_ind++; } if (zero_padding_insertion_ind + 1 < str_arg_l - && tmp[zero_padding_insertion_ind] == '0' + && tmp[zero_padding_insertion_ind] == '0' && (tmp[zero_padding_insertion_ind + 1] == 'x' || tmp[zero_padding_insertion_ind + 1] == 'X' || tmp[zero_padding_insertion_ind + 1] == 'b' @@ -1456,7 +1456,7 @@ int vim_vsnprintf_typval(char *str, size_t str_m, const char *fmt, va_list ap, t } if (tvs && tvs[arg_idx - 1].v_type != VAR_UNKNOWN) { - EMSG(_("E767: Too many arguments to printf()")); + emsg(_("E767: Too many arguments to printf()")); } // return the number of characters formatted (excluding trailing nul diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index b194620b53..d134870138 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -1082,7 +1082,6 @@ static void syn_stack_alloc(void) // Make sure that all valid entries fit in the new array. while (syn_block->b_sst_len - syn_block->b_sst_freecount + 2 > len && syn_stack_cleanup()) { - ; } if (len < syn_block->b_sst_len - syn_block->b_sst_freecount + 2) { len = syn_block->b_sst_len - syn_block->b_sst_freecount + 2; @@ -3006,7 +3005,7 @@ static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T } if (timed_out && !syn_win->w_s->b_syn_slow) { syn_win->w_s->b_syn_slow = true; - MSG(_("'redrawtime' exceeded, syntax highlighting disabled")); + msg(_("'redrawtime' exceeded, syntax highlighting disabled")); } if (r > 0) { @@ -3111,16 +3110,16 @@ static void syn_cmd_conceal(exarg_T *eap, int syncing) next = skiptowhite(arg); if (*arg == NUL) { if (curwin->w_s->b_syn_conceal) { - MSG(_("syntax conceal on")); + msg(_("syntax conceal on")); } else { - MSG(_("syntax conceal off")); + msg(_("syntax conceal off")); } } else if (STRNICMP(arg, "on", 2) == 0 && next - arg == 2) { curwin->w_s->b_syn_conceal = true; } else if (STRNICMP(arg, "off", 3) == 0 && next - arg == 3) { curwin->w_s->b_syn_conceal = false; } else { - EMSG2(_(e_illegal_arg), arg); + semsg(_(e_illegal_arg), arg); } } @@ -3140,16 +3139,16 @@ static void syn_cmd_case(exarg_T *eap, int syncing) next = skiptowhite(arg); if (*arg == NUL) { if (curwin->w_s->b_syn_ic) { - MSG(_("syntax case ignore")); + msg(_("syntax case ignore")); } else { - MSG(_("syntax case match")); + msg(_("syntax case match")); } } else if (STRNICMP(arg, "match", 5) == 0 && next - arg == 5) { curwin->w_s->b_syn_ic = false; } else if (STRNICMP(arg, "ignore", 6) == 0 && next - arg == 6) { curwin->w_s->b_syn_ic = true; } else { - EMSG2(_(e_illegal_arg), arg); + semsg(_(e_illegal_arg), arg); } } @@ -3167,9 +3166,9 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) if (*arg == NUL) { switch (curwin->w_s->b_syn_foldlevel) { case SYNFLD_START: - MSG(_("syntax foldlevel start")); break; + msg(_("syntax foldlevel start")); break; case SYNFLD_MINIMUM: - MSG(_("syntax foldlevel minimum")); break; + msg(_("syntax foldlevel minimum")); break; default: break; } @@ -3182,13 +3181,13 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) } else if (STRNICMP(arg, "minimum", 7) == 0 && arg_end - arg == 7) { curwin->w_s->b_syn_foldlevel = SYNFLD_MINIMUM; } else { - EMSG2(_(e_illegal_arg), arg); + semsg(_(e_illegal_arg), arg); return; } arg = skipwhite(arg_end); if (*arg != NUL) { - EMSG2(_(e_illegal_arg), arg); + semsg(_(e_illegal_arg), arg); } } @@ -3208,11 +3207,11 @@ static void syn_cmd_spell(exarg_T *eap, int syncing) next = skiptowhite(arg); if (*arg == NUL) { if (curwin->w_s->b_syn_spell == SYNSPL_TOP) { - MSG(_("syntax spell toplevel")); + msg(_("syntax spell toplevel")); } else if (curwin->w_s->b_syn_spell == SYNSPL_NOTOP) { - MSG(_("syntax spell notoplevel")); + msg(_("syntax spell notoplevel")); } else { - MSG(_("syntax spell default")); + msg(_("syntax spell default")); } } else if (STRNICMP(arg, "toplevel", 8) == 0 && next - arg == 8) { curwin->w_s->b_syn_spell = SYNSPL_TOP; @@ -3221,7 +3220,7 @@ static void syn_cmd_spell(exarg_T *eap, int syncing) } else if (STRNICMP(arg, "default", 7) == 0 && next - arg == 7) { curwin->w_s->b_syn_spell = SYNSPL_DEFAULT; } else { - EMSG2(_(e_illegal_arg), arg); + semsg(_(e_illegal_arg), arg); return; } @@ -3242,9 +3241,9 @@ static void syn_cmd_iskeyword(exarg_T *eap, int syncing) arg = skipwhite(arg); if (*arg == NUL) { - MSG_PUTS("\n"); + msg_puts("\n"); if (curwin->w_s->b_syn_isk != empty_option) { - MSG_PUTS(_("syntax iskeyword ")); + msg_puts(_("syntax iskeyword ")); msg_outtrans(curwin->w_s->b_syn_isk); } else { msg_outtrans((char_u *)_("syntax iskeyword not set")); @@ -3445,7 +3444,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) if (*arg == '@') { id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { - EMSG2(_("E391: No such syntax cluster: %s"), arg); + semsg(_("E391: No such syntax cluster: %s"), arg); break; } else { // We can't physically delete a cluster without changing @@ -3458,7 +3457,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) } else { id = syn_name2id_len(arg, (int)(arg_end - arg)); if (id == 0) { - EMSG2(_(e_nogroup), arg); + semsg(_(e_nogroup), arg); break; } else { syn_clear_one(id, syncing); @@ -3567,41 +3566,41 @@ static void syn_cmd_list(exarg_T *eap, int syncing) } if (!syntax_present(curwin)) { - MSG(_(msg_no_items)); + msg(_(msg_no_items)); return; } if (syncing) { if (curwin->w_s->b_syn_sync_flags & SF_CCOMMENT) { - MSG_PUTS(_("syncing on C-style comments")); + msg_puts(_("syncing on C-style comments")); syn_lines_msg(); syn_match_msg(); return; } else if (!(curwin->w_s->b_syn_sync_flags & SF_MATCH)) { if (curwin->w_s->b_syn_sync_minlines == 0) { - MSG_PUTS(_("no syncing")); + msg_puts(_("no syncing")); } else { if (curwin->w_s->b_syn_sync_minlines == MAXLNUM) { - MSG_PUTS(_("syncing starts at the first line")); + msg_puts(_("syncing starts at the first line")); } else { - MSG_PUTS(_("syncing starts ")); + msg_puts(_("syncing starts ")); msg_outnum(curwin->w_s->b_syn_sync_minlines); - MSG_PUTS(_(" lines before top line")); + msg_puts(_(" lines before top line")); } syn_match_msg(); } return; } - MSG_PUTS_TITLE(_("\n--- Syntax sync items ---")); + msg_puts_title(_("\n--- Syntax sync items ---")); if (curwin->w_s->b_syn_sync_minlines > 0 || curwin->w_s->b_syn_sync_maxlines > 0 || curwin->w_s->b_syn_sync_linebreaks > 0) { - MSG_PUTS(_("\nsyncing on items")); + msg_puts(_("\nsyncing on items")); syn_lines_msg(); syn_match_msg(); } } else { - MSG_PUTS_TITLE(_("\n--- Syntax items ---")); + msg_puts_title(_("\n--- Syntax items ---")); } if (ends_excmd(*arg)) { /* @@ -3622,14 +3621,14 @@ static void syn_cmd_list(exarg_T *eap, int syncing) if (*arg == '@') { int id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { - EMSG2(_("E392: No such syntax cluster: %s"), arg); + semsg(_("E392: No such syntax cluster: %s"), arg); } else { syn_list_cluster(id - SYNID_CLUSTER); } } else { int id = syn_name2id_len(arg, (int)(arg_end - arg)); if (id == 0) { - EMSG2(_(e_nogroup), arg); + semsg(_(e_nogroup), arg); } else { syn_list_one(id, syncing, true); } @@ -3644,22 +3643,22 @@ static void syn_lines_msg(void) { if (curwin->w_s->b_syn_sync_maxlines > 0 || curwin->w_s->b_syn_sync_minlines > 0) { - MSG_PUTS("; "); + msg_puts("; "); if (curwin->w_s->b_syn_sync_minlines == MAXLNUM) { - MSG_PUTS(_("from the first line")); + msg_puts(_("from the first line")); } else { if (curwin->w_s->b_syn_sync_minlines > 0) { - MSG_PUTS(_("minimal ")); + msg_puts(_("minimal ")); msg_outnum(curwin->w_s->b_syn_sync_minlines); if (curwin->w_s->b_syn_sync_maxlines) { - MSG_PUTS(", "); + msg_puts(", "); } } if (curwin->w_s->b_syn_sync_maxlines > 0) { - MSG_PUTS(_("maximal ")); + msg_puts(_("maximal ")); msg_outnum(curwin->w_s->b_syn_sync_maxlines); } - MSG_PUTS(_(" lines before top line")); + msg_puts(_(" lines before top line")); } } } @@ -3667,9 +3666,9 @@ static void syn_lines_msg(void) static void syn_match_msg(void) { if (curwin->w_s->b_syn_sync_linebreaks > 0) { - MSG_PUTS(_("; match ")); + msg_puts(_("; match ")); msg_outnum(curwin->w_s->b_syn_sync_linebreaks); - MSG_PUTS(_(" line breaks")); + msg_puts(_(" line breaks")); } } @@ -3768,7 +3767,7 @@ static void syn_list_one(const int id, const bool syncing, const bool link_only) msg_outtrans(HL_TABLE()[SYN_ITEMS(curwin->w_s) [spp->sp_sync_idx].sp_syn.id - 1].sg_name); } else { - MSG_PUTS("NONE"); + msg_puts("NONE"); } msg_putchar(' '); } @@ -4230,7 +4229,7 @@ static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_cha if (flagtab[fidx].argtype == 1) { if (!opt->has_cont_list) { - EMSG(_("E395: contains argument not accepted here")); + emsg(_("E395: contains argument not accepted here")); return NULL; } if (get_id_list(&arg, 8, &opt->cont_list, skip) == FAIL) { @@ -4249,7 +4248,7 @@ static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_cha *conceal_char = utf_ptr2char(arg + 6); arg += mb_ptr2len(arg + 6) - 1; if (!vim_isprintc_strict(*conceal_char)) { - EMSG(_("E844: invalid cchar value")); + emsg(_("E844: invalid cchar value")); return NULL; } arg = skipwhite(arg + 7); @@ -4260,7 +4259,7 @@ static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_cha if (flagtab[fidx].flags == HL_SYNC_HERE || flagtab[fidx].flags == HL_SYNC_THERE) { if (opt->sync_idx == NULL) { - EMSG(_("E393: group[t]here not accepted here")); + emsg(_("E393: group[t]here not accepted here")); return NULL; } gname_start = arg; @@ -4282,7 +4281,7 @@ static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_cha } } if (i < 0) { - EMSG2(_("E394: Didn't find region item for %s"), gname); + semsg(_("E394: Didn't find region item for %s"), gname); xfree(gname); return NULL; } @@ -4333,7 +4332,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) int sgl_id = 1; char_u *group_name_end; char_u *rest; - char_u *errormsg = NULL; + char *errormsg = NULL; int prev_toplvl_grp; int prev_syn_inc_tag; bool source = false; @@ -4347,7 +4346,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) ++arg; rest = get_group_name(arg, &group_name_end); if (rest == NULL) { - EMSG((char_u *)_("E397: Filename required")); + emsg(_("E397: Filename required")); return; } sgl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); @@ -4371,7 +4370,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) source = true; if (expand_filename(eap, syn_cmdlinep, &errormsg) == FAIL) { if (errormsg != NULL) { - EMSG(errormsg); + emsg(errormsg); } return; } @@ -4382,7 +4381,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) * include" tag around the actual inclusion. */ if (running_syn_inc_tag >= MAX_SYN_INC_TAG) { - EMSG((char_u *)_("E847: Too many syntax includes")); + emsg(_("E847: Too many syntax includes")); return; } prev_syn_inc_tag = current_syn_inc_tag; @@ -4392,7 +4391,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) if (source ? do_source((char *)eap->arg, false, DOSO_NONE) == FAIL : source_runtime((char *)eap->arg, DIP_ALL) == FAIL) { - EMSG2(_(e_notopen), eap->arg); + semsg(_(e_notopen), eap->arg); } curwin->w_s->b_syn_topgrp = prev_toplvl_grp; current_syn_inc_tag = prev_syn_inc_tag; @@ -4472,12 +4471,12 @@ static void syn_cmd_keyword(exarg_T *eap, int syncing) break; } if (p[1] == NUL) { - emsgf(_("E789: Missing ']': %s"), kw); + semsg(_("E789: Missing ']': %s"), kw); goto error; } if (p[1] == ']') { if (p[2] != NUL) { - emsgf(_("E890: trailing char after ']': %s]%s"), + semsg(_("E890: trailing char after ']': %s]%s"), kw, &p[2]); goto error; } @@ -4502,7 +4501,7 @@ error: if (rest != NULL) { eap->nextcmd = check_nextcmd(rest); } else { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } redraw_curbuf_later(SOME_VALID); @@ -4604,7 +4603,7 @@ static void syn_cmd_match(exarg_T *eap, int syncing) xfree(syn_opt_arg.next_list); if (rest == NULL) { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } } @@ -4692,7 +4691,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) rest = skipwhite(key_end); if (*rest != '=') { rest = NULL; - EMSG2(_("E398: Missing '=': %s"), arg); + semsg(_("E398: Missing '=': %s"), arg); break; } rest = skipwhite(rest + 1); @@ -4831,9 +4830,9 @@ static void syn_cmd_region(exarg_T *eap, int syncing) xfree(syn_opt_arg.cont_in_list); xfree(syn_opt_arg.next_list); if (not_enough) { - EMSG2(_("E399: Not enough arguments: syntax region %s"), arg); + semsg(_("E399: Not enough arguments: syntax region %s"), arg); } else if (illegal || rest == NULL) { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } } } @@ -5030,7 +5029,7 @@ static int syn_add_cluster(char_u *name) int len = curwin->w_s->b_syn_clusters.ga_len; if (len >= MAX_CLUSTER_ID) { - EMSG((char_u *)_("E848: Too many syntax clusters")); + emsg(_("E848: Too many syntax clusters")); xfree(name); return 0; } @@ -5098,7 +5097,7 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) int16_t *clstr_list = NULL; if (get_id_list(&rest, opt_len, &clstr_list, eap->skip) == FAIL) { - EMSG2(_(e_invarg2), rest); + semsg(_(e_invarg2), rest); break; } if (scl_id >= 0) { @@ -5117,10 +5116,10 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) } if (!got_clstr) { - EMSG(_("E400: No cluster specified")); + emsg(_("E400: No cluster specified")); } if (rest == NULL || !ends_excmd(*rest)) { - EMSG2(_(e_invarg2), arg); + semsg(_(e_invarg2), arg); } } @@ -5152,7 +5151,7 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) end = skip_regexp(arg + 1, *arg, TRUE, NULL); if (*end != *arg) { // end delimiter not found - EMSG2(_("E401: Pattern delimiter not found: %s"), arg); + semsg(_("E401: Pattern delimiter not found: %s"), arg); return NULL; } // store the pattern and compiled regexp program @@ -5224,7 +5223,7 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) } while (idx >= 0); if (!ends_excmd(*end) && !ascii_iswhite(*end)) { - EMSG2(_("E402: Garbage after pattern: %s"), arg); + semsg(_("E402: Garbage after pattern: %s"), arg); return NULL; } return skipwhite(end); @@ -5303,7 +5302,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) break; } if (curwin->w_s->b_syn_linecont_pat != NULL) { - EMSG(_("E403: syntax sync: line continuations pattern specified twice")); + emsg(_("E403: syntax sync: line continuations pattern specified twice")); finished = TRUE; break; } @@ -5352,7 +5351,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) } xfree(key); if (illegal) { - EMSG2(_("E404: Illegal arguments: %s"), arg_start); + semsg(_("E404: Illegal arguments: %s"), arg_start); } else if (!finished) { eap->nextcmd = check_nextcmd(arg_start); redraw_curbuf_later(SOME_VALID); @@ -5388,12 +5387,12 @@ static int get_id_list(char_u **const arg, const int keylen, int16_t **const lis // skip "contains" p = skipwhite(*arg + keylen); if (*p != '=') { - EMSG2(_("E405: Missing equal sign: %s"), *arg); + semsg(_("E405: Missing equal sign: %s"), *arg); break; } p = skipwhite(p + 1); if (ends_excmd(*p)) { - EMSG2(_("E406: Empty argument: %s"), *arg); + semsg(_("E406: Empty argument: %s"), *arg); break; } @@ -5409,13 +5408,13 @@ static int get_id_list(char_u **const arg, const int keylen, int16_t **const lis || STRCMP(name + 1, "TOP") == 0 || STRCMP(name + 1, "CONTAINED") == 0) { if (TOUPPER_ASC(**arg) != 'C') { - EMSG2(_("E407: %s not allowed here"), name + 1); + semsg(_("E407: %s not allowed here"), name + 1); failed = true; xfree(name); break; } if (count != 0) { - EMSG2(_("E408: %s must be first in contains list"), + semsg(_("E408: %s must be first in contains list"), name + 1); failed = true; xfree(name); @@ -5480,7 +5479,7 @@ static int get_id_list(char_u **const arg, const int keylen, int16_t **const lis } xfree(name); if (id == 0) { - EMSG2(_("E409: Unknown group name: %s"), p); + semsg(_("E409: Unknown group name: %s"), p); failed = true; break; } @@ -5698,7 +5697,7 @@ void ex_syntax(exarg_T *eap) } for (int i = 0;; i++) { if (subcommands[i].name == NULL) { - EMSG2(_("E410: Invalid :syntax subcommand: %s"), subcmd_name); + semsg(_("E410: Invalid :syntax subcommand: %s"), subcmd_name); break; } if (STRCMP(subcmd_name, (char_u *)subcommands[i].name) == 0) { @@ -5770,7 +5769,7 @@ static enum { EXP_SUBCMD, // expand ":syn" sub-commands EXP_CASE, // expand ":syn case" arguments EXP_SPELL, // expand ":syn spell" arguments - EXP_SYNC // expand ":syn sync" arguments + EXP_SYNC, // expand ":syn sync" arguments } expand_what; /* @@ -6003,7 +6002,7 @@ void ex_syntime(exarg_T *eap) } else if (STRCMP(eap->arg, "report") == 0) { syntime_report(); } else { - EMSG2(_(e_invarg2), eap->arg); + semsg(_(e_invarg2), eap->arg); } } @@ -6023,7 +6022,7 @@ static void syntime_clear(void) synpat_T *spp; if (!syntax_present(curwin)) { - MSG(_(msg_no_items)); + msg(_(msg_no_items)); return; } for (int idx = 0; idx < curwin->w_s->b_syn_patterns.ga_len; ++idx) { @@ -6065,7 +6064,7 @@ static int syn_compare_syntime(const void *v1, const void *v2) static void syntime_report(void) { if (!syntax_present(curwin)) { - MSG(_(msg_no_items)); + msg(_(msg_no_items)); return; } @@ -6099,28 +6098,28 @@ static void syntime_report(void) syn_compare_syntime); } - MSG_PUTS_TITLE(_(" TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN")); - MSG_PUTS("\n"); + msg_puts_title(_(" TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN")); + msg_puts("\n"); for (int idx = 0; idx < ga.ga_len && !got_int; ++idx) { p = ((time_entry_T *)ga.ga_data) + idx; - MSG_PUTS(profile_msg(p->total)); - MSG_PUTS(" "); // make sure there is always a separating space + msg_puts(profile_msg(p->total)); + msg_puts(" "); // make sure there is always a separating space msg_advance(13); msg_outnum(p->count); - MSG_PUTS(" "); + msg_puts(" "); msg_advance(20); msg_outnum(p->match); - MSG_PUTS(" "); + msg_puts(" "); msg_advance(26); - MSG_PUTS(profile_msg(p->slowest)); - MSG_PUTS(" "); + msg_puts(profile_msg(p->slowest)); + msg_puts(" "); msg_advance(38); - MSG_PUTS(profile_msg(p->average)); - MSG_PUTS(" "); + msg_puts(profile_msg(p->average)); + msg_puts(" "); msg_advance(50); msg_outtrans(HL_TABLE()[p->id - 1].sg_name); - MSG_PUTS(" "); + msg_puts(" "); msg_advance(69); int len; @@ -6133,15 +6132,15 @@ static void syntime_report(void) len = (int)STRLEN(p->pattern); } msg_outtrans_len(p->pattern, len); - MSG_PUTS("\n"); + msg_puts("\n"); } ga_clear(&ga); if (!got_int) { - MSG_PUTS("\n"); - MSG_PUTS(profile_msg(total_total)); + msg_puts("\n"); + msg_puts(profile_msg(total_total)); msg_advance(13); msg_outnum(total_count); - MSG_PUTS("\n"); + msg_puts("\n"); } } @@ -6776,7 +6775,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (!doclear && !dolink && ends_excmd((uint8_t)(*linep))) { id = syn_name2id_len((const char_u *)line, (int)(name_end - line)); if (id == 0) { - emsgf(_("E411: highlight group not found: %s"), line); + semsg(_("E411: highlight group not found: %s"), line); } else { highlight_list_one(id); } @@ -6799,13 +6798,13 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (ends_excmd((uint8_t)(*from_start)) || ends_excmd((uint8_t)(*to_start))) { - emsgf(_("E412: Not enough arguments: \":highlight link %s\""), + semsg(_("E412: Not enough arguments: \":highlight link %s\""), from_start); return; } if (!ends_excmd(*skipwhite((const char_u *)to_end))) { - emsgf(_("E413: Too many arguments: \":highlight link %s\""), from_start); + semsg(_("E413: Too many arguments: \":highlight link %s\""), from_start); return; } @@ -6831,7 +6830,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (to_id > 0 && !forceit && !init && hl_has_settings(from_id - 1, dodefault)) { if (sourcing_name == NULL && !dodefault) { - EMSG(_("E414: group has settings, highlight link ignored")); + emsg(_("E414: group has settings, highlight link ignored")); } } else if (hlgroup->sg_link != to_id || hlgroup->sg_script_ctx.sc_sid != current_sctx.sc_sid @@ -6903,7 +6902,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) while (!ends_excmd((uint8_t)(*linep))) { key_start = linep; if (*linep == '=') { - emsgf(_("E415: unexpected equal sign: %s"), key_start); + semsg(_("E415: unexpected equal sign: %s"), key_start); error = true; break; } @@ -6930,7 +6929,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) // Check for the equal sign. if (*linep != '=') { - emsgf(_("E416: missing equal sign: %s"), key_start); + semsg(_("E416: missing equal sign: %s"), key_start); error = true; break; } @@ -6942,7 +6941,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) arg_start = ++linep; linep = strchr(linep, '\''); if (linep == NULL) { - emsgf(_(e_invarg2), key_start); + semsg(_(e_invarg2), key_start); error = true; break; } @@ -6951,7 +6950,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) linep = (const char *)skiptowhite((const char_u *)linep); } if (linep == arg_start) { - emsgf(_("E417: missing argument: %s"), key_start); + semsg(_("E417: missing argument: %s"), key_start); error = true; break; } @@ -6978,7 +6977,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) } } if (i < 0) { - emsgf(_("E418: Illegal value: %s"), arg); + semsg(_("E418: Illegal value: %s"), arg); error = true; break; } @@ -7026,7 +7025,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (cterm_normal_fg_color) { color = cterm_normal_fg_color - 1; } else { - EMSG(_("E419: FG color unknown")); + emsg(_("E419: FG color unknown")); error = true; break; } @@ -7034,7 +7033,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (cterm_normal_bg_color > 0) { color = cterm_normal_bg_color - 1; } else { - EMSG(_("E420: BG color unknown")); + emsg(_("E420: BG color unknown")); error = true; break; } @@ -7048,7 +7047,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) } } if (i < 0) { - emsgf(_("E421: Color name or number not recognized: %s"), + semsg(_("E421: Color name or number not recognized: %s"), key_start); error = true; break; @@ -7181,7 +7180,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) HL_TABLE()[idx].sg_blend = -1; } } else { - emsgf(_("E423: Illegal argument: %s"), key_start); + semsg(_("E423: Illegal argument: %s"), key_start); error = true; break; } @@ -7417,8 +7416,8 @@ static bool highlight_list_arg(const int id, bool didh, const int type, int iarg didh = true; if (!got_int) { if (*name != NUL) { - MSG_PUTS_ATTR(name, HL_ATTR(HLF_D)); - MSG_PUTS_ATTR("=", HL_ATTR(HLF_D)); + msg_puts_attr(name, HL_ATTR(HLF_D)); + msg_puts_attr("=", HL_ATTR(HLF_D)); } msg_outtrans((char_u *)ts); } @@ -7699,14 +7698,14 @@ static int syn_add_group(char_u *name) // Check that the name is ASCII letters, digits and underscore. for (p = name; *p != NUL; ++p) { if (!vim_isprintc(*p)) { - EMSG(_("E669: Unprintable character in group name")); + emsg(_("E669: Unprintable character in group name")); xfree(name); return 0; } else if (!ASCII_ISALNUM(*p) && *p != '_') { /* This is an error, but since there previously was no check only * give a warning. */ msg_source(HL_ATTR(HLF_W)); - MSG(_("W18: Invalid character in group name")); + msg(_("W18: Invalid character in group name")); break; } } @@ -7720,7 +7719,7 @@ static int syn_add_group(char_u *name) } if (highlight_ga.ga_len >= MAX_HL_ID) { - EMSG(_("E849: Too many highlight and syntax groups")); + emsg(_("E849: Too many highlight and syntax groups")); xfree(name); return 0; } @@ -7771,8 +7770,6 @@ int syn_id2attr(int hl_id) } - - /* * Translate a group ID to the final group ID (following links). */ diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 94f51c3b24..673ebc2668 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -178,7 +178,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) static int flags; if (tfu_in_use) { - EMSG(_(recurmsg)); + emsg(_(recurmsg)); return false; } @@ -271,14 +271,14 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : tagstacklen == 0) { // empty stack - EMSG(_(e_tagstack)); + emsg(_(e_tagstack)); goto end_do_tag; } if (type == DT_POP) { // go to older position const bool old_KeyTyped = KeyTyped; if ((tagstackidx -= count) < 0) { - EMSG(_(bottommsg)); + emsg(_(bottommsg)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; @@ -288,7 +288,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) { // count == 0? - EMSG(_(topmsg)); + emsg(_(topmsg)); goto end_do_tag; } @@ -342,10 +342,10 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) * position. */ tagstackidx = tagstacklen - 1; - EMSG(_(topmsg)); + emsg(_(topmsg)); save_pos = false; } else if (tagstackidx < 0) { // must have been count == 0 - EMSG(_(bottommsg)); + emsg(_(bottommsg)); tagstackidx = 0; goto end_do_tag; } @@ -383,7 +383,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) if (cur_match >= MAXCOL) { cur_match = MAXCOL - 1; } else if (cur_match < 0) { - EMSG(_("E425: Cannot go before first matching tag")); + emsg(_("E425: Cannot go before first matching tag")); skip_msg = true; cur_match = 0; cur_fnum = curbuf->b_fnum; @@ -519,7 +519,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) if (num_matches <= 0) { if (verbose) { - EMSG2(_("E426: tag not found: %s"), name); + semsg(_("E426: tag not found: %s"), name); } g_do_tagpreview = 0; } else { @@ -562,13 +562,13 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. - // There will be an EMSG("file doesn't exist") below then. + // There will be an emsg("file doesn't exist") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) { - EMSG(_("E427: There is only one matching tag")); + emsg(_("E427: There is only one matching tag")); } else { - EMSG(_("E428: Cannot go beyond last matching tag")); + emsg(_("E428: Cannot go beyond last matching tag")); } skip_msg = true; } @@ -596,7 +596,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) /* * Only when going to try the next match, report that the previous - * file didn't exist. Otherwise an EMSG() is given below. + * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) { smsg(_("File \"%s\" does not exist"), nofile_fname); @@ -621,7 +621,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) if (ic) { msg_attr((const char *)IObuff, HL_ATTR(HLF_W)); } else { - msg(IObuff); + msg((char *)IObuff); } msg_scroll = true; // Don't overwrite this message. } else { @@ -663,7 +663,7 @@ int do_tag(char_u *tag, int type, int count, int forceit, int verbose) } continue; } - EMSG2(_("E429: File \"%s\" does not exist"), nofile_fname); + semsg(_("E429: File \"%s\" does not exist"), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. @@ -1038,7 +1038,7 @@ void do_tags(exarg_T *eap) int tagstacklen = curwin->w_tagstacklen; // Highlight title - MSG_PUTS_TITLE(_("\n # TO tag FROM line in file/text")); + msg_puts_title(_("\n # TO tag FROM line in file/text")); for (i = 0; i < tagstacklen; ++i) { if (tagstack[i].tagname != NULL) { name = fm_getname(&(tagstack[i].fmark), 30); @@ -1061,12 +1061,11 @@ void do_tags(exarg_T *eap) ui_flush(); // show one line at a time } if (tagstackidx == tagstacklen) { // idx at top of stack - MSG_PUTS("\n>"); + msg_puts("\n>"); } } - /* * Compare two strings, for length "len", ignoring case the ASCII way. * return 0 for match, < 0 for smaller, > 0 for bigger @@ -1197,7 +1196,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl } if (rettv.v_type != VAR_LIST || !rettv.vval.v_list) { tv_clear(&rettv); - EMSG(_(tfu_inv_ret_msg)); + emsg(_(tfu_inv_ret_msg)); return FAIL; } taglist = rettv.vval.v_list; @@ -1211,7 +1210,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl int name_only = flags & TAG_NAMES; if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT) { - EMSG(_(tfu_inv_ret_msg)); + emsg(_(tfu_inv_ret_msg)); break; } @@ -1257,7 +1256,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl } if (!res_name || !res_fname || !res_cmd) { - EMSG(_(tfu_inv_ret_msg)); + emsg(_(tfu_inv_ret_msg)); break; } @@ -1404,7 +1403,7 @@ int find_tags(char_u *pat, int *num_matches, char_u ***matchesp, int flags, int TS_LINEAR, // linear searching forward, till EOF TS_BINARY, // binary searching TS_SKIP_BACK, // skipping backwards - TS_STEP_FORWARD // stepping forwards + TS_STEP_FORWARD, // stepping forwards } state; // Current search state int cmplen; @@ -1757,7 +1756,6 @@ line_read_in: } - /* * When still at the start of the file, check for Emacs tags file * format, and for "not sorted" flag. @@ -2195,9 +2193,9 @@ parse_line: } // forever if (line_error) { - EMSG2(_("E431: Format error in tags file \"%s\""), tag_fname); + semsg(_("E431: Format error in tags file \"%s\""), tag_fname); if (!use_cscope) { - EMSGN(_("Before byte %" PRId64), vim_ftell(fp)); + semsg(_("Before byte %" PRId64), (int64_t)vim_ftell(fp)); } stop_searching = true; line_error = false; @@ -2212,7 +2210,7 @@ parse_line: tag_file_sorted = NUL; if (sort_error) { - EMSG2(_("E432: Tags file not sorted: %s"), tag_fname); + semsg(_("E432: Tags file not sorted: %s"), tag_fname); sort_error = false; } @@ -2246,7 +2244,7 @@ parse_line: if (!stop_searching) { if (!did_open && verbose) { // never opened any tags file - EMSG(_("E433: No tags file")); + emsg(_("E433: No tags file")); } retval = OK; // It's OK even when no tag found } @@ -2883,7 +2881,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) *tagp.tagname_end = cc; } if (found == 0) { - EMSG(_("E434: Can't find tag pattern")); + emsg(_("E434: Can't find tag pattern")); curwin->w_cursor.lnum = save_lnum; } else { /* @@ -2891,7 +2889,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) * is set and match found while ignoring case. */ if (found == 2 || !save_p_ic) { - MSG(_("E435: Couldn't find tag, just guessing!")); + msg(_("E435: Couldn't find tag, just guessing!")); if (!msg_scrolled && msg_silent == 0) { ui_flush(); os_delay(1010L, true); @@ -3456,13 +3454,13 @@ int set_tagstack(win_T *wp, const dict_T *d, int action) // not allowed to alter the tag stack entries from inside tagfunc if (tfu_in_use) { - EMSG(_(recurmsg)); + emsg(_(recurmsg)); return FAIL; } if ((di = tv_dict_find(d, "items", -1)) != NULL) { if (di->di_tv.v_type != VAR_LIST) { - EMSG(_(e_listreq)); + emsg(_(e_listreq)); return FAIL; } l = di->di_tv.vval.v_list; diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c index fb025265f2..13005b263e 100644 --- a/src/nvim/terminal.c +++ b/src/nvim/terminal.c @@ -725,7 +725,7 @@ void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr, int *te int attr_id = 0; - if (hl_attrs ||!fg_default || !bg_default) { + if (hl_attrs || !fg_default || !bg_default) { attr_id = hl_get_term_attr(&(HlAttrs) { .cterm_ae_attr = (int16_t)hl_attrs, .cterm_fg_color = vt_fg_idx, diff --git a/src/nvim/testdir/test_diffmode.vim b/src/nvim/testdir/test_diffmode.vim index 32cee7ca56..61da3cbcaa 100644 --- a/src/nvim/testdir/test_diffmode.vim +++ b/src/nvim/testdir/test_diffmode.vim @@ -984,6 +984,9 @@ func Test_diff_with_scroll_and_change() call term_sendkeys(buf, "ax\<Esc>") call VerifyScreenDump(buf, 'Test_diff_scroll_change_02', {}) + call term_sendkeys(buf, "\<C-W>lay\<Esc>") + call VerifyScreenDump(buf, 'Test_diff_scroll_change_03', {}) + " clean up call StopVimInTerminal(buf) call delete('Xtest_scroll_change') diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index ec277f7a4e..5bb6059fa7 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -151,7 +151,7 @@ static void tinput_paste_event(void **argv) Error err = ERROR_INIT; nvim_paste(keys, true, phase, &err); if (ERROR_SET(&err)) { - emsgf("paste: %s", err.msg); + semsg("paste: %s", err.msg); api_clear_error(&err); } diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index fcfe862044..bb75286369 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -1484,7 +1484,6 @@ static void unibi_goto(UI *ui, int row, int col) if (str) { \ unibi_var_t vars[26 + 26]; \ size_t orig_pos = data->bufpos; \ - \ memset(&vars, 0, sizeof(vars)); \ data->cork = true; \ retry: \ @@ -1664,6 +1663,14 @@ static void patch_terminfo_bugs(TUIData *data, const char *term, const char *col ILOG("Disabling smglr with TERM=xterm for non-xterm."); unibi_set_str(ut, unibi_set_lr_margin, NULL); } + if (unibi_get_str(ut, unibi_set_left_margin_parm)) { + ILOG("Disabling smglp with TERM=xterm for non-xterm."); + unibi_set_str(ut, unibi_set_left_margin_parm, NULL); + } + if (unibi_get_str(ut, unibi_set_right_margin_parm)) { + ILOG("Disabling smgrp with TERM=xterm for non-xterm."); + unibi_set_str(ut, unibi_set_right_margin_parm, NULL); + } } #ifdef WIN32 @@ -1688,6 +1695,14 @@ static void patch_terminfo_bugs(TUIData *data, const char *term, const char *col ILOG("Disabling smglr with TERM=screen.xterm for screen."); unibi_set_str(ut, unibi_set_lr_margin, NULL); } + if (unibi_get_str(ut, unibi_set_left_margin_parm)) { + ILOG("Disabling smglp with TERM=screen.xterm for screen."); + unibi_set_str(ut, unibi_set_left_margin_parm, NULL); + } + if (unibi_get_str(ut, unibi_set_right_margin_parm)) { + ILOG("Disabling smgrp with TERM=screen.xterm for screen."); + unibi_set_str(ut, unibi_set_right_margin_parm, NULL); + } } else if (tmux) { unibi_set_if_empty(ut, unibi_to_status_line, "\x1b_"); unibi_set_if_empty(ut, unibi_from_status_line, "\x1b\\"); diff --git a/src/nvim/undo.c b/src/nvim/undo.c index de396428a7..7eb76abd2c 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -135,7 +135,8 @@ static int seen_b_u_curhead; static int seen_b_u_newhead; static int header_count; -static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) { +static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) +{ u_entry_T *uep; if (uhp == NULL) { @@ -143,25 +144,25 @@ static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *e } ++header_count; if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1) { - EMSG("b_u_curhead found twice (looping?)"); + emsg("b_u_curhead found twice (looping?)"); return; } if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1) { - EMSG("b_u_newhead found twice (looping?)"); + emsg("b_u_newhead found twice (looping?)"); return; } if (uhp->uh_magic != UH_MAGIC) { - EMSG("uh_magic wrong (may be using freed memory)"); + emsg("uh_magic wrong (may be using freed memory)"); } else { // Check pointers back are correct. if (uhp->uh_next.ptr != exp_uh_next) { - EMSG("uh_next wrong"); + emsg("uh_next wrong"); smsg("expected: 0x%x, actual: 0x%x", exp_uh_next, uhp->uh_next.ptr); } if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev) { - EMSG("uh_alt_prev wrong"); + emsg("uh_alt_prev wrong"); smsg("expected: 0x%x, actual: 0x%x", exp_uh_alt_prev, uhp->uh_alt_prev.ptr); } @@ -169,7 +170,7 @@ static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *e // Check the undo tree at this header. for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { if (uep->ue_magic != UE_MAGIC) { - EMSG("ue_magic wrong (may be using freed memory)"); + emsg("ue_magic wrong (may be using freed memory)"); break; } } @@ -182,7 +183,8 @@ static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *e } } -static void u_check(int newhead_may_be_NULL) { +static void u_check(int newhead_may_be_NULL) +{ seen_b_u_newhead = 0; seen_b_u_curhead = 0; header_count = 0; @@ -191,13 +193,13 @@ static void u_check(int newhead_may_be_NULL) { if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL)) { - EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); + semsg("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); } if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0) { - EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); + semsg("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); } if (header_count != curbuf->b_u_numhead) { - EMSG("b_u_numhead invalid"); + emsg("b_u_numhead invalid"); smsg("expected: %" PRId64 ", actual: %" PRId64, (int64_t)header_count, (int64_t)curbuf->b_u_numhead); } @@ -281,20 +283,20 @@ bool undo_allowed(buf_T *buf) { // Don't allow changes when 'modifiable' is off. if (!MODIFIABLE(buf)) { - EMSG(_(e_modifiable)); + emsg(_(e_modifiable)); return false; } // In the sandbox it's not allowed to change the text. if (sandbox != 0) { - EMSG(_(e_sandbox)); + emsg(_(e_sandbox)); return false; } // Don't allow changes in the buffer while editing the cmdline. The // caller of getcmdline() may get confused. if (textlock != 0) { - EMSG(_(e_secure)); + emsg(_(e_secure)); return false; } @@ -355,7 +357,7 @@ int u_savecommon(buf_T *buf, linenr_T top, linenr_T bot, linenr_T newbot, int re if (bot > buf->b_ml.ml_line_count + 1) { // This happens when the FileChangedRO autocommand changes the // file in a way it becomes shorter. - EMSG(_("E881: Line count changed unexpectedly")); + emsg(_("E881: Line count changed unexpectedly")); return FAIL; } } @@ -719,7 +721,7 @@ char *u_get_undo_file_name(const char *const buf_ffname, const bool reading) int ret; char *failed_dir; if ((ret = os_mkdir_recurse(dir_name, 0755, &failed_dir)) != 0) { - EMSG3(_("E5003: Unable to create directory \"%s\" for undo file: %s"), + semsg(_("E5003: Unable to create directory \"%s\" for undo file: %s"), failed_dir, os_strerror(ret)); xfree(failed_dir); } else { @@ -758,7 +760,7 @@ char *u_get_undo_file_name(const char *const buf_ffname, const bool reading) static void corruption_error(const char *const mesg, const char *const file_name) FUNC_ATTR_NONNULL_ALL { - EMSG3(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); + semsg(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); } static void u_free_uhp(u_header_T *uhp) @@ -1265,7 +1267,7 @@ void u_write_undo(const char *const name, const bool forceit, buf_T *const buf, fd = os_open(file_name, O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) { - EMSG2(_(e_not_open), file_name); + semsg(_(e_not_open), file_name); goto theend; } (void)os_setperm(file_name, perm); @@ -1299,7 +1301,7 @@ void u_write_undo(const char *const name, const bool forceit, buf_T *const buf, fp = fdopen(fd, "w"); if (fp == NULL) { - EMSG2(_(e_not_open), file_name); + semsg(_(e_not_open), file_name); close(fd); os_remove(file_name); goto theend; @@ -1355,15 +1357,15 @@ void u_write_undo(const char *const name, const bool forceit, buf_T *const buf, } #ifdef U_DEBUG if (headers_written != buf->b_u_numhead) { - EMSGN("Written %" PRId64 " headers, ...", headers_written); - EMSGN("... but numhead is %" PRId64, buf->b_u_numhead); + semsg("Written %" PRId64 " headers, ...", (int64_t)headers_written); + semsg("... but numhead is %" PRId64, (int64_t)buf->b_u_numhead); } #endif write_error: fclose(fp); if (!write_ok) { - EMSG2(_("E829: write error in undo file: %s"), file_name); + semsg(_("E829: write error in undo file: %s"), file_name); } #ifdef HAVE_ACL @@ -1432,7 +1434,7 @@ void u_read_undo(char *name, const char_u *hash, const char_u *orig_name FUNC_AT FILE *fp = os_fopen(file_name, "r"); if (fp == NULL) { if (name != NULL || p_verbose > 0) { - EMSG2(_("E822: Cannot open undo file for reading: %s"), file_name); + semsg(_("E822: Cannot open undo file for reading: %s"), file_name); } goto error; } @@ -1445,12 +1447,12 @@ void u_read_undo(char *name, const char_u *hash, const char_u *orig_name FUNC_AT char_u magic_buf[UF_START_MAGIC_LEN]; if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1 || memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { - EMSG2(_("E823: Not an undo file: %s"), file_name); + semsg(_("E823: Not an undo file: %s"), file_name); goto error; } int version = get2c(fp); if (version != UF_VERSION) { - EMSG2(_("E824: Incompatible undo file: %s"), file_name); + semsg(_("E824: Incompatible undo file: %s"), file_name); goto error; } @@ -1653,7 +1655,7 @@ void u_read_undo(char *name, const char_u *hash, const char_u *orig_name FUNC_AT #ifdef U_DEBUG for (int i = 0; i < num_head; i++) { if (uhp_table_used[i] == 0) { - EMSGN("uhp_table entry %" PRId64 " not used, leaking memory", i); + semsg("uhp_table entry %" PRId64 " not used, leaking memory", (int64_t)i); } } xfree(uhp_table_used); @@ -1902,7 +1904,7 @@ static void u_doit(int startcount, bool quiet, bool do_buf_event) curbuf->b_u_curhead = curbuf->b_u_oldhead; beep_flush(); if (count == startcount - 1) { - MSG(_("Already at oldest change")); + msg(_("Already at oldest change")); return; } break; @@ -1913,7 +1915,7 @@ static void u_doit(int startcount, bool quiet, bool do_buf_event) if (curbuf->b_u_curhead == NULL || get_undolevel(curbuf) <= 0) { beep_flush(); // nothing to redo if (count == startcount - 1) { - MSG(_("Already at newest change")); + msg(_("Already at newest change")); return; } break; @@ -2138,15 +2140,15 @@ void undo_time(long step, bool sec, bool file, bool absolute) } if (absolute) { - EMSGN(_("E830: Undo number %" PRId64 " not found"), step); + semsg(_("E830: Undo number %" PRId64 " not found"), (int64_t)step); return; } if (closest == closest_start) { if (step < 0) { - MSG(_("Already at oldest change")); + msg(_("Already at oldest change")); } else { - MSG(_("Already at newest change")); + msg(_("Already at newest change")); } return; } @@ -2329,7 +2331,7 @@ static void u_undoredo(int undo, bool do_buf_event) if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) { unblock_autocmds(); - IEMSG(_("E438: u_undo: line numbers wrong")); + iemsg(_("E438: u_undo: line numbers wrong")); changed(); // don't want UNCHANGED now return; } @@ -2728,7 +2730,7 @@ void ex_undolist(exarg_T *eap) } if (GA_EMPTY(&ga)) { - MSG(_("Nothing to undo")); + msg(_("Nothing to undo")); } else { sort_strings((char_u **)ga.ga_data, ga.ga_len); @@ -2757,7 +2759,7 @@ void ex_undojoin(exarg_T *eap) return; // nothing changed before } if (curbuf->b_u_curhead != NULL) { - EMSG(_("E790: undojoin is not allowed after undo")); + emsg(_("E790: undojoin is not allowed after undo")); return; } if (!curbuf->b_u_synced) { @@ -2854,7 +2856,7 @@ static void u_unch_branch(u_header_T *uhp) static u_entry_T *u_get_headentry(buf_T *buf) { if (buf->b_u_newhead == NULL || buf->b_u_newhead->uh_entry == NULL) { - IEMSG(_("E439: undo list corrupt")); + iemsg(_("E439: undo list corrupt")); return NULL; } return buf->b_u_newhead->uh_entry; @@ -2884,7 +2886,7 @@ static void u_getbot(buf_T *buf) extra = buf->b_ml.ml_line_count - uep->ue_lcount; uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra; if (uep->ue_bot < 1 || uep->ue_bot > buf->b_ml.ml_line_count) { - IEMSG(_("E440: undo line missing")); + iemsg(_("E440: undo line missing")); uep->ue_bot = uep->ue_top + 1; // assume all lines deleted, will // get all the old lines back // without deleting the current diff --git a/src/nvim/version.c b/src/nvim/version.c index 9e2358c9a3..1fcbae8be3 100644 --- a/src/nvim/version.c +++ b/src/nvim/version.c @@ -29,8 +29,8 @@ // for ":version", ":intro", and "nvim --version" #ifndef NVIM_VERSION_MEDIUM -# define NVIM_VERSION_MEDIUM "v" STR(NVIM_VERSION_MAJOR)\ - "." STR(NVIM_VERSION_MINOR) "." STR(NVIM_VERSION_PATCH)\ +# define NVIM_VERSION_MEDIUM "v" STR(NVIM_VERSION_MAJOR) \ + "." STR(NVIM_VERSION_MINOR) "." STR(NVIM_VERSION_PATCH) \ NVIM_VERSION_PRERELEASE #endif #define NVIM_VERSION_LONG "NVIM " NVIM_VERSION_MEDIUM @@ -1992,7 +1992,8 @@ bool has_vim_patch(int n) return false; } -Dictionary version_dict(void) { +Dictionary version_dict(void) +{ Dictionary d = ARRAY_DICT_INIT; PUT(d, "major", INTEGER_OBJ(NVIM_VERSION_MAJOR)); PUT(d, "minor", INTEGER_OBJ(NVIM_VERSION_MINOR)); @@ -2137,32 +2138,32 @@ void list_lua_version(void) Object ret = nlua_exec(cstr_as_string(code), (Array)ARRAY_DICT_INIT, &err); assert(!ERROR_SET(&err)); assert(ret.type == kObjectTypeString); - MSG(ret.data.string.data); + msg(ret.data.string.data); api_free_object(ret); } void list_version(void) { - MSG(longVersion); - MSG(version_buildtype); + msg(longVersion); + msg(version_buildtype); list_lua_version(); #ifndef NDEBUG - MSG(version_cflags); + msg(version_cflags); #endif #ifdef HAVE_PATHDEF if ((*compiled_user != NUL) || (*compiled_sys != NUL)) { - MSG_PUTS(_("\nCompiled ")); + msg_puts(_("\nCompiled ")); if (*compiled_user != NUL) { - MSG_PUTS(_("by ")); - MSG_PUTS(compiled_user); + msg_puts(_("by ")); + msg_puts((const char *)compiled_user); } if (*compiled_sys != NUL) { - MSG_PUTS("@"); - MSG_PUTS(compiled_sys); + msg_puts("@"); + msg_puts((const char *)compiled_sys); } } #endif // ifdef HAVE_PATHDEF diff --git a/src/nvim/vim.h b/src/nvim/vim.h index 7d49ca6ff1..726670f082 100644 --- a/src/nvim/vim.h +++ b/src/nvim/vim.h @@ -24,7 +24,7 @@ #include "nvim/os/os_defs.h" // bring lots of system header files /// length of a buffer to store a number in ASCII (64 bits binary + NUL) -enum { NUMBUFLEN = 65 }; +enum { NUMBUFLEN = 65, }; #define MAX_TYPENR 65535 @@ -164,8 +164,6 @@ enum { }; - - // Minimal size for block 0 of a swap file. // NOTE: This depends on size of struct block0! It's not done with a sizeof(), // because struct block0 is defined in memline.c (Sorry). @@ -175,7 +173,6 @@ enum { #define MAX_SWAP_PAGE_SIZE 50000 - // Boolean constants #ifndef TRUE @@ -199,7 +196,7 @@ enum { #define DIALOG_MSG_SIZE 1000 // buffer size for dialog_msg() -enum { FOLD_TEXT_LEN = 51 }; //!< buffer size for get_foldtext() +enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext() // Maximum length of key sequence to be mapped. @@ -257,9 +254,9 @@ enum { FOLD_TEXT_LEN = 51 }; //!< buffer size for get_foldtext() #include "nvim/message.h" -// Prefer using emsgf(), because perror() may send the output to the wrong +// Prefer using semsg(), because perror() may send the output to the wrong // destination and mess up the screen. -#define PERROR(msg) (void)emsgf("%s: %s", msg, strerror(errno)) +#define PERROR(msg) (void)semsg("%s: %s", msg, strerror(errno)) #define SHOWCMD_COLS 10 // columns needed by shown command diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c index 39687a8e8d..4f028fa87f 100644 --- a/src/nvim/viml/parser/expressions.c +++ b/src/nvim/viml/parser/expressions.c @@ -1525,7 +1525,6 @@ static inline void east_set_error(const ParserState *const pstate, ExprASTError assert(want_node == kENodeOperator); \ /* Operator: may only be curly braces name, but only under certain */ \ /* conditions. */ \ -\ /* First condition is that there is no space before a part of complex */ \ /* identifier. */ \ if (prev_token.type == kExprLexSpacing) { \ @@ -1534,7 +1533,6 @@ static inline void east_set_error(const ParserState *const pstate, ExprASTError switch ((*top_node_p)->type) { \ /* Second is that previous node is one of the identifiers: */ \ /* complex, plain, curly braces. */ \ -\ /* TODO(ZyX-I): Extend syntax to allow ${expr}. This is needed to */ \ /* handle environment variables like those bash uses for */ \ /* `export -f`: their names consist not only of alphanumeric */ \ diff --git a/src/nvim/viml/parser/expressions.h b/src/nvim/viml/parser/expressions.h index 325df643e7..fe9327b27d 100644 --- a/src/nvim/viml/parser/expressions.h +++ b/src/nvim/viml/parser/expressions.h @@ -361,7 +361,7 @@ typedef struct { typedef struct { /// When AST is not correct this message will be printed. /// - /// Uses `emsgf(msg, arg_len, arg);`, `msg` is assumed to contain only `%.*s`. + /// Uses `semsg(msg, arg_len, arg);`, `msg` is assumed to contain only `%.*s`. ExprASTError err; /// Root node of the AST. ExprASTNode *root; diff --git a/src/nvim/window.c b/src/nvim/window.c index 67bad9f8cf..ff5b39eb84 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -59,8 +59,6 @@ #endif - - #define NOWIN (win_T *)-1 // non-existing window #define ROWS_AVAIL (Rows - p_ch - tabline_height()) @@ -94,7 +92,7 @@ void do_window(int nchar, long Prenum, int xchar) #define CHECK_CMDWIN \ do { \ if (cmdwin_type != 0) { \ - EMSG(_(e_cmdwin)); \ + emsg(_(e_cmdwin)); \ return; \ } \ } while (0) @@ -135,9 +133,9 @@ void do_window(int nchar, long Prenum, int xchar) if (buflist_findnr(Prenum == 0 ? curwin->w_alt_fnum : Prenum) == NULL) { if (Prenum == 0) { - EMSG(_(e_noalt)); + emsg(_(e_noalt)); } else { - EMSGN(_("E92: Buffer %" PRId64 " not found"), Prenum); + semsg(_("E92: Buffer %" PRId64 " not found"), (int64_t)Prenum); } break; } @@ -201,7 +199,7 @@ newwindow: } } if (wp == NULL) { - EMSG(_("E441: There is no preview window")); + emsg(_("E441: There is no preview window")); } else { win_goto(wp); } @@ -294,7 +292,7 @@ newwindow: // move window to new tab page case 'T': if (one_window()) { - MSG(_(m_onlyone)); + msg(_(m_onlyone)); } else { tabpage_T *oldtab = curtab; tabpage_T *newtab; @@ -552,7 +550,7 @@ wingotofile: config.external = true; Error err = ERROR_INIT; if (!win_new_float(curwin, config, &err)) { - EMSG(err.msg); + emsg(err.msg); api_clear_error(&err); beep_flush(); } @@ -921,7 +919,7 @@ int win_split(int size, int flags) // Add flags from ":vertical", ":topleft" and ":botright". flags |= cmdmod.split; if ((flags & WSP_TOP) && (flags & WSP_BOT)) { - EMSG(_("E442: Can't split topleft and botright at the same time")); + emsg(_("E442: Can't split topleft and botright at the same time")); return FAIL; } @@ -974,7 +972,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) // add a status line when p_ls == 1 and splitting the first window if (one_nonfloat() && p_ls == 1 && oldwin->w_status_height == 0) { if (oldwin->w_height <= p_wmh && new_in_layout) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); return FAIL; } need_status = STATUS_HEIGHT; @@ -1023,7 +1021,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) needed += minwidth; } if (available < needed && new_in_layout) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); return FAIL; } if (new_size == 0) { @@ -1103,7 +1101,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) needed += minheight; } if (available < needed && new_in_layout) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); return FAIL; } oldwin_height = oldwin->w_height; @@ -1659,7 +1657,7 @@ static void win_exchange(long Prenum) int temp; if (curwin->w_floating) { - EMSG(e_floatexchange); + emsg(e_floatexchange); return; } @@ -1746,7 +1744,7 @@ static void win_rotate(bool upwards, int count) int n; if (curwin->w_floating) { - EMSG(e_floatexchange); + emsg(e_floatexchange); return; } @@ -1759,7 +1757,7 @@ static void win_rotate(bool upwards, int count) // Check if all frames in this row/col have one window. FOR_ALL_FRAMES(frp, curwin->w_frame->fr_parent->fr_child) { if (frp->fr_win == NULL) { - EMSG(_("E443: Cannot rotate when another window is split")); + emsg(_("E443: Cannot rotate when another window is split")); return; } } @@ -1776,7 +1774,6 @@ static void win_rotate(bool upwards, int count) // find last frame and append removed window/frame after it for (; frp->fr_next != NULL; frp = frp->fr_next) { - ; } win_append(frp->fr_win, wp1); frame_append(frp, wp1->w_frame); @@ -1786,7 +1783,6 @@ static void win_rotate(bool upwards, int count) // find last window/frame in the list and remove it for (frp = curwin->w_frame; frp->fr_next != NULL; frp = frp->fr_next) { - ; } wp1 = frp->fr_win; wp2 = wp1->w_prev; // will become last window @@ -2399,7 +2395,7 @@ int win_close(win_T *win, bool free_buf) const bool had_diffmode = win->w_p_diff; if (last_window() && !win->w_floating) { - EMSG(_("E444: Cannot close last window")); + emsg(_("E444: Cannot close last window")); return FAIL; } @@ -2408,17 +2404,17 @@ int win_close(win_T *win, bool free_buf) return FAIL; // window is already being closed } if (win == aucmd_win) { - EMSG(_(e_autocmd_close)); + emsg(_(e_autocmd_close)); return FAIL; } if ((firstwin == aucmd_win || lastwin == aucmd_win) && one_window()) { - EMSG(_("E814: Cannot close window, only autocmd window would remain")); + emsg(_("E814: Cannot close window, only autocmd window would remain")); return FAIL; } if ((firstwin == win && lastwin_nofloating() == win) && lastwin->w_floating) { // TODO(bfredl): we might close the float also instead - EMSG(e_floatonly); + emsg(e_floatonly); return FAIL; } @@ -2710,7 +2706,6 @@ void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) // Careful: Autocommands may have closed the tab page or made it the // current tab page. for (ptp = first_tabpage; ptp != NULL && ptp != tp; ptp = ptp->tp_next) { - ; } if (ptp == NULL || tp == curtab) { return; @@ -3048,7 +3043,6 @@ static tabpage_T *alt_tabpage(void) // Find the last but one tab page. for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next) { - ; } return tp; } @@ -3153,12 +3147,14 @@ static void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wf break; } if (topfirst) { - do + do{ frp = frp->fr_next; + } while (wfh && frp != NULL && frame_fixed_height(frp)); } else { - do + do{ frp = frp->fr_prev; + } while (wfh && frp != NULL && frame_fixed_height(frp)); } // Increase "height" if we could not reduce enough frames. @@ -3351,12 +3347,14 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw break; } if (leftfirst) { - do + do{ frp = frp->fr_next; + } while (wfw && frp != NULL && frame_fixed_width(frp)); } else { - do + do{ frp = frp->fr_prev; + } while (wfw && frp != NULL && frame_fixed_width(frp)); } // Increase "width" if we could not reduce enough frames. @@ -3526,7 +3524,7 @@ void close_others(int message, int forceit) if (curwin->w_floating) { if (message && !autocmd_busy) { - EMSG(e_floatonly); + emsg(e_floatonly); } return; } @@ -3534,7 +3532,7 @@ void close_others(int message, int forceit) if (one_window() && !lastwin->w_floating) { if (message && !autocmd_busy) { - MSG(_(m_onlyone)); + msg(_(m_onlyone)); } return; } @@ -3568,7 +3566,7 @@ void close_others(int message, int forceit) } if (message && !ONE_WINDOW) { - EMSG(_("E445: Other window contains changes")); + emsg(_("E445: Other window contains changes")); } } @@ -4123,14 +4121,12 @@ void goto_tabpage(int n) for (i = n; i < 0; ++i) { for (tp = first_tabpage; tp->tp_next != ttp && tp->tp_next != NULL; tp = tp->tp_next) { - ; } ttp = tp; } } else if (n == 9999) { // Go to last tab page. for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next) { - ; } } else { // Go to tab page "n". @@ -5009,7 +5005,6 @@ void do_autocmd_winscrolled(win_T *wp) * Save the size of all windows in "gap". */ void win_size_save(garray_T *gap) - { ga_init(gap, (int)sizeof(int), 1); ga_grow(gap, win_count() * 2 + 1); @@ -5523,7 +5518,7 @@ void win_setminheight(void) } p_wmh--; if (first) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); first = false; } } @@ -5543,7 +5538,7 @@ void win_setminwidth(void) } p_wmw--; if (first) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); first = false; } } @@ -6038,7 +6033,7 @@ void command_height(void) if (p_ch > old_p_ch) { // p_ch got bigger while (p_ch > old_p_ch) { if (frp == NULL) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); p_ch = old_p_ch; curtab->tp_ch_used = p_ch; cmdline_row = Rows - p_ch; @@ -6160,7 +6155,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u } if (*ptr == NUL) { // nothing found if (options & FNAME_MESS) { - EMSG(_("E446: No file name under cursor")); + emsg(_("E446: No file name under cursor")); } return NULL; } @@ -6273,7 +6268,7 @@ static void last_status_rec(frame_T *fr, bool statusline) fp = fr; while (fp->fr_height <= frame_minheight(fp, NULL)) { if (fp == topframe) { - EMSG(_(e_noroom)); + emsg(_(e_noroom)); return; } // In a column of frames: go to frame above. If already at @@ -6303,7 +6298,6 @@ static void last_status_rec(frame_T *fr, bool statusline) } else { // horizontally split window, set status line for last one for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next) { - ; } last_status_rec(fp, statusline); } @@ -6684,16 +6678,16 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, return -1; } if (id < -1 || id == 0) { - EMSGN(_("E799: Invalid ID: %" PRId64 + semsg(_("E799: Invalid ID: %" PRId64 " (must be greater than or equal to 1)"), - id); + (int64_t)id); return -1; } if (id != -1) { cur = wp->w_match_head; while (cur != NULL) { if (cur->id == id) { - EMSGN(_("E801: ID already taken: %" PRId64), id); + semsg(_("E801: ID already taken: %" PRId64), (int64_t)id); return -1; } cur = cur->next; @@ -6703,7 +6697,7 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, return -1; } if (pat != NULL && (regprog = vim_regcomp((char_u *)pat, RE_MAGIC)) == NULL) { - EMSG2(_(e_invarg2), pat); + semsg(_(e_invarg2), pat); return -1; } @@ -6749,7 +6743,7 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, const list_T *const subl = TV_LIST_ITEM_TV(li)->vval.v_list; const listitem_T *subli = tv_list_first(subl); if (subli == NULL) { - emsgf(_("E5030: Empty list at position %d"), + semsg(_("E5030: Empty list at position %d"), (int)tv_list_idx_of_item(pos_list, li)); goto fail; } @@ -6791,7 +6785,7 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, m->pos.pos[i].col = 0; m->pos.pos[i].len = 0; } else { - emsgf(_("E5031: List or number required at position %d"), + semsg(_("E5031: List or number required at position %d"), (int)tv_list_idx_of_item(pos_list, li)); goto fail; } @@ -6863,9 +6857,9 @@ int match_delete(win_T *wp, int id, bool perr) if (id < 1) { if (perr) { - EMSGN(_("E802: Invalid ID: %" PRId64 + semsg(_("E802: Invalid ID: %" PRId64 " (must be greater than or equal to 1)"), - id); + (int64_t)id); } return -1; } @@ -6875,7 +6869,7 @@ int match_delete(win_T *wp, int id, bool perr) } if (cur == NULL) { if (perr) { - EMSGN(_("E803: ID not found: %" PRId64), id); + semsg(_("E803: ID not found: %" PRId64), (int64_t)id); } return -1; } @@ -7163,7 +7157,8 @@ void win_ui_flush(void) } } -win_T *lastwin_nofloating(void) { +win_T *lastwin_nofloating(void) +{ win_T *res = lastwin; while (res->w_floating) { res = res->w_prev; diff --git a/src/uncrustify.cfg b/src/uncrustify.cfg index 13d1f472ed..c06bf41d47 100644 --- a/src/uncrustify.cfg +++ b/src/uncrustify.cfg @@ -160,16 +160,16 @@ sp_pp_stringify = ignore # ignore/add/remove/force/not_defined sp_before_pp_stringify = ignore # ignore/add/remove/force/not_defined # Add or remove space around boolean operators '&&' and '||'. -sp_bool = ignore # ignore/add/remove/force/not_defined +sp_bool = force # ignore/add/remove/force/not_defined # Add or remove space around compare operator '<', '>', '==', etc. -sp_compare = ignore # ignore/add/remove/force/not_defined +sp_compare = force # ignore/add/remove/force/not_defined # Add or remove space inside '(' and ')'. -sp_inside_paren = ignore # ignore/add/remove/force/not_defined +sp_inside_paren = remove # ignore/add/remove/force/not_defined # Add or remove space between nested parentheses, i.e. '((' vs. ') )'. -sp_paren_paren = ignore # ignore/add/remove/force/not_defined +sp_paren_paren = remove # ignore/add/remove/force/not_defined # Add or remove space between back-to-back parentheses, i.e. ')(' vs. ') ('. sp_cparen_oparen = ignore # ignore/add/remove/force/not_defined @@ -301,7 +301,7 @@ sp_angle_word = ignore # ignore/add/remove/force/not_defined # Add or remove space between '>' and '>' in '>>' (template stuff). # # Default: add -sp_angle_shift = ignore # ignore/add/remove/force/not_defined +sp_angle_shift = add # ignore/add/remove/force/not_defined # (C++11) Permit removal of the space between '>>' in 'foo<bar<int> >'. Note # that sp_angle_shift cannot remove the space without this option. @@ -309,10 +309,10 @@ sp_permit_cpp11_shift = false # true/false # Add or remove space before '(' of control statements ('if', 'for', 'switch', # 'while', etc.). -sp_before_sparen = ignore # ignore/add/remove/force/not_defined +sp_before_sparen = force # ignore/add/remove/force/not_defined # Add or remove space inside '(' and ')' of control statements. -sp_inside_sparen = ignore # ignore/add/remove/force/not_defined +sp_inside_sparen = remove # ignore/add/remove/force/not_defined # Add or remove space after '(' of control statements. # @@ -370,12 +370,12 @@ sp_between_semi_for_empty = ignore # ignore/add/remove/force/not_defined # Add or remove space after ';', except when followed by a comment. # # Default: add -sp_after_semi = ignore # ignore/add/remove/force/not_defined +sp_after_semi = add # ignore/add/remove/force/not_defined # Add or remove space after ';' in non-empty 'for' statements. # # Default: force -sp_after_semi_for = ignore # ignore/add/remove/force/not_defined +sp_after_semi_for = force # ignore/add/remove/force/not_defined # Add or remove space after the final semicolon of an empty part of a for # statement, as in 'for ( ; ; <here> )'. @@ -387,7 +387,7 @@ sp_before_square = ignore # ignore/add/remove/force/not_defined # Add or remove space before '[' for a variable definition. # # Default: remove -sp_before_vardef_square = ignore # ignore/add/remove/force/not_defined +sp_before_vardef_square = remove # ignore/add/remove/force/not_defined # Add or remove space before '[' for asm block. sp_before_square_asm_block = ignore # ignore/add/remove/force/not_defined @@ -432,7 +432,7 @@ sp_between_mdatype_commas = ignore # ignore/add/remove/force/not_defined # i.e. '(,' vs. '( ,'. # # Default: force -sp_paren_comma = ignore # ignore/add/remove/force/not_defined +sp_paren_comma = force # ignore/add/remove/force/not_defined # Add or remove space after the variadic '...' when preceded by a # non-punctuator. @@ -474,12 +474,12 @@ sp_before_class_colon = ignore # ignore/add/remove/force/not_defined # Add or remove space after class constructor ':'. # # Default: add -sp_after_constr_colon = ignore # ignore/add/remove/force/not_defined +sp_after_constr_colon = add # ignore/add/remove/force/not_defined # Add or remove space before class constructor ':'. # # Default: add -sp_before_constr_colon = ignore # ignore/add/remove/force/not_defined +sp_before_constr_colon = add # ignore/add/remove/force/not_defined # Add or remove space before case ':'. # @@ -502,14 +502,14 @@ sp_after_operator_sym_empty = ignore # ignore/add/remove/force/not_defined sp_after_cast = remove # ignore/add/remove/force/not_defined # Add or remove spaces inside cast parentheses. -sp_inside_paren_cast = ignore # ignore/add/remove/force/not_defined +sp_inside_paren_cast = remove # ignore/add/remove/force/not_defined # Add or remove space between the type and open parenthesis in a C++ cast, # i.e. 'int(exp)' vs. 'int (exp)'. sp_cpp_cast_paren = ignore # ignore/add/remove/force/not_defined # Add or remove space between 'sizeof' and '('. -sp_sizeof_paren = ignore # ignore/add/remove/force/not_defined +sp_sizeof_paren = remove # ignore/add/remove/force/not_defined # Add or remove space between 'sizeof' and '...'. sp_sizeof_ellipsis = ignore # ignore/add/remove/force/not_defined @@ -694,12 +694,12 @@ sp_scope_paren = ignore # ignore/add/remove/force/not_defined # Add or remove space between 'super' and '(' in 'super (something)'. # # Default: remove -sp_super_paren = ignore # ignore/add/remove/force/not_defined +sp_super_paren = remove # ignore/add/remove/force/not_defined # Add or remove space between 'this' and '(' in 'this (something)'. # # Default: remove -sp_this_paren = ignore # ignore/add/remove/force/not_defined +sp_this_paren = remove # ignore/add/remove/force/not_defined # Add or remove space between a macro name and its definition. sp_macro = ignore # ignore/add/remove/force/not_defined @@ -751,7 +751,7 @@ sp_word_brace_init_lst = ignore # ignore/add/remove/force/not_defined # Add or remove space between a variable and '{' for a namespace. # # Default: add -sp_word_brace_ns = ignore # ignore/add/remove/force/not_defined +sp_word_brace_ns = add # ignore/add/remove/force/not_defined # Add or remove space before the '::' operator. sp_before_dc = ignore # ignore/add/remove/force/not_defined @@ -765,34 +765,34 @@ sp_d_array_colon = ignore # ignore/add/remove/force/not_defined # Add or remove space after the '!' (not) unary operator. # # Default: remove -sp_not = ignore # ignore/add/remove/force/not_defined +sp_not = remove # ignore/add/remove/force/not_defined # Add or remove space after the '~' (invert) unary operator. # # Default: remove -sp_inv = ignore # ignore/add/remove/force/not_defined +sp_inv = remove # ignore/add/remove/force/not_defined # Add or remove space after the '&' (address-of) unary operator. This does not # affect the spacing after a '&' that is part of a type. # # Default: remove -sp_addr = ignore # ignore/add/remove/force/not_defined +sp_addr = remove # ignore/add/remove/force/not_defined # Add or remove space around the '.' or '->' operators. # # Default: remove -sp_member = ignore # ignore/add/remove/force/not_defined +sp_member = remove # ignore/add/remove/force/not_defined # Add or remove space after the '*' (dereference) unary operator. This does # not affect the spacing after a '*' that is part of a type. # # Default: remove -sp_deref = ignore # ignore/add/remove/force/not_defined +sp_deref = remove # ignore/add/remove/force/not_defined # Add or remove space after '+' or '-', as in 'x = -5' or 'y = +7'. # # Default: remove -sp_sign = ignore # ignore/add/remove/force/not_defined +sp_sign = remove # ignore/add/remove/force/not_defined # Add or remove space between '++' and '--' the word to which it is being # applied, as in '(--x)' or 'y++;'. @@ -803,7 +803,7 @@ sp_incdec = remove # ignore/add/remove/force/not_defined # Add or remove space before a backslash-newline at the end of a line. # # Default: add -sp_before_nl_cont = ignore # ignore/add/remove/force/not_defined +sp_before_nl_cont = force # ignore/add/remove/force/not_defined # (OC) Add or remove space after the scope '+' or '-', as in '-(void) foo;' # or '+(int) bar;'. @@ -1549,7 +1549,7 @@ nl_enum_identifier_colon = ignore # ignore/add/remove/force/not_defined nl_enum_colon_type = ignore # ignore/add/remove/force/not_defined # Add or remove newline between 'struct and '{'. -nl_struct_brace = ignore # ignore/add/remove/force/not_defined +nl_struct_brace = remove # ignore/add/remove/force/not_defined # Add or remove newline between 'union' and '{'. nl_union_brace = ignore # ignore/add/remove/force/not_defined @@ -1565,16 +1565,16 @@ nl_brace_else = remove # ignore/add/remove/force/not_defined nl_elseif_brace = ignore # ignore/add/remove/force/not_defined # Add or remove newline between 'else' and '{'. -nl_else_brace = ignore # ignore/add/remove/force/not_defined +nl_else_brace = remove # ignore/add/remove/force/not_defined # Add or remove newline between 'else' and 'if'. -nl_else_if = ignore # ignore/add/remove/force/not_defined +nl_else_if = remove # ignore/add/remove/force/not_defined # Add or remove newline before '{' opening brace nl_before_opening_brace_func_class_def = ignore # ignore/add/remove/force/not_defined # Add or remove newline before 'if'/'else if' closing parenthesis. -nl_before_if_closing_paren = ignore # ignore/add/remove/force/not_defined +nl_before_if_closing_paren = remove # ignore/add/remove/force/not_defined # Add or remove newline between '}' and 'finally'. nl_brace_finally = ignore # ignore/add/remove/force/not_defined @@ -1897,7 +1897,7 @@ nl_template_end = false # true/false nl_oc_msg_args = false # true/false # Add or remove newline between function signature and '{'. -nl_fdef_brace = ignore # ignore/add/remove/force/not_defined +nl_fdef_brace = force # ignore/add/remove/force/not_defined # Add or remove newline between function signature and '{', # if signature ends with ')'. Overrides nl_fdef_brace. @@ -1907,7 +1907,7 @@ nl_fdef_brace_cond = ignore # ignore/add/remove/force/not_defined nl_cpp_ldef_brace = ignore # ignore/add/remove/force/not_defined # Add or remove newline between 'return' and the return expression. -nl_return_expr = ignore # ignore/add/remove/force/not_defined +nl_return_expr = remove # ignore/add/remove/force/not_defined # Whether to add a newline after semicolons, except in 'for' statements. nl_after_semicolon = false # true/false @@ -2093,7 +2093,7 @@ donot_add_nl_before_cpp_comment = false # true/false # # The maximum number of consecutive newlines (3 = 2 blank lines). -nl_max = 0 # unsigned number +nl_max = 3 # unsigned number # The maximum number of consecutive newlines in a function. nl_max_blank_in_func = 0 # unsigned number @@ -2886,7 +2886,7 @@ cmt_insert_before_ctor_dtor = false # true/false # # Add or remove braces on a single-line 'do' statement. -mod_full_brace_do = ignore # ignore/add/remove/force/not_defined +mod_full_brace_do = add # ignore/add/remove/force/not_defined # Add or remove braces on a single-line 'for' statement. mod_full_brace_for = add # ignore/add/remove/force/not_defined @@ -2947,10 +2947,10 @@ mod_pawn_semicolon = false # true/false mod_full_paren_if_bool = false # true/false # Whether to remove superfluous semicolons. -mod_remove_extra_semicolon = false # true/false +mod_remove_extra_semicolon = true # true/false # Whether to remove duplicate include. -mod_remove_duplicate_include = false # true/false +mod_remove_duplicate_include = true # true/false # If a function body exceeds the specified number of newlines and doesn't have # a comment after the close brace, a comment will be added. @@ -3022,7 +3022,7 @@ mod_case_brace = remove # ignore/add/remove/force/not_defined mod_remove_empty_return = false # true/false # Add or remove the comma after the last value of an enumeration. -mod_enum_last_comma = ignore # ignore/add/remove/force/not_defined +mod_enum_last_comma = add # ignore/add/remove/force/not_defined # (OC) Whether to organize the properties. If true, properties will be # rearranged according to the mod_sort_oc_property_*_weight factors. @@ -3307,5 +3307,5 @@ set QUESTION REAL_FATTR_CONST set QUESTION REAL_FATTR_NONNULL_ALL set QUESTION REAL_FATTR_PURE set QUESTION REAL_FATTR_WARN_UNUSED_RESULT -# option(s) with 'not default' value: 66 +# option(s) with 'not default' value: 69 # diff --git a/test/functional/api/buffer_spec.lua b/test/functional/api/buffer_spec.lua index 01fcfab543..a0c97804b7 100644 --- a/test/functional/api/buffer_spec.lua +++ b/test/functional/api/buffer_spec.lua @@ -711,46 +711,46 @@ describe('api/buf', function() describe('nvim_buf_set_mark', function() it('works with buffer local marks', function() curbufmeths.set_lines(-1, -1, true, {'a', 'bit of', 'text'}) - eq(true, curbufmeths.set_mark('z', 1, 1)) + eq(true, curbufmeths.set_mark('z', 1, 1, {})) eq({1, 1}, curbufmeths.get_mark('z')) end) it('works with file/uppercase marks', function() curbufmeths.set_lines(-1, -1, true, {'a', 'bit of', 'text'}) - eq(true, curbufmeths.set_mark('Z', 3, 1)) + eq(true, curbufmeths.set_mark('Z', 3, 1, {})) eq({3, 1}, curbufmeths.get_mark('Z')) end) it('fails when invalid marks names are used', function() - eq(false, pcall(curbufmeths.set_mark, '!', 1, 0)) - eq(false, pcall(curbufmeths.set_mark, 'fail', 1, 0)) + eq(false, pcall(curbufmeths.set_mark, '!', 1, 0, {})) + eq(false, pcall(curbufmeths.set_mark, 'fail', 1, 0, {})) end) it('fails when invalid buffer number is used', function() - eq(false, pcall(meths.buf_set_mark, 99, 'a', 1, 1)) + eq(false, pcall(meths.buf_set_mark, 99, 'a', 1, 1, {})) end) end) describe('nvim_buf_del_mark', function() it('works with buffer local marks', function() curbufmeths.set_lines(-1, -1, true, {'a', 'bit of', 'text'}) - curbufmeths.set_mark('z', 3, 1) + curbufmeths.set_mark('z', 3, 1, {}) eq(true, curbufmeths.del_mark('z')) eq({0, 0}, curbufmeths.get_mark('z')) end) it('works with file/uppercase marks', function() curbufmeths.set_lines(-1, -1, true, {'a', 'bit of', 'text'}) - curbufmeths.set_mark('Z', 3, 3) + curbufmeths.set_mark('Z', 3, 3, {}) eq(true, curbufmeths.del_mark('Z')) eq({0, 0}, curbufmeths.get_mark('Z')) end) it('returns false in marks not set in this buffer', function() local abuf = meths.create_buf(false,true) bufmeths.set_lines(abuf, -1, -1, true, {'a', 'bit of', 'text'}) - bufmeths.set_mark(abuf, 'A', 2, 2) + bufmeths.set_mark(abuf, 'A', 2, 2, {}) eq(false, curbufmeths.del_mark('A')) eq({2, 2}, bufmeths.get_mark(abuf, 'A')) end) it('returns false if mark was not deleted', function() curbufmeths.set_lines(-1, -1, true, {'a', 'bit of', 'text'}) - curbufmeths.set_mark('z', 3, 1) + curbufmeths.set_mark('z', 3, 1, {}) eq(true, curbufmeths.del_mark('z')) eq(false, curbufmeths.del_mark('z')) -- Mark was already deleted end) diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index 2e95b2cf6a..21de4925b5 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -2389,7 +2389,7 @@ describe('API', function() it('works', function() local buf = meths.create_buf(false,true) meths.buf_set_lines(buf, -1, -1, true, {'a', 'bit of', 'text'}) - eq(true, meths.buf_set_mark(buf, 'F', 2, 2)) + eq(true, meths.buf_set_mark(buf, 'F', 2, 2, {})) eq(true, meths.del_mark('F')) eq({0, 0}, meths.buf_get_mark(buf, 'F')) end) @@ -2403,9 +2403,9 @@ describe('API', function() it('works', function() local buf = meths.create_buf(false,true) meths.buf_set_lines(buf, -1, -1, true, {'a', 'bit of', 'text'}) - meths.buf_set_mark(buf, 'F', 2, 2) + meths.buf_set_mark(buf, 'F', 2, 2, {}) meths.buf_set_name(buf, "mybuf") - local mark = meths.get_mark('F') + local mark = meths.get_mark('F', {}) -- Compare the path tail ony assert(string.find(mark[4], "mybuf$")) eq({2, 2, buf.id, mark[4]}, mark) @@ -2417,7 +2417,7 @@ describe('API', function() end) it('returns the expected when mark is not set', function() eq(true, meths.del_mark('A')) - eq({0, 0, 0, ''}, meths.get_mark('A')) + eq({0, 0, 0, ''}, meths.get_mark('A', {})) end) it('works with deleted buffers', function() local fname = tmpname() @@ -2425,12 +2425,12 @@ describe('API', function() nvim("command", "edit " .. fname) local buf = meths.get_current_buf() - meths.buf_set_mark(buf, 'F', 2, 2) + meths.buf_set_mark(buf, 'F', 2, 2, {}) nvim("command", "new") -- Create new buf to avoid :bd failing nvim("command", "bd! " .. buf.id) os.remove(fname) - local mark = meths.get_mark('F') + local mark = meths.get_mark('F', {}) -- To avoid comparing relative vs absolute path local mfname = mark[4] local tail_patt = [[[\/][^\/]*$]] diff --git a/test/functional/core/startup_spec.lua b/test/functional/core/startup_spec.lua index cc6e2c8067..d1dce0f8da 100644 --- a/test/functional/core/startup_spec.lua +++ b/test/functional/core/startup_spec.lua @@ -414,6 +414,11 @@ describe('startup', function() eq({'ordinary', 'funky!', 'FANCY', 'mittel', 'FANCY after', 'ordinary after'}, exec_lua [[ return _G.test_loadorder ]]) eq({'ordinary', 'funky!', 'mittel', 'ordinary after'}, exec_lua [[ return _G.nested_order ]]) end) + + it("handles the correct order when prepending packpath", function() + clear{args={'--cmd', 'set packpath^=test/functional/fixtures', '--cmd', [[ lua _G.test_loadorder = {} vim.cmd "runtime! filen.lua" ]]}, env={XDG_CONFIG_HOME='test/functional/fixtures/'}} + eq({'ordinary', 'FANCY', 'FANCY after', 'ordinary after'}, exec_lua [[ return _G.test_loadorder ]]) + end) end) describe('sysinit', function() diff --git a/test/functional/editor/meta_key_spec.lua b/test/functional/editor/meta_key_spec.lua index c219204409..2280f5bb24 100644 --- a/test/functional/editor/meta_key_spec.lua +++ b/test/functional/editor/meta_key_spec.lua @@ -1,6 +1,8 @@ local helpers = require('test.functional.helpers')(after_each) local clear, feed, insert = helpers.clear, helpers.feed, helpers.insert local command = helpers.command +local exec_lua = helpers.exec_lua +local eval = helpers.eval local expect = helpers.expect local funcs = helpers.funcs local eq = helpers.eq @@ -61,4 +63,30 @@ describe('meta-keys #8226 #13042', function() feed('u') expect('hello') end) + + it('ALT/META terminal-mode', function() + exec_lua([[ + _G.input_data = '' + vim.api.nvim_open_term(0, { on_input = function(_, _, _, data) + _G.input_data = _G.input_data .. vim.fn.strtrans(data) + end }) + ]]) + -- Mapped ALT-chord behaves as mapped. + command('tnoremap <M-l> meta-l') + command('tnoremap <A-j> alt-j') + feed('i<M-l> xxx <A-j>') + eq('meta-l xxx alt-j', exec_lua([[return _G.input_data]])) + -- Unmapped ALT-chord is sent to terminal as-is. #16220 + exec_lua([[_G.input_data = '']]) + command('tunmap <M-l>') + feed('<M-l>') + local meta_l_seq = exec_lua([[return _G.input_data]]) + command('tnoremap <Esc> <C-\\><C-N>') + feed('yyy<M-l><A-j>') + eq(meta_l_seq .. 'yyy' .. meta_l_seq .. 'alt-j', exec_lua([[return _G.input_data]])) + eq('t', eval('mode(1)')) + feed('<Esc>j') + eq({ 0, 2, 1, 0, }, funcs.getpos('.')) + eq('nt', eval('mode(1)')) + end) end) diff --git a/test/functional/fixtures/fake-lsp-server.lua b/test/functional/fixtures/fake-lsp-server.lua index 9abf478070..5c0de50731 100644 --- a/test/functional/fixtures/fake-lsp-server.lua +++ b/test/functional/fixtures/fake-lsp-server.lua @@ -275,6 +275,55 @@ function tests.check_forward_content_modified() } end +function tests.check_pending_request_tracked() + skeleton { + on_init = function(_) + return { capabilities = {} } + end; + body = function() + local msg = read_message() + assert_eq('slow_request', msg.method) + expect_notification('release') + respond(msg.id, nil, {}) + expect_notification('finish') + notify('finish') + end; + } +end + +function tests.check_cancel_request_tracked() + skeleton { + on_init = function(_) + return { capabilities = {} } + end; + body = function() + local msg = read_message() + assert_eq('slow_request', msg.method) + expect_notification('$/cancelRequest', {id=msg.id}) + expect_notification('release') + respond(msg.id, {code = -32800}, nil) + notify('finish') + end; + } +end + +function tests.check_tracked_requests_cleared() + skeleton { + on_init = function(_) + return { capabilities = {} } + end; + body = function() + local msg = read_message() + assert_eq('slow_request', msg.method) + expect_notification('$/cancelRequest', {id=msg.id}) + expect_notification('release') + respond(msg.id, nil, {}) + expect_notification('finish') + notify('finish') + end; + } +end + function tests.basic_finish() skeleton { on_init = function(params) @@ -622,6 +671,20 @@ function tests.code_action_with_resolve() } end +function tests.clientside_commands() + skeleton { + on_init = function() + return { + capabilities = {} + } + end; + body = function() + notify('start') + notify('shutdown') + end; + } +end + -- Tests will be indexed by TEST_NAME local kill_timer = vim.loop.new_timer() diff --git a/test/functional/lua/api_spec.lua b/test/functional/lua/api_spec.lua index 8551c3d2a0..81e00bba6d 100644 --- a/test/functional/lua/api_spec.lua +++ b/test/functional/lua/api_spec.lua @@ -2,6 +2,7 @@ local helpers = require('test.functional.helpers')(after_each) local exc_exec = helpers.exc_exec +local remove_trace = helpers.remove_trace local funcs = helpers.funcs local clear = helpers.clear local eval = helpers.eval @@ -159,44 +160,44 @@ describe('luaeval(vim.api.…)', function() it('errors out correctly when working with API', function() -- Conversion errors eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua type', - exc_exec([[call luaeval("vim.api.nvim__id(vim.api.nvim__id)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id(vim.api.nvim__id)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua table', - exc_exec([[call luaeval("vim.api.nvim__id({1, foo=42})")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id({1, foo=42})")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua type', - exc_exec([[call luaeval("vim.api.nvim__id({42, vim.api.nvim__id})")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id({42, vim.api.nvim__id})")]]))) -- Errors in number of arguments eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected 1 argument', - exc_exec([[call luaeval("vim.api.nvim__id()")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id()")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected 1 argument', - exc_exec([[call luaeval("vim.api.nvim__id(1, 2)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id(1, 2)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected 2 arguments', - exc_exec([[call luaeval("vim.api.nvim_set_var(1, 2, 3)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim_set_var(1, 2, 3)")]]))) -- Error in argument types eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua string', - exc_exec([[call luaeval("vim.api.nvim_set_var(1, 2)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim_set_var(1, 2)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua number', - exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 'test', 1, false)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 'test', 1, false)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Number is not integral', - exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 1.5, 1, false)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 1.5, 1, false)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua table', - exc_exec([[call luaeval("vim.api.nvim__id_float('test')")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_float('test')")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Unexpected type', - exc_exec([[call luaeval("vim.api.nvim__id_float({[vim.type_idx]=vim.types.dictionary})")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_float({[vim.type_idx]=vim.types.dictionary})")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua table', - exc_exec([[call luaeval("vim.api.nvim__id_array(1)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_array(1)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Unexpected type', - exc_exec([[call luaeval("vim.api.nvim__id_array({[vim.type_idx]=vim.types.dictionary})")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_array({[vim.type_idx]=vim.types.dictionary})")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua table', - exc_exec([[call luaeval("vim.api.nvim__id_dictionary(1)")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_dictionary(1)")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Unexpected type', - exc_exec([[call luaeval("vim.api.nvim__id_dictionary({[vim.type_idx]=vim.types.array})")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_dictionary({[vim.type_idx]=vim.types.array})")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua table', - exc_exec([[call luaeval("vim.api.nvim_set_keymap('', '', '', '')")]])) + remove_trace(exc_exec([[call luaeval("vim.api.nvim_set_keymap('', '', '', '')")]]))) -- TODO: check for errors with Tabpage argument -- TODO: check for errors with Window argument diff --git a/test/functional/lua/commands_spec.lua b/test/functional/lua/commands_spec.lua index 2e0d0ea899..9b9ba531b0 100644 --- a/test/functional/lua/commands_spec.lua +++ b/test/functional/lua/commands_spec.lua @@ -17,6 +17,7 @@ local pcall_err = helpers.pcall_err local write_file = helpers.write_file local exec_capture = helpers.exec_capture local curbufmeths = helpers.curbufmeths +local remove_trace = helpers.remove_trace before_each(clear) @@ -46,9 +47,9 @@ describe(':lua command', function() eq([[Vim(lua):E5107: Error loading lua [string ":lua"]:0: unexpected symbol near ')']], pcall_err(command, 'lua ()')) eq([[Vim(lua):E5108: Error executing lua [string ":lua"]:1: TEST]], - exc_exec('lua error("TEST")')) + remove_trace(exc_exec('lua error("TEST")'))) eq([[Vim(lua):E5108: Error executing lua [string ":lua"]:1: Invalid buffer id: -10]], - exc_exec('lua vim.api.nvim_buf_set_lines(-10, 1, 1, false, {"TEST"})')) + remove_trace(exc_exec('lua vim.api.nvim_buf_set_lines(-10, 1, 1, false, {"TEST"})'))) eq({''}, curbufmeths.get_lines(0, 100, false)) end) it('works with NULL errors', function() @@ -95,15 +96,15 @@ describe(':lua command', function() feed(':lua error("fail\\nmuch error\\nsuch details")<cr>') screen:expect{grid=[[ - | - {1:~ }| - {1:~ }| - {1:~ }| {2: }| {3:E5108: Error executing lua [string ":lua}| {3:"]:1: fail} | {3:much error} | {3:such details} | + {3:stack traceback:} | + {3: [C]: in function 'error'} | + {3: [string ":lua"]:1: in main chunk}| + | {4:Press ENTER or type command to continue}^ | ]]} feed('<cr>') @@ -119,24 +120,24 @@ describe(':lua command', function() {1:~ }| | ]]} - eq('E5108: Error executing lua [string ":lua"]:1: fail\nmuch error\nsuch details', eval('v:errmsg')) + eq('E5108: Error executing lua [string ":lua"]:1: fail\nmuch error\nsuch details', remove_trace(eval('v:errmsg'))) local status, err = pcall(command,'lua error("some error\\nin a\\nAPI command")') local expected = 'Vim(lua):E5108: Error executing lua [string ":lua"]:1: some error\nin a\nAPI command' eq(false, status) - eq(expected, string.sub(err, -string.len(expected))) + eq(expected, string.sub(remove_trace(err), -string.len(expected))) feed(':messages<cr>') screen:expect{grid=[[ - | - {1:~ }| - {1:~ }| - {1:~ }| {2: }| {3:E5108: Error executing lua [string ":lua}| {3:"]:1: fail} | {3:much error} | {3:such details} | + {3:stack traceback:} | + {3: [C]: in function 'error'} | + {3: [string ":lua"]:1: in main chunk}| + | {4:Press ENTER or type command to continue}^ | ]]} end) @@ -219,7 +220,7 @@ describe(':luafile', function() exc_exec('luafile ' .. fname)) write_file(fname, 'vimm.api.nvim_buf_set_lines(1, 1, 2, false, {"ETTS"})') eq(("Vim(luafile):E5113: Error while calling lua chunk: %s:1: attempt to index global 'vimm' (a nil value)"):format(fname), - exc_exec('luafile ' .. fname)) + remove_trace(exc_exec('luafile ' .. fname))) end) it('works with NULL errors', function() write_file(fname, 'error(nil)') diff --git a/test/functional/lua/diagnostic_spec.lua b/test/functional/lua/diagnostic_spec.lua index 1cbfa224cc..e8bbee671e 100644 --- a/test/functional/lua/diagnostic_spec.lua +++ b/test/functional/lua/diagnostic_spec.lua @@ -6,6 +6,8 @@ local clear = helpers.clear local exec_lua = helpers.exec_lua local eq = helpers.eq local nvim = helpers.nvim +local matches = helpers.matches +local pcall_err = helpers.pcall_err describe('vim.diagnostic', function() before_each(function() @@ -47,7 +49,21 @@ describe('vim.diagnostic', function() end function count_extmarks(bufnr, namespace) - return #vim.api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, {}) + local ns = vim.diagnostic.get_namespace(namespace) + local extmarks = 0 + if ns.user_data.virt_text_ns then + extmarks = extmarks + #vim.api.nvim_buf_get_extmarks(bufnr, ns.user_data.virt_text_ns, 0, -1, {}) + end + if ns.user_data.underline_ns then + extmarks = extmarks + #vim.api.nvim_buf_get_extmarks(bufnr, ns.user_data.underline_ns, 0, -1, {}) + end + return extmarks + end + + function get_virt_text_extmarks(ns) + local ns = vim.diagnostic.get_namespace(ns) + local virt_text_ns = ns.user_data.virt_text_ns + return vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, virt_text_ns, 0, -1, {details = true}) end ]] @@ -567,7 +583,7 @@ describe('vim.diagnostic', function() ]] eq(1, exec_lua [[return count_diagnostics(diagnostic_bufnr, vim.diagnostic.severity.ERROR, diagnostic_ns)]]) - eq(1, exec_lua [[return count_extmarks(diagnostic_bufnr, diagnostic_ns)]]) + -- eq(1, exec_lua [[return count_extmarks(diagnostic_bufnr, diagnostic_ns)]]) end) it('allows filtering by severity', function() @@ -615,7 +631,7 @@ describe('vim.diagnostic', function() severity_sort = severity_sort, }) - local virt_text = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true})[1][4].virt_text + local virt_text = get_virt_text_extmarks(diagnostic_ns)[1][4].virt_text local virt_texts = {} for i = 2, #virt_text do @@ -661,7 +677,7 @@ describe('vim.diagnostic', function() } }) - local extmarks = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true}) + local extmarks = get_virt_text_extmarks(diagnostic_ns) local virt_text = extmarks[1][4].virt_text[2][1] return virt_text ]] @@ -676,7 +692,7 @@ describe('vim.diagnostic', function() } }, diagnostic_ns) - local extmarks = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true}) + local extmarks = get_virt_text_extmarks(diagnostic_ns) local virt_text = extmarks[1][4].virt_text[2][1] return virt_text ]] @@ -696,7 +712,7 @@ describe('vim.diagnostic', function() } }) - local extmarks = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true}) + local extmarks = get_virt_text_extmarks(diagnostic_ns) local virt_text = {extmarks[1][4].virt_text[2][1], extmarks[2][4].virt_text[2][1]} return virt_text ]] @@ -724,7 +740,7 @@ describe('vim.diagnostic', function() make_error('Error', 1, 0, 1, 0), }) - local extmarks = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true}) + local extmarks = get_virt_text_extmarks(diagnostic_ns) return {extmarks[1][4].virt_text, extmarks[2][4].virt_text} ]] eq(" 👀 Warning", result[1][2][1]) @@ -752,7 +768,7 @@ describe('vim.diagnostic', function() make_error('Error', 1, 0, 1, 0, 'another_linter'), }) - local extmarks = vim.api.nvim_buf_get_extmarks(diagnostic_bufnr, diagnostic_ns, 0, -1, {details = true}) + local extmarks = get_virt_text_extmarks(diagnostic_ns) return {extmarks[1][4].virt_text, extmarks[2][4].virt_text} ]] eq(" some_linter: 👀 Warning", result[1][2][1]) @@ -800,13 +816,11 @@ describe('vim.diagnostic', function() virtual_text = true, }) - -- Count how many times we call display. - SetVirtualTextOriginal = vim.diagnostic._set_virtual_text - DisplayCount = 0 - vim.diagnostic._set_virtual_text = function(...) + local set_virtual_text = vim.diagnostic.handlers.virtual_text.show + vim.diagnostic.handlers.virtual_text.show = function(...) DisplayCount = DisplayCount + 1 - return SetVirtualTextOriginal(...) + return set_virtual_text(...) end vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { @@ -850,13 +864,12 @@ describe('vim.diagnostic', function() virtual_text = false, }) - -- Count how many times we call display. - SetVirtualTextOriginal = vim.diagnostic._set_virtual_text DisplayCount = 0 - vim.diagnostic._set_virtual_text = function(...) + local set_virtual_text = vim.diagnostic.handlers.virtual_text.show + vim.diagnostic.handlers.virtual_text.show = function(...) DisplayCount = DisplayCount + 1 - return SetVirtualTextOriginal(...) + return set_virtual_text(...) end vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { @@ -1227,6 +1240,41 @@ describe('vim.diagnostic', function() return lines ]]) end) + + it('can filter by severity', function() + local count_diagnostics_with_severity = function(min_severity, max_severity) + return exec_lua([[ + local min_severity, max_severity = ... + vim.diagnostic.config({ + float = { + severity = {min=min_severity, max=max_severity}, + }, + }) + + vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { + make_error("Syntax error", 0, 1, 0, 3), + make_info('Info', 0, 3, 0, 4), + make_error('Error', 0, 2, 0, 2), + make_warning('Warning', 0, 0, 0, 1), + }) + + local float_bufnr, winnr = vim.diagnostic.open_float(diagnostic_bufnr, { show_header = false }) + if not float_bufnr then + return 0 + end + + local lines = vim.api.nvim_buf_get_lines(float_bufnr, 0, -1, false) + vim.api.nvim_win_close(winnr, true) + return #lines + ]], min_severity, max_severity) + end + + eq(2, count_diagnostics_with_severity("ERROR")) + eq(3, count_diagnostics_with_severity("WARN")) + eq(1, count_diagnostics_with_severity("WARN", "WARN")) + eq(4, count_diagnostics_with_severity("HINT")) + eq(0, count_diagnostics_with_severity("HINT", "HINT")) + end) end) describe('setloclist()', function() @@ -1347,4 +1395,73 @@ describe('vim.diagnostic', function() eq(result[1], result[2]) end) end) + + describe('handlers', function() + it('checks that a new handler is a table', function() + matches([[.*handler: expected table, got string.*]], pcall_err(exec_lua, [[ vim.diagnostic.handlers.foo = "bar" ]])) + matches([[.*handler: expected table, got function.*]], pcall_err(exec_lua, [[ vim.diagnostic.handlers.foo = function() end ]])) + end) + + it('can add new handlers', function() + eq(true, exec_lua [[ + local handler_called = false + vim.diagnostic.handlers.test = { + show = function(namespace, bufnr, diagnostics, opts) + assert(namespace == diagnostic_ns) + assert(bufnr == diagnostic_bufnr) + assert(#diagnostics == 1) + assert(opts.test.some_opt == 42) + handler_called = true + end, + } + + vim.diagnostic.config({test = {some_opt = 42}}) + vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { + make_warning("Warning", 0, 0, 0, 0), + }) + return handler_called + ]]) + end) + + it('can disable handlers by setting the corresponding option to false', function() + eq(false, exec_lua [[ + local handler_called = false + vim.diagnostic.handlers.test = { + show = function(namespace, bufnr, diagnostics, opts) + handler_called = true + end, + } + + vim.diagnostic.config({test = false}) + vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { + make_warning("Warning", 0, 0, 0, 0), + }) + return handler_called + ]]) + end) + + it('always calls a handler\'s hide function if defined', function() + eq({false, true}, exec_lua [[ + local hide_called = false + local show_called = false + vim.diagnostic.handlers.test = { + show = function(namespace, bufnr, diagnostics, opts) + show_called = true + end, + hide = function(namespace, bufnr) + assert(namespace == diagnostic_ns) + assert(bufnr == diagnostic_bufnr) + hide_called = true + end, + } + + vim.diagnostic.config({test = false}) + vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { + make_warning("Warning", 0, 0, 0, 0), + }) + vim.diagnostic.hide(diagnostic_ns, diagnostic_bufnr) + return {show_called, hide_called} + ]]) + end) + end) end) diff --git a/test/functional/lua/loop_spec.lua b/test/functional/lua/loop_spec.lua index 992d1666f6..7f3787d7bf 100644 --- a/test/functional/lua/loop_spec.lua +++ b/test/functional/lua/loop_spec.lua @@ -84,14 +84,14 @@ describe('vim.loop', function() screen:expect([[ | - {1:~ }| - {1:~ }| - {1:~ }| - {1:~ }| {2: }| {3:Error executing luv callback:} | {3:[string "<nvim>"]:5: E5560: nvim_set_var must not }| {3:be called in a lua loop callback} | + {3:stack traceback:} | + {3: [C]: in function 'nvim_set_var'} | + {3: [string "<nvim>"]:5: in function <[string }| + {3:"<nvim>"]:2>} | {4:Press ENTER or type command to continue}^ | ]]) feed('<cr>') diff --git a/test/functional/lua/luaeval_spec.lua b/test/functional/lua/luaeval_spec.lua index ab76e71a12..c543dd1995 100644 --- a/test/functional/lua/luaeval_spec.lua +++ b/test/functional/lua/luaeval_spec.lua @@ -4,6 +4,7 @@ local Screen = require('test.functional.ui.screen') local pcall_err = helpers.pcall_err local exc_exec = helpers.exc_exec +local remove_trace = helpers.remove_trace local exec_lua = helpers.exec_lua local command = helpers.command local meths = helpers.meths @@ -424,11 +425,11 @@ describe('luaeval()', function() it('errors out correctly when doing incorrect things in lua', function() -- Conversion errors eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: attempt to call field \'xxx_nonexistent_key_xxx\' (a nil value)', - exc_exec([[call luaeval("vim.xxx_nonexistent_key_xxx()")]])) + remove_trace(exc_exec([[call luaeval("vim.xxx_nonexistent_key_xxx()")]]))) eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: ERROR', - exc_exec([[call luaeval("error('ERROR')")]])) + remove_trace(exc_exec([[call luaeval("error('ERROR')")]]))) eq('Vim(call):E5108: Error executing lua [NULL]', - exc_exec([[call luaeval("error(nil)")]])) + remove_trace(exc_exec([[call luaeval("error(nil)")]]))) end) it('does not leak memory when called with too long line', diff --git a/test/functional/lua/mpack_spec.lua b/test/functional/lua/mpack_spec.lua index ef693f01f3..cc788ed8bb 100644 --- a/test/functional/lua/mpack_spec.lua +++ b/test/functional/lua/mpack_spec.lua @@ -7,16 +7,16 @@ local exec_lua = helpers.exec_lua describe('lua vim.mpack', function() before_each(clear) - it('can pack vim.NIL', function() + it('encodes vim.NIL', function() eq({true, true, true, true}, exec_lua [[ - local var = vim.mpack.unpack(vim.mpack.pack({33, vim.NIL, 77})) + local var = vim.mpack.decode(vim.mpack.encode({33, vim.NIL, 77})) return {var[1]==33, var[2]==vim.NIL, var[3]==77, var[4]==nil} ]]) end) - it('can pack vim.empty_dict()', function() + it('encodes vim.empty_dict()', function() eq({{{}, "foo", {}}, true, false}, exec_lua [[ - local var = vim.mpack.unpack(vim.mpack.pack({{}, "foo", vim.empty_dict()})) + local var = vim.mpack.decode(vim.mpack.encode({{}, "foo", vim.empty_dict()})) return {var, vim.tbl_islist(var[1]), vim.tbl_islist(var[3])} ]]) end) diff --git a/test/functional/lua/overrides_spec.lua b/test/functional/lua/overrides_spec.lua index 636479b81f..b0712ff366 100644 --- a/test/functional/lua/overrides_spec.lua +++ b/test/functional/lua/overrides_spec.lua @@ -161,15 +161,15 @@ describe('debug.debug', function() {0:~ }| {0:~ }| {0:~ }| - {0:~ }| - {0:~ }| - {0:~ }| nil | lua_debug> print("TEST") | TEST | | {E:E5108: Error executing lua [string ":lua"]:5: attempt}| {E: to perform arithmetic on local 'a' (a nil value)} | + {E:stack traceback:} | + {E: [string ":lua"]:5: in function 'Test'} | + {E: [string ":lua"]:1: in main chunk} | Interrupt: {cr:Press ENTER or type command to continue}^ | ]]} feed('<C-l>:lua Test()\n') @@ -197,13 +197,13 @@ describe('debug.debug', function() {0:~ }| {0:~ }| {0:~ }| - {0:~ }| - {0:~ }| - {0:~ }| nil | lua_debug> | {E:E5108: Error executing lua [string ":lua"]:5: attempt}| {E: to perform arithmetic on local 'a' (a nil value)} | + {E:stack traceback:} | + {E: [string ":lua"]:5: in function 'Test'} | + {E: [string ":lua"]:1: in main chunk} | {cr:Press ENTER or type command to continue}^ | ]]} end) diff --git a/test/functional/lua/vim_spec.lua b/test/functional/lua/vim_spec.lua index 8c691b1121..3832d27a22 100644 --- a/test/functional/lua/vim_spec.lua +++ b/test/functional/lua/vim_spec.lua @@ -4,7 +4,6 @@ local Screen = require('test.functional.ui.screen') local funcs = helpers.funcs local meths = helpers.meths -local dedent = helpers.dedent local command = helpers.command local insert = helpers.insert local clear = helpers.clear @@ -19,6 +18,7 @@ local source = helpers.source local NIL = helpers.NIL local retry = helpers.retry local next_msg = helpers.next_msg +local remove_trace = helpers.remove_trace before_each(clear) @@ -121,11 +121,6 @@ describe('lua stdlib', function() eq(1, funcs.luaeval('vim.stricmp("\\0C\\0", "\\0B\\0")')) end) - -- for brevity, match only the error header (not the traceback) - local function pcall_header(...) - return string.gsub(string.gsub(pcall_err(exec_lua, ...), '[\r\n].*', ''), '^Error executing lua: ', '') - end - it('vim.startswith', function() eq(true, funcs.luaeval('vim.startswith("123", "1")')) eq(true, funcs.luaeval('vim.startswith("123", "")')) @@ -136,8 +131,10 @@ describe('lua stdlib', function() eq(false, funcs.luaeval('vim.startswith("123", "2")')) eq(false, funcs.luaeval('vim.startswith("123", "1234")')) - eq("vim/shared.lua:0: prefix: expected string, got nil", pcall_header 'return vim.startswith("123", nil)') - eq("vim/shared.lua:0: s: expected string, got nil", pcall_header 'return vim.startswith(nil, "123")') + eq("Error executing lua: vim/shared.lua:0: prefix: expected string, got nil", + pcall_err(exec_lua, 'return vim.startswith("123", nil)')) + eq("Error executing lua: vim/shared.lua:0: s: expected string, got nil", + pcall_err(exec_lua, 'return vim.startswith(nil, "123")')) end) it('vim.endswith', function() @@ -150,8 +147,10 @@ describe('lua stdlib', function() eq(false, funcs.luaeval('vim.endswith("123", "2")')) eq(false, funcs.luaeval('vim.endswith("123", "1234")')) - eq("vim/shared.lua:0: suffix: expected string, got nil", pcall_header 'return vim.endswith("123", nil)') - eq("vim/shared.lua:0: s: expected string, got nil", pcall_header 'return vim.endswith(nil, "123")') + eq("Error executing lua: vim/shared.lua:0: suffix: expected string, got nil", + pcall_err(exec_lua, 'return vim.endswith("123", nil)')) + eq("Error executing lua: vim/shared.lua:0: s: expected string, got nil", + pcall_err(exec_lua, 'return vim.endswith(nil, "123")')) end) it("vim.str_utfindex/str_byteindex", function() @@ -179,6 +178,31 @@ describe('lua stdlib', function() end end) + it("vim.str_utf_start", function() + exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]]) + local expected_positions = {0,0,0,0,-1,0,-1,0,-1,0,0,-1,0,0,-1,-2,0,-1,-2,0,0,-1,-2,0,0,-1,-2,-3,0,0,-1,-2,-3,0,0,0,-1,0,0,-1,0,-1,0,-1,0,-1,0,-1} + eq(expected_positions, exec_lua([[ + local start_codepoint_positions = {} + for idx = 1, #_G.test_text do + table.insert(start_codepoint_positions, vim.str_utf_start(_G.test_text, idx)) + end + return start_codepoint_positions + ]])) + end) + + it("vim.str_utf_end", function() + exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]]) + local expected_positions = {0,0,0,1,0,1,0,1,0,0,1,0,0,2,1,0,2,1,0,0,2,1,0,0,3,2,1,0,0,3,2,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,1,0 } + eq(expected_positions, exec_lua([[ + local end_codepoint_positions = {} + for idx = 1, #_G.test_text do + table.insert(end_codepoint_positions, vim.str_utf_end(_G.test_text, idx)) + end + return end_codepoint_positions + ]])) + end) + + it("vim.str_utf_pos", function() exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]]) local expected_positions = { 1,2,3,4,6,8,10,11,13,14,17,20,21,24,25,29,30,34,35,36,38,39,41,43,45,47 } @@ -208,7 +232,7 @@ describe('lua stdlib', function() ]]) feed("<cr>") - eq('Error executing vim.schedule lua callback: [string "<nvim>"]:2: big failure\nvery async', eval("v:errmsg")) + eq('Error executing vim.schedule lua callback: [string "<nvim>"]:2: big failure\nvery async', remove_trace(eval("v:errmsg"))) local screen = Screen.new(60,5) screen:set_default_attr_ids({ @@ -234,10 +258,10 @@ describe('lua stdlib', function() end) ]]) screen:expect{grid=[[ - | - {2: }| - {3:Error executing vim.schedule lua callback: [string "<nvim>"]}| - {3::2: Vim(echo):E115: Missing quote: 'err} | + {3:stack traceback:} | + {3: [C]: in function 'nvim_command'} | + {3: [string "<nvim>"]:2: in function <[string "<nvim>"]:}| + {3:1>} | {4:Press ENTER or type command to continue}^ | ]]} end) @@ -281,22 +305,11 @@ describe('lua stdlib', function() -- Validates args. eq(true, pcall(split, 'string', 'string')) - eq(dedent([[ - Error executing lua: vim/shared.lua:0: s: expected string, got number - stack traceback: - vim/shared.lua:0: in function 'gsplit' - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: s: expected string, got number', pcall_err(split, 1, 'string')) - eq(dedent([[ - Error executing lua: vim/shared.lua:0: sep: expected string, got number - stack traceback: - vim/shared.lua:0: in function 'gsplit' - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: sep: expected string, got number', pcall_err(split, 'string', 1)) - eq(dedent([[ - Error executing lua: vim/shared.lua:0: kwargs: expected table, got number - stack traceback: - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: kwargs: expected table, got number', pcall_err(split, 'string', 'string', 1)) end) @@ -317,10 +330,7 @@ describe('lua stdlib', function() end -- Validates args. - eq(dedent([[ - Error executing lua: vim/shared.lua:0: s: expected string, got number - stack traceback: - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: s: expected string, got number', pcall_err(trim, 2)) end) @@ -399,10 +409,7 @@ describe('lua stdlib', function() eq('foo%%%-bar', exec_lua([[return vim.pesc(vim.pesc('foo-bar'))]])) -- Validates args. - eq(dedent([[ - Error executing lua: vim/shared.lua:0: s: expected string, got number - stack traceback: - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: s: expected string, got number', pcall_err(exec_lua, [[return vim.pesc(2)]])) end) @@ -685,10 +692,7 @@ describe('lua stdlib', function() it('vim.list_extend', function() eq({1,2,3}, exec_lua [[ return vim.list_extend({1}, {2,3}) ]]) - eq(dedent([[ - Error executing lua: vim/shared.lua:0: src: expected table, got nil - stack traceback: - vim/shared.lua:0: in function <vim/shared.lua:0>]]), + eq('Error executing lua: vim/shared.lua:0: src: expected table, got nil', pcall_err(exec_lua, [[ return vim.list_extend({1}, nil) ]])) eq({1,2}, exec_lua [[ return vim.list_extend({1}, {2;a=1}) ]]) eq(true, exec_lua [[ local a = {1} return vim.list_extend(a, {2;a=1}) == a ]]) @@ -820,12 +824,12 @@ describe('lua stdlib', function() end) ]]) screen:expect{grid=[[ - foo | - {1:~ }| - {2: }| - {3:Error executing luv callback:} | {3:[string "<nvim>"]:6: E5560: rpcrequest must not be}| {3: called in a lua loop callback} | + {3:stack traceback:} | + {3: [C]: in function 'rpcrequest'} | + {3: [string "<nvim>"]:6: in function <[string }| + {3:"<nvim>"]:2>} | {4:Press ENTER or type command to continue}^ | ]]} feed('<cr>') @@ -889,76 +893,37 @@ describe('lua stdlib', function() exec_lua("vim.validate{arg1={{}, 't' }, arg2={ 'foo', 's' }}") exec_lua("vim.validate{arg1={2, function(a) return (a % 2) == 0 end, 'even number' }}") - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: opt[1]: expected table, got number - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: opt[1]: expected table, got number', pcall_err(exec_lua, "vim.validate{ 1, 'x' }")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: invalid type name: x - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: invalid type name: x', pcall_err(exec_lua, "vim.validate{ arg1={ 1, 'x' }}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: invalid type name: 1 - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: invalid type name: 1', pcall_err(exec_lua, "vim.validate{ arg1={ 1, 1 }}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: invalid type name: nil - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: invalid type name: nil', pcall_err(exec_lua, "vim.validate{ arg1={ 1 }}")) -- Validated parameters are required by default. - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil', pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's' }}")) -- Explicitly required. - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil', pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's', false }}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected table, got number - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected table, got number', pcall_err(exec_lua, "vim.validate{arg1={1, 't'}}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg2: expected string, got number - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got number', pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={1, 's'}}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil', pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil', pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected even number, got 3 - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected even number, got 3', pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1 end, 'even number'}}")) - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3 - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3', pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1 end}}")) -- Pass an additional message back. - eq(dedent([[ - Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3. Info: TEST_MSG - stack traceback: - [string "<nvim>"]:0: in main chunk]]), + eq('Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3. Info: TEST_MSG', pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1, 'TEST_MSG' end}}")) end) @@ -2108,9 +2073,10 @@ describe('lua stdlib', function() end) it('should not crash when callback errors', function() - eq({false, '[string "<nvim>"]:1: As Expected'}, exec_lua [[ + local result = exec_lua [[ return {pcall(function() vim.wait(1000, function() error("As Expected") end) end)} - ]]) + ]] + eq({false, '[string "<nvim>"]:1: As Expected'}, {result[1], remove_trace(result[2])}) end) it('if callback is passed, it must be a function', function() diff --git a/test/functional/plugin/health_spec.lua b/test/functional/plugin/health_spec.lua index b84e9d1533..b567b3e20c 100644 --- a/test/functional/plugin/health_spec.lua +++ b/test/functional/plugin/health_spec.lua @@ -134,7 +134,7 @@ describe('health.vim', function() command("checkhealth test_plug*") local buf_lines = helpers.curbuf('get_lines', 0, -1, true) -- avoid dealing with path separators - local received = table.concat(buf_lines, '\n', 1, #buf_lines - 2) + local received = table.concat(buf_lines, '\n', 1, #buf_lines - 5) local expected = helpers.dedent([[ test_plug: require("test_plug.health").check() @@ -175,10 +175,10 @@ describe('health.vim', function() it("gracefully handles broken lua healthcheck", function() command("checkhealth test_plug.submodule_failed") local buf_lines = helpers.curbuf('get_lines', 0, -1, true) - local received = table.concat(buf_lines, '\n', 1, #buf_lines - 2) + local received = table.concat(buf_lines, '\n', 1, #buf_lines - 5) -- avoid dealing with path separators local lua_err = "attempt to perform arithmetic on a nil value" - local last_line = buf_lines[#buf_lines - 1] + local last_line = buf_lines[#buf_lines - 4] assert(string.find(last_line, lua_err) ~= nil, "Lua error not present") local expected = global_helpers.dedent([[ diff --git a/test/functional/plugin/lsp/codelens_spec.lua b/test/functional/plugin/lsp/codelens_spec.lua index c8b75e65fc..ecc2f579b8 100644 --- a/test/functional/plugin/lsp/codelens_spec.lua +++ b/test/functional/plugin/lsp/codelens_spec.lua @@ -60,31 +60,4 @@ describe('vim.lsp.codelens', function() eq({[1] = {'Lens1', 'LspCodeLens'}}, virtual_text_chunks) end) - it('codelens uses client commands', function() - local fake_uri = "file:///fake/uri" - local cmd = exec_lua([[ - fake_uri = ... - local bufnr = vim.uri_to_bufnr(fake_uri) - vim.fn.bufload(bufnr) - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {'One line'}) - local lenses = { - { - range = { - start = { line = 0, character = 0, }, - ['end'] = { line = 0, character = 8 } - }, - command = { title = 'Lens1', command = 'Dummy' } - }, - } - vim.lsp.codelens.on_codelens(nil, lenses, {method='textDocument/codeLens', client_id=1, bufnr=bufnr}) - local cmd_called = nil - vim.lsp.commands['Dummy'] = function(command) - cmd_called = command - end - vim.api.nvim_set_current_buf(bufnr) - vim.lsp.codelens.run() - return cmd_called - ]], fake_uri) - eq({ command = 'Dummy', title = 'Lens1' }, cmd) - end) end) diff --git a/test/functional/plugin/lsp/diagnostic_spec.lua b/test/functional/plugin/lsp/diagnostic_spec.lua index 243ad6bdb8..1269a2350c 100644 --- a/test/functional/plugin/lsp/diagnostic_spec.lua +++ b/test/functional/plugin/lsp/diagnostic_spec.lua @@ -3,7 +3,6 @@ local helpers = require('test.functional.helpers')(after_each) local clear = helpers.clear local exec_lua = helpers.exec_lua local eq = helpers.eq -local nvim = helpers.nvim describe('vim.lsp.diagnostic', function() local fake_uri @@ -45,11 +44,32 @@ describe('vim.lsp.diagnostic', function() } end - count_of_extmarks_for_client = function(bufnr, client_id) - return #vim.api.nvim_buf_get_extmarks( - bufnr, vim.lsp.diagnostic.get_namespace(client_id), 0, -1, {} - ) + function get_extmarks(bufnr, client_id) + local namespace = vim.lsp.diagnostic.get_namespace(client_id) + local ns = vim.diagnostic.get_namespace(namespace) + local extmarks = {} + if ns.user_data.virt_text_ns then + for _, e in pairs(vim.api.nvim_buf_get_extmarks(bufnr, ns.user_data.virt_text_ns, 0, -1, {details=true})) do + table.insert(extmarks, e) + end + end + if ns.user_data.underline_ns then + for _, e in pairs(vim.api.nvim_buf_get_extmarks(bufnr, ns.user_data.underline_ns, 0, -1, {details=true})) do + table.insert(extmarks, e) + end + end + return extmarks end + + client_id = vim.lsp.start_client { + cmd_env = { + NVIM_LUA_NOTRACK = "1"; + }; + cmd = { + vim.v.progpath, '-es', '-u', 'NONE', '--headless' + }; + offset_encoding = "utf-16"; + } ]] fake_uri = "file:///fake/uri" @@ -69,366 +89,6 @@ describe('vim.lsp.diagnostic', function() end) describe('vim.lsp.diagnostic', function() - describe('handle_publish_diagnostics', function() - it('should be able to retrieve diagnostics from all buffers and clients', function() - local result = exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - make_error('Diagnostic #2', 2, 1, 2, 1), - }, 1, 1 - ) - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #3', 3, 1, 3, 1), - }, 2, 2 - ) - return vim.lsp.diagnostic.get_all() - ]] - eq(2, #result) - eq(2, #result[1]) - eq('Diagnostic #1', result[1][1].message) - end) - it('should be able to save and count a single client error', function() - eq(1, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - }, 0, 1 - ) - return vim.lsp.diagnostic.get_count(0, "Error", 1) - ]]) - end) - - it('should be able to save and count from two clients', function() - eq(2, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - make_error('Diagnostic #2', 2, 1, 2, 1), - }, 0, 1 - ) - return vim.lsp.diagnostic.get_count(0, "Error", 1) - ]]) - end) - - it('should be able to save and count from multiple clients', function() - eq({1, 1, 2}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic From Server 1', 1, 1, 1, 1), - }, 0, 1 - ) - vim.lsp.diagnostic.save( - { - make_error('Diagnostic From Server 2', 1, 1, 1, 1), - }, 0, 2 - ) - return { - -- Server 1 - vim.lsp.diagnostic.get_count(0, "Error", 1), - -- Server 2 - vim.lsp.diagnostic.get_count(0, "Error", 2), - -- All servers - vim.lsp.diagnostic.get_count(0, "Error", nil), - } - ]]) - end) - - it('should be able to save and count from multiple clients with respect to severity', function() - eq({3, 0, 3}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic From Server 1:1', 1, 1, 1, 1), - make_error('Diagnostic From Server 1:2', 2, 2, 2, 2), - make_error('Diagnostic From Server 1:3', 2, 3, 3, 2), - }, 0, 1 - ) - vim.lsp.diagnostic.save( - { - make_warning('Warning From Server 2', 3, 3, 3, 3), - }, 0, 2 - ) - return { - -- Server 1 - vim.lsp.diagnostic.get_count(0, "Error", 1), - -- Server 2 - vim.lsp.diagnostic.get_count(0, "Error", 2), - -- All servers - vim.lsp.diagnostic.get_count(0, "Error", nil), - } - ]]) - end) - it('should handle one server clearing highlights while the other still has highlights', function() - -- 1 Error (1) - -- 1 Warning (2) - -- 1 Warning (2) + 1 Warning (1) - -- 2 highlights and 2 underlines (since error) - -- 1 highlight + 1 underline - local all_highlights = {1, 1, 2, 4, 2} - eq(all_highlights, exec_lua [[ - local server_1_diags = { - make_error("Error 1", 1, 1, 1, 5), - make_warning("Warning on Server 1", 2, 1, 2, 5), - } - local server_2_diags = { - make_warning("Warning 1", 2, 1, 2, 5), - } - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_1_diags }, {client_id=1}) - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_2_diags }, {client_id=2}) - return { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]]) - - -- Clear diagnostics from server 1, and make sure we have the right amount of stuff for client 2 - eq({1, 1, 2, 0, 2}, exec_lua [[ - vim.lsp.diagnostic.disable(diagnostic_bufnr, 1) - return { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]]) - - -- Show diagnostics from server 1 again - eq(all_highlights, exec_lua([[ - vim.lsp.diagnostic.enable(diagnostic_bufnr, 1) - return { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]])) - end) - - it('should not display diagnostics when disabled', function() - eq({0, 2}, exec_lua [[ - local server_1_diags = { - make_error("Error 1", 1, 1, 1, 5), - make_warning("Warning on Server 1", 2, 1, 2, 5), - } - local server_2_diags = { - make_warning("Warning 1", 2, 1, 2, 5), - } - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_1_diags }, {client_id=1}) - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_2_diags }, {client_id=2}) - - vim.lsp.diagnostic.disable(diagnostic_bufnr, 1) - - return { - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]]) - - eq({4, 0}, exec_lua [[ - vim.lsp.diagnostic.enable(diagnostic_bufnr, 1) - vim.lsp.diagnostic.disable(diagnostic_bufnr, 2) - - return { - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]]) - end) - - describe('reset', function() - it('diagnostic count is 0 and displayed diagnostics are 0 after call', function() - -- 1 Error (1) - -- 1 Warning (2) - -- 1 Warning (2) + 1 Warning (1) - -- 2 highlights and 2 underlines (since error) - -- 1 highlight + 1 underline - local all_highlights = {1, 1, 2, 4, 2} - eq(all_highlights, exec_lua [[ - local server_1_diags = { - make_error("Error 1", 1, 1, 1, 5), - make_warning("Warning on Server 1", 2, 1, 2, 5), - } - local server_2_diags = { - make_warning("Warning 1", 2, 1, 2, 5), - } - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_1_diags }, {client_id=1}) - vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = server_2_diags }, {client_id=2}) - return { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } - ]]) - - -- Reset diagnostics from server 1 - exec_lua([[ vim.lsp.diagnostic.reset(1, { [ diagnostic_bufnr ] = { [ 1 ] = true ; [ 2 ] = true } } )]]) - - -- Make sure we have the right diagnostic count - eq({0, 1, 1, 0, 2} , exec_lua [[ - local diagnostic_count = {} - vim.wait(100, function () diagnostic_count = { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } end ) - return diagnostic_count - ]]) - - -- Reset diagnostics from server 2 - exec_lua([[ vim.lsp.diagnostic.reset(2, { [ diagnostic_bufnr ] = { [ 1 ] = true ; [ 2 ] = true } } )]]) - - -- Make sure we have the right diagnostic count - eq({0, 0, 0, 0, 0}, exec_lua [[ - local diagnostic_count = {} - vim.wait(100, function () diagnostic_count = { - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", 2), - vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Warning", nil), - count_of_extmarks_for_client(diagnostic_bufnr, 1), - count_of_extmarks_for_client(diagnostic_bufnr, 2), - } end ) - return diagnostic_count - ]]) - - end) - end) - - describe('get_next_diagnostic_pos', function() - it('can find the next pos with only one client', function() - eq({1, 1}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - return vim.lsp.diagnostic.get_next_pos() - ]]) - end) - - it('can find next pos with two errors', function() - eq({4, 4}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - make_error('Diagnostic #2', 4, 4, 4, 4), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_next_pos { client_id = 1 } - ]]) - end) - - it('can cycle when position is past error', function() - eq({1, 1}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_next_pos { client_id = 1 } - ]]) - end) - - it('will not cycle when wrap is off', function() - eq(false, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_next_pos { client_id = 1, wrap = false } - ]]) - end) - - it('can cycle even from the last line', function() - eq({4, 4}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #2', 4, 4, 4, 4), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {vim.api.nvim_buf_line_count(0), 1}) - return vim.lsp.diagnostic.get_prev_pos { client_id = 1 } - ]]) - end) - end) - - describe('get_prev_diagnostic_pos', function() - it('can find the prev pos with only one client', function() - eq({1, 1}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_prev_pos() - ]]) - end) - - it('can find prev pos with two errors', function() - eq({1, 1}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #1', 1, 1, 1, 1), - make_error('Diagnostic #2', 4, 4, 4, 4), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_prev_pos { client_id = 1 } - ]]) - end) - - it('can cycle when position is past error', function() - eq({4, 4}, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #2', 4, 4, 4, 4), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_prev_pos { client_id = 1 } - ]]) - end) - - it('respects wrap parameter', function() - eq(false, exec_lua [[ - vim.lsp.diagnostic.save( - { - make_error('Diagnostic #2', 4, 4, 4, 4), - }, diagnostic_bufnr, 1 - ) - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.api.nvim_win_set_cursor(0, {3, 1}) - return vim.lsp.diagnostic.get_prev_pos { client_id = 1, wrap = false} - ]]) - end) - end) - end) - it('maintains LSP information when translating diagnostics', function() local result = exec_lua [[ local diagnostics = { @@ -442,7 +102,7 @@ describe('vim.lsp.diagnostic', function() vim.lsp.diagnostic.on_publish_diagnostics(nil, { uri = fake_uri, diagnostics = diagnostics, - }, {client_id=1}) + }, {client_id=client_id}) return { vim.diagnostic.get(diagnostic_bufnr, {lnum=1})[1], @@ -456,246 +116,7 @@ describe('vim.lsp.diagnostic', function() end) end) - describe("vim.lsp.diagnostic.get_line_diagnostics", function() - it('should return an empty table when no diagnostics are present', function() - eq({}, exec_lua [[return vim.lsp.diagnostic.get_line_diagnostics(diagnostic_bufnr, 1)]]) - end) - - it('should return all diagnostics when no severity is supplied', function() - eq(2, exec_lua [[ - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error("Error 1", 1, 1, 1, 5), - make_warning("Warning on Server 1", 1, 1, 2, 5), - make_error("Error On Other Line", 2, 1, 1, 5), - } - }, {client_id=1}) - - return #vim.lsp.diagnostic.get_line_diagnostics(diagnostic_bufnr, 1) - ]]) - end) - - it('should return only requested diagnostics when severity_limit is supplied', function() - eq(2, exec_lua [[ - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error("Error 1", 1, 1, 1, 5), - make_warning("Warning on Server 1", 1, 1, 2, 5), - make_information("Ignored information", 1, 1, 2, 5), - make_error("Error On Other Line", 2, 1, 1, 5), - } - }, {client_id=1}) - - return #vim.lsp.diagnostic.get_line_diagnostics(diagnostic_bufnr, 1, { severity_limit = "Warning" }) - ]]) - end) - end) - describe("vim.lsp.diagnostic.on_publish_diagnostics", function() - it('can use functions for config values', function() - exec_lua [[ - vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - virtual_text = function() return true end, - })(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(2, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - - -- Now, don't enable virtual text. - -- We should have one less extmark displayed. - exec_lua [[ - vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - virtual_text = function() return false end, - })(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(1, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - end) - - it('can perform updates after insert_leave', function() - exec_lua [[vim.api.nvim_set_current_buf(diagnostic_bufnr)]] - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - -- Save the diagnostics - exec_lua [[ - vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - update_in_insert = false, - })(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - -- No diagnostics displayed yet. - eq({mode='i', blocking=false}, nvim("get_mode")) - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(0, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(2, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - end) - - it('does not perform updates when not needed', function() - exec_lua [[vim.api.nvim_set_current_buf(diagnostic_bufnr)]] - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - -- Save the diagnostics - exec_lua [[ - PublishDiagnostics = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - update_in_insert = false, - virtual_text = true, - }) - - -- Count how many times we call display. - SetVirtualTextOriginal = vim.diagnostic._set_virtual_text - - DisplayCount = 0 - vim.diagnostic._set_virtual_text = function(...) - DisplayCount = DisplayCount + 1 - return SetVirtualTextOriginal(...) - end - - PublishDiagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - -- No diagnostics displayed yet. - eq({mode='i', blocking=false}, nvim("get_mode")) - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(0, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - eq(0, exec_lua [[return DisplayCount]]) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(2, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - eq(1, exec_lua [[return DisplayCount]]) - - -- Go in and out of insert mode one more time. - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - -- Should not have set the virtual text again. - eq(1, exec_lua [[return DisplayCount]]) - end) - - it('never sets virtual text, in combination with insert leave', function() - exec_lua [[vim.api.nvim_set_current_buf(diagnostic_bufnr)]] - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - -- Save the diagnostics - exec_lua [[ - PublishDiagnostics = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - update_in_insert = false, - virtual_text = false, - }) - - -- Count how many times we call display. - SetVirtualTextOriginal = vim.lsp.diagnostic.set_virtual_text - - DisplayCount = 0 - vim.lsp.diagnostic.set_virtual_text = function(...) - DisplayCount = DisplayCount + 1 - return SetVirtualTextOriginal(...) - end - - PublishDiagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - -- No diagnostics displayed yet. - eq({mode='i', blocking=false}, nvim("get_mode")) - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(0, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - eq(0, exec_lua [[return DisplayCount]]) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(1, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - eq(0, exec_lua [[return DisplayCount]]) - - -- Go in and out of insert mode one more time. - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - -- Should not have set the virtual text still. - eq(0, exec_lua [[return DisplayCount]]) - end) - - it('can perform updates while in insert mode, if desired', function() - exec_lua [[vim.api.nvim_set_current_buf(diagnostic_bufnr)]] - nvim("input", "o") - eq({mode='i', blocking=false}, nvim("get_mode")) - - -- Save the diagnostics - exec_lua [[ - vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - update_in_insert = true, - })(nil, { - uri = fake_uri, - diagnostics = { - make_error('Delayed Diagnostic', 4, 4, 4, 4), - } - }, {client_id=1} - ) - ]] - - -- Diagnostics are displayed, because the user wanted them that way! - eq({mode='i', blocking=false}, nvim("get_mode")) - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(2, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - - nvim("input", "<esc>") - eq({mode='n', blocking=false}, nvim("get_mode")) - - eq(1, exec_lua [[return vim.lsp.diagnostic.get_count(diagnostic_bufnr, "Error", 1)]]) - eq(2, exec_lua [[return count_of_extmarks_for_client(diagnostic_bufnr, 1)]]) - end) - it('allows configuring the virtual text via vim.lsp.with', function() local expected_spacing = 10 local extmarks = exec_lua([[ @@ -710,16 +131,10 @@ describe('vim.lsp.diagnostic', function() diagnostics = { make_error('Delayed Diagnostic', 4, 4, 4, 4), } - }, {client_id=1} + }, {client_id=client_id} ) - return vim.api.nvim_buf_get_extmarks( - diagnostic_bufnr, - vim.lsp.diagnostic.get_namespace(1), - 0, - -1, - { details = true } - ) + return get_extmarks(diagnostic_bufnr, client_id) ]], expected_spacing) local virt_text = extmarks[1][4].virt_text @@ -728,7 +143,6 @@ describe('vim.lsp.diagnostic', function() eq(expected_spacing, #spacing) end) - it('allows configuring the virtual text via vim.lsp.with using a function', function() local expected_spacing = 10 local extmarks = exec_lua([[ @@ -747,16 +161,10 @@ describe('vim.lsp.diagnostic', function() diagnostics = { make_error('Delayed Diagnostic', 4, 4, 4, 4), } - }, {client_id=1} + }, {client_id=client_id} ) - return vim.api.nvim_buf_get_extmarks( - diagnostic_bufnr, - vim.lsp.diagnostic.get_namespace(1), - 0, - -1, - { details = true } - ) + return get_extmarks(diagnostic_bufnr, client_id) ]], expected_spacing) local virt_text = extmarks[1][4].virt_text @@ -780,10 +188,10 @@ describe('vim.lsp.diagnostic', function() diagnostics = { make_warning('Delayed Diagnostic', 4, 4, 4, 4), } - }, {client_id=1} + }, {client_id=client_id} ) - return count_of_extmarks_for_client(diagnostic_bufnr, 1) + return #get_extmarks(diagnostic_bufnr, client_id) ]], severity_limit) end @@ -799,16 +207,6 @@ describe('vim.lsp.diagnostic', function() local line = "All 💼 and no 🎉 makes Jack a dull 👦" local result = exec_lua([[ local line = ... - local client_id = vim.lsp.start_client { - cmd_env = { - NVIM_LUA_NOTRACK = "1"; - }; - cmd = { - vim.v.progpath, '-es', '-u', 'NONE', '--headless' - }; - offset_encoding = "utf-16"; - } - vim.api.nvim_buf_set_lines(diagnostic_bufnr, 0, -1, false, {line}) vim.lsp.diagnostic.on_publish_diagnostics(nil, { @@ -829,145 +227,4 @@ describe('vim.lsp.diagnostic', function() eq(exec_lua([[return vim.str_byteindex(..., 8, true)]], line), result[1].end_col) end) end) - - describe('lsp.util.show_line_diagnostics', function() - it('creates floating window and returns popup bufnr and winnr if current line contains diagnostics', function() - -- Two lines: - -- Diagnostic: - -- 1. <msg> - eq(2, exec_lua [[ - local buffer = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_lines(buffer, 0, -1, false, { - "testing"; - "123"; - }) - local diagnostics = { - { - range = { - start = { line = 0; character = 1; }; - ["end"] = { line = 0; character = 3; }; - }; - severity = vim.lsp.protocol.DiagnosticSeverity.Error; - message = "Syntax error"; - }, - } - vim.api.nvim_win_set_buf(0, buffer) - vim.lsp.diagnostic.save(diagnostics, buffer, 1) - local popup_bufnr, winnr = vim.lsp.diagnostic.show_line_diagnostics() - return #vim.api.nvim_buf_get_lines(popup_bufnr, 0, -1, false) - ]]) - end) - - it('creates floating window and returns popup bufnr and winnr without header, if requested', function() - -- One line (since no header): - -- 1. <msg> - eq(1, exec_lua [[ - local buffer = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_lines(buffer, 0, -1, false, { - "testing"; - "123"; - }) - local diagnostics = { - { - range = { - start = { line = 0; character = 1; }; - ["end"] = { line = 0; character = 3; }; - }; - severity = vim.lsp.protocol.DiagnosticSeverity.Error; - message = "Syntax error"; - }, - } - vim.api.nvim_win_set_buf(0, buffer) - vim.lsp.diagnostic.save(diagnostics, buffer, 1) - local popup_bufnr, winnr = vim.lsp.diagnostic.show_line_diagnostics { show_header = false } - return #vim.api.nvim_buf_get_lines(popup_bufnr, 0, -1, false) - ]]) - end) - end) - - describe('set_signs', function() - -- TODO(tjdevries): Find out why signs are not displayed when set from Lua...?? - pending('sets signs by default', function() - exec_lua [[ - PublishDiagnostics = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - update_in_insert = true, - signs = true, - }) - - local diagnostics = { - make_error('Delayed Diagnostic', 1, 1, 1, 2), - make_error('Delayed Diagnostic', 3, 3, 3, 3), - } - - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = diagnostics - }, {client_id=1} - ) - - vim.lsp.diagnostic.set_signs(diagnostics, diagnostic_bufnr, 1) - -- return vim.fn.sign_getplaced() - ]] - - nvim("input", "o") - nvim("input", "<esc>") - - -- TODO(tjdevries): Find a way to get the signs to display in the test... - eq(nil, exec_lua [[ - return im.fn.sign_getplaced()[1].signs - ]]) - end) - end) - - describe('set_loclist()', function() - it('sets diagnostics in lnum order', function() - local loc_list = exec_lua [[ - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error('Farther Diagnostic', 4, 4, 4, 4), - make_error('Lower Diagnostic', 1, 1, 1, 1), - } - }, {client_id=1} - ) - - vim.lsp.diagnostic.set_loclist() - - return vim.fn.getloclist(0) - ]] - - assert(loc_list[1].lnum < loc_list[2].lnum) - end) - - it('sets diagnostics in lnum order, regardless of client', function() - local loc_list = exec_lua [[ - vim.api.nvim_win_set_buf(0, diagnostic_bufnr) - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_error('Lower Diagnostic', 1, 1, 1, 1), - } - }, {client_id=1} - ) - - vim.lsp.diagnostic.on_publish_diagnostics(nil, { - uri = fake_uri, - diagnostics = { - make_warning('Farther Diagnostic', 4, 4, 4, 4), - } - }, {client_id=2} - ) - - vim.lsp.diagnostic.set_loclist() - - return vim.fn.getloclist(0) - ]] - - assert(loc_list[1].lnum < loc_list[2].lnum) - end) - end) end) diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index ce50abb50d..c025e9f4ab 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -3,9 +3,11 @@ local helpers = require('test.functional.helpers')(after_each) local assert_log = helpers.assert_log local clear = helpers.clear local buf_lines = helpers.buf_lines +local command = helpers.command local dedent = helpers.dedent local exec_lua = helpers.exec_lua local eq = helpers.eq +local eval = helpers.eval local matches = helpers.matches local pcall_err = helpers.pcall_err local pesc = helpers.pesc @@ -272,7 +274,7 @@ describe('LSP', function() return end local expected_handlers = { - {NIL, {}, {method="shutdown", client_id=1}}; + {NIL, {}, {method="shutdown", bufnr=1, client_id=1}}; {NIL, {}, {method="test", client_id=1}}; } test_rpc_server { @@ -486,7 +488,7 @@ describe('LSP', function() it('should forward ContentModified to callback', function() local expected_handlers = { {NIL, {}, {method="finish", client_id=1}}; - {{code = -32801}, NIL, {method = "error_code_test", client_id=1}}; + {{code = -32801}, NIL, {method = "error_code_test", bufnr=1, client_id=1}}; } local client test_rpc_server { @@ -509,6 +511,140 @@ describe('LSP', function() } end) + it('should track pending requests to the language server', function() + local expected_handlers = { + {NIL, {}, {method="finish", client_id=1}}; + {NIL, {}, {method="slow_request", bufnr=1, client_id=1}}; + } + local client + test_rpc_server { + test_name = "check_pending_request_tracked"; + on_init = function(_client) + client = _client + client.request("slow_request") + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq("slow_request", request.method) + eq("pending", request.type) + client.notify("release") + end; + on_exit = function(code, signal) + eq(0, code, "exit code", fake_lsp_logfile) + eq(0, signal, "exit signal", fake_lsp_logfile) + eq(0, #expected_handlers, "did not call expected handler") + end; + on_handler = function(err, _, ctx) + eq(table.remove(expected_handlers), {err, {}, ctx}, "expected handler") + if ctx.method == 'slow_request' then + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq(NIL, request) + client.notify("finish") + end + if ctx.method == 'finish' then client.stop() end + end; + } + end) + + it('should track cancel requests to the language server', function() + local expected_handlers = { + {NIL, {}, {method="finish", client_id=1}}; + } + local client + test_rpc_server { + test_name = "check_cancel_request_tracked"; + on_init = function(_client) + client = _client + client.request("slow_request") + client.cancel_request(2) + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq("slow_request", request.method) + eq("cancel", request.type) + client.notify("release") + end; + on_exit = function(code, signal) + eq(0, code, "exit code", fake_lsp_logfile) + eq(0, signal, "exit signal", fake_lsp_logfile) + eq(0, #expected_handlers, "did not call expected handler") + end; + on_handler = function(err, _, ctx) + eq(table.remove(expected_handlers), {err, {}, ctx}, "expected handler") + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq(NIL, request) + if ctx.method == 'finish' then client.stop() end + end; + } + end) + + it('should clear pending and cancel requests on reply', function() + local expected_handlers = { + {NIL, {}, {method="finish", client_id=1}}; + {NIL, {}, {method="slow_request", bufnr=1, client_id=1}}; + } + local client + test_rpc_server { + test_name = "check_tracked_requests_cleared"; + on_init = function(_client) + client = _client + client.request("slow_request") + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq("slow_request", request.method) + eq("pending", request.type) + client.cancel_request(2) + request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq("slow_request", request.method) + eq("cancel", request.type) + client.notify("release") + end; + on_exit = function(code, signal) + eq(0, code, "exit code", fake_lsp_logfile) + eq(0, signal, "exit signal", fake_lsp_logfile) + eq(0, #expected_handlers, "did not call expected handler") + end; + on_handler = function(err, _, ctx) + eq(table.remove(expected_handlers), {err, {}, ctx}, "expected handler") + if ctx.method == 'slow_request' then + local request = exec_lua([=[ return TEST_RPC_CLIENT.requests[2] ]=]) + eq(NIL, request) + client.notify("finish") + end + if ctx.method == 'finish' then client.stop() end + end; + } + end) + + it('should trigger LspRequest autocmd when requests table changes', function() + local expected_handlers = { + {NIL, {}, {method="finish", client_id=1}}; + {NIL, {}, {method="slow_request", bufnr=1, client_id=1}}; + } + local client + test_rpc_server { + test_name = "check_tracked_requests_cleared"; + on_init = function(_client) + command('let g:requests = 0') + command('autocmd User LspRequest let g:requests+=1') + client = _client + client.request("slow_request") + eq(1, eval('g:requests')) + client.cancel_request(2) + eq(2, eval('g:requests')) + client.notify("release") + end; + on_exit = function(code, signal) + eq(0, code, "exit code", fake_lsp_logfile) + eq(0, signal, "exit signal", fake_lsp_logfile) + eq(0, #expected_handlers, "did not call expected handler") + eq(3, eval('g:requests')) + end; + on_handler = function(err, _, ctx) + eq(table.remove(expected_handlers), {err, {}, ctx}, "expected handler") + if ctx.method == 'slow_request' then + client.notify("finish") + end + if ctx.method == 'finish' then client.stop() end + end; + } + end) + it('should not send didOpen if the buffer closes before init', function() local expected_handlers = { {NIL, {}, {method="shutdown", client_id=1}}; @@ -790,7 +926,7 @@ describe('LSP', function() -- TODO(askhan) we don't support full for now, so we can disable these tests. pending('should check the body and didChange incremental normal mode editing', function() local expected_handlers = { - {NIL, {}, {method="shutdown", client_id=1}}; + {NIL, {}, {method="shutdown", bufnr=1, client_id=1}}; {NIL, {}, {method="finish", client_id=1}}; {NIL, {}, {method="start", client_id=1}}; } @@ -1017,15 +1153,9 @@ describe('LSP', function() end) it('should invalid cmd argument', function() - eq(dedent([[ - Error executing lua: .../lsp.lua:0: cmd: expected list, got nvim - stack traceback: - .../lsp.lua:0: in function <.../lsp.lua:0>]]), + eq('Error executing lua: .../lsp.lua:0: cmd: expected list, got nvim', pcall_err(_cmd_parts, 'nvim')) - eq(dedent([[ - Error executing lua: .../lsp.lua:0: cmd argument: expected string, got number - stack traceback: - .../lsp.lua:0: in function <.../lsp.lua:0>]]), + eq('Error executing lua: .../lsp.lua:0: cmd argument: expected string, got number', pcall_err(_cmd_parts, {'nvim', 1})) end) end) @@ -2395,4 +2525,57 @@ describe('LSP', function() ) end) end) + describe('vim.lsp.codelens', function() + it('uses client commands', function() + local client + local expected_handlers = { + {NIL, {}, {method="shutdown", client_id=1}}; + {NIL, {}, {method="start", client_id=1}}; + } + test_rpc_server { + test_name = 'clientside_commands', + on_init = function(client_) + client = client_ + end, + on_setup = function() + end, + on_exit = function(code, signal) + eq(0, code, "exit code", fake_lsp_logfile) + eq(0, signal, "exit signal", fake_lsp_logfile) + end, + on_handler = function(err, result, ctx) + eq(table.remove(expected_handlers), {err, result, ctx}) + if ctx.method == 'start' then + local fake_uri = "file:///fake/uri" + local cmd = exec_lua([[ + fake_uri = ... + local bufnr = vim.uri_to_bufnr(fake_uri) + vim.fn.bufload(bufnr) + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {'One line'}) + local lenses = { + { + range = { + start = { line = 0, character = 0, }, + ['end'] = { line = 0, character = 8 } + }, + command = { title = 'Lens1', command = 'Dummy' } + }, + } + vim.lsp.codelens.on_codelens(nil, lenses, {method='textDocument/codeLens', client_id=1, bufnr=bufnr}) + local cmd_called = nil + vim.lsp.commands['Dummy'] = function(command) + cmd_called = command + end + vim.api.nvim_set_current_buf(bufnr) + vim.lsp.codelens.run() + return cmd_called + ]], fake_uri) + eq({ command = 'Dummy', title = 'Lens1' }, cmd) + elseif ctx.method == 'shutdown' then + client.stop() + end + end + } + end) + end) end) diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua index f7520b14d4..6b9586b4de 100644 --- a/test/functional/terminal/tui_spec.lua +++ b/test/functional/terminal/tui_spec.lua @@ -494,6 +494,8 @@ describe('TUI', function() it('paste: recovers from vim.paste() failure', function() child_session:request('nvim_exec_lua', [[ _G.save_paste_fn = vim.paste + -- Stack traces for this test are non-deterministic, so disable them + _G.debug.traceback = function(msg) return msg end vim.paste = function(lines, phase) error("fake fail") end ]], {}) -- Prepare something for dot-repeat/redo. @@ -514,7 +516,7 @@ describe('TUI', function() foo | | {5: }| - {8:paste: Error executing lua: [string "<nvim>"]:2: f}| + {8:paste: Error executing lua: [string "<nvim>"]:4: f}| {8:ake fail} | {10:Press ENTER or type command to continue}{1: } | {3:-- TERMINAL --} | @@ -579,12 +581,16 @@ describe('TUI', function() it("paste: 'nomodifiable' buffer", function() child_session:request('nvim_command', 'set nomodifiable') + child_session:request('nvim_exec_lua', [[ + -- Stack traces for this test are non-deterministic, so disable them + _G.debug.traceback = function(msg) return msg end + ]], {}) feed_data('\027[200~fail 1\nfail 2\n\027[201~') screen:expect{grid=[[ | {4:~ }| {5: }| - {MATCH:paste: Error executing lua: vim.lua:%d+: Vim:E21: }| + {8:paste: Error executing lua: vim.lua:243: Vim:E21: }| {8:Cannot make changes, 'modifiable' is off} | {10:Press ENTER or type command to continue}{1: } | {3:-- TERMINAL --} | @@ -671,8 +677,8 @@ describe('TUI', function() item 2997 | item 2998 | item 2999 | - item 3000 en{1:d}d | - {5:[No Name] [+] 5999,13 Bot}| + item 3000 en{1:d} | + {5:[No Name] [+] 3000,13 Bot}| | {3:-- TERMINAL --} | ]]) diff --git a/test/functional/ui/decorations_spec.lua b/test/functional/ui/decorations_spec.lua index 40c33d9a4d..dce6384b9b 100644 --- a/test/functional/ui/decorations_spec.lua +++ b/test/functional/ui/decorations_spec.lua @@ -992,7 +992,7 @@ if (h->n_buckets < new_n_buckets) { // expand ]]} end) - it('works with text et the end of the buffer', function() + it('works with text at the end of the buffer', function() insert(example_text) feed 'G' @@ -1213,7 +1213,7 @@ if (h->n_buckets < new_n_buckets) { // expand | ]]} - meths.buf_set_extmark(0, ns, 2, 0, { + local markid = meths.buf_set_extmark(0, ns, 2, 0, { virt_lines={ {{"Some special", "Special"}}; {{"remark about codes", "Comment"}}; @@ -1235,13 +1235,13 @@ if (h->n_buckets < new_n_buckets) { // expand | ]]} - meths.buf_clear_namespace(0, ns, 0, -1) meths.buf_set_extmark(0, ns, 2, 0, { virt_lines={ {{"Some special", "Special"}}; {{"remark about codes", "Comment"}}; }; virt_lines_leftcol=true; + id=markid; }) screen:expect{grid=[[ {8: }{9: 1 }^if (h->n_buckets < new_n_buckets) { // expan| diff --git a/test/functional/ui/diff_spec.lua b/test/functional/ui/diff_spec.lua index df750a1a68..13949b0756 100644 --- a/test/functional/ui/diff_spec.lua +++ b/test/functional/ui/diff_spec.lua @@ -1196,4 +1196,27 @@ it('Align the filler lines when changing text in diff mode', function() {8:[No Name] [+] }{3:[No Name] [+] }| | ]]} + feed('<C-W>lay<Esc>') + screen:expect{grid=[[ + {1: }{2:-----------------}{3:│}{1: }{4:6 }| + {1: }{2:-----------------}{3:│}{1: }{4:7 }| + {1: }{2:-----------------}{3:│}{1: }{4:8 }| + {1: }9 {3:│}{1: }9 | + {1: }10 {3:│}{1: }10 | + {1: }11 {3:│}{1: }11 | + {1: }12 {3:│}{1: }12 | + {1: }13 {3:│}{1: }13 | + {1: }14 {3:│}{1: }14 | + {1: }{5:15}{6:x}{5: }{3:│}{1: }{5:15}{6:^y}{5: }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {7:~ }{3:│}{7:~ }| + {3:[No Name] [+] }{8:[No Name] [+] }| + | + ]]} end) diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index c238898244..f038348253 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -750,8 +750,13 @@ describe('ui/ext_messages', function() {1:~ }| {1:~ }| ]], messages={{ - content = {{'E5108: Error executing lua [string ":lua"]:1: such\nmultiline\nerror', 2}}, - kind = "lua_error" + content = {{[[E5108: Error executing lua [string ":lua"]:1: such +multiline +error +stack traceback: + [C]: in function 'error' + [string ":lua"]:1: in main chunk]], 2}}, + kind = "lua_error", }}} end) @@ -1048,12 +1053,12 @@ vimComment xxx match /\s"[^\-:.%#=*].*$/ms=s+1,lc=1 excludenl contains=@vim -- edge case: just covers statusline feed(':set colorcolumn=5 | lua error("x\\n\\nx")<cr>') screen:expect{grid=[[ - | - {1:~ }| - {3: }| {2:E5108: Error executing lua [string ":lua"]:1: x} | | {2:x} | + {2:stack traceback:} | + {2: [C]: in function 'error'} | + {2: [string ":lua"]:1: in main chunk} | {4:Press ENTER or type command to continue}^ | ]]} @@ -1071,24 +1076,24 @@ vimComment xxx match /\s"[^\-:.%#=*].*$/ms=s+1,lc=1 excludenl contains=@vim -- edge case: just covers lowest window line feed(':set colorcolumn=5 | lua error("x\\n\\n\\nx")<cr>') screen:expect{grid=[[ - | - {3: }| {2:E5108: Error executing lua [string ":lua"]:1: x} | | | {2:x} | - {4:Press ENTER or type command to continue}^ | + {2:stack traceback:} | + {2: [C]: in function 'error'} | + {4:-- More --}^ | ]]} feed('<cr>') screen:expect{grid=[[ | - {1:~ }| - {8:[No Name] }| - ^ {9: } | - {1:~ }| - {3:[No Name] }| | + {2:x} | + {2:stack traceback:} | + {2: [C]: in function 'error'} | + {2: [string ":lua"]:1: in main chunk} | + {4:Press ENTER or type command to continue}^ | ]]} end) end) @@ -1360,14 +1365,14 @@ aliquip ex ea commodo consequat.]]) ]]} feed('d') screen:expect{grid=[[ + {2:mpor} | {2:incididunt ut labore et dolore magn}| {2:a aliqua.} | {2:Ut enim ad minim veniam, quis nostr}| {2:ud xercitation} | {2:ullamco laboris nisi ut} | {2:aliquip ex ea commodo consequat.} | - {4:Press ENTER or type command to cont}| - {4:inue}^ | + {4:-- More --}^ | ]]} feed('u') screen:expect{grid=[[ @@ -1460,14 +1465,14 @@ aliquip ex ea commodo consequat.]]) ]]} feed('d') screen:expect{grid=[[ + {3:mpor}{5: }| {3:incididunt ut labore et dolore magn}| {3:a aliqua.}{5: }| {3:Ut enim ad minim veniam, quis nostr}| {3:ud xercitation}{5: }| {3:ullamco laboris nisi ut}{5: }| {3:aliquip ex ea commodo consequat.}{5: }| - {6:Press ENTER or type command to cont}| - {6:inue}{5:^ }| + {6:-- More --}{5:^ }| ]]} feed('u') screen:expect{grid=[[ @@ -1667,6 +1672,7 @@ aliquip ex ea commodo consequat.]]) -- wrapped at the new screen size. feed('<cr>') screen:expect{grid=[[ + {2:":lua"]:1: Lorem ipsum dolor s}| {2:et, consectetur} | {2:adipisicing elit, sed do eiusm}| {2:mpore} | @@ -1677,8 +1683,7 @@ aliquip ex ea commodo consequat.]]) {2:ullamco laboris nisi ut} | {2:aliquip ex ea commodo consequa}| {2:t.} | - {4:Press ENTER or type command to}| - {4: continue}^ | + {4:-- More --}^ | ]]} feed('q') diff --git a/test/functional/vimscript/executable_spec.lua b/test/functional/vimscript/executable_spec.lua index 28aefb72e5..048a65188d 100644 --- a/test/functional/vimscript/executable_spec.lua +++ b/test/functional/vimscript/executable_spec.lua @@ -18,7 +18,7 @@ describe('executable()', function() end) it('fails for invalid values', function() - for _, input in ipairs({'""', 'v:null', 'v:true', 'v:false', '{}', '[]'}) do + for _, input in ipairs({'v:null', 'v:true', 'v:false', '{}', '[]'}) do eq('Vim(call):E928: String required', exc_exec('call executable('..input..')')) end command('let $PATH = fnamemodify("./test/functional/fixtures/bin", ":p")') @@ -27,6 +27,10 @@ describe('executable()', function() end end) + it('returns 0 for empty strings', function() + eq(0, call('executable', '""')) + end) + it('returns 0 for non-existent files', function() eq(0, call('executable', 'no_such_file_exists_209ufq23f')) end) diff --git a/test/functional/vimscript/exepath_spec.lua b/test/functional/vimscript/exepath_spec.lua index 08d2c59af8..bbca954511 100644 --- a/test/functional/vimscript/exepath_spec.lua +++ b/test/functional/vimscript/exepath_spec.lua @@ -20,9 +20,10 @@ describe('exepath()', function() end) it('fails for invalid values', function() - for _, input in ipairs({'""', 'v:null', 'v:true', 'v:false', '{}', '[]'}) do + for _, input in ipairs({'v:null', 'v:true', 'v:false', '{}', '[]'}) do eq('Vim(call):E928: String required', exc_exec('call exepath('..input..')')) end + eq('Vim(call):E1142: Non-empty string required', exc_exec('call exepath("")')) command('let $PATH = fnamemodify("./test/functional/fixtures/bin", ":p")') for _, input in ipairs({'v:null', 'v:true', 'v:false'}) do eq('Vim(call):E928: String required', exc_exec('call exepath('..input..')')) diff --git a/test/functional/vimscript/has_spec.lua b/test/functional/vimscript/has_spec.lua index a3af2d1a20..c03fd13e0c 100644 --- a/test/functional/vimscript/has_spec.lua +++ b/test/functional/vimscript/has_spec.lua @@ -59,7 +59,12 @@ describe('has()', function() end) it('"wsl"', function() - if 1 == funcs.has('win32') or 1 == funcs.has('mac') then + local luv = require('luv') + local is_wsl = + luv.os_uname()['release']:lower():match('microsoft') and true or false + if is_wsl then + eq(1, funcs.has('wsl')) + else eq(0, funcs.has('wsl')) end end) diff --git a/test/functional/vimscript/null_spec.lua b/test/functional/vimscript/null_spec.lua index 7ecbcd2fd6..f23f00bcc5 100644 --- a/test/functional/vimscript/null_spec.lua +++ b/test/functional/vimscript/null_spec.lua @@ -161,7 +161,7 @@ describe('NULL', function() null_test('does not crash :echomsg', 'echomsg S', 0) null_test('does not crash :execute', 'execute S', 0) null_expr_test('does not crash execute()', 'execute(S)', 0, '') - null_expr_test('makes executable() error out', 'executable(S)', 'E928: String required', 0) + null_expr_test('does not crash executable()', 'executable(S)', 0, 0) null_expr_test('makes timer_start() error out', 'timer_start(0, S)', 'E921: Invalid callback argument', -1) null_expr_test('does not crash filereadable()', 'filereadable(S)', 0, 0) null_expr_test('does not crash filewritable()', 'filewritable(S)', 0, 0) diff --git a/test/helpers.lua b/test/helpers.lua index 9ac3904776..09b113c01d 100644 --- a/test/helpers.lua +++ b/test/helpers.lua @@ -155,12 +155,20 @@ function module.pcall_err_withfile(fn, ...) return errmsg end -function module.pcall_err(fn, ...) +function module.pcall_err_withtrace(fn, ...) local errmsg = module.pcall_err_withfile(fn, ...) return errmsg:gsub('.../helpers.lua:0: ', '') end +function module.pcall_err(...) + return module.remove_trace(module.pcall_err_withtrace(...)) +end + +function module.remove_trace(s) + return (s:gsub("\n%s*stack traceback:.*", "")) +end + -- initial_path: directory to recurse into -- re: include pattern (string) -- exc_re: exclude pattern(s) (string or table) diff --git a/test/unit/api/private_helpers_spec.lua b/test/unit/api/private_helpers_spec.lua index a534d83165..dbb4b3ae5a 100644 --- a/test/unit/api/private_helpers_spec.lua +++ b/test/unit/api/private_helpers_spec.lua @@ -18,7 +18,7 @@ local type_key = api_helpers.type_key local obj2lua = api_helpers.obj2lua local func_type = api_helpers.func_type -local api = cimport('./src/nvim/api/private/helpers.h') +local api = cimport('./src/nvim/api/private/helpers.h', './src/nvim/api/private/converter.h') describe('vim_to_object', function() local vim_to_object = function(l) diff --git a/third-party/CMakeLists.txt b/third-party/CMakeLists.txt index 29ff0daa8d..8ad71cfd3a 100644 --- a/third-party/CMakeLists.txt +++ b/third-party/CMakeLists.txt @@ -151,8 +151,8 @@ set(MSGPACK_URL https://github.com/msgpack/msgpack-c/releases/download/cpp-3.0.0 set(MSGPACK_SHA256 bfbb71b7c02f806393bc3cbc491b40523b89e64f83860c58e3e54af47de176e4) # https://github.com/LuaJIT/LuaJIT/tree/v2.1 -set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/787736990ac3b7d5ceaba2697c7d0f58f77bb782.tar.gz) -set(LUAJIT_SHA256 2e3f74bc279f46cc463abfc67b36e69faaf0366237004771f4cac4bf2a9f5efb) +set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/b4b2dce9fc3ffaaaede39b36d06415311e2aa516.tar.gz) +set(LUAJIT_SHA256 6c9e46877db2df16ca0fa76db4043ed30a1ae60c89d9ba2c3e4d35eb2360cd4d) set(LUA_URL https://www.lua.org/ftp/lua-5.1.5.tar.gz) set(LUA_SHA256 2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333) @@ -169,9 +169,9 @@ set(LIBTERMKEY_SHA256 6945bd3c4aaa83da83d80a045c5563da4edd7d0374c62c0d35aec09eb3 set(LIBVTERM_URL http://www.leonerd.org.uk/code/libvterm/libvterm-0.1.4.tar.gz) set(LIBVTERM_SHA256 bc70349e95559c667672fc8c55b9527d9db9ada0fb80a3beda533418d782d3dd) -set(LUV_VERSION 1.42.0-0) +set(LUV_VERSION 1.42.0-1) set(LUV_URL https://github.com/luvit/luv/archive/${LUV_VERSION}.tar.gz) -set(LUV_SHA256 8caee38de2fba0da32abbe96f55244e4a2c67d6cdde161a1935af94bffd5470f) +set(LUV_SHA256 a55563e6da9294ea26f77a2111598aa49188c5806b8bd1e1f4bdf402f340713e) set(LUA_COMPAT53_URL https://github.com/keplerproject/lua-compat-5.3/archive/v0.9.tar.gz) set(LUA_COMPAT53_SHA256 ad05540d2d96a48725bb79a1def35cf6652a4e2ec26376e2617c8ce2baa6f416) diff --git a/third-party/cmake/BuildLibuv.cmake b/third-party/cmake/BuildLibuv.cmake index 32fe2659a4..dce64c777b 100644 --- a/third-party/cmake/BuildLibuv.cmake +++ b/third-party/cmake/BuildLibuv.cmake @@ -5,7 +5,7 @@ function(BuildLibuv) cmake_parse_arguments(_libuv "BUILD_IN_SOURCE" "TARGET" - "CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND" + "PATCH_COMMAND;CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND" ${ARGN}) if(NOT _libuv_CONFIGURE_COMMAND AND NOT _libuv_BUILD_COMMAND @@ -28,6 +28,7 @@ function(BuildLibuv) -DTARGET=${_libuv_TARGET} -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake + PATCH_COMMAND "${_libuv_PATCH_COMMAND}" BUILD_IN_SOURCE ${_libuv_BUILD_IN_SOURCE} CONFIGURE_COMMAND "${_libuv_CONFIGURE_COMMAND}" BUILD_COMMAND "${_libuv_BUILD_COMMAND}" @@ -62,6 +63,10 @@ elseif(WIN32) set(BUILD_SHARED ON) elseif(MINGW) set(BUILD_SHARED OFF) + set(LIBUV_PATCH_COMMAND + ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libuv init + COMMAND ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libuv apply --ignore-whitespace + ${CMAKE_CURRENT_SOURCE_DIR}/patches/libuv-disable-typedef-MinGW.patch) else() message(FATAL_ERROR "Trying to build libuv in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}") endif() @@ -75,6 +80,7 @@ elseif(WIN32) -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DBUILD_SHARED_LIBS=${BUILD_SHARED} -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR} + PATCH_COMMAND ${LIBUV_PATCH_COMMAND} BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE} INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE}) diff --git a/third-party/cmake/BuildLuajit.cmake b/third-party/cmake/BuildLuajit.cmake index 512d5ef5ae..c4e5112dce 100644 --- a/third-party/cmake/BuildLuajit.cmake +++ b/third-party/cmake/BuildLuajit.cmake @@ -53,7 +53,7 @@ else() endif() set(INSTALLCMD_UNIX ${MAKE_PRG} CFLAGS=-fPIC CFLAGS+=-DLUA_USE_APICHECK - CFLAGS+=-DLUA_USE_ASSERT + CFLAGS+=-funwind-tables ${NO_STACK_CHECK} ${AMD64_ABI} CCDEBUG+=-g @@ -109,7 +109,7 @@ elseif(MINGW) BuildLuaJit(BUILD_COMMAND ${LUAJIT_MAKE_PRG} CC=${DEPS_C_COMPILER} PREFIX=${DEPS_INSTALL_DIR} CFLAGS+=-DLUA_USE_APICHECK - CFLAGS+=-DLUA_USE_ASSERT + CFLAGS+=-funwind-tables CCDEBUG+=-g BUILDMODE=static # Build a DLL too diff --git a/third-party/patches/libuv-disable-typedef-MinGW.patch b/third-party/patches/libuv-disable-typedef-MinGW.patch new file mode 100644 index 0000000000..a47893cede --- /dev/null +++ b/third-party/patches/libuv-disable-typedef-MinGW.patch @@ -0,0 +1,19 @@ +diff --git a/include/uv/win.h b/include/uv/win.h +index f5f1d3a3..64a0dfd9 100644 +--- a/include/uv/win.h ++++ b/include/uv/win.h +@@ -45,7 +45,14 @@ typedef struct pollfd { + #endif + + #include <mswsock.h> ++// Disable the typedef in mstcpip.h of MinGW. ++#define _TCP_INITIAL_RTO_PARAMETERS _TCP_INITIAL_RTO_PARAMETERS__ ++#define TCP_INITIAL_RTO_PARAMETERS TCP_INITIAL_RTO_PARAMETERS__ ++#define PTCP_INITIAL_RTO_PARAMETERS PTCP_INITIAL_RTO_PARAMETERS__ + #include <ws2tcpip.h> ++#undef _TCP_INITIAL_RTO_PARAMETERS ++#undef TCP_INITIAL_RTO_PARAMETERS ++#undef PTCP_INITIAL_RTO_PARAMETERS + #include <windows.h> + + #include <process.h> |