Detect existing key binding before creating one Planned maintenance scheduled April 17/18,...

Why is my conclusion inconsistent with the van't Hoff equation?

Can a non-EU citizen traveling with me come with me through the EU passport line?

51k Euros annually for a family of 4 in Berlin: Is it enough?

How to deal with a team lead who never gives me credit?

Fundamental Solution of the Pell Equation

How to run gsettings for another user Ubuntu 18.04.2 LTS

Why light coming from distant stars is not discreet?

Dating a Former Employee

The logistics of corpse disposal

How to tell that you are a giant?

At the end of Thor: Ragnarok why don't the Asgardians turn and head for the Bifrost as per their original plan?

Why am I getting the error "non-boolean type specified in a context where a condition is expected" for this request?

How to call a function with default parameter through a pointer to function that is the return of another function?

Overriding an object in memory with placement new

Using et al. for a last / senior author rather than for a first author

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

How come Sam didn't become Lord of Horn Hill?

What's the purpose of writing one's academic biography in the third person?

What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?

What would be the ideal power source for a cybernetic eye?

Do I really need recursive chmod to restrict access to a folder?

Can an alien society believe that their star system is the universe?

What is a non-alternating simple group with big order, but relatively few conjugacy classes?

How widely used is the term Treppenwitz? Is it something that most Germans know?



Detect existing key binding before creating one



Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Figure out which plugin is responsible for a key bindingKey binding for enter key in insert modeIs there a one-key command to insert before the first character of the line?How do you undefine existing functions and key maps?Getting tab and windows movement with one key combinationVim default key bindingKey binding conflict of paste and rectangular blocks selectKey binding to select the current paragraphHow to limit a key binding to a single keyExiting and entering insert mode again with key-binding












2















A plugin I've recently started maintaining currently checks to see if any bindings exist to its functions before creating the default ones. This makes it easy to setup custom bindings and not have to do anything about the default ones.



if !hasmapto('<Plug>MyFunction', 'n')
nmap <buffer> <Leader>f <Plug>MyFunction
endif


What this doesn't do is keep these default bindings from clobbering existing mappings. How can I detect if, say, there is an existing normal mode mapping for <leader>f before clobbering it with the plugin's default mapping.










share|improve this question

























  • Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

    – Caleb
    19 hours ago
















2















A plugin I've recently started maintaining currently checks to see if any bindings exist to its functions before creating the default ones. This makes it easy to setup custom bindings and not have to do anything about the default ones.



if !hasmapto('<Plug>MyFunction', 'n')
nmap <buffer> <Leader>f <Plug>MyFunction
endif


What this doesn't do is keep these default bindings from clobbering existing mappings. How can I detect if, say, there is an existing normal mode mapping for <leader>f before clobbering it with the plugin's default mapping.










share|improve this question

























  • Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

    – Caleb
    19 hours ago














2












2








2








A plugin I've recently started maintaining currently checks to see if any bindings exist to its functions before creating the default ones. This makes it easy to setup custom bindings and not have to do anything about the default ones.



if !hasmapto('<Plug>MyFunction', 'n')
nmap <buffer> <Leader>f <Plug>MyFunction
endif


What this doesn't do is keep these default bindings from clobbering existing mappings. How can I detect if, say, there is an existing normal mode mapping for <leader>f before clobbering it with the plugin's default mapping.










share|improve this question
















A plugin I've recently started maintaining currently checks to see if any bindings exist to its functions before creating the default ones. This makes it easy to setup custom bindings and not have to do anything about the default ones.



if !hasmapto('<Plug>MyFunction', 'n')
nmap <buffer> <Leader>f <Plug>MyFunction
endif


What this doesn't do is keep these default bindings from clobbering existing mappings. How can I detect if, say, there is an existing normal mode mapping for <leader>f before clobbering it with the plugin's default mapping.







key-bindings vimscript leader






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 19 hours ago







Caleb

















asked 20 hours ago









CalebCaleb

96211125




96211125













  • Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

    – Caleb
    19 hours ago



















  • Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

    – Caleb
    19 hours ago

















Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

– Caleb
19 hours ago





Related question (from the opposite end of the stick): How can I prevent plugins from overwriting my key mappings?

– Caleb
19 hours ago










2 Answers
2






active

oldest

votes


















3














You can use the mapcheck() function to check if the user mapped a key to something:



:echo json_encode(mapcheck('<F1>', 'n'))
""

:echo mapcheck('<F11>', 'n')
:set cursorcolumn!<CR>:set cursorcolumn?<CR>


So in your mapping, you can do:



if !hasmapto('<Plug>MyFunction', 'n') && mapcheck('<Leader>f', 'n') is# ''
nmap <buffer> <Leader>f <Plug>MyFunction
endif




