Action

Create new entry

Posted by @scripts4drafts, Last update over 5 years ago

This script creates a new entry in the current draft, right after the entry where the cursor is. The separator between entries is set in the ‘Init’ function.

Steps

  • script

    function Init() {
      // set separator
      this.sep = '***';
      // locate cursor
      this.loc = editor.getSelectedRange()[0];
      // locate the end of current draft
      let eod = draft.content.length;
      // set regexp before
      let reb = new RegExp('^([\\s\\S]*' + RegExp.quote(this.sep) + ')?[\\s\\S]*?$');
      //set regexp after
      let rea = new RegExp('^([\\s\\S]*?)(' + RegExp.quote(this.sep) + '[\\s\\S]*)?$');
      // regexp before cursor
      editor.getTextInRange(0, this.loc).match(reb);
      // locate start of current entry
      this.sce = (RegExp.$1?RegExp.$1.length:0);
      // regexp before start of current entry
      editor.getTextInRange(this.loc, eod).match(rea);
      // set length of current entry
      this.lce = this.loc - this.sce + RegExp.$1.length;
      // check if current entry is the last one in draft
      this.ile = (RegExp.$2?false:true);
      // set current entry
      this.cue = editor.getTextInRange(this.sce, this.lce).trim();
    }
    
    Object.prototype.newEntry = function() {
      // modify current entry with no empty lines before and after entry, then add separators
      var str = (!this.sce && !this.cue?this.sep:'') + '\n' + this.cue + (this.cue?'\n' + this.sep + '\n':'') + (this.ile?'':'\n');
      // replace current entry with modified entry
      editor.setTextInRange(this.sce, this.lce, str);
      // locate the start of new entry
      this.loc = this.sce + str.length - (this.ile?0:1);
      // move the cursor at the start of new entry
      editor.setSelectedRange(this.loc, 0);
      editor.setSelectedText('');
    }
    
    RegExp.quote = function(str) {
      return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }
    
    let it = new Init();
    it.newEntry();

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.