edu.rice.cs.drjava.model
Class AbstractDJDocument

java.lang.Object
  extended by javax.swing.text.AbstractDocument
      extended by javax.swing.text.DefaultStyledDocument
          extended by edu.rice.cs.util.text.SwingDocument
              extended by edu.rice.cs.drjava.model.AbstractDJDocument
All Implemented Interfaces:
OptionConstants, DJDocument, AbstractDocumentInterface, EditDocumentInterface, SwingDocumentInterface, Serializable, Document, StyledDocument
Direct Known Subclasses:
DefinitionsDocument, InteractionsDJDocument

public abstract class AbstractDJDocument
extends SwingDocument
implements DJDocument, OptionConstants

This class contains code supporting the concept of a "DJDocument"; it is shared between DefinitionsDocument and InteractionsDJDocument. This partial implementation of Document contains a "reduced model". The reduced model is automatically kept in sync when this document is updated. Also, that synchronization is maintained even across undo/redo -- this is done by making the undo/redo commands know how to restore the reduced model state. The reduced model is not thread-safe, so it is essential that its methods are only called from the event thread. In addition, any information from the reduced model should be obtained through helper methods in this class/subclasses.

See Also:
BraceReduction, ReducedModelControl, ReducedModelComment, ReducedModelBrace, Serialized Form

Nested Class Summary
protected  class AbstractDJDocument.CharInsertCommand
           
protected  class AbstractDJDocument.InsertCommand
           
protected  class AbstractDJDocument.RemoveCommand
           
protected  class AbstractDJDocument.UninsertCommand
           
protected  class AbstractDJDocument.UnremoveCommand
           
 
Nested classes/interfaces inherited from class javax.swing.text.DefaultStyledDocument
DefaultStyledDocument.AttributeUndoableEdit, DefaultStyledDocument.ElementBuffer, DefaultStyledDocument.ElementSpec, DefaultStyledDocument.SectionElement
 
Nested classes/interfaces inherited from class javax.swing.text.AbstractDocument
AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement
 
Nested classes/interfaces inherited from interface edu.rice.cs.drjava.config.OptionConstants
OptionConstants.AccessLevelChoices, OptionConstants.DefaultFont, OptionConstants.HeapSizeChoices, OptionConstants.LookAndFeels, OptionConstants.PlasticThemes, OptionConstants.VersionNotificationChoices
 
Field Summary
protected  int _currentLocation
          The absolute character offset in the document.
protected  int _indent
          The default indent setting.
protected static HashSet<String> _keywords
          A set of Java keywords.
protected static HashSet<String> _normEndings
          A set of normal endings for lines.
protected static HashSet<String> _primTypes
          A set of Java keywords.
 ReducedModelControl _reduced
          The reduced model of the document (stored in field _reduced) handles most of the document logic and keeps track of state.
static char[] CLOSING_BRACES
          The set of closing braces recognized in most indenting operations.
protected static String delimiters
           
protected static char newline
           
static int POS_THRESHOLD
          Constant specifying how large pos must be before incremental analysis is applied in posInBlockComment
 
Fields inherited from class edu.rice.cs.util.text.SwingDocument
_condition, _isModifiedSinceSave, _styles, _wrappedPosListLock
 
Fields inherited from class javax.swing.text.DefaultStyledDocument
buffer, BUFFER_SIZE_DEFAULT
 
Fields inherited from class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName
 
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
 
