match-manager.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const _ = require('underscore-plus')
  2. const {CompositeDisposable} = require('atom')
  3. module.exports =
  4. class MatchManager {
  5. appendPair (pairList, [itemLeft, itemRight]) {
  6. const newPair = {}
  7. newPair[itemLeft] = itemRight
  8. pairList = _.extend(pairList, newPair)
  9. }
  10. processAutoPairs (autocompletePairs, pairedList, dataFun) {
  11. if (autocompletePairs.length) {
  12. for (let autocompletePair of autocompletePairs) {
  13. const pairArray = autocompletePair.split('')
  14. this.appendPair(pairedList, dataFun(pairArray))
  15. }
  16. }
  17. }
  18. updateConfig () {
  19. this.pairedCharacters = {}
  20. this.pairedCharactersInverse = {}
  21. this.pairRegexes = {}
  22. this.pairsWithExtraNewline = {}
  23. this.processAutoPairs(this.getScopedSetting('bracket-matcher.autocompleteCharacters'), this.pairedCharacters, x => [x[0], x[1]])
  24. this.processAutoPairs(this.getScopedSetting('bracket-matcher.autocompleteCharacters'), this.pairedCharactersInverse, x => [x[1], x[0]])
  25. this.processAutoPairs(this.getScopedSetting('bracket-matcher.pairsWithExtraNewline'), this.pairsWithExtraNewline, x => [x[0], x[1]])
  26. for (let startPair in this.pairedCharacters) {
  27. const endPair = this.pairedCharacters[startPair]
  28. this.pairRegexes[startPair] = new RegExp(`[${_.escapeRegExp(startPair + endPair)}]`, 'g')
  29. }
  30. }
  31. getScopedSetting (key) {
  32. return atom.config.get(key, {scope: this.editor.getRootScopeDescriptor()})
  33. }
  34. constructor (editor, editorElement) {
  35. this.destroy = this.destroy.bind(this)
  36. this.editor = editor
  37. this.subscriptions = new CompositeDisposable()
  38. this.updateConfig()
  39. // Subscribe to config changes
  40. const scope = this.editor.getRootScopeDescriptor()
  41. this.subscriptions.add(
  42. atom.config.observe('bracket-matcher.autocompleteCharacters', {scope}, () => this.updateConfig()),
  43. atom.config.observe('bracket-matcher.pairsWithExtraNewline', {scope}, () => this.updateConfig()),
  44. this.editor.onDidDestroy(this.destroy)
  45. )
  46. this.changeBracketsMode = false
  47. }
  48. destroy () {
  49. this.subscriptions.dispose()
  50. }
  51. }