public LocationTracker replace()

in tools/query_breakdown/src/main/java/com/google/bigquery/LocationTracker.java [134:189]


  public LocationTracker replace(int startLine, int startColumn, int endLine,
      int endColumn, String replaceFrom, String replaceTo) {
    // same line, same length replacement
    if (replaceFrom.length() == replaceTo.length() && startLine == endLine) {
      return this;

    }
    LocationTracker locationTracker = cloneTracker();

    // position of last character of replaceFrom
    int end = (startLine == endLine) ? endColumn : location.get(startLine - 1).size();

    // how much the replaceTo is longer by
    int longer = (startLine == endLine) ? replaceTo.length() - replaceFrom.length() :
        replaceTo.length() - (end - startColumn);

    // how much the replaceTo is shorter by
    int shorter = (startLine == endLine) ? replaceFrom.length() - replaceTo.length() :
        end - startColumn - replaceTo.length();

    // if we replace the token with a longer token and need to add to the locationTracker
    if (longer > 0) {
      for (int i = end + 1; i <= end + longer; i++) {
        /* adding letters that are not in the original document, but still need to have them
           appear in the original document in the frontend as well as cli*/
        locationTracker.add(startLine, i, location.get(startLine - 1).get(end - 1).getX(), i);
      }
    }
    // if we replace the token with a shorter token and need to subtract from the locationTracker
    else {
      for (int j = end - shorter; j < end; j++) {
        locationTracker.remove(startLine, startColumn + replaceTo.length());
      }
    }

    /* multi-line replacement considerations (end line and middle line). Note that replace
       the component only in the startLine for simplicity.
     */
    if (startLine != endLine) {
      if (endColumn == locationTracker.getLocation().get(endLine - 1).size()) {
        locationTracker.removeLine(endLine);
      }
      else {
        for (int k = 1; k < endColumn + 1; k++) {
          locationTracker.remove(endLine, 1);
        }
      }
      // lines in the middle
      if (endLine - startLine > 1) {
        for (int z = startLine + 1; z < endLine; z++) {
          locationTracker.removeLine(z);
        }
      }
    }
    return locationTracker;
  }