Personally, I'm not completely convinced this is actually a good approach though. While it does prevent overriding user mappings, it's also very "magic" and may be surprising.



An approach that I often use is to make a single setting to disable all mappings:



if get(g:, 'myplugin_map_keys', 1)
nmap <buffer> <Leader>f <Plug>MyFunction
endif


This way users have a reasonable set of mappings by default, but can disable mappings and do their own thing if they want something custom.



Another option is to map from a variable:



exe printf('nmap <buffer> %s <Plug>MyFunction',
get(g:, 'myplugin_map_foo', '<Leader>f')


This way users can set their own keys for a specific mapping, without having to remap everything.





I don't think there is "one right way". Aside from personal preference, it also depends on the kind of plugin you're working on. For some plugins a key mapping is just an "extra bonus", whereas it's critical for others. Some plugins map just one or two keys, others dozens or even hundreds.



For smaller plugins with just one or two mappings, the first method will usually be better; for larger plugins with a lot of mappings, the second is often better. Of course, you can also do both.






share|improve this answer
























  • Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

    – Caleb
    19 hours ago








  • 2





    @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

    – Martin Tournoij
    19 hours ago





















1














silent! {map} <unique> {lhs} {rhs}


Works too. The <unique> modifier issues an error if there is already a mapping for the left-hand side, which silent swallows.






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%2f19597%2fdetect-existing-key-binding-before-creating-one%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









    3














    You can use the mapcheck() function to check if the user mapped a key to something:



    :echo json_encode(mapcheck('<F1>', 'n'))
    ""

    :echo mapcheck('<F11>', 'n')
    :set cursorcolumn!<CR>:set cursorcolumn?<CR>


    So in your mapping, you can do:



    if !hasmapto('<Plug>MyFunction', 'n') && mapcheck('<Leader>f', 'n') is# ''
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif




    Personally, I'm not completely convinced this is actually a good approach though. While it does prevent overriding user mappings, it's also very "magic" and may be surprising.



    An approach that I often use is to make a single setting to disable all mappings:



    if get(g:, 'myplugin_map_keys', 1)
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif


    This way users have a reasonable set of mappings by default, but can disable mappings and do their own thing if they want something custom.



    Another option is to map from a variable:



    exe printf('nmap <buffer> %s <Plug>MyFunction',
    get(g:, 'myplugin_map_foo', '<Leader>f')


    This way users can set their own keys for a specific mapping, without having to remap everything.





    I don't think there is "one right way". Aside from personal preference, it also depends on the kind of plugin you're working on. For some plugins a key mapping is just an "extra bonus", whereas it's critical for others. Some plugins map just one or two keys, others dozens or even hundreds.



    For smaller plugins with just one or two mappings, the first method will usually be better; for larger plugins with a lot of mappings, the second is often better. Of course, you can also do both.






    share|improve this answer
























    • Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

      – Caleb
      19 hours ago








    • 2





      @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

      – Martin Tournoij
      19 hours ago


















    3














    You can use the mapcheck() function to check if the user mapped a key to something:



    :echo json_encode(mapcheck('<F1>', 'n'))
    ""

    :echo mapcheck('<F11>', 'n')
    :set cursorcolumn!<CR>:set cursorcolumn?<CR>


    So in your mapping, you can do:



    if !hasmapto('<Plug>MyFunction', 'n') && mapcheck('<Leader>f', 'n') is# ''
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif




    Personally, I'm not completely convinced this is actually a good approach though. While it does prevent overriding user mappings, it's also very "magic" and may be surprising.



    An approach that I often use is to make a single setting to disable all mappings:



    if get(g:, 'myplugin_map_keys', 1)
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif


    This way users have a reasonable set of mappings by default, but can disable mappings and do their own thing if they want something custom.



    Another option is to map from a variable:



    exe printf('nmap <buffer> %s <Plug>MyFunction',
    get(g:, 'myplugin_map_foo', '<Leader>f')


    This way users can set their own keys for a specific mapping, without having to remap everything.





    I don't think there is "one right way". Aside from personal preference, it also depends on the kind of plugin you're working on. For some plugins a key mapping is just an "extra bonus", whereas it's critical for others. Some plugins map just one or two keys, others dozens or even hundreds.



    For smaller plugins with just one or two mappings, the first method will usually be better; for larger plugins with a lot of mappings, the second is often better. Of course, you can also do both.






    share|improve this answer
























    • Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

      – Caleb
      19 hours ago








    • 2





      @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

      – Martin Tournoij
      19 hours ago
















    3












    3








    3







    You can use the mapcheck() function to check if the user mapped a key to something:



    :echo json_encode(mapcheck('<F1>', 'n'))
    ""

    :echo mapcheck('<F11>', 'n')
    :set cursorcolumn!<CR>:set cursorcolumn?<CR>


    So in your mapping, you can do:



    if !hasmapto('<Plug>MyFunction', 'n') && mapcheck('<Leader>f', 'n') is# ''
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif




    Personally, I'm not completely convinced this is actually a good approach though. While it does prevent overriding user mappings, it's also very "magic" and may be surprising.



    An approach that I often use is to make a single setting to disable all mappings:



    if get(g:, 'myplugin_map_keys', 1)
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif


    This way users have a reasonable set of mappings by default, but can disable mappings and do their own thing if they want something custom.



    Another option is to map from a variable:



    exe printf('nmap <buffer> %s <Plug>MyFunction',
    get(g:, 'myplugin_map_foo', '<Leader>f')


    This way users can set their own keys for a specific mapping, without having to remap everything.





    I don't think there is "one right way". Aside from personal preference, it also depends on the kind of plugin you're working on. For some plugins a key mapping is just an "extra bonus", whereas it's critical for others. Some plugins map just one or two keys, others dozens or even hundreds.



    For smaller plugins with just one or two mappings, the first method will usually be better; for larger plugins with a lot of mappings, the second is often better. Of course, you can also do both.






    share|improve this answer













    You can use the mapcheck() function to check if the user mapped a key to something:



    :echo json_encode(mapcheck('<F1>', 'n'))
    ""

    :echo mapcheck('<F11>', 'n')
    :set cursorcolumn!<CR>:set cursorcolumn?<CR>


    So in your mapping, you can do:



    if !hasmapto('<Plug>MyFunction', 'n') && mapcheck('<Leader>f', 'n') is# ''
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif




    Personally, I'm not completely convinced this is actually a good approach though. While it does prevent overriding user mappings, it's also very "magic" and may be surprising.



    An approach that I often use is to make a single setting to disable all mappings:



    if get(g:, 'myplugin_map_keys', 1)
    nmap <buffer> <Leader>f <Plug>MyFunction
    endif


    This way users have a reasonable set of mappings by default, but can disable mappings and do their own thing if they want something custom.



    Another option is to map from a variable:



    exe printf('nmap <buffer> %s <Plug>MyFunction',
    get(g:, 'myplugin_map_foo', '<Leader>f')


    This way users can set their own keys for a specific mapping, without having to remap everything.





    I don't think there is "one right way". Aside from personal preference, it also depends on the kind of plugin you're working on. For some plugins a key mapping is just an "extra bonus", whereas it's critical for others. Some plugins map just one or two keys, others dozens or even hundreds.



    For smaller plugins with just one or two mappings, the first method will usually be better; for larger plugins with a lot of mappings, the second is often better. Of course, you can also do both.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 19 hours ago









    Martin TournoijMartin Tournoij

    35.9k14111185




    35.9k14111185













    • Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

      – Caleb
      19 hours ago








    • 2





      @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

      – Martin Tournoij
      19 hours ago





















    • Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

      – Caleb
      19 hours ago








    • 2





      @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

      – Martin Tournoij
      19 hours ago



















    Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

    – Caleb
    19 hours ago







    Thanks. Using this I searched around for other implementations and am now wondering why you used ... is# '' instead of ... == ''. Can you clarify that bit?

    – Caleb
    19 hours ago






    2




    2





    @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

    – Martin Tournoij
    19 hours ago







    @Caleb is is the "strict comparison", similar to === in JavaScript and PHP. 0 == '' is 1, which is often not what you want, but 0 is '' is 0. The # is to explicitly match case (otherwise ignorecase setting is used). Neither are strictly needed here, but it's just a habit I've picked up after I ran in to a few bugs with ==, and I think everyone should probably be using it (just like everyone is using ===). Also see :help expr4.

    – Martin Tournoij
    19 hours ago













    1














    silent! {map} <unique> {lhs} {rhs}


    Works too. The <unique> modifier issues an error if there is already a mapping for the left-hand side, which silent swallows.






    share|improve this answer




























      1














      silent! {map} <unique> {lhs} {rhs}


      Works too. The <unique> modifier issues an error if there is already a mapping for the left-hand side, which silent swallows.






      share|improve this answer


























        1












        1








        1







        silent! {map} <unique> {lhs} {rhs}


        Works too. The <unique> modifier issues an error if there is already a mapping for the left-hand side, which silent swallows.






        share|improve this answer













        silent! {map} <unique> {lhs} {rhs}


        Works too. The <unique> modifier issues an error if there is already a mapping for the left-hand side, which silent swallows.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 13 hours ago









        D. Ben KnobleD. Ben Knoble

        2,4381520




        2,4381520






























            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%2f19597%2fdetect-existing-key-binding-before-creating-one%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

            VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

            Tribunal Administrativo e Fiscal de Mirandela Referências Menu de...

            looking for continuous Screen Capture for retroactivly reproducing errors, timeback machineRolling desktop...