Fields inherited from interface edu.rice.cs.drjava.config.OptionConstants
accessLevelChoices, ALLOW_PRIVATE_ACCESS, ALWAYS_COMPILE_BEFORE_JUNIT, ALWAYS_SAVE_BEFORE_COMPILE, ALWAYS_SAVE_BEFORE_DEBUG, ALWAYS_SAVE_BEFORE_JAVADOC, ALWAYS_SAVE_BEFORE_RUN, apiJavadocChoices, apiJavadocVersionChoices, AUTO_CLOSE_COMMENTS, BACKUP_FILES, BOOKMARK_COLOR, BROWSER_FILE, BROWSER_HISTORY_MAX_SIZE, BROWSER_STRING, choices, CLIPBOARD_HISTORY_SIZE, COMPILER_ERROR_COLOR, DEBUG_BREAKPOINT_COLOR, DEBUG_BREAKPOINT_DISABLED_COLOR, DEBUG_MESSAGE_COLOR, DEBUG_PANEL_HEIGHT, DEBUG_SOURCEPATH, DEBUG_STEP_DRJAVA, DEBUG_STEP_EXCLUDE, DEBUG_STEP_INTERPRETER, DEBUG_STEP_JAVA, DEBUG_THREAD_COLOR, DEFINITIONS_BACKGROUND_COLOR, DEFINITIONS_COMMENT_COLOR, DEFINITIONS_DOUBLE_QUOTED_COLOR, DEFINITIONS_KEYWORD_COLOR, DEFINITIONS_MATCH_COLOR, DEFINITIONS_NORMAL_COLOR, DEFINITIONS_NUMBER_COLOR, DEFINITIONS_SINGLE_QUOTED_COLOR, DEFINITIONS_TYPE_COLOR, DETACH_DEBUGGER, DETACH_TABBEDPANES, DIALOG_AUTOIMPORT_ENABLED, DIALOG_AUTOIMPORT_STATE, DIALOG_AUTOIMPORT_STORE_POSITION, DIALOG_CLIPBOARD_HISTORY_STATE, DIALOG_CLIPBOARD_HISTORY_STORE_POSITION, DIALOG_COMPLETE_JAVAAPI, DIALOG_COMPLETE_SCAN_CLASS_FILES, DIALOG_COMPLETE_WORD_STATE, DIALOG_COMPLETE_WORD_STORE_POSITION, DIALOG_DEBUGFRAME_STATE, DIALOG_DEBUGFRAME_STORE_POSITION, DIALOG_DRJAVA_ERROR_POPUP_ENABLED, DIALOG_DRJAVA_SURVEY_ENABLED, DIALOG_EDITEXTERNALPROCESS_STATE, DIALOG_EDITEXTERNALPROCESS_STORE_POSITION, DIALOG_EXTERNALPROCESS_STATE, DIALOG_EXTERNALPROCESS_STORE_POSITION, DIALOG_GOTOFILE_FULLY_QUALIFIED, DIALOG_GOTOFILE_STATE, DIALOG_GOTOFILE_STORE_POSITION, DIALOG_JAROPTIONS_STATE, DIALOG_JAROPTIONS_STORE_POSITION, DIALOG_LIGHTWEIGHT_PARSING_DELAY, DIALOG_OPENJAVADOC_STATE, DIALOG_OPENJAVADOC_STORE_POSITION, DIALOG_TABBEDPANES_STATE, DIALOG_TABBEDPANES_STORE_POSITION, DOC_LIST_WIDTH, DRJAVA_ERRORS_BUTTON_COLOR, DRJAVA_SURVEY_DAYS, DRJAVA_USE_FORCE_QUIT, EXTERNAL_SAVED_CMDLINES, EXTERNAL_SAVED_COUNT, EXTERNAL_SAVED_ENCLOSING_DJAPP_FILES, EXTERNAL_SAVED_NAMES, EXTERNAL_SAVED_PREFIX, EXTERNAL_SAVED_WORKDIRS, EXTPROCESS_FILE_EXTENSION, EXTPROCESS_FILE_NAME_INSIDE_JAR, EXTRA_CLASSPATH, EXTRA_COMPILERS, FIND_ALL_DOCUMENTS, FIND_MATCH_CASE, FIND_NO_COMMENTS_STRINGS, FIND_NO_TEST_CASES, FIND_REPLACE_FOCUS_IN_DEFPANE, FIND_RESULTS_COLOR1, FIND_RESULTS_COLOR2, FIND_RESULTS_COLOR3, FIND_RESULTS_COLOR4, FIND_RESULTS_COLOR5, FIND_RESULTS_COLOR6, FIND_RESULTS_COLOR7, FIND_RESULTS_COLOR8, FIND_RESULTS_COLORS, FIND_SEARCH_BACKWARDS, FIND_WHOLE_WORD, FOLLOW_FILE_DELAY, FOLLOW_FILE_LINES, FONT_DOCLIST, FONT_LINE_NUMBERS, FONT_MAIN, FONT_TOOLBAR, FORCE_TEST_SUFFIX, heapSizeChoices, HISTORY_MAX_SIZE, INDENT_LEVEL, INTERACTIONS_ERROR_COLOR, INTERACTIONS_EXIT_PROMPT, INTERACTIONS_RESET_PROMPT, JAVAC_LOCATION, JAVADOC_1_3_LINK, JAVADOC_1_3_TEXT, JAVADOC_1_4_LINK, JAVADOC_1_4_TEXT, JAVADOC_1_5_LINK, JAVADOC_1_5_TEXT, JAVADOC_1_6_LINK, JAVADOC_1_6_TEXT, JAVADOC_ACCESS_LEVEL, JAVADOC_API_REF_VERSION, JAVADOC_AUTO_TEXT, JAVADOC_CUSTOM_PARAMS, JAVADOC_DESTINATION, JAVADOC_FROM_ROOTS, JAVADOC_LINK_VERSION, JAVADOC_NONE_TEXT, JAVADOC_PROMPT_FOR_DESTINATION, KEY_ABOUT, KEY_BACKWARD, KEY_BEGIN_DOCUMENT, KEY_BEGIN_LINE, KEY_BOOKMARKS_PANEL, KEY_BOOKMARKS_TOGGLE, KEY_BROWSE_BACK, KEY_BROWSE_FORWARD, KEY_CHECK_NEW_VERSION, KEY_CLEAR_CONSOLE, KEY_CLEAR_HISTORY, KEY_CLEAR_LINE, KEY_CLOSE_ALL_FILES, KEY_CLOSE_FILE, KEY_CLOSE_PROJECT, KEY_CLOSING_BRACE, KEY_COMMENT_LINES, KEY_COMPILE, KEY_COMPILE_ALL, KEY_COMPLETE_FILE, KEY_COPY, KEY_CUT, KEY_CUT_LINE, KEY_DEBUG_BREAKPOINT_PANEL, KEY_DEBUG_BREAKPOINT_TOGGLE, KEY_DEBUG_CLEAR_ALL_BREAKPOINTS, KEY_DEBUG_MODE_TOGGLE, KEY_DEBUG_RESUME, KEY_DEBUG_STEP_INTO, KEY_DEBUG_STEP_OUT, KEY_DEBUG_STEP_OVER, KEY_DELETE_NEXT, KEY_DELETE_PREVIOUS, KEY_DETACH_DEBUGGER, KEY_DETACH_TABBEDPANES, KEY_DOWN, KEY_DRJAVA_ERRORS, KEY_DRJAVA_SURVEY, KEY_END_DOCUMENT, KEY_END_LINE, KEY_EXEC_PROCESS, KEY_EXECUTE_HISTORY, KEY_EXPORT_OLD, KEY_FIND_NEXT, KEY_FIND_PREV, KEY_FIND_REPLACE, KEY_FOLLOW_FILE, KEY_FORCE_QUIT, KEY_FORWARD, KEY_GOTO_FILE, KEY_GOTO_FILE_UNDER_CURSOR, KEY_GOTO_LINE, KEY_HELP, KEY_JAVADOC_ALL, KEY_JAVADOC_CURRENT, KEY_LIFT_CURRENT_INTERACTION, KEY_LOAD_HISTORY_SCRIPT, KEY_NEW_FILE, KEY_NEW_TEST, KEY_NEXT_DOCUMENT, KEY_NEXT_PANE, KEY_NEXT_WORD, KEY_OPEN_FILE, KEY_OPEN_FOLDER, KEY_OPEN_JAVADOC, KEY_OPEN_JAVADOC_UNDER_CURSOR, KEY_OPEN_PROJECT, KEY_OPENING_BRACE, KEY_PAGE_DOWN, KEY_PAGE_SETUP, KEY_PAGE_UP, KEY_PASTE, KEY_PASTE_FROM_HISTORY, KEY_PREFERENCES, KEY_PREVIOUS_DOCUMENT, KEY_PREVIOUS_PANE, KEY_PREVIOUS_WORD, KEY_PRINT, KEY_PRINT_CONSOLE, KEY_PRINT_INTERACTIONS, KEY_PRINT_PREVIEW, KEY_QUICKSTART, KEY_QUIT, KEY_REDO, KEY_RENAME_FILE, KEY_RESET_INTERACTIONS, KEY_REVERT_FILE, KEY_RUN, KEY_RUN_MAIN, KEY_SAVE_ALL_FILES, KEY_SAVE_FILE, KEY_SAVE_FILE_AS, KEY_SAVE_HISTORY, KEY_SELECT_ALL, KEY_SHIFT_DELETE_NEXT, KEY_SHIFT_DELETE_PREVIOUS, KEY_TEST, KEY_TEST_ALL, KEY_UNCOMMENT_LINES, KEY_UNDO, KEY_UP, KEY_VIEW_INTERACTIONS_CLASSPATH, LANGUAGE_LEVEL, LAST_DIRECTORY, LAST_DRJAVA_SURVEY, LAST_DRJAVA_SURVEY_RESULT, LAST_INTERACTIONS_DIRECTORY, LAST_NEW_VERSION_NOTIFICATION, LIGHTWEIGHT_PARSING_ENABLED, LINEENUM_ENABLED, linkVersionChoices, LOOK_AND_FEEL, MASK, MASTER_JVM_ARGS, MASTER_JVM_XMX, NEW_VERSION_NOTIFICATION, NEW_VERSION_NOTIFICATION_CHOICES, NEW_VERSION_NOTIFICATION_DAYS, OLD_PROJECT_FILE_EXTENSION, OPEN_FOLDER_RECURSIVE, PLASTIC_THEMES, PROJECT_FILE_EXTENSION, PROMPT_BEFORE_CLEAN, QUIT_PROMPT, RECENT_FILES, RECENT_FILES_MAX_SIZE, RECENT_PROJECTS, REMOTE_CONTROL_ENABLED, REMOTE_CONTROL_PORT, RESET_CLEAR_CONSOLE, RUN_WITH_ASSERT, SHOW_CODE_PREVIEW_POPUPS, SHOW_DEBUG_CONSOLE, SHOW_DEPRECATION_WARNINGS, SHOW_FALLTHROUGH_WARNINGS, SHOW_FINALLY_WARNINGS, SHOW_PATH_WARNINGS, SHOW_SERIAL_WARNINGS, SHOW_SOURCE_WHEN_SWITCHING, SHOW_UNCHECKED_WARNINGS, SLAVE_JVM_ARGS, SLAVE_JVM_XMX, STICKY_INTERACTIONS_DIRECTORY, SYSTEM_ERR_COLOR, SYSTEM_IN_COLOR, SYSTEM_OUT_COLOR, TABS_HEIGHT, TEXT_ANTIALIAS, TOOLBAR_ENABLED, TOOLBAR_ICONS_ENABLED, TOOLBAR_TEXT_ENABLED, WARN_BREAKPOINT_OUT_OF_SYNC, WARN_CHANGE_LAF, WARN_CHANGE_THEME, WARN_DEBUG_MODIFIED_FILE, WARN_PATH_CONTAINS_POUND, WINDOW_HEIGHT, WINDOW_STATE, WINDOW_STORE_POSITION, WINDOW_WIDTH, WINDOW_X, WINDOW_Y
 
Constructor Summary
protected AbstractDJDocument()
          Constructor used in super calls from DefinitionsDocument and InteractionsDJDocument.
protected AbstractDJDocument(Indenter indenter)
          Constructor used to build a new document with an existing indenter.
protected AbstractDJDocument(int indentLevel)
          Constructor used from anonymous test classes.
 
Method Summary
protected  Object _checkCache(Query key)
          Checks the query cache for a stored value.
protected  void _clearCache(int offset)
          Clears the memozing cache of queries with offset >= than specified value.
 int _findPrevCharPos(int pos, char[] whitespace)
          Finds the position of the first non-whitespace, non-comment character before pos.
 int _findPrevNonWSCharPos(int pos)
           
 BraceInfo _getEnclosingBrace()
          Cached version of _reduced.getEnclosingBrace().
 int _getIndentOfCurrStmt(int pos)
          Returns the number of blanks in the indent prefix for the start of the statement identified by pos.
 int _getIndentOfCurrStmt(int pos, char[] delims)
          Returns the number of blanks in the indent prefix of the start of the statement identified by pos.
 int _getIndentOfCurrStmt(int pos, char[] delims, char[] whitespace)
          Returns the number of blanks in the indent prefix of the start of the statement identified by pos, assuming that the statement is already properly indented
 BraceInfo _getLineEnclosingBrace()
          Cached version of _reduced.getLineEnclosingBrace().
 int _getLineEndPos(int pos)
          Returns the absolute position of the end of the current line.
 int _getLineFirstCharPos(int pos)
          Returns the absolute position of the first non-blank/tab character on the current line including comment text or the end of the line if no non-blank/tab character is found.
 int _getLineStartPos(int pos)
          Returns the absolute position of the beginning of the current line.
 boolean _inBlockComment(int pos)
          Determines if pos lies within a block comment using the reduced model (ignoring the cache).
 boolean _indentLine(Indenter.IndentReason reason)
          Indents a line using the Indenter.
 boolean _inParenPhrase(int pos)
          Returns true if the given position is inside a paren phrase.
protected static boolean _isStartOfComment(String text, int pos)
          Helper method for getFirstNonWSCharPos Determines whether the current character is the start of a comment: "/*" or "//"
protected static HashSet<String> _makeKeywords()
          Create a set of Java/GJ keywords for special coloring.
protected static HashSet<String> _makeNormEndings()
          Create a set of normal endings, i.e., semi-colons and braces for the purposes of indenting.
protected static HashSet<String> _makePrimTypes()
          Create a set of Java/GJ primitive types for special coloring.
protected  void _removeIndenter()
           
protected  void _storeInCache(Query query, Object answer, int offset)
          Stores the given result in the helper method cache.
protected abstract  void _styleChanged()
          Fire event that styles changed from current location to the end.
protected abstract  void addUndoRedo(AbstractDocument.DefaultDocumentEvent chng, Runnable undoCommand, Runnable doCommand)
           
 int balanceBackward()
          Finds the match for the closing brace immediately to the left, assuming there is such a brace.
 int balanceForward()
          FindS the match for the open brace immediately to the right, assuming there is such a brace.
 void clear()
          Clears the entire text of the document.
protected abstract  void endCompoundEdit(int i)
           
protected abstract  void endLastCompoundEdit()
           
 boolean findCharInStmtBeforePos(char findChar, int position)
          This function finds the given character in the same statement as the given position, and before the given position.
 int findCharOnLine(int pos, char findChar)
          Determines if the given character exists on the line where the given cursor position is.
 int findNextEnclosingBrace(int pos, char opening, char closing)
          Searching forward, finds the position of the enclosing brace, which may be a pointy bracket.
 int findPrevDelimiter(int pos, char[] delims)
          Searching backwards, finds the position of the first character that is one of the given delimiters.
 int findPrevDelimiter(int pos, char[] delims, boolean skipBracePhrases)
          Searching backwards, finds position of first character that is a given delimiter, skipping over balanced braces if so instructed.
 int findPrevEnclosingBrace(int pos, char opening, char closing)
          Searching backwards, finds the position of the enclosing brace of specified type.
 int getAndResetNumLinesChangedAfter()
          Gets the value of _numLinesChangedAfter field and reset it -1.
 byte[] getBytes()
          Returns the byte image (as written to a file) of this document.
 int getCurrentLocation()
          Get the current location of the cursor in the document.
 int getFirstNonWSCharPos(int pos)
          Finds the position of the first non-whitespace character after pos.
 int getFirstNonWSCharPos(int pos, boolean acceptComments)
          Similar to the single-argument version, but allows including comments.
 int getFirstNonWSCharPos(int pos, char[] whitespace, boolean acceptComments)
          Finds the position of the first non-whitespace character after pos.
 ArrayList<HighlightStatus> getHighlightStatus(int start, int end)
          Return all highlight status info for text between start and end.
 int getIndent()
          Get the indent level.
 int getIntelligentBeginLinePos(int currPos)
          Returns the "intelligent" beginning of line.
 ReducedModelControl getReduced()
          This method is used ONLY inside of document Read Lock.
 ReducedModelState getStateAtCurrent()
          Assumes that read lock and reduced lock are already held.
static boolean hasOnlySpaces(String text)
          Returns whether the given text only has spaces.
 void indentLines(int selStart, int selEnd)
          Default indentation - uses OTHER flag and no progress indicator.
 void indentLines(int selStart, int selEnd, Indenter.IndentReason reason, ProgressMonitor pm)
          Parameterized indentation for special-case handling.
protected  void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)
          Updates document structure as a result of text insertion.
 boolean isShadowed()
           
 boolean isShadowed(int pos)
           
 void move(int dist)
          Moves _currentLocation the specified distance.
protected  boolean notInBlock(int pos)
          Returns true if the given position is not inside a paren/brace/etc phrase.
protected  void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
          Updates document structure as a result of text removal.
 void resetReducedModelLocation()
          Assumes that read lock and reduced lock are already held.
 void setCurrentLocation(int loc)
          Change the current location of the document.
 void setIndent(int indent)
          Set the indent to a particular number of spaces.
 void setTab(int tab, int pos)
          Inserts the number of blanks specified as the whitespace prefix for the line identified by pos.
 void setTab(String tab, int pos)
          Inserts the string specified by tab at the beginning of the line identified by pos.
protected abstract  int startCompoundEdit()
           
 ReducedModelState stateAtRelLocation(int dist)
          Assumes that read lock and reduced lock are already held.
 
Methods inherited from class edu.rice.cs.util.text.SwingDocument
_getText, addColoring, append, append, append, createUnwrappedPosition, forceInsertText, forceRemoveText, getDefaultStyle, getDocStyle, getDocText, getEditCondition, getPageable, getText, insertString, insertText, print, remove, removeText, setDocStyle, setEditCondition
 
Methods inherited from class javax.swing.text.DefaultStyledDocument
addDocumentListener, addStyle, create, createDefaultRoot, getBackground, getCharacterElement, getDefaultRootElement, getFont, getForeground, getLogicalStyle, getParagraphElement, getStyle, getStyleNames, insert, removeDocumentListener, removeStyle, setCharacterAttributes, setLogicalStyle, setParagraphAttributes, styleChanged
 
Methods inherited from class javax.swing.text.AbstractDocument
addUndoableEditListener, createBranchElement, createLeafElement, createPosition, dump, fireChangedUpdate, fireInsertUpdate, fireRemoveUpdate, fireUndoableEditUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, postRemoveUpdate, putProperty, readLock, readUnlock, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface edu.rice.cs.drjava.model.DJDocument
getText, insertString, remove
 
Methods inherited from interface edu.rice.cs.util.text.AbstractDocumentInterface
append, createPosition, getLength, getText
 
Methods inherited from interface javax.swing.text.StyledDocument
addStyle, getBackground, getCharacterElement, getFont, getForeground, getLogicalStyle, getParagraphElement, getStyle, removeStyle, setCharacterAttributes, setLogicalStyle, setParagraphAttributes
 
Methods inherited from interface javax.swing.text.Document
addDocumentListener, addUndoableEditListener, createPosition, getDefaultRootElement, getEndPosition, getLength, getProperty, getRootElements, getStartPosition, getText, getText, putProperty, removeDocumentListener, removeUndoableEditListener, render
 
Methods inherited from interface edu.rice.cs.util.text.EditDocumentInterface
getLength
 

Field Detail

delimiters

protected static final String delimiters
See Also:
Constant Field Values

newline

protected static final char newline
See Also:
Constant Field Values

_normEndings

protected static final HashSet<String> _normEndings
A set of normal endings for lines.


_keywords

protected static final HashSet<String> _keywords
A set of Java keywords.


_primTypes

protected static final HashSet<String> _primTypes
A set of Java keywords.


_indent

protected volatile int _indent
The default indent setting.


POS_THRESHOLD

public static final int POS_THRESHOLD
Constant specifying how large pos must be before incremental analysis is applied in posInBlockComment

See Also:
Constant Field Values

CLOSING_BRACES

public static final char[] CLOSING_BRACES
The set of closing braces recognized in most indenting operations.


_reduced

public final ReducedModelControl _reduced
The reduced model of the document (stored in field _reduced) handles most of the document logic and keeps track of state. This field together with _currentLocation function as a virtual object for purposes of synchronization. All operations that access or modify this virtual object should be synchronized on _reduced.


_currentLocation

protected volatile int _currentLocation
The absolute character offset in the document. Treated as part of the _reduced (model) for locking purposes.

Constructor Detail

AbstractDJDocument

protected AbstractDJDocument()
Constructor used in super calls from DefinitionsDocument and InteractionsDJDocument.


AbstractDJDocument

protected AbstractDJDocument(int indentLevel)
Constructor used from anonymous test classes.


AbstractDJDocument

protected AbstractDJDocument(Indenter indenter)
Constructor used to build a new document with an existing indenter. Used in tests and super calls from DefinitionsDocument and interactions documents.

Method Detail

getIndent

public int getIndent()
Get the indent level.

Specified by:
getIndent in interface DJDocument
Returns:
the indent level

setIndent

public void setIndent(int indent)
Set the indent to a particular number of spaces.

Specified by:
setIndent in interface DJDocument
Parameters:
indent - the size of indent that you want for the document

_removeIndenter

protected void _removeIndenter()

_makeNormEndings

protected static HashSet<String> _makeNormEndings()
Create a set of normal endings, i.e., semi-colons and braces for the purposes of indenting.

Returns:
the set of normal endings

_makeKeywords

protected static HashSet<String> _makeKeywords()
Create a set of Java/GJ keywords for special coloring.

Returns:
the set of keywords

_makePrimTypes

protected static HashSet<String> _makePrimTypes()
Create a set of Java/GJ primitive types for special coloring.

Returns:
the set of primitive types

getHighlightStatus

public ArrayList<HighlightStatus> getHighlightStatus(int start,
                                                     int end)
Return all highlight status info for text between start and end. This should collapse adjoining blocks with the same status into one. ONLY runs in the event thread. Perturbs _currentLocation to improve performance.

Specified by:
getHighlightStatus in interface DJDocument

hasOnlySpaces

public static boolean hasOnlySpaces(String text)
Returns whether the given text only has spaces.


_styleChanged

protected abstract void _styleChanged()
Fire event that styles changed from current location to the end. Right now we do this every time there is an insertion or removal. Two possible future optimizations:
  1. Only fire changed event if text other than that which was inserted or removed *actually* changed status. If we didn't changed the status of other text (by inserting or deleting unmatched pair of quote or comment chars), no change need be fired.
  2. If a change must be fired, we could figure out the exact end of what has been changed. Right now we fire the event saying that everything changed to the end of the document.
I don't think we'll need to do either one since it's still fast now. I think this is because the UI only actually paints the things on the screen anyway.


getCurrentLocation

public int getCurrentLocation()
Get the current location of the cursor in the document. Unlike the usual swing document model, which is stateless, we maintain a cursor position within our implementation of the reduced model. Can be modified by any thread locking _reduced. The returned value may be stale if _reduced lock is not held

Specified by:
getCurrentLocation in interface DJDocument
Returns:
where the cursor is as the number of characters into the document

setCurrentLocation

public void setCurrentLocation(int loc)
Change the current location of the document. Only runs in the event thread.

Specified by:
setCurrentLocation in interface DJDocument
Parameters:
loc - the new absolute location

move

public void move(int dist)
Moves _currentLocation the specified distance. Identical to _setCurrentLocation, except that input arg is relative rather than absolute and the new location is bounds checked. Only runs in the event thread.

Specified by:
move in interface DJDocument
Parameters:
dist - the distance from the current location to the new location.

balanceBackward

public int balanceBackward()
Finds the match for the closing brace immediately to the left, assuming there is such a brace. On failure, returns -1. Only runs in the event thread.

Specified by:
balanceBackward in interface DJDocument
Returns:
the relative distance backwards to the offset before the matching brace.

balanceForward

public int balanceForward()
FindS the match for the open brace immediately to the right, assuming there is such a brace. On failure, returns -1. Only runs in event thread.

Specified by:
balanceForward in interface DJDocument
Returns:
the relative distance forwards to the offset after the matching brace.

getReduced

public ReducedModelControl getReduced()
This method is used ONLY inside of document Read Lock. This method is UNSAFE in any other context!

Specified by:
getReduced in interface DJDocument
Returns:
The reduced model of this document.

stateAtRelLocation

public ReducedModelState stateAtRelLocation(int dist)
Assumes that read lock and reduced lock are already held.


getStateAtCurrent

public ReducedModelState getStateAtCurrent()
Assumes that read lock and reduced lock are already held.

Specified by:
getStateAtCurrent in interface DJDocument

resetReducedModelLocation

public void resetReducedModelLocation()
Assumes that read lock and reduced lock are already held.


findPrevEnclosingBrace

public int findPrevEnclosingBrace(int pos,
                                  char opening,
                                  char closing)
                           throws BadLocationException
Searching backwards, finds the position of the enclosing brace of specified type. Ignores comments. Only runs in event thread. TODO: implement this method by iterating getEnclosingBrace until brace of specified form is found

Specified by:
findPrevEnclosingBrace in interface DJDocument
Parameters:
pos - Position to start from
opening - opening brace character
closing - closing brace character
Returns:
position of enclosing brace, or ERROR_INDEX (-1) if beginning of document is reached.
Throws:
BadLocationException

isShadowed

public boolean isShadowed()
Returns:
true iff _currentLocation is inside comment pr string.

isShadowed

public boolean isShadowed(int pos)
Returns:
true iff specified pos is inside comment pr string.

findNextEnclosingBrace

public int findNextEnclosingBrace(int pos,
                                  char opening,
                                  char closing)
                           throws BadLocationException
Searching forward, finds the position of the enclosing brace, which may be a pointy bracket. NB: ignores comments. Only runs in event thread.

Specified by:
findNextEnclosingBrace in interface DJDocument
Parameters:
pos - Position to start from
opening - opening brace character
closing - closing brace character
Returns:
position of enclosing brace, or ERROR_INDEX (-1) if beginning of document is reached.
Throws:
BadLocationException

findPrevDelimiter

public int findPrevDelimiter(int pos,
                             char[] delims)
                      throws BadLocationException
Searching backwards, finds the position of the first character that is one of the given delimiters. Does not look for delimiters inside bracketed phrases (e.g., skips semicolons used inside for statements.). Bracketed phrases exclude those ending a delimiter (e.g., '}' if a delimiter). NB: ignores comments.

Specified by:
findPrevDelimiter in interface DJDocument
Parameters:
pos - Position to start from
delims - array of characters to search for
Returns:
position of first matching delimiter, or ERROR_INDEX (-1) if beginning of document is reached.
Throws:
BadLocationException

findPrevDelimiter

public int findPrevDelimiter(int pos,
                             char[] delims,
                             boolean skipBracePhrases)
                      throws BadLocationException
Searching backwards, finds position of first character that is a given delimiter, skipping over balanced braces if so instructed. Does not look for delimiters inside a brace phrase if skipBracePhrases is true. Ignores comments. Only runs in event thread.

Specified by:
findPrevDelimiter in interface DJDocument
Parameters:
pos - Position to start from
delims - array of characters to search for
skipBracePhrases - whether to look for delimiters inside brace phrases
Returns:
position of first matching delimiter, or ERROR_INDEX (-1) if beginning of document is reached.
Throws:
BadLocationException

findCharInStmtBeforePos

public boolean findCharInStmtBeforePos(char findChar,
                                       int position)
This function finds the given character in the same statement as the given position, and before the given position. It is used by QuestionExistsCharInStmt and QuestionExistsCharInPrevStmt


_findPrevCharPos

public int _findPrevCharPos(int pos,
                            char[] whitespace)
                     throws BadLocationException
Finds the position of the first non-whitespace, non-comment character before pos. Skips comments and all whitespace, including newlines.

Parameters:
pos - Position to start from
whitespace - chars considered as white space
Returns:
position of first non-whitespace character before pos OR ERROR_INDEX (-1) if no such char
Throws:
BadLocationException

_checkCache

protected Object _checkCache(Query key)
Checks the query cache for a stored value. Returns the value if it has been cached, or null otherwise. Calling convention for keys: methodName:arg1:arg2.

Parameters:
key - Name of the method and arguments

_storeInCache

protected void _storeInCache(Query query,
                             Object answer,
                             int offset)
Stores the given result in the helper method cache. Query classes define equality structurally.

Parameters:
query - A canonical description of the query
answer - The answer returned for the query
offset - The offset bounding the right edge of the text on which the query depends; if (0:offset) in the document is unchanged, the query should return the same answer.

_clearCache

protected void _clearCache(int offset)
Clears the memozing cache of queries with offset >= than specified value. Should be called every time the document is modified.


indentLines

public void indentLines(int selStart,
                        int selEnd)
Default indentation - uses OTHER flag and no progress indicator. Assume write lock is already held.

Specified by:
indentLines in interface DJDocument
Parameters:
selStart - the offset of the initial character of the region to indent
selEnd - the offset of the last character of the region to indent

indentLines

public void indentLines(int selStart,
                        int selEnd,
                        Indenter.IndentReason reason,
                        ProgressMonitor pm)
                 throws OperationCanceledException
Parameterized indentation for special-case handling. If selStart == selEnd, then the line containing the currentLocation is indented. The values of selStart and selEnd are ignored!

Specified by:
indentLines in interface DJDocument
Parameters:
selStart - the offset of the initial character of the region to indent
selEnd - the offset of the last character of the region to indent
reason - a flag from Indenter to indicate the reason for the indent (indent logic may vary slightly based on the trigger action)
pm - used to display progress, null if no reporting is desired
Throws:
OperationCanceledException

_indentLine

public boolean _indentLine(Indenter.IndentReason reason)
Indents a line using the Indenter. Public ONLY for testing purposes.


getIntelligentBeginLinePos

public int getIntelligentBeginLinePos(int currPos)
                               throws BadLocationException
Returns the "intelligent" beginning of line. If currPos is to the right of the first non-whitespace character, the position of the first non-whitespace character is returned. If currPos is at or to the left of the first non-whitespace character, the beginning of the line is returned.

Specified by:
getIntelligentBeginLinePos in interface DJDocument
Parameters:
currPos - A position on the current line
Throws:
BadLocationException

_getIndentOfCurrStmt

