From 4f881c4f64d9caac1f59ebd5d14963f99db3d71a Mon Sep 17 00:00:00 2001 From: bad Date: Fri, 27 Aug 2021 13:57:58 +0200 Subject: [PATCH] Initial commit --- lua/fold_if_err_nil.lua | 33 +++++++++++++++++++++++++++++++++ plugin/gofoldiferrnil.vim | 20 ++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 lua/fold_if_err_nil.lua create mode 100644 plugin/gofoldiferrnil.vim diff --git a/lua/fold_if_err_nil.lua b/lua/fold_if_err_nil.lua new file mode 100644 index 0000000..5d8c9db --- /dev/null +++ b/lua/fold_if_err_nil.lua @@ -0,0 +1,33 @@ +-- Neovim lua api doesn't support multiline regexes so we use this hack instead +regexStrs = { + "^\\s*if err != nil {\\s*$", + "^\\s*return.\\{-}.err.*$", + "^\\s*}\\s*$" +} + +regexes = {} +for _,str in pairs(regexStrs) do + table.insert(regexes, vim.regex(str)) +end +function foldIfErrNills() do + local line_count = vim.api.nvim_buf_line_count(0) + for i = 0,(line_count-#regexStrs) do + local allMatched = true + for j,regex in pairs(regexes) do + if not regex:match_line(0,i+j-1) then + allMatched = false + break + end + end + if allMatched then + range_start = i+1 + range_end = i+#regexes + vim.cmd(range_start..","..range_end.."fo") + end + end +end +end + +return { + foldIfErrNills = foldIfErrNills + } diff --git a/plugin/gofoldiferrnil.vim b/plugin/gofoldiferrnil.vim new file mode 100644 index 0000000..11035c4 --- /dev/null +++ b/plugin/gofoldiferrnil.vim @@ -0,0 +1,20 @@ +" A small plugin to fold if err nil statements that do nothing except for +" propagating errors +" License: Unlicense + +if exists('g:loaded_gofoldiferrnil') | finish | endif " prevent loading file twice + +if !has('nvim-0.5') + echoerr 'You need neovim 0.5 or newer to run this plugin' + finish +endif + +let s:save_cpo = &cpo +set cpo&vim + +command! GoFoldIfErr lua require('fold_if_err_nil').foldIfErrNills() + +let &cpo = s:save_cpo +unlet s:save_cpo + +let g:loaded_whid = 1