Home  >  Article  >  Development Tools  >  Through operation examples, see how to add custom shortcut keys in atom

Through operation examples, see how to add custom shortcut keys in atom

青灯夜游
青灯夜游forward
2022-02-24 10:38:303154browse

How to add custom shortcut keys in atom? This article will take language-markdown as an example to introduce how to quickly set markdown multi-level titles. I hope it will be helpful to you!

Through operation examples, see how to add custom shortcut keys in atom

Description of the problem

When using Markdown to write study notes, I initially selected markdownpad 2 as the editor, but markdownpad is not suitable for latex formulas and textures. It is very unfriendly to use, but there are some friendly shortcut keys, such as ctrl 1 to quickly add a level 1 title, and a toolbar is also set up to quickly bold text, insert URL hyperlinks, etc. , more suitable for novices. However, markdownpad 2 does not work well for latex and other mathematical formulas, pasting pictures, etc.

atom is a very good markdown editor, (download URL), supports multiple programming language formats, and is open source. There are many third-party packages and themes to make the editor more user-friendly. [Related recommendations: atom usage tutorial]

The language-markdown is a markdown enhancement library that atom must install, which sets a series of shortcuts, such as:

Through operation examples, see how to add custom shortcut keys in atom
But there is no shortcut key to quickly add markdown titles in atom. In order to solve this problem, you need to customize shortcut keys. (PS: As of the time of posting, I have not seen any other similar tutorials) This is my entire analysis and operation idea. If the reader does not have time, it is recommended to directly download the file I modified and overwrite the file with the same name in the language-markdown directory. folder and restart atom: CSDN download link

atom custom shortcut key-keymaps analysis and application

The shortcut key function in atom is very powerful, the same Shortcut keys implement different functions on different windows of atom, and they also support customization. Check

Through operation examples, see how to add custom shortcut keys in atom in

settings-keybindings

of atom and you can find that ctrl corresponds to 3 According to the source function, different functions are indeed implemented in different views. According to the interface prompts, we copy the shortcut key syntax in markdown-preview-plus, as follows:

'.platform-win32 .markdown-preview-plus':
  'ctrl-+': 'markdown-preview-plus:zoom-in'

Compare it in Description of keybindings:
Through operation examples, see how to add custom shortcut keys in atom

We can find that the grammatical characteristics of atom shortcut key setting are:

'Selector':
  'keystroke': 'Command'

keystroke is what we want to set Shortcut keys, Command is the command executed by the shortcut key, and source indicates which package the shortcut key is in, and Selector is the selector, which can be considered similar to the CSS selector. They are all positioning elements. In atom, they probably identify the contextual position where the shortcut key occurs. Focusing on the analysis of Command, it feels like this refers to a function in the package.

Modify the language-markdown package to realize the quick setting of markdown multi-level titles in atom

View a shortcut key set in language-markdown:

'atom-text-editor[data-grammar="text md"]':
  '*': 'markdown:strong-emphasis'

In the package , searched for the keyword strong-emphasis, and found multiple matching records in the 'main.js` of the lib file, and found the following content (lines 189-202):

  addCommands () {
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:indent-list-item', (event) => this.indentListItem(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:outdent-list-item', (event) => this.outdentListItem(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:emphasis', (event) => this.emphasizeSelection(event, '_')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:strong-emphasis', (event) => this.emphasizeSelection(event, '**')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:strike-through', (event) => this.emphasizeSelection(event, '~~')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:link', (event) => this.linkSelection(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:image', (event) => this.linkSelection(event, true)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:toggle-task', (event) => this.toggleTask(event)))
    if (atom.inDevMode()) {
      this.subscriptions.add(atom.commands.add('atom-workspace', 'markdown:compile-grammar-and-reload', () => this.compileGrammar()))
    }
  },

This piece of code appears in the shortcut key description of the language-markdown package shown in the problem description Command, and found that strong-emphasis is calling in js emphasizeSelection function. Since strong-emphasis implements the bold display function of text, and the bold display of text in markdown is actually to add ** before and after the text to be bolded, and markdown settings Setting the title is actually adding multiple # before and after the text. Therefore, we can analyze the emphasizeSelection function to achieve our goal. The emphasizeSelection function is as follows:

emphasizeSelection (event, token) {
    let didSomeWrapping = false
    if (atom.config.get('language-markdown.emphasisShortcuts')) {
      const editor = atom.workspace.getActiveTextEditor()
      if (!editor) return

      const ranges = this.getSelectedBufferRangesReversed(editor)
      for (const range of ranges) {
        const text = editor.getTextInBufferRange(range)
        /*
        Skip texts that contain a line-break, or are empty.
        Multi-line emphasis is not supported 'anyway'.

        If afterwards not a single selection has been wrapped, cancel the event
        and insert the character as normal.

        If two cursors were found, but only one of them was a selection, and the
        other a normal cursor, then the normal cursor is ignored, and the single
        selection will be wrapped.
        */
        if (text.length !== 0 && text.indexOf('\n') === -1) {
          const wrappedText = this.wrapText(text, token)
          editor.setTextInBufferRange(range, wrappedText)
          didSomeWrapping = true
        }
      }
    }
    if (!didSomeWrapping) {
      event.abortKeyBinding()
    }
    return
  },

From the source code, we know from the analysis that under the judgment of a series of conditions : When there is selected text and it is a single line, add token before and after text, and token is exactly the ** set in the addcommand function. But because markdown sets the title, there is a space before and after the text, and then #: # header1 #. So we can make a very simple modification to this function, that is, when calling this.wrapText(text, token), just add a space character directly to text For example, copy a copy of the emphasizeSelection code and name it addwords:

  addwords (event, token) {
    let didSomeWrapping = false
    if (atom.config.get('language-markdown.emphasisShortcuts')) {
      const editor = atom.workspace.getActiveTextEditor()
      if (!editor) return

      const ranges = this.getSelectedBufferRangesReversed(editor)
      for (const range of ranges) {
        const text = editor.getTextInBufferRange(range)
        /*
        Skip texts that contain a line-break, or are empty.
        Multi-line emphasis is not supported 'anyway'.

        If afterwards not a single selection has been wrapped, cancel the event
        and insert the character as normal.

        If two cursors were found, but only one of them was a selection, and the
        other a normal cursor, then the normal cursor is ignored, and the single
        selection will be wrapped.
        */
        if (text.length !== 0 && text.indexOf('\n') === -1) {
          //2021年2月4日 14:55:26,这里需要在text文本上前后加空格,不然,不能正常的设定1-3级标题
          const wrappedText = this.wrapText(" "+text+" ", token)
          editor.setTextInBufferRange(range, wrappedText)
          didSomeWrapping = true
        }
      }
    }
    if (!didSomeWrapping) {
      event.abortKeyBinding()
    }
    return
  }

addCommands中中添加三行关于 addwords的设定,即可完成快捷键Command的设定,当选中文本调用'markdown:header1',便会自动将文本设定为一级标题,修改后的addCommands

  addCommands () {
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:indent-list-item', (event) => this.indentListItem(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:outdent-list-item', (event) => this.outdentListItem(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:emphasis', (event) => this.emphasizeSelection(event, '_')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:strong-emphasis', (event) => this.emphasizeSelection(event, '**')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:strike-through', (event) => this.emphasizeSelection(event, '~~')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:link', (event) => this.linkSelection(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:image', (event) => this.linkSelection(event, true)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:toggle-task', (event) => this.toggleTask(event)))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:header1', (event) => this.addwords(event, '#')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:header2', (event) => this.addwords(event, '##')))
    this.subscriptions.add(atom.commands.add('atom-text-editor', 'markdown:header3', (event) => this.addwords(event, '###')))

    if (atom.inDevMode()) {
      this.subscriptions.add(atom.commands.add('atom-workspace', 'markdown:compile-grammar-and-reload', () => this.compileGrammar()))
    }
  },

现在已经完成快捷键的设定了,然后就可以用我们在分析keybindings分析得的快捷键语法,在keymap文件中设定快捷键,如:

'atom-text-editor[data-grammar="text md"]':
  'ctrl-1': 'markdown:header1'
  'ctrl-2': 'markdown:header2'
  'ctrl-3': 'markdown:header3'

ctrl+数字的方法跟markdownpad2中的快捷键保持一致,但要注意这里只设计到三级标题,可以应对大部分的写作情况。当然,也可分析源码,自定义其他的功能函数,来实现更为复杂的命令。

另外一种设定快捷键的方式,是直接改写Through operation examples, see how to add custom shortcut keys in atom配置文件。在atom中,快捷键的自定义设定在keymaps.cson文件中设定,分析language-markdown发现,其存在keymaps中的文件夹,其中有一个cson文件,打开文件,发现果然是有关快捷键的设定:

'.platform-darwin atom-workspace':
  'cmd-alt-ctrl-c': 'markdown:compile-grammar-and-reload''.platform-win32 atom-workspace':
  'shift-alt-ctrl-c': 'markdown:compile-grammar-and-reload''.platform-linux atom-workspace':
  'shift-alt-ctrl-c': 'markdown:compile-grammar-and-reload''.platform-darwin atom-text-editor[data-grammar="text md"]':
  'cmd-shift-x': 'markdown:toggle-task''.platform-win32 atom-text-editor[data-grammar="text md"]':
  'ctrl-shift-x': 'markdown:toggle-task''.platform-linux atom-text-editor[data-grammar="text md"]':
  'ctrl-shift-x': 'markdown:toggle-task''atom-text-editor[data-grammar="text md"]':
  'tab': 'markdown:indent-list-item'
  'shift-tab': 'markdown:outdent-list-item'
  '_': 'markdown:emphasis'
  '*': 'markdown:strong-emphasis'
  '~': 'markdown:strike-through'
  '@': 'markdown:link'
  '!': 'markdown:image'

我们将上述的三条ctrl+数字的命令粘贴在这里,重启atom后,发现成功添加了快捷键,在markdown测试也正常:

Through operation examples, see how to add custom shortcut keys in atom经过对比发现,在keymaps文件中重载快捷键,其Source为user,而在language-markdown中的cson中修改,其Source显示为language-markdown。显然后者看起来更统一,符合强迫症患者的需求…

【相关推荐:《atom教程》】

The above is the detailed content of Through operation examples, see how to add custom shortcut keys in atom. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete