// UpdateIndex // V1.0 creates table of contents/index at top of outline file // Peter@TurtleCoveTech.com // // Assumes the file is organized as non-indented headers with indented contents // Finds all header lines and replaces the section titled "Index" with a list of all the headers import java.util.regex.Pattern; import java.util.regex.Matcher; // Gather headers String body=textArea.getText(); StringBuffer indexSection=new StringBuffer("Index\n"); Matcher titleMatcher=Pattern.compile("^[^ \t\n].*$", Pattern.MULTILINE).matcher(body); while(titleMatcher.find()) { title=titleMatcher.group(); if (!title.equals("Index")) { indexSection.append("\t").append(title).append("\n"); } } indexSection.append("\n"); // replace index section // SearchAndReplace didn't work. Multiline problem? // use getText, replace, setText Matcher bodyMatcher= Pattern.compile("^[Ii]ndex\n(^[ \t]+[^\\n]+$\n)+\n", Pattern.MULTILINE) .matcher(body); textArea.setText( bodyMatcher.replaceFirst( indexSection.toString())); // setText leaves cursor at end. Better to leave cursor on our new Index Matcher newindexMatcher= Pattern. compile("^Index$",Pattern.MULTILINE) .matcher(textArea.getText()); if (newindexMatcher.find()) { textArea.setCaretPosition( newindexMatcher.start()); }