public int _getIndentOfCurrStmt(int pos)
Returns the number of blanks in the indent prefix for the start of the statement identified by pos. Uses a default set of delimiters. (';', '{', '}') and a default set of whitespace characters (' ', '\t', n', ',')

Specified by:
_getIndentOfCurrStmt in interface DJDocument
Parameters:
pos - Cursor position

_getIndentOfCurrStmt

public int _getIndentOfCurrStmt(int pos,
                                char[] delims)
Returns the number of blanks in the indent prefix of the start of the statement identified by pos. Uses a default set of whitespace characters: {' ', '\t', '\n', ','}

Specified by:
_getIndentOfCurrStmt in interface DJDocument
Parameters:
pos - Cursor position

_getIndentOfCurrStmt

public int _getIndentOfCurrStmt(int pos,
                                char[] delims,
                                char[] whitespace)
Returns the number of blanks in the indent prefix of the start of the statement identified by pos, assuming that the statement is already properly indented

Specified by:
_getIndentOfCurrStmt in interface DJDocument
Parameters:
pos - the position identifying the current statement
delims - delimiter characters denoting end of statement
whitespace - characters to skip when looking for beginning of next statement

findCharOnLine

public int findCharOnLine(int pos,
                          char findChar)
Determines if the given character exists on the line where the given cursor position is. Does not search inside quotes or comments. Does not work if character being searched for is a '/' or a '*'. Only read lock is already held.

Specified by:
findCharOnLine in interface DJDocument
Parameters:
pos - Cursor position
findChar - Character to search for
Returns:
true if this node's rule holds.

_getLineStartPos

public int _getLineStartPos(int pos)
Returns the absolute position of the beginning of the current line. (Just after most recent newline, or 0.) Doesn't ignore comments.

Specified by:
_getLineStartPos in interface DJDocument
Parameters:
pos - Any position on the current line
Returns:
position of the beginning of this line

_getLineEndPos

public int _getLineEndPos(int pos)
Returns the absolute position of the end of the current line. (At the next newline, or the end of the document.)

Specified by:
_getLineEndPos in interface DJDocument
Parameters:
pos - Any position on the current line
Returns:
position of the end of this line

_getLineFirstCharPos

public int _getLineFirstCharPos(int pos)
Returns the absolute position of the first non-blank/tab character on the current line including comment text or the end of the line if no non-blank/tab character is found. TODO: get rid of tab character references in AbstractDJDocument and related files and prevent insertion of tabs

Specified by:
_getLineFirstCharPos in interface DJDocument
Parameters:
pos - position on the line
Returns:
position of first non-blank/tab character on this line, or the end of the line if no non-blank/tab character is found.

getFirstNonWSCharPos

public int getFirstNonWSCharPos(int pos)
                         throws BadLocationException
Finds the position of the first non-whitespace character after pos. NB: Skips comments and all whitespace, including newlines.

Specified by:
getFirstNonWSCharPos in interface DJDocument
Parameters:
pos - Position to start from
Returns:
position of first non-whitespace character after pos, or ERROR_INDEX (-1) if end of document is reached
Throws:
BadLocationException

getFirstNonWSCharPos

public int getFirstNonWSCharPos(int pos,
                                boolean acceptComments)
                         throws BadLocationException
Similar to the single-argument version, but allows including comments.

Specified by:
getFirstNonWSCharPos in interface DJDocument
Parameters:
pos - Position to start from
acceptComments - if true, find non-whitespace chars in comments
Returns:
position of first non-whitespace character after pos, or ERROR_INDEX (-1) if end of document is reached
Throws:
BadLocationException

getFirstNonWSCharPos

public int getFirstNonWSCharPos(int pos,
                                char[] whitespace,
                                boolean acceptComments)
                         throws BadLocationException
Finds the position of the first non-whitespace character after pos. NB: Skips comments and all whitespace, including newlines.

Specified by:
getFirstNonWSCharPos in interface DJDocument
Parameters:
pos - Position to start from
whitespace - array of whitespace chars to ignore
acceptComments - if true, find non-whitespace chars in comments
Returns:
position of first non-whitespace character after pos, or ERROR_INDEX (-1) if end of document is reached
Throws:
BadLocationException

_findPrevNonWSCharPos

public int _findPrevNonWSCharPos(int pos)
                          throws BadLocationException
Throws:
BadLocationException

_isStartOfComment

protected static boolean _isStartOfComment(String text,
                                           int pos)
Helper method for getFirstNonWSCharPos Determines whether the current character is the start of a comment: "/*" or "//"


_inParenPhrase

public boolean _inParenPhrase(int pos)
Returns true if the given position is inside a paren phrase.

Parameters:
pos - the position we're looking at
Returns:
true if pos is immediately inside parentheses

_getLineEnclosingBrace

public BraceInfo _getLineEnclosingBrace()
Cached version of _reduced.getLineEnclosingBrace(). Assumes that read lock and reduced lock are already held.


_getEnclosingBrace

public BraceInfo _getEnclosingBrace()
Cached version of _reduced.getEnclosingBrace(). Assumes that read lock and reduced lock are already held.


_inBlockComment

public boolean _inBlockComment(int pos)
Determines if pos lies within a block comment using the reduced model (ignoring the cache). Assumes that read lock and reduced lock are already held.


notInBlock

protected boolean notInBlock(int pos)
Returns true if the given position is not inside a paren/brace/etc phrase. Assumes that read lock and reduced lock are already held.

Parameters:
pos - the position we're looking at
Returns:
true if pos is immediately inside a paren/brace/etc

setTab

public void setTab(int tab,
                   int pos)
Inserts the number of blanks specified as the whitespace prefix for the line identified by pos. The prefix replaces the prefix is already there. Assumes that the prefix consists of blanks. ASSUMES write lock is already held.g1

Parameters:
tab - The string to be placed between previous newline and first non-whitespace character

setTab

public void setTab(String tab,
                   int pos)
Inserts the string specified by tab at the beginning of the line identified by pos. ASSUMES write lock is already held.

Parameters:
tab - The string to be placed between previous newline and first non-whitespace character

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This happens after the text has actually been inserted. Here we update the reduced model (using an InsertCommand) and store information for how to undo/redo the reduced model changes inside the DefaultDocumentEvent. NOTE: an exclusive read lock on the document is already held when this code runs.

Overrides:
insertUpdate in class DefaultStyledDocument
See Also:
AbstractDJDocument.InsertCommand, AbstractDocument.DefaultDocumentEvent, DefinitionsDocument.CommandUndoableEdit

removeUpdate

protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates document structure as a result of text removal. This happens within the swing remove operation before the text has actually been removed. Updates the reduced model (using a RemoveCommand) and store information for how to undo/redo the reduced model changes inside the DefaultDocumentEvent. NOTE: an exclusive read lock on the document is already held when this code runs.

Overrides:
removeUpdate in class DefaultStyledDocument
See Also:
AbstractDJDocument.RemoveCommand, AbstractDocument.DefaultDocumentEvent

getBytes

public byte[] getBytes()
Returns the byte image (as written to a file) of this document.


clear

public void clear()
Description copied from interface: DJDocument
Clears the entire text of the document. Without this operation, a client must use locking to perform this task safely.

Specified by:
clear in interface DJDocument
Overrides:
clear in class SwingDocument

startCompoundEdit

protected abstract int startCompoundEdit()

endCompoundEdit

protected abstract void endCompoundEdit(int i)

endLastCompoundEdit

protected abstract void endLastCompoundEdit()

addUndoRedo

protected abstract void addUndoRedo(AbstractDocument.DefaultDocumentEvent chng,
                                    Runnable undoCommand,
                                    Runnable doCommand)

getAndResetNumLinesChangedAfter

public int getAndResetNumLinesChangedAfter()
Gets the value of _numLinesChangedAfter field and reset it -1.