Vim - can I pass multiple args to a custom command without writing a function





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I have written following custom command in my .vimrc file:



command! -nargs=+ Sub :%s/<args>/g


It allows me to substitute one word for another and is executed like this:



:Sub <word>/<new word>


I would prefer to write commands with multiple args, like this:



:Sub <word> <new word>


Am I able to rewrite the command to accept multiple arguments?



Ideally I would like something like this:



command! -nargs=+ Sub :%s/<arg1>/<arg2>/g


Thank you in advance.










share|improve this question





























    1















    I have written following custom command in my .vimrc file:



    command! -nargs=+ Sub :%s/<args>/g


    It allows me to substitute one word for another and is executed like this:



    :Sub <word>/<new word>


    I would prefer to write commands with multiple args, like this:



    :Sub <word> <new word>


    Am I able to rewrite the command to accept multiple arguments?



    Ideally I would like something like this:



    command! -nargs=+ Sub :%s/<arg1>/<arg2>/g


    Thank you in advance.










    share|improve this question

























      1












      1








      1








      I have written following custom command in my .vimrc file:



      command! -nargs=+ Sub :%s/<args>/g


      It allows me to substitute one word for another and is executed like this:



      :Sub <word>/<new word>


      I would prefer to write commands with multiple args, like this:



      :Sub <word> <new word>


      Am I able to rewrite the command to accept multiple arguments?



      Ideally I would like something like this:



      command! -nargs=+ Sub :%s/<arg1>/<arg2>/g


      Thank you in advance.










      share|improve this question














      I have written following custom command in my .vimrc file:



      command! -nargs=+ Sub :%s/<args>/g


      It allows me to substitute one word for another and is executed like this:



      :Sub <word>/<new word>


      I would prefer to write commands with multiple args, like this:



      :Sub <word> <new word>


      Am I able to rewrite the command to accept multiple arguments?



      Ideally I would like something like this:



      command! -nargs=+ Sub :%s/<arg1>/<arg2>/g


      Thank you in advance.







      linux command-line bash vim vimscript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 26 at 14:33









      Alex MckayAlex Mckay

      82




      82






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Do the parsing on your own



          If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:



          command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'


          We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():



          command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))


          This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.



          Vim can parse arguments



          A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.



          command! -nargs=+ Sub call Sub(<f-args>)
          function! Sub( ... )
          execute printf('%%substitute/%s/%s/g', a:1, a:2)
          endfunction


          With a function, you can easily check for the correct number of arguments:



          function! Sub( ... )
          if a:0 != 2
          echo "Need two arguments"
          return
          endif
          ...


          The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.



          Bonus: Where to take it from there




          • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.

          • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.


          Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.






          share|improve this answer
























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "3"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1398719%2fvim-can-i-pass-multiple-args-to-a-custom-command-without-writing-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Do the parsing on your own



            If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:



            command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'


            We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():



            command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))


            This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.



            Vim can parse arguments



            A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.



            command! -nargs=+ Sub call Sub(<f-args>)
            function! Sub( ... )
            execute printf('%%substitute/%s/%s/g', a:1, a:2)
            endfunction


            With a function, you can easily check for the correct number of arguments:



            function! Sub( ... )
            if a:0 != 2
            echo "Need two arguments"
            return
            endif
            ...


            The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.



            Bonus: Where to take it from there




            • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.

            • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.


            Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.






            share|improve this answer




























              1














              Do the parsing on your own



              If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:



              command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'


              We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():



              command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))


              This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.



              Vim can parse arguments



              A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.



              command! -nargs=+ Sub call Sub(<f-args>)
              function! Sub( ... )
              execute printf('%%substitute/%s/%s/g', a:1, a:2)
              endfunction


              With a function, you can easily check for the correct number of arguments:



              function! Sub( ... )
              if a:0 != 2
              echo "Need two arguments"
              return
              endif
              ...


              The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.



              Bonus: Where to take it from there




              • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.

              • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.


              Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.






              share|improve this answer


























                1












                1








                1







                Do the parsing on your own



                If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:



                command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'


                We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():



                command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))


                This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.



                Vim can parse arguments



                A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.



                command! -nargs=+ Sub call Sub(<f-args>)
                function! Sub( ... )
                execute printf('%%substitute/%s/%s/g', a:1, a:2)
                endfunction


                With a function, you can easily check for the correct number of arguments:



                function! Sub( ... )
                if a:0 != 2
                echo "Need two arguments"
                return
                endif
                ...


                The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.



                Bonus: Where to take it from there




                • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.

                • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.


                Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.






                share|improve this answer













                Do the parsing on your own



                If you use :help <q-args>, you get a quoted string that you can split() into the two space-separated parts:



                command! -nargs=+ Sub execute '%substitute/' . split(<q-args>, ' ')[0] . '/' . split(<q-args>, ' ')[1] . '/g'


                We can avoid parsing this twice with a bit of metaprogramming (call()) and printf():



                command! -nargs=+ Sub execute call('printf', ['%%substitute/%s/%s/g'] + split(<q-args>, ' '))


                This works, but error handling still isn't good (if you only pass one arg, it'll complain with E766: Insufficient arguments for printf()). You'll get more control by extracting the code into a :function.



                Vim can parse arguments



                A separate :function also allows Vim to do the argument parsing for you, via :help <f-args>.



                command! -nargs=+ Sub call Sub(<f-args>)
                function! Sub( ... )
                execute printf('%%substitute/%s/%s/g', a:1, a:2)
                endfunction


                With a function, you can easily check for the correct number of arguments:



                function! Sub( ... )
                if a:0 != 2
                echo "Need two arguments"
                return
                endif
                ...


                The downside of a function is that errors (e.g. the pattern doesn't match, buffer is not modifiable) cause a multi-line, unfriendly error message. try...catch would have to be used to derive a nice, single-line error message.



                Bonus: Where to take it from there




                • As you're hiding the :s command (and the used delimiters) from the user, I think it shouldn't be required that the delimiters need to be escaped. Use escape(a:1, '/') instead of a:1 / a:2.

                • With :help :command-range, you can still default the command to work on the entire buffer, but also allow to pass other ranges.


                Also consider whether the command really pulls its weight. Regardless of the used parsing, whitespace in arguments are problematic, a downside that the original :s doesn't have. The only benefit I see is that it's a bit easier to type, but the same can also be achieve via mapping(s) that pre-fill the command-line with an incomplete :s command, and position the cursor right in the middle.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 28 at 9:02









                Ingo KarkatIngo Karkat

                17.8k22646




                17.8k22646






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Super User!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1398719%2fvim-can-i-pass-multiple-args-to-a-custom-command-without-writing-a-function%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    RAC Tourist Trophy