Get file name and directory in .vimrc fileWhy is make running against a wrong file?a highlight command resets previously declared highlightsWhy cannot I source vimrc for the current file being editing?Sourcing Vimplug plugins in a separate fileWhy can't I set <Home> or t_kh in my vimrc file?Common vimrc config for unix and windowsCannot set (let) mapleader and use <leader> in global vimrc

Ending a line of dialogue with "?!": Allowed or obnoxious?

Can I use images from my published papers in my thesis without copyright infringment?

Subgroup generated by a subgroup and a conjugate of it

Is a suspension needed to do wheelies?

Number of matrices with bounded products of rows and columns

What's the relationship betweeen MS-DOS and XENIX?

When does The Truman Show take place?

Unconventional examples of mathematical modelling

Quick destruction of a helium filled airship?

Would getting a natural 20 with a penalty still count as a critical hit?

What's a good pattern to calculate a variable only when it is used the first time?

Why can't I see 1861 / 1871 census entries on Freecen website when I can see them on Ancestry website?

Are unaudited server logs admissible in a court of law?

What was the intention with the Commodore 128?

When and which board game was the first to be ever invented?

Gofer work in exchange for LoR

Expressing a chain of boolean ORs using ILP

Output with the same length always

What should I do with the stock I own if I anticipate there will be a recession?

Combinatorial Argument for Exponential and Logarithmic Function Being Inverse

Have made several mistakes during the course of my PhD. Can't help but feel resentment. Can I get some advice about how to move forward?

Do predators tend to have vertical slit pupils versus horizontal for prey animals?

The Lucky House

Why is su world executable?



Get file name and directory in .vimrc file


Why is make running against a wrong file?a highlight command resets previously declared highlightsWhy cannot I source vimrc for the current file being editing?Sourcing Vimplug plugins in a separate fileWhy can't I set <Home> or t_kh in my vimrc file?Common vimrc config for unix and windowsCannot set (let) mapleader and use <leader> in global vimrc






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have mapped my f5 key in vimrc file to run the code using the following command:



map <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ test.cpp && ./a.out



It is working well. But it only runs for test.cpp file. I want to make it generic by inserting the name of my current file. Is there any way of doing this?










share|improve this question






























    1















    I have mapped my f5 key in vimrc file to run the code using the following command:



    map <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ test.cpp && ./a.out



    It is working well. But it only runs for test.cpp file. I want to make it generic by inserting the name of my current file. Is there any way of doing this?










    share|improve this question


























      1












      1








      1








      I have mapped my f5 key in vimrc file to run the code using the following command:



      map <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ test.cpp && ./a.out



      It is working well. But it only runs for test.cpp file. I want to make it generic by inserting the name of my current file. Is there any way of doing this?










      share|improve this question














      I have mapped my f5 key in vimrc file to run the code using the following command:



      map <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ test.cpp && ./a.out



      It is working well. But it only runs for test.cpp file. I want to make it generic by inserting the name of my current file. Is there any way of doing this?







      vimrc variables






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 10 hours ago









      Hashir SarwarHashir Sarwar

      114 bronze badges




      114 bronze badges























          2 Answers
          2






          active

          oldest

          votes


















          1














          You can use % to expand to the current filename.



          See :help :!, which goes into quite some level of detail about that!




          If cmd contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:



          :!ls "%"



          Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.



          The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.



          Putting it all together:



          :map <F5> :!set -x; g++ "%" && ./a.out<cr>



          Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.



          They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.






          share|improve this answer

























          • Ahem. Already answered.

            – B Layer
            9 hours ago











          • @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

            – filbranden
            9 hours ago











          • Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

            – B Layer
            9 hours ago











          • @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

            – filbranden
            9 hours ago











          • Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

            – B Layer
            9 hours ago



















          2














          Use "Ex special characters" :h cmdline-special.



          Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...



          noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>


          (I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)



          In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.



          There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.



          By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash as I alluded to before.






          share|improve this answer





























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "599"
            ;
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fvi.stackexchange.com%2fquestions%2f20924%2fget-file-name-and-directory-in-vimrc-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can use % to expand to the current filename.



            See :help :!, which goes into quite some level of detail about that!




            If cmd contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:



            :!ls "%"



            Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.



            The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.



            Putting it all together:



            :map <F5> :!set -x; g++ "%" && ./a.out<cr>



            Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.



            They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.






            share|improve this answer

























            • Ahem. Already answered.

              – B Layer
              9 hours ago











            • @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

              – filbranden
              9 hours ago











            • Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

              – B Layer
              9 hours ago











            • @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

              – filbranden
              9 hours ago











            • Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

              – B Layer
              9 hours ago
















            1














            You can use % to expand to the current filename.



            See :help :!, which goes into quite some level of detail about that!




            If cmd contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:



            :!ls "%"



            Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.



            The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.



            Putting it all together:



            :map <F5> :!set -x; g++ "%" && ./a.out<cr>



            Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.



            They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.






            share|improve this answer

























            • Ahem. Already answered.

              – B Layer
              9 hours ago











            • @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

              – filbranden
              9 hours ago











            • Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

              – B Layer
              9 hours ago











            • @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

              – filbranden
              9 hours ago











            • Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

              – B Layer
              9 hours ago














            1












            1








            1







            You can use % to expand to the current filename.



            See :help :!, which goes into quite some level of detail about that!




            If cmd contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:



            :!ls "%"



            Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.



            The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.



            Putting it all together:



            :map <F5> :!set -x; g++ "%" && ./a.out<cr>



            Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.



            They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.






            share|improve this answer













            You can use % to expand to the current filename.



            See :help :!, which goes into quite some level of detail about that!




            If cmd contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:



            :!ls "%"



            Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.



            The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.



            Putting it all together:



            :map <F5> :!set -x; g++ "%" && ./a.out<cr>



            Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.



            They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 9 hours ago









            filbrandenfilbranden

            2,2555 silver badges15 bronze badges




            2,2555 silver badges15 bronze badges















            • Ahem. Already answered.

              – B Layer
              9 hours ago











            • @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

              – filbranden
              9 hours ago











            • Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

              – B Layer
              9 hours ago











            • @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

              – filbranden
              9 hours ago











            • Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

              – B Layer
              9 hours ago


















            • Ahem. Already answered.

              – B Layer
              9 hours ago











            • @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

              – filbranden
              9 hours ago











            • Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

              – B Layer
              9 hours ago











            • @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

              – filbranden
              9 hours ago











            • Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

              – B Layer
              9 hours ago

















            Ahem. Already answered.

            – B Layer
            9 hours ago





            Ahem. Already answered.

            – B Layer
            9 hours ago













            @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

            – filbranden
            9 hours ago





            @BLayer Oh, thanks for letting me know. There wasn't any answer when I started to type mine. I'm on mobile, so I don't see notifications. In any case, there's no problem with "too many answers", in fact that's usually encouraged by the site. I did upvote yours right away, as it clearly addresses the question very well.

            – filbranden
            9 hours ago













            Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

            – B Layer
            9 hours ago





            Well, except your answer is, at its core, the same as mine. %. If you have something to add then edit the existing one. Some people would consider this not proper netiquette. I'm getting the impression that rep points are priority above all else for you.

            – B Layer
            9 hours ago













            @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

            – filbranden
            9 hours ago





            @BLayer Like I mentioned, I didn't see your answer before I wrote mine. I really don't see why you seem to be having a problem with my answering questions here. I'm only here to help and to learn in the process. (It's amazing how much more I've learned about Vim through coming here.) Can we just leave this alone?

            – filbranden
            9 hours ago













            Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

            – B Layer
            9 hours ago






            Second time in days with "no notifications". I don't get any notifications yet I and everyone else seem to be able to look what's there before posting. I don't have a problem with your answering questions...that's a silly statement. I have a problem with stepping on toes. No one else here does it.

            – B Layer
            9 hours ago














            2














            Use "Ex special characters" :h cmdline-special.



            Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...



            noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>


            (I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)



            In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.



            There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.



            By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash as I alluded to before.






            share|improve this answer































              2














              Use "Ex special characters" :h cmdline-special.



              Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...



              noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>


              (I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)



              In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.



              There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.



              By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash as I alluded to before.






              share|improve this answer





























                2












                2








                2







                Use "Ex special characters" :h cmdline-special.



                Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...



                noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>


                (I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)



                In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.



                There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.



                By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash as I alluded to before.






                share|improve this answer















                Use "Ex special characters" :h cmdline-special.



                Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...



                noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>


                (I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)



                In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.



                There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.



                By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash as I alluded to before.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 9 hours ago

























                answered 10 hours ago









                B LayerB Layer

                7,1061 gold badge6 silver badges25 bronze badges




                7,1061 gold badge6 silver badges25 bronze badges






























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Vi and Vim Stack Exchange!


                    • 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%2fvi.stackexchange.com%2fquestions%2f20924%2fget-file-name-and-directory-in-vimrc-file%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

                    Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                    The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                    19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу