Find comma after sub andd add NodeWithPosition in node
330904
def find_next_comma(self, node, sub):
        """"""
        position = (sub.last_line, sub.last_col)
        first, last = find_next_comma(self.lcode, position)
        if first:  # comma exists
            node.op_pos.append(NodeWithPosition(last, first))
236107
def insert_or_append(parent, node, next_sibling):
    
    # simple insert
    if next_sibling:
        parent.insertBefore(node, next_sibling)
    else:
        parent.appendChild(node)
1323891
function replace(node, nodeName) {
  if (node.nodeName.toUpperCase() === nodeName.toUpperCase()) {
    return node;
  }

  const newNode = create(nodeName);

  if (node.style.cssText) {
    newNode.style.cssText = node.style.cssText;
  }

  appendChildNodes(newNode, lists.from(node.childNodes));
  insertAfter(newNode, node);
  remove(node);

  return newNode;
}
793036
function(str, pos) {
    var T = this, k, child;
    if (str.length == 0) {
      if (pos === undefined) {
        return T.getAllWords(str);
      } else {
        return [];
      }
    }
    if (pos === undefined) {
      pos = 0;
    }
    k = str[pos];
    child = T.children[k];
    if (child === undefined) {
      //node doesn't exist
      return [];
    }
    if (pos === str.length - 1) {
      return child.getAllWords(str);
    }
    return child.autoComplete(str, pos + 1);
  }
1289600
function position() {
      var before = now()

      return update

      // Add the position to a node.
      function update(node, indent) {
        var prev = node.position
        var start = prev ? prev.start : before
        var combined = []
        var n = prev && prev.end.line
        var l = before.line

        node.position = new Position(start)

        // If there was already a `position`, this node was merged.  Fixing
        // `start` wasn’t hard, but the indent is different.  Especially
        // because some information, the indent between `n` and `l` wasn’t
        // tracked.  Luckily, that space is (should be?) empty, so we can
        // safely check for it now.
        if (prev && indent && prev.indent) {
          combined = prev.indent

          if (n < l) {
            while (++n < l) {
              combined.push((offset[n] || 0) + 1)
            }

            combined.push(before.column)
          }

          indent = combined.concat(indent)
        }

        node.position.indent = indent || []

        return node
      }
    }
1389
function pointAt(node){
      var parent = node.parentNode;
      var next = node.nextSibling;
      return function(newnode) {
        parent.insertBefore(newnode, next);
      };
    }
479937
def insert(self, i, tag, affix, cmd="hassuf", tagged=None):
        
        if affix.startswith("-") and affix.endswith("-"):
            affix, cmd = affix[+1:-1], "char"
        if affix.startswith("-"):
            affix, cmd = affix[+1:-0], "hassuf"
        if affix.endswith("-"):
            affix, cmd = affix[+0:-1], "haspref"
        if tagged:
            r = [tagged, affix, "f"+cmd.lstrip("f"), tag, "x"]
        else:
            r = [affix, cmd.lstrip("f"), tag, "x"]
        lazylist.insert(self, i, r)
776312
function processNode(node) {
    if (node.tagName === 'P' || node.tagName === 'DIV' || node.tagName === 'UL' || node.tagName === 'OL' || node.tagName === 'PRE')
      setContent(node, getContent(node), '\n\n', '\n\n');
    else if (node.tagName === 'BR')
      setContent(node, '\n\n');
    else if (node.tagName === 'HR')
      setContent(node, '\n***\n');
    else if (node.tagName === 'H1')
      setContent(node, nltrim(getContent(node)), '\n# ', '\n');
    else if (node.tagName === 'H2') 
      setContent(node, nltrim(getContent(node)), '\n## ', '\n');
    else if (node.tagName === 'H3')
      setContent(node, nltrim(getContent(node)), '\n### ', '\n');
    else if (node.tagName === 'H4') 
      setContent(node, nltrim(getContent(node)), '\n#### ', '\n');
    else if (node.tagName === 'H5') 
      setContent(node, nltrim(getContent(node)), '\n##### ', '\n');
    else if (node.tagName === 'H6')
      setContent(node, nltrim(getContent(node)), '\n###### ', '\n');
    else if (node.tagName === 'B' || node.tagName === 'STRONG')
      setContent(node, nltrim(getContent(node)), '**', '**');
    else if (node.tagName === 'I' || node.tagName === 'EM')
      setContent(node, nltrim(getContent(node)), '_', '_');
    else if (node.tagName === 'A') {
      var href = node.href ? nltrim(node.href) : '', text = nltrim(getContent(node)) || href, title = node.title ? nltrim(node.title) : '';
      if (href.length > 0)
        setContent(node, '[' + text + '](' + href + (title ? ' "' + title + '"' : '') + ')');
      else
        setContent(node, '');
    } else if (node.tagName === 'IMG') {
      var src = node.getAttribute('src') ? nltrim(node.getAttribute('src')) : '', alt = node.alt ? nltrim(node.alt) : '', caption = node.title ? nltrim(node.title) : '';
      if (src.length > 0)
        setContent(node, '![' + alt + '](' + src  + (caption ? ' "' + caption + '"' : '') + ')');
      else
        setContent(node, '');
    } else if (node.tagName === 'BLOCKQUOTE') {
      var block_content = getContent(node);
      if (block_content.length > 0)
        setContent(node, prefixBlock('> ', block_content), '\n\n', '\n\n');
      else
        setContent(node, '');
    } else if (node.tagName === 'CODE') {
      if (node._bfs_parent.tagName === 'PRE' && node._bfs_parent._bfs_parent !== null)
        setContent(node, prefixBlock('    ', getContent(node)));
      else
        setContent(node, nltrim(getContent(node)), '`', '`');
    } else if (node.tagName === 'LI') {
      var list_content = getContent(node);
      if (list_content.length > 0)
        if (node._bfs_parent.tagName === 'OL') 
          setContent(node, trim(prefixBlock('    ', list_content, true)), '1. ', '\n\n');
        else
          setContent(node, trim(prefixBlock('    ', list_content, true)), '- ', '\n\n');
      else
        setContent(node, '');
    } else 
      setContent(node, getContent(node));
  }
185341
def on_subscript(self, node):    # ('value', 'slice', 'ctx')
        """"""
        val = self.run(node.value)
        nslice = self.run(node.slice)
        ctx = node.ctx.__class__
        if ctx in (ast.Load, ast.Store):
            if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)):
                return val.__getitem__(nslice)
            elif isinstance(node.slice, ast.ExtSlice):
                return val[nslice]
        else:
            msg = "subscript with unknown context"
            self.raise_exception(node, msg=msg)
1080490
def calculate_infixop(self, node, previous, next_node):
        """"""
        previous_position = (previous.last_line, previous.last_col - 1)
        position = (next_node.first_line, next_node.first_col + 1)
        possible = []
        for ch in OPERATORS[node.__class__]:
            try:
                pos = self.operators[ch].find_previous(position)
                if previous_position < pos[1] < position:
                    possible.append(pos)
            except KeyError:
                pass

        if not possible:
            raise ValueError("not a single {} between {} and {}".format(
                OPERATORS[node.__class__], previous_position, position))

        return NodeWithPosition(
            *min(possible, key=lambda x: tuple(map(sub, position, x[0])))
        )
143565
function (node) {
    // Skip inline
    if (node.loc.start.line === node.loc.end.line) {
      return;
    }

    var elements = (node.type === 'ArrayExpression') ? node.elements : node.properties;

    // Skip if first element is in same line with this node
    if (elements.length > 0 && elements[0].loc.start.line === node.loc.start.line) {
      return;
    }

    var nodeIndent = getNodeIndent(node);

    var elementsIndent = nodeIndent + indentSize;
    // Elements can have double indent (detected by first item)
    if (elements.length > 0 &&
        getNodeIndent(elements[0]) === elementsIndent + indentSize) {
      elementsIndent = elementsIndent + indentSize;
    }

    // Comma can be placed before property name
    checkNodesIndent(elements, elementsIndent, true);

    if (elements.length > 0) {
      // Skip last block line check if last item in same line
      if (elements[elements.length - 1].loc.end.line === node.loc.end.line) {
        return;
      }
    }

    checkLastNodeLineIndent(node, elementsIndent - indentSize);
  }
1006436
function findSubscribersRecursively( node, parts, subscribers ) {
   if( Array.isArray( node[ SUBSCRIBER_FIELD ] ) ) {
      subscribers.push( ...node[ SUBSCRIBER_FIELD ] );
   }

   if( parts.length === 0 ) {
      return;
   }

   const [ part, ...remainder ] = parts;
   if( part.indexOf( SUB_TOPIC_SEPARATOR ) !== -1 ) {
      let index = part.length;
      let currentPart = part;
      do {
         currentPart = currentPart.substring( 0, index );
         if( currentPart in node ) {
            findSubscribersRecursively( node[ currentPart ], remainder, subscribers );
         }
         index = currentPart.lastIndexOf( SUB_TOPIC_SEPARATOR );
      }
      while( index !== -1 );
   }
   else if( part in node ) {
      findSubscribersRecursively( node[ part ], remainder, subscribers );
   }

   if( WILDCARD in node ) {
      findSubscribersRecursively( node[ WILDCARD ], remainder, subscribers );
   }
}
736136
function updatePosition(subvalue) {
      var lastIndex = -1
      var index = subvalue.indexOf('\n')

      while (index !== -1) {
        line++
        lastIndex = index
        index = subvalue.indexOf('\n', index + 1)
      }

      if (lastIndex === -1) {
        column += subvalue.length
      } else {
        column = subvalue.length - lastIndex
      }

      if (line in offset) {
        if (lastIndex !== -1) {
          column += offset[line]
        } else if (column <= offset[line]) {
          column = offset[line] + 1
        }
      }
    }
256763
def has_match_at_current_position(self, sub):
        
        return self.text.find(sub, self.cursor_position) == self.cursor_position
797409
function formatNodes(merged, notSplit) {
    // grab the class name out (if it exists)
    remainingNodes = _.reject(merged, function(i) {
      if (i["tagname"] === "class") {
        classPrefix = i["name"];
        nodes[classPrefix] = createBasicTranslation(classPrefix, "class", i, options);

        if (i["inherits"] !== undefined && i["inherits"].length > 0) 
          nodes[classPrefix]["inherits"] = i["inherits"];

        if (i["allowchild"] !== undefined) 
          nodes[classPrefix]["allowchild"] = i["allowchild"].doc;

        return true;
      }
    });

    // flag nodes that don't have doc
    // or that just contain "@todo" in the beginning
    remainingNodes = _.map(remainingNodes, function(n) {
      if (n["doc"] === undefined || /^@todo/i.test(n["doc"]))
        n.undocumented = true;

      return n;
    });

    remainingNodes = _.reject(remainingNodes, function(i) {
      var isEvent = i["tagname"] == "event";
      var isConstructor = i["tagname"] == "constructor";
      var joinChar = isEvent ? "@" : ".";

      if (classPrefix === undefined && options.globalNS) 
        classPrefix = options.globalNS;

      if (new RegExp("^" + options.globalNS + joinChar + i["name"]).test(i["original_name"]))
        className = options.globalNS;
      else
        className = classPrefix;

      memberName = [className, i["name"]].join(joinChar);

      if (memberName.lastIndexOf(".") === memberName.length - 1 && i["inheritdoc"] === undefined) {
        console.error(i);    
        console.error("FATAL".red + ": this object doesn't have a proper name. Check that your comment is written correctly. Typically, his happens when: ");
        console.error("   * A statement above is missing a semicolon--including closing function tags--see this bug: " + "http://code.google.com/p/esprima/issues/detail?id=347&thanks=347&ts=1348621099".cyan);
        console.error("   * The line above a comment is a single line comment--see this bug: " + "https://github.com/senchalabs/jsduck/issues/247".cyan);
        process.exit(1)
      }

      if (isConstructor)
        memberName = classPrefix + ".new";
      
      if (memberName.charAt(0) == ".")
        memberName = memberName.slice(1);

      if (i["tagname"] === "method" || i["tagname"] === "constructor" || isEvent) {
        nodes[memberName] = createBasicTranslation(memberName, i["tagname"], i, options);
        nodes[memberName]["signatures"] = [];
        var ret = {};

        // these next blocks don't yet handle alternate signatures...
        // but are written as if they will :)
        if (i["params"] !== undefined) {
            var sig = { "arguments": [] };
            nodes[memberName]["arguments"] = [];

            _.each(i["params"], function(p) {
              // construct the args object
              var args = {};
              args.name = p["name"];
              args.description = p["doc"];
              args.default_value = p["default"];

              args.types = [];

              // types could be multiple
              if (p["type"].indexOf("|") >= 0) {
                p["type"].split("|").forEach(function(t) {
                  args.types.push(trim(t));
                });
              }
              else if (p["type"].indexOf(",") >= 0) {
                console.warn("Warning".yellow + ": you're using ',' to separate types in " + memberName + ", use '|' instead.");
              }
              else {
                args.types.push(p["type"]);
              }

              args.optional = p["optional"];

              sig.arguments.push(args);

              // there are args on "signatures" and a separate arguments property
              nodes[memberName]["arguments"].push(args);
            });
        }

        if (i["return"] !== undefined && i["return"].type !== undefined) {
          if (i["return"].type.indexOf("[") == 0) { // TODO: probably not best to do this here
            ret.type = i["return"].type.substr(1, i["return"].type.length - 2);
            ret.isArray = true;
          }
          else {
            ret.type = i["return"].type;
          }

          ret.description = i["return"].doc;

          // there are returns on "signatures" and a separate returns property
          //nodes[memberName]["returns"].push(ret);
        }

        var pushedObj = { };

        if (_.size(nodes[memberName]["arguments"]) > 0)    
          pushedObj["arguments"] = nodes[memberName]["arguments"];

        if (_.size(ret) > 0 && ret.type !== "undefined")
          pushedObj["returns"] = [ret];

        nodes[memberName]["signatures"].push(pushedObj);

        if (isEvent) {
          if (i["cancelable"] !== undefined)
            nodes[memberName]["cancelable"] = i["cancelable"];
          if (i["bubbles"] !== undefined)
            nodes[memberName]["bubbles"] = i["bubbles"];
        }

        if (i["tagname"] === "method") {
          // avoid reinitializing on each node loop
          if (reportObject[className] === undefined) {
              reportObject[className] = {};
              reportObject[className].missingMembers = [];
          }
          
          // go through the list of what esprima said were methods
          // and make sure they have real documentation
          var funcLength = availableFunctions.length;

          for (var l = 0; l < funcLength; l++) {
            var func = availableFunctions[l];

            // we found a matching function! 
            if (func.name === i["name"]) { 
              // if it's tagged as incomplete or private, just skip it
              if (nodes[memberName]["private"] || nodes[memberName]["ignore"]) {
                // no op, we'll slice below
              }
              // now make sure the parameters match, too
              else if (func.params !== undefined) {
                _.any(func.params, function (funcArg, idx) {
                  // catch instance where args are missing documentation
                  if (idx >= nodes[memberName]["arguments"].length) {
                    reportObject[className].missingMembers.push({name: i["name"], member: nodes[memberName], reason: "Missing documented arguments"});
                    return true;
                  }
                  // catch instance where arg and func names don't match
                  else if (funcArg.name !== nodes[memberName]["arguments"][idx].name) {
                    reportObject[className].missingMembers.push({name: i["name"], member: nodes[memberName], reason: "Documented arguments missing proper name"});
                    return true;
                  }
                });
              }

              // all the doc "tests" passed, remove this method from the reporting object
              availableFunctions.splice(l, 1);
              break;
            }
          }
        }

        methodCount++;
        return true;
      }

      else if (i["tagname"] === "property") {
        nodes[memberName] = createBasicTranslation(memberName, "property", i, options);
        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: [ { type: i["type"], default_value: i["default"] } ] } ];
        return true;
      }

      else if (i["tagname"] === "attribute") {
        nodes[memberName] = createBasicTranslation(memberName, "attribute", i, options);

        var returnsArray = [];

        if (i["default"] !== undefined && i["default"] !== null)
          nodes[memberName]["defaults"] = i["default"];

        if (i["type"]) {
          var types = i["type"].split("|");

          _.each(types, function(t) {
            returnsArray.push({type: trim(t)});
          });
        }

        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: returnsArray } ];
        return true;
      }

      else if (i["tagname"] === "binding") {
        nodes[memberName] = createBasicTranslation(memberName, "binding", i, options);
        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: [ { type: i["type"] } ] } ];
        return true;
      }

      else {
        console.warn("Warning".yellow + ": I don't know what " + i["tagname"] + " is supposed to do in " + file);
        return true;
      }
    });

    if (notSplit) {
      checkMissingFunctions(notSplit);      
      reportObject[className].documented = methodCount;
    }

    // do pre-distribute early work
    _.each(nodes, function (node, id) {
      var clone;

      // assign hierarchy helpers
      node.aliases  = [];
      node.children = [];

      // set source file of the node
      node.file = file;

      if ('class' === node.type) {
        node.subclasses = [];
      }

      // collect sections
      if ('section' === node.type) {
        list[node.id] = node;
        return;
      }

      // elements with undefined section get '' section,
      // and will be resolved later, when we'll have full
      // element list
      list[(node.section || '') + '.' + node.id] = node;

      // bound methods produce two methods with the same description but different signatures
      // E.g. Element.foo(@element, a, b) becomes
      // Element.foo(element, a, b) and Element#foo(a, b)
      if ('method' === node.type && node.bound) {
        clone = _.clone(node);
        clone.id = node.id.replace(/(.+)\.(.+)$/, '$1#$2');

        // link to methods
        node.bound = clone.id;
        clone.bound = node.id;

        // insert bound method clone
        list[(node.section || '') + '.' + clone.id] = clone;
      }
    });
  }
720838
function(param, test) {
  var $ = param.replace(/\s+/g, '')
    , group
    , offset;

  if ($ === 'even') $ = '2n+0';
  else if ($ === 'odd') $ = '2n+1';
  else if (!~$.indexOf('n')) $ = '0n' + $;

  $ = /^([+-])?(\d+)?n([+-])?(\d+)?$/.exec($);
  group = $[1] === '-' ? -($[2] || 1) : +($[2] || 1);
  offset = $[4] ? ($[3] === '-' ? -$[4] : +$[4]) : 0;
  param = $ = null;

  return function(el) {
    if (el.parentNode.nodeType !== 1) return;

    var diff
      , pos = 0
      , rel = child(el.parentNode);

    while (rel) {
      if (test(rel, el)) pos++;
      if (rel === el) {
        diff = pos - offset;
        return !group ? !diff : !(diff % group);
      }
      rel = next(rel);
    }
  };
}
672669
function (node, preceding) {
            var next = preceding.nextSibling, parent = preceding.parentNode;
            if (next) {
                parent.insertBefore(node, next);
            } else {
                parent.appendChild(node);
            }
            return node;
        }