I simply want to map < leader> pu to erase all occurrences of the carriage return character (represented as ^M) in a file.

I can execute the command:


and it works.

Any attempts to use vim.keymap.set in my remap.lua file, however, error out when I try to source it.

Attempts include:

vim.keymap.set('n', '<leader>pu', vim.cmd('%s/\r//g'))

Errors with "Pattern not found:" using square brackets errors with "Pattern not found:\r"

vim.keymap.set('n', '<leader>pu', vim.cmd.substitute{ range = '%', args = {'\r',''} })

Errors with " Invalid command arg: expected non-whitespace"

An attempt with a different character, 'r', sources, but applies the command inside the sourced file instead of mapping it.

vim.keymap.set('n', '<leader>pu', vim.cmd('%s/r//g'))

I have other mappings using vim.cmd that work fine, and do not apply in the remap file.

Maybe this is a skill issue, but I need some assistance.

  • See :help file-formats. Would :set fileformat=unix solve your problem? This will only affect CRLF line endings while your regexp will also erase CR characters not at the end of a line. Depends on what you want to achieve.
    – Friedrich
    Jul 11, 2023 at 5:38
  • Thanks for the response. Due to the file formats, when pasting into nvim on WSL from system clipboard, <CR>s are at the end of each line. Just tried changing the file format, but they still appear (using both dos and unix). I just don't understand why I cannot map this replace, as typing it in manually every time I paste something in is getting tiresome.
    – fireq1
    Jul 11, 2023 at 6:19
  • You should ask about how not to get CRLF line endings when pasting in the first place. Being forced to run a mapping whenever you paste something is not a solution.
    – Friedrich
    Jul 11, 2023 at 9:55
  • I slapped paste from clipboard in there too, so no additional keystrokes are required. When I asked the question I did not know about file formats; this works for me where the other responses dealing with file formats do not.
    – fireq1
    Jul 11, 2023 at 15:49

2 Answers 2


I would do:

vim.api.nvim_set_keymap('n', '<leader>pu', ':%s/\\r//<CR>', {})
  • 2
    For the record, I think the issue is that vim.cmd is evaluated when constructing the mapping (since Lua is expression-oriented and has no macros, the expression can only be delayed with a function wrapper or, in this particular case, using a string)
    – D. Ben Knoble
    Jul 11, 2023 at 12:32

why not write it directly in unix format?

:w ++ff=unix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.