b7fa4936f655ed9d64589889f5fde66aadc21fad
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / corext / template / DocumentTemplateContext.java
1 /*
2  * (c) Copyright IBM Corp. 2000, 2001.
3  * All Rights Reserved.
4  */
5 package net.sourceforge.phpdt.internal.corext.template;
6
7 import net.sourceforge.phpdt.internal.corext.Assert;
8
9 import org.eclipse.jface.text.BadLocationException;
10 import org.eclipse.jface.text.IDocument;
11
12
13 /**
14  * A typical text based document template context.
15  */
16 public abstract class DocumentTemplateContext extends TemplateContext {
17
18   /** The text of the document. */
19   private final IDocument fDocument;
20   /** The completion offset. */
21   private final int fCompletionOffset;
22   /** The completion length. */
23   private final int fCompletionLength;
24
25   /**
26    * Creates a document template context.
27    */
28   protected DocumentTemplateContext(ContextType type, IDocument document,
29     int completionOffset, int completionLength)
30   {
31     super(type);
32                 
33     Assert.isNotNull(document);
34     Assert.isTrue(completionOffset >= 0 && completionOffset <= document.getLength());
35     Assert.isTrue(completionLength >= 0);
36                 
37     fDocument= document;
38     fCompletionOffset= completionOffset;
39     fCompletionLength= completionLength;
40   }
41         
42   public IDocument getDocument() {
43     return fDocument;   
44   }
45         
46   /**
47    * Returns the completion offset within the string of the context.
48    */
49   public int getCompletionOffset() {
50     return fCompletionOffset;   
51   }
52         
53   /**
54    * Returns the completion length within the string of the context.
55    */
56   public int getCompletionLength() {
57     return fCompletionLength;
58   }
59         
60   /**
61    * Returns the keyword which triggered template insertion.
62    */
63   public String getKey() {
64     int offset= getStart();
65     int length= getEnd() - offset;
66     try {
67       return fDocument.get(offset, length);
68     } catch (BadLocationException e) {
69       return ""; //$NON-NLS-1$  
70     }
71   }
72
73   /**
74    * Returns the beginning offset of the keyword.
75    */
76   public int getStart() {
77     return fCompletionOffset;           
78   }
79         
80   /**
81    * Returns the end offset of the keyword.
82    */
83   public int getEnd() {
84     return fCompletionOffset + fCompletionLength;
85   }
86                 
87 }
88