message: Extract finding last complete filter to own function
diff: @@ -225,6 +225,26 @@ const lastWordRegex = /(\b[\w:"'<=>]{3,}|#\w*)$/;
  // matches a string that seems to end with a closing, not opening, quote
  const closingQuoteRegex = /\w["']$/;
  +/**
  + * Find the position of the last "complete" filter segment of the query before the caretIndex
  + * @returns the start index and term of the last complete filter
  + */
  +export function findLastFilter(
  + query: string,
  + caretIndex: number
  +): {
  + term: string;
  + index: number;
  +} | null {
  + const execResult = lastWordRegex.exec(query.slice(0, caretIndex));
  + if (execResult) {
  + const [__, term] = execResult;
  + const { index } = execResult;
  + return { term, index };
  + }
  + return null;
  +}
  +
  /**
  * Given a query and a cursor position, isolate the term that's being typed and offer reformulated queries
  * that replace that term with one from our filterComplete function.
  @@ -242,17 +262,14 @@ export function autocompleteTermSuggestions(
  // Seek to the end of the current part
  caretIndex = (caretEndRegex.exec(query.slice(caretIndex))?.index || 0) + caretIndex;
  - // Find the last word that looks like a search
  - const match = lastWordRegex.exec(query.slice(0, caretIndex));
  - if (!match) {
  - return [];
  - }
  - const term = match[1];
  - if (closingQuoteRegex.test(term)) {
  + const lastFilter = findLastFilter(query, caretIndex);
  +
  + if (!lastFilter || closingQuoteRegex.test(lastFilter.term)) {
  return [];
  }
  - const candidates = filterComplete(term);
  - const base = query.slice(0, match.index);
  +
  + const base = query.slice(0, lastFilter.index);
  + const candidates = filterComplete(lastFilter.term);
  // new query is existing query minus match plus suggestion
  return candidates.map((word) => {
  @@ -272,7 +289,7 @@ export function autocompleteTermSuggestions(
  type: SearchItemType.Autocomplete,
  highlightRange: {
  section: 'body',
  - range: [match.index, match.index + word.length],
  + range: [lastFilter.index, lastFilter.index + word.length],
  },
  };
  });
  