1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is inline spellchecker code.
17 * The Initial Developer of the Original Code is Google Inc.
18 * Portions created by the Initial Developer are Copyright (C) 2004-2006
19 * the Initial Developer. All Rights Reserved.
22 * Brett Wilson <brettw@gmail.com> (original author)
23 * Robert O'Callahan <rocallahan@novell.com>
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
39 #include "mozInlineSpellWordUtil.h"
42 #include "nsComponentManagerUtils.h"
43 #include "nsIDOMCSSStyleDeclaration.h"
44 #include "nsIDOMDocumentView.h"
45 #include "nsIDOMElement.h"
46 #include "nsIDOMNSRange.h"
47 #include "nsIDOMRange.h"
48 #include "nsIEditor.h"
49 #include "nsIDOMNode.h"
50 #include "nsIDOMHTMLBRElement.h"
51 #include "nsUnicharUtilCIID.h"
52 #include "nsServiceManagerUtils.h"
54 // IsIgnorableCharacter
56 // These characters are ones that we should ignore in input.
58 inline PRBool
IsIgnorableCharacter(PRUnichar ch
)
60 return (ch
== 0x200D || // ZERO-WIDTH JOINER
61 ch
== 0xAD || // SOFT HYPHEN
62 ch
== 0x1806); // MONGOLIAN TODO SOFT HYPHEN
65 // IsConditionalPunctuation
67 // Some characters (like apostrophes) require characters on each side to be
68 // part of a word, and are otherwise punctuation.
70 inline PRBool
IsConditionalPunctuation(PRUnichar ch
)
73 ch
== 0x2019); // RIGHT SINGLE QUOTATION MARK
76 // mozInlineSpellWordUtil::Init
79 mozInlineSpellWordUtil::Init(nsWeakPtr aWeakEditor
)
83 mCategories
= do_GetService(NS_UNICHARCATEGORY_CONTRACTID
, &rv
);
87 // getting the editor can fail commonly because the editor was detached, so
89 nsCOMPtr
<nsIEditor
> editor
= do_QueryReferent(aWeakEditor
, &rv
);
93 nsCOMPtr
<nsIDOMDocument
> domDoc
;
94 rv
= editor
->GetDocument(getter_AddRefs(domDoc
));
95 NS_ENSURE_SUCCESS(rv
, rv
);
97 mDocument
= do_QueryInterface(domDoc
, &rv
);
98 NS_ENSURE_SUCCESS(rv
, rv
);
100 mDOMDocumentRange
= do_QueryInterface(domDoc
, &rv
);
101 NS_ENSURE_SUCCESS(rv
, rv
);
104 nsCOMPtr
<nsIDOMDocumentView
> docView
= do_QueryInterface(domDoc
, &rv
);
105 NS_ENSURE_SUCCESS(rv
, rv
);
106 nsCOMPtr
<nsIDOMAbstractView
> abstractView
;
107 rv
= docView
->GetDefaultView(getter_AddRefs(abstractView
));
108 NS_ENSURE_SUCCESS(rv
, rv
);
109 mCSSView
= do_QueryInterface(abstractView
, &rv
);
110 NS_ENSURE_SUCCESS(rv
, rv
);
112 // Find the root node for the editor. For contenteditable we'll need something
114 nsCOMPtr
<nsIDOMElement
> rootElt
;
115 rv
= editor
->GetRootElement(getter_AddRefs(rootElt
));
116 NS_ENSURE_SUCCESS(rv
, rv
);
119 NS_ASSERTION(mRootNode
, "GetRootElement returned null *and* claimed to suceed!");
124 IsTextNode(nsIDOMNode
* aNode
)
127 aNode
->GetNodeType(&type
);
128 return type
== nsIDOMNode::TEXT_NODE
;
131 typedef void (* OnLeaveNodeFunPtr
)(nsIDOMNode
* aNode
, void* aClosure
);
133 // Find the next node in the DOM tree in preorder. This isn't fast because
134 // one call to GetNextSibling can be O(N) in the number of siblings...
135 // Calls OnLeaveNodeFunPtr when the traversal leaves a node
137 FindNextNode(nsIDOMNode
* aNode
, nsIDOMNode
* aRoot
,
138 OnLeaveNodeFunPtr aOnLeaveNode
= nsnull
, void* aClosure
= nsnull
)
140 NS_PRECONDITION(aNode
, "Null starting node?");
142 nsCOMPtr
<nsIDOMNode
> next
;
143 aNode
->GetFirstChild(getter_AddRefs(next
));
147 // Don't look at siblings or otherwise outside of aRoot
151 aNode
->GetNextSibling(getter_AddRefs(next
));
158 aOnLeaveNode(aNode
, aClosure
);
161 aNode
->GetParentNode(getter_AddRefs(next
));
162 if (next
== aRoot
|| ! next
)
166 aNode
->GetNextSibling(getter_AddRefs(next
));
172 // aNode is not a text node. Find the first text node starting at aNode/aOffset
173 // in a preorder DOM traversal.
175 FindNextTextNode(nsIDOMNode
* aNode
, PRInt32 aOffset
, nsIDOMNode
* aRoot
)
177 NS_PRECONDITION(aNode
, "Null starting node?");
178 NS_ASSERTION(!IsTextNode(aNode
), "FindNextTextNode should start with a non-text node");
180 nsIDOMNode
* checkNode
;
181 // Need to start at the aOffset'th child
182 nsCOMPtr
<nsIDOMNode
> child
;
183 aNode
->GetFirstChild(getter_AddRefs(child
));
184 while (child
&& aOffset
> 0) {
185 nsCOMPtr
<nsIDOMNode
> next
;
186 child
->GetNextSibling(getter_AddRefs(next
));
193 // aOffset was beyond the end of the child list. Start checking at the next
194 // node after the last child, or aNode if there are no children.
195 aNode
->GetLastChild(getter_AddRefs(child
));
197 checkNode
= FindNextNode(child
, aRoot
);
199 checkNode
= FindNextNode(aNode
, aRoot
);
203 while (checkNode
&& !IsTextNode(checkNode
)) {
204 checkNode
= FindNextNode(checkNode
, aRoot
);
209 // mozInlineSpellWordUtil::SetEnd
211 // We have two ranges "hard" and "soft". The hard boundary is simply
212 // the scope of the root node. The soft boundary is that which is set
213 // by the caller of this class by calling this function. If this function is
214 // not called, the soft boundary is the same as the hard boundary.
216 // When we reach the soft boundary (mSoftEnd), we keep
217 // going until we reach the end of a word. This allows the caller to set the
218 // end of the range to anything, and we will always check whole multiples of
219 // words. When we reach the hard boundary we stop no matter what.
221 // There is no beginning soft boundary. This is because we only go to the
222 // previous node once, when finding the previous word boundary in
223 // SetPosition(). You might think of the soft boundary as being this initial
227 mozInlineSpellWordUtil::SetEnd(nsIDOMNode
* aEndNode
, PRInt32 aEndOffset
)
229 NS_PRECONDITION(aEndNode
, "Null end node?");
231 NS_ASSERTION(mRootNode
, "Not initialized");
235 if (!IsTextNode(aEndNode
)) {
236 // End at the start of the first text node after aEndNode/aEndOffset.
237 aEndNode
= FindNextTextNode(aEndNode
, aEndOffset
, mRootNode
);
240 mSoftEnd
= NodeOffset(aEndNode
, aEndOffset
);
245 mozInlineSpellWordUtil::SetPosition(nsIDOMNode
* aNode
, PRInt32 aOffset
)
249 if (!IsTextNode(aNode
)) {
250 // Start at the start of the first text node after aNode/aOffset.
251 aNode
= FindNextTextNode(aNode
, aOffset
, mRootNode
);
254 mSoftBegin
= NodeOffset(aNode
, aOffset
);
258 PRInt32 textOffset
= MapDOMPositionToSoftTextOffset(mSoftBegin
);
261 mNextWordIndex
= FindRealWordContaining(textOffset
, HINT_END
, PR_TRUE
);
266 mozInlineSpellWordUtil::EnsureWords()
272 mSoftTextValid
= PR_TRUE
;
276 mozInlineSpellWordUtil::MakeRangeForWord(const RealWord
& aWord
, nsIDOMRange
** aRange
)
278 NodeOffset begin
= MapSoftTextOffsetToDOMPosition(aWord
.mSoftTextOffset
, HINT_BEGIN
);
279 NodeOffset end
= MapSoftTextOffsetToDOMPosition(aWord
.EndOffset(), HINT_END
);
280 return MakeRange(begin
, end
, aRange
);
283 // mozInlineSpellWordUtil::GetRangeForWord
286 mozInlineSpellWordUtil::GetRangeForWord(nsIDOMNode
* aWordNode
,
288 nsIDOMRange
** aRange
)
290 // Set our soft end and start
291 NodeOffset pt
= NodeOffset(aWordNode
, aWordOffset
);
294 mSoftBegin
= mSoftEnd
= pt
;
297 PRInt32 offset
= MapDOMPositionToSoftTextOffset(pt
);
299 return MakeRange(pt
, pt
, aRange
);
300 PRInt32 wordIndex
= FindRealWordContaining(offset
, HINT_BEGIN
, PR_FALSE
);
302 return MakeRange(pt
, pt
, aRange
);
303 return MakeRangeForWord(mRealWords
[wordIndex
], aRange
);
306 // This is to fix characters that the spellchecker may not like
308 NormalizeWord(const nsSubstring
& aInput
, PRInt32 aPos
, PRInt32 aLen
, nsAString
& aOutput
)
311 for (PRInt32 i
= 0; i
< aLen
; i
++) {
312 PRUnichar ch
= aInput
.CharAt(i
+ aPos
);
314 // remove ignorable characters from the word
315 if (IsIgnorableCharacter(ch
))
318 // the spellchecker doesn't handle curly apostrophes in all languages
319 if (ch
== 0x2019) { // RIGHT SINGLE QUOTATION MARK
327 // mozInlineSpellWordUtil::GetNextWord
329 // FIXME-optimization: we shouldn't have to generate a range every single
330 // time. It would be better if the inline spellchecker didn't require a
331 // range unless the word was misspelled. This may or may not be possible.
334 mozInlineSpellWordUtil::GetNextWord(nsAString
& aText
, nsIDOMRange
** aRange
,
335 PRBool
* aSkipChecking
)
337 #ifdef DEBUG_SPELLCHECK
338 printf("GetNextWord called; mNextWordIndex=%d\n", mNextWordIndex
);
341 if (mNextWordIndex
< 0 ||
342 mNextWordIndex
>= PRInt32(mRealWords
.Length())) {
345 *aSkipChecking
= PR_TRUE
;
349 const RealWord
& word
= mRealWords
[mNextWordIndex
];
350 nsresult rv
= MakeRangeForWord(word
, aRange
);
351 NS_ENSURE_SUCCESS(rv
, rv
);
353 *aSkipChecking
= !word
.mCheckableWord
;
354 ::NormalizeWord(mSoftText
, word
.mSoftTextOffset
, word
.mLength
, aText
);
356 #ifdef DEBUG_SPELLCHECK
357 printf("GetNextWord returning: %s (skip=%d)\n",
358 NS_ConvertUTF16toUTF8(aText
).get(), *aSkipChecking
);
364 // mozInlineSpellWordUtil::MakeRange
366 // Convenience function for creating a range over the current document.
369 mozInlineSpellWordUtil::MakeRange(NodeOffset aBegin
, NodeOffset aEnd
,
370 nsIDOMRange
** aRange
)
372 if (! mDOMDocumentRange
)
373 return NS_ERROR_NOT_INITIALIZED
;
375 nsresult rv
= mDOMDocumentRange
->CreateRange(aRange
);
376 NS_ENSURE_SUCCESS(rv
, rv
);
378 rv
= (*aRange
)->SetStart(aBegin
.mNode
, aBegin
.mOffset
);
379 NS_ENSURE_SUCCESS(rv
, rv
);
380 rv
= (*aRange
)->SetEnd(aEnd
.mNode
, aEnd
.mOffset
);
381 NS_ENSURE_SUCCESS(rv
, rv
);
386 /*********** DOM text extraction ************/
388 // IsDOMWordSeparator
390 // Determines if the given character should be considered as a DOM Word
391 // separator. Basically, this is whitespace, although it could also have
392 // certain punctuation that we know ALWAYS breaks words. This is important.
393 // For example, we can't have any punctuation that could appear in a URL
394 // or email address in this, because those need to always fit into a single
398 IsDOMWordSeparator(PRUnichar ch
)
401 if (ch
== ' ' || ch
== '\t' || ch
== '\n' || ch
== '\r')
404 // complex spaces - check only if char isn't ASCII (uncommon)
406 (ch
== 0x00A0 || // NO-BREAK SPACE
407 ch
== 0x2002 || // EN SPACE
408 ch
== 0x2003 || // EM SPACE
409 ch
== 0x2009 || // THIN SPACE
410 ch
== 0x200C || // ZERO WIDTH NON-JOINER
411 ch
== 0x3000)) // IDEOGRAPHIC SPACE
414 // otherwise not a space
419 IsBRElement(nsIDOMNode
* aNode
)
422 nsCOMPtr
<nsIDOMHTMLBRElement
> elt
= do_QueryInterface(aNode
, &rv
);
423 return NS_SUCCEEDED(rv
);
427 GetNodeText(nsIDOMNode
* aNode
, nsAutoString
& aText
)
429 nsresult rv
= aNode
->GetNodeValue(aText
);
430 NS_ASSERTION(NS_SUCCEEDED(rv
), "Unable to get node text");
433 // Find the previous node in the DOM tree in preorder. This isn't fast because
434 // one call to GetPrevSibling can be O(N) in the number of siblings...
436 FindPrevNode(nsIDOMNode
* aNode
, nsIDOMNode
* aRoot
)
441 nsCOMPtr
<nsIDOMNode
> prev
;
442 aNode
->GetPreviousSibling(getter_AddRefs(prev
));
445 nsCOMPtr
<nsIDOMNode
> lastChild
;
446 prev
->GetLastChild(getter_AddRefs(lastChild
));
453 // No prev sibling. So we are the first child of our parent, if any. Our
454 // parent is our previous node.
455 aNode
->GetParentNode(getter_AddRefs(prev
));
460 * Check if there's a DOM word separator before aBeforeOffset in this node.
461 * Always returns PR_TRUE if it's a BR element.
462 * aSeparatorOffset is set to the index of the last separator if any is found
463 * (0 for BR elements).
466 ContainsDOMWordSeparator(nsIDOMNode
* aNode
, PRInt32 aBeforeOffset
,
467 PRInt32
* aSeparatorOffset
)
469 if (IsBRElement(aNode
)) {
470 *aSeparatorOffset
= 0;
474 if (!IsTextNode(aNode
))
478 GetNodeText(aNode
, str
);
479 for (PRInt32 i
= PR_MIN(aBeforeOffset
, PRInt32(str
.Length())) - 1; i
>= 0; --i
) {
480 if (IsDOMWordSeparator(str
.CharAt(i
))) {
481 *aSeparatorOffset
= i
;
489 IsBreakElement(nsIDOMViewCSS
* aDocView
, nsIDOMNode
* aNode
)
491 nsCOMPtr
<nsIDOMElement
> element
= do_QueryInterface(aNode
);
495 if (IsBRElement(aNode
))
498 nsCOMPtr
<nsIDOMCSSStyleDeclaration
> style
;
499 aDocView
->GetComputedStyle(element
, EmptyString(), getter_AddRefs(style
));
503 #ifdef DEBUG_SPELLCHECK
504 printf(" searching element %p\n", (void*)aNode
);
507 nsAutoString display
;
508 style
->GetPropertyValue(NS_LITERAL_STRING("display"), display
);
509 #ifdef DEBUG_SPELLCHECK
510 printf(" display=\"%s\"\n", NS_ConvertUTF16toUTF8(display
).get());
512 if (!display
.EqualsLiteral("inline"))
515 nsAutoString position
;
516 style
->GetPropertyValue(NS_LITERAL_STRING("position"), position
);
517 #ifdef DEBUG_SPELLCHECK
518 printf(" position=%s\n", NS_ConvertUTF16toUTF8(position
).get());
520 if (!position
.EqualsLiteral("static"))
523 // XXX What about floats? What else?
527 struct CheckLeavingBreakElementClosure
{
528 nsIDOMViewCSS
* mDocView
;
529 PRPackedBool mLeftBreakElement
;
533 CheckLeavingBreakElement(nsIDOMNode
* aNode
, void* aClosure
)
535 CheckLeavingBreakElementClosure
* cl
=
536 static_cast<CheckLeavingBreakElementClosure
*>(aClosure
);
537 if (!cl
->mLeftBreakElement
&& IsBreakElement(cl
->mDocView
, aNode
)) {
538 cl
->mLeftBreakElement
= PR_TRUE
;
543 mozInlineSpellWordUtil::NormalizeWord(nsSubstring
& aWord
)
546 ::NormalizeWord(aWord
, 0, aWord
.Length(), result
);
551 mozInlineSpellWordUtil::BuildSoftText()
553 // First we have to work backwards from mSoftStart to find a text node
554 // containing a DOM word separator, a non-inline-element
555 // boundary, or the hard start node. That's where we'll start building the
557 nsIDOMNode
* node
= mSoftBegin
.mNode
;
558 PRInt32 firstOffsetInNode
= 0;
559 PRInt32 checkBeforeOffset
= mSoftBegin
.mOffset
;
561 if (ContainsDOMWordSeparator(node
, checkBeforeOffset
, &firstOffsetInNode
))
563 checkBeforeOffset
= PR_INT32_MAX
;
564 if (IsBreakElement(mCSSView
, node
)) {
565 // Since FindPrevNode follows tree *preorder*, we're about to traverse
566 // up out of 'node'. Since node induces breaks (e.g., it's a block),
567 // don't bother trying to look outside it, just stop now.
570 node
= FindPrevNode(node
, mRootNode
);
573 // Now build up the string moving forward through the DOM until we reach
574 // the soft end and *then* see a DOM word separator, a non-inline-element
575 // boundary, or the hard end node.
576 mSoftText
.Truncate();
577 mSoftTextDOMMapping
.Clear();
578 PRBool seenSoftEnd
= PR_FALSE
;
579 // Leave this outside the loop so large heap string allocations can be reused
583 if (node
== mSoftEnd
.mNode
) {
584 seenSoftEnd
= PR_TRUE
;
587 PRBool exit
= PR_FALSE
;
588 if (IsTextNode(node
)) {
589 GetNodeText(node
, str
);
590 PRInt32 lastOffsetInNode
= str
.Length();
593 // check whether we can stop after this
594 for (PRInt32 i
= node
== mSoftEnd
.mNode
? mSoftEnd
.mOffset
: 0;
595 i
< PRInt32(str
.Length()); ++i
) {
596 if (IsDOMWordSeparator(str
.CharAt(i
))) {
598 // stop at the first separator after the soft end point
599 lastOffsetInNode
= i
;
605 if (firstOffsetInNode
< lastOffsetInNode
) {
606 PRInt32 len
= lastOffsetInNode
- firstOffsetInNode
;
607 mSoftTextDOMMapping
.AppendElement(
608 DOMTextMapping(NodeOffset(node
, firstOffsetInNode
), mSoftText
.Length(), len
));
609 mSoftText
.Append(Substring(str
, firstOffsetInNode
, len
));
612 firstOffsetInNode
= 0;
618 CheckLeavingBreakElementClosure closure
= { mCSSView
, PR_FALSE
};
619 node
= FindNextNode(node
, mRootNode
, CheckLeavingBreakElement
, &closure
);
620 if (closure
.mLeftBreakElement
|| (node
&& IsBreakElement(mCSSView
, node
))) {
621 // We left, or are entering, a break element (e.g., block). Maybe we can
626 mSoftText
.Append(' ');
630 #ifdef DEBUG_SPELLCHECK
631 printf("Got DOM string: %s\n", NS_ConvertUTF16toUTF8(mSoftText
).get());
636 mozInlineSpellWordUtil::BuildRealWords()
638 // This is pretty simple. We just have to walk mSoftText, tokenizing it
639 // into "real words".
640 // We do an outer traversal of words delimited by IsDOMWordSeparator, calling
641 // SplitDOMWord on each of those DOM words
642 PRInt32 wordStart
= -1;
644 for (PRInt32 i
= 0; i
< PRInt32(mSoftText
.Length()); ++i
) {
645 if (IsDOMWordSeparator(mSoftText
.CharAt(i
))) {
646 if (wordStart
>= 0) {
647 SplitDOMWord(wordStart
, i
);
656 if (wordStart
>= 0) {
657 SplitDOMWord(wordStart
, mSoftText
.Length());
661 /*********** DOM/realwords<->mSoftText mapping functions ************/
664 mozInlineSpellWordUtil::MapDOMPositionToSoftTextOffset(NodeOffset aNodeOffset
)
666 if (!mSoftTextValid
) {
667 NS_ERROR("Soft text must be valid if we're to map into it");
671 for (PRInt32 i
= 0; i
< PRInt32(mSoftTextDOMMapping
.Length()); ++i
) {
672 const DOMTextMapping
& map
= mSoftTextDOMMapping
[i
];
673 if (map
.mNodeOffset
.mNode
== aNodeOffset
.mNode
) {
674 // Allow offsets at either end of the string, in particular, allow the
675 // offset that's at the end of the contributed string
676 PRInt32 offsetInContributedString
=
677 aNodeOffset
.mOffset
- map
.mNodeOffset
.mOffset
;
678 if (offsetInContributedString
>= 0 &&
679 offsetInContributedString
<= map
.mLength
)
680 return map
.mSoftTextOffset
+ offsetInContributedString
;
687 mozInlineSpellWordUtil::NodeOffset
688 mozInlineSpellWordUtil::MapSoftTextOffsetToDOMPosition(PRInt32 aSoftTextOffset
,
691 NS_ASSERTION(mSoftTextValid
, "Soft text must be valid if we're to map out of it");
693 return NodeOffset(nsnull
, -1);
695 // The invariant is that the range start..end includes the last mapping,
696 // if any, such that mSoftTextOffset <= aSoftTextOffset
698 PRInt32 end
= mSoftTextDOMMapping
.Length();
699 while (end
- start
>= 2) {
700 PRInt32 mid
= (start
+ end
)/2;
701 const DOMTextMapping
& map
= mSoftTextDOMMapping
[mid
];
702 if (map
.mSoftTextOffset
> aSoftTextOffset
) {
710 return NodeOffset(nsnull
, -1);
712 // 'start' is now the last mapping, if any, such that
713 // mSoftTextOffset <= aSoftTextOffset.
714 // If we're doing HINT_END, then we may want to return the end of the
715 // the previous mapping instead of the start of this mapping
716 if (aHint
== HINT_END
&& start
> 0) {
717 const DOMTextMapping
& map
= mSoftTextDOMMapping
[start
- 1];
718 if (map
.mSoftTextOffset
+ map
.mLength
== aSoftTextOffset
)
719 return NodeOffset(map
.mNodeOffset
.mNode
, map
.mNodeOffset
.mOffset
+ map
.mLength
);
722 // We allow ourselves to return the end of this mapping even if we're
723 // doing HINT_START. This will only happen if there is no mapping which this
724 // point is the start of. I'm not 100% sure this is OK...
725 const DOMTextMapping
& map
= mSoftTextDOMMapping
[start
];
726 PRInt32 offset
= aSoftTextOffset
- map
.mSoftTextOffset
;
727 if (offset
>= 0 && offset
<= map
.mLength
)
728 return NodeOffset(map
.mNodeOffset
.mNode
, map
.mNodeOffset
.mOffset
+ offset
);
730 return NodeOffset(nsnull
, -1);
734 mozInlineSpellWordUtil::FindRealWordContaining(PRInt32 aSoftTextOffset
,
735 DOMMapHint aHint
, PRBool aSearchForward
)
737 NS_ASSERTION(mSoftTextValid
, "Soft text must be valid if we're to map out of it");
741 // The invariant is that the range start..end includes the last word,
742 // if any, such that mSoftTextOffset <= aSoftTextOffset
744 PRInt32 end
= mRealWords
.Length();
745 while (end
- start
>= 2) {
746 PRInt32 mid
= (start
+ end
)/2;
747 const RealWord
& word
= mRealWords
[mid
];
748 if (word
.mSoftTextOffset
> aSoftTextOffset
) {
758 // 'start' is now the last word, if any, such that
759 // mSoftTextOffset <= aSoftTextOffset.
760 // If we're doing HINT_END, then we may want to return the end of the
761 // the previous word instead of the start of this word
762 if (aHint
== HINT_END
&& start
> 0) {
763 const RealWord
& word
= mRealWords
[start
- 1];
764 if (word
.mSoftTextOffset
+ word
.mLength
== aSoftTextOffset
)
768 // We allow ourselves to return the end of this word even if we're
769 // doing HINT_START. This will only happen if there is no word which this
770 // point is the start of. I'm not 100% sure this is OK...
771 const RealWord
& word
= mRealWords
[start
];
772 PRInt32 offset
= aSoftTextOffset
- word
.mSoftTextOffset
;
773 if (offset
>= 0 && offset
<= word
.mLength
)
776 if (aSearchForward
) {
777 if (mRealWords
[0].mSoftTextOffset
> aSoftTextOffset
) {
778 // All words have mSoftTextOffset > aSoftTextOffset
781 // 'start' is the last word such that mSoftTextOffset <= aSoftTextOffset.
782 // Word start+1, if it exists, will be the first with
783 // mSoftTextOffset > aSoftTextOffset.
784 if (start
+ 1 < PRInt32(mRealWords
.Length()))
791 /*********** Word Splitting ************/
793 // classifies a given character in the DOM word
796 CHAR_CLASS_SEPARATOR
,
797 CHAR_CLASS_END_OF_INPUT
};
799 // Encapsulates DOM-word to real-word splitting
800 struct WordSplitState
802 mozInlineSpellWordUtil
* mWordUtil
;
803 const nsDependentSubstring mDOMWordText
;
804 PRInt32 mDOMWordOffset
;
805 CharClass mCurCharClass
;
807 WordSplitState(mozInlineSpellWordUtil
* aWordUtil
,
808 const nsString
& aString
, PRInt32 aStart
, PRInt32 aLen
)
809 : mWordUtil(aWordUtil
), mDOMWordText(aString
, aStart
, aLen
),
810 mDOMWordOffset(0), mCurCharClass(CHAR_CLASS_END_OF_INPUT
) {}
812 CharClass
ClassifyCharacter(PRInt32 aIndex
, PRBool aRecurse
) const;
814 void AdvanceThroughSeparators();
815 void AdvanceThroughWord();
817 // Finds special words like email addresses and URLs that may start at the
818 // current position, and returns their length, or 0 if not found. This allows
819 // arbitrary word breaking rules to be used for these special entities, as
820 // long as they can not contain whitespace.
821 PRInt32
FindSpecialWord();
823 // Similar to FindSpecialWord except that this takes a split word as
824 // input. This checks for things that do not require special word-breaking
826 PRBool
ShouldSkipWord(PRInt32 aStart
, PRInt32 aLength
);
829 // WordSplitState::ClassifyCharacter
832 WordSplitState::ClassifyCharacter(PRInt32 aIndex
, PRBool aRecurse
) const
834 NS_ASSERTION(aIndex
>= 0 && aIndex
<= PRInt32(mDOMWordText
.Length()),
835 "Index out of range");
836 if (aIndex
== PRInt32(mDOMWordText
.Length()))
837 return CHAR_CLASS_SEPARATOR
;
839 // this will classify the character, we want to treat "ignorable" characters
840 // such as soft hyphens as word characters.
841 nsIUGenCategory::nsUGenCategory
842 charCategory
= mWordUtil
->GetCategories()->Get(PRUint32(mDOMWordText
[aIndex
]));
843 if (charCategory
== nsIUGenCategory::kLetter
||
844 IsIgnorableCharacter(mDOMWordText
[aIndex
]))
845 return CHAR_CLASS_WORD
;
847 // If conditional punctuation is surrounded immediately on both sides by word
848 // characters it also counts as a word character.
849 if (IsConditionalPunctuation(mDOMWordText
[aIndex
])) {
851 // not allowed to look around, this punctuation counts like a separator
852 return CHAR_CLASS_SEPARATOR
;
855 // check the left-hand character
857 return CHAR_CLASS_SEPARATOR
;
858 if (ClassifyCharacter(aIndex
- 1, false) != CHAR_CLASS_WORD
)
859 return CHAR_CLASS_SEPARATOR
;
861 // now we know left char is a word-char, check the right-hand character
862 if (aIndex
== PRInt32(mDOMWordText
.Length()) - 1)
863 return CHAR_CLASS_SEPARATOR
;
864 if (ClassifyCharacter(aIndex
+ 1, false) != CHAR_CLASS_WORD
)
865 return CHAR_CLASS_SEPARATOR
;
867 // char on either side is a word, this counts as a word
868 return CHAR_CLASS_WORD
;
871 // all other punctuation
872 if (charCategory
== nsIUGenCategory::kSeparator
||
873 charCategory
== nsIUGenCategory::kOther
||
874 charCategory
== nsIUGenCategory::kPunctuation
||
875 charCategory
== nsIUGenCategory::kSymbol
)
876 return CHAR_CLASS_SEPARATOR
;
878 // any other character counts as a word
879 return CHAR_CLASS_WORD
;
883 // WordSplitState::Advance
886 WordSplitState::Advance()
888 NS_ASSERTION(mDOMWordOffset
>= 0, "Negative word index");
889 NS_ASSERTION(mDOMWordOffset
< (PRInt32
)mDOMWordText
.Length(),
890 "Length beyond end");
893 if (mDOMWordOffset
>= (PRInt32
)mDOMWordText
.Length())
894 mCurCharClass
= CHAR_CLASS_END_OF_INPUT
;
896 mCurCharClass
= ClassifyCharacter(mDOMWordOffset
, PR_TRUE
);
900 // WordSplitState::AdvanceThroughSeparators
903 WordSplitState::AdvanceThroughSeparators()
905 while (mCurCharClass
== CHAR_CLASS_SEPARATOR
)
909 // WordSplitState::AdvanceThroughWord
912 WordSplitState::AdvanceThroughWord()
914 while (mCurCharClass
== CHAR_CLASS_WORD
)
919 // WordSplitState::FindSpecialWord
922 WordSplitState::FindSpecialWord()
926 // Search for email addresses. We simply define these as any sequence of
927 // characters with an '@' character in the middle. The DOM word is already
928 // split on whitepace, so we know that everything to the end is the address
930 // Also look for periods, this tells us if we want to run the URL finder.
931 PRBool foundDot
= PR_FALSE
;
932 PRInt32 firstColon
= -1;
933 for (i
= mDOMWordOffset
;
934 i
< PRInt32(mDOMWordText
.Length()); i
++) {
935 if (mDOMWordText
[i
] == '@') {
936 // only accept this if there are unambiguous word characters (don't bother
937 // recursing to disambiguate apostrophes) on each side. This prevents
938 // classifying, e.g. "@home" as an email address
940 // Use this condition to only accept words with '@' in the middle of
941 // them. It works, but the inlinespellcker doesn't like this. The problem
942 // is that you type "fhsgfh@" that's a misspelled word followed by a
943 // symbol, but when you type another letter "fhsgfh@g" that first word
944 // need to be unmarked misspelled. It doesn't do this. it only checks the
945 // current position for potentially removing a spelling range.
946 if (i
> 0 && ClassifyCharacter(i
- 1, PR_FALSE
) == CHAR_CLASS_WORD
&&
947 i
< (PRInt32
)mDOMWordText
.Length() - 1 &&
948 ClassifyCharacter(i
+ 1, PR_FALSE
) == CHAR_CLASS_WORD
)
950 return mDOMWordText
.Length() - mDOMWordOffset
;
951 } else if (mDOMWordText
[i
] == '.' && ! foundDot
&&
952 i
> 0 && i
< (PRInt32
)mDOMWordText
.Length() - 1) {
953 // we found a period not at the end, we should check harder for URLs
955 } else if (mDOMWordText
[i
] == ':' && firstColon
< 0) {
960 // If the first colon is followed by a slash, consider it a URL
961 // This will catch things like asdf://foo.com
962 if (firstColon
>= 0 && firstColon
< (PRInt32
)mDOMWordText
.Length() - 1 &&
963 mDOMWordText
[firstColon
+ 1] == '/') {
964 return mDOMWordText
.Length() - mDOMWordOffset
;
967 // Check the text before the first colon against some known protocols. It
968 // is impossible to check against all protocols, especially since you can
969 // plug in new protocols. We also don't want to waste time here checking
970 // against a lot of obscure protocols.
971 if (firstColon
> mDOMWordOffset
) {
972 nsString
protocol(Substring(mDOMWordText
, mDOMWordOffset
,
973 firstColon
- mDOMWordOffset
));
974 if (protocol
.EqualsIgnoreCase("http") ||
975 protocol
.EqualsIgnoreCase("https") ||
976 protocol
.EqualsIgnoreCase("news") ||
977 protocol
.EqualsIgnoreCase("ftp") ||
978 protocol
.EqualsIgnoreCase("file") ||
979 protocol
.EqualsIgnoreCase("javascript") ||
980 protocol
.EqualsIgnoreCase("ftp")) {
981 return mDOMWordText
.Length() - mDOMWordOffset
;
985 // not anything special
989 // WordSplitState::ShouldSkipWord
992 WordSplitState::ShouldSkipWord(PRInt32 aStart
, PRInt32 aLength
)
994 PRInt32 last
= aStart
+ aLength
;
996 // check to see if the word contains a digit
997 for (PRInt32 i
= aStart
; i
< last
; i
++) {
998 PRUnichar ch
= mDOMWordText
[i
];
999 // XXX Shouldn't this be something a lot more complex, Unicode-based?
1000 if (ch
>= '0' && ch
<= '9')
1008 // mozInlineSpellWordUtil::SplitDOMWord
1011 mozInlineSpellWordUtil::SplitDOMWord(PRInt32 aStart
, PRInt32 aEnd
)
1013 WordSplitState
state(this, mSoftText
, aStart
, aEnd
- aStart
);
1014 state
.mCurCharClass
= state
.ClassifyCharacter(0, PR_TRUE
);
1016 while (state
.mCurCharClass
!= CHAR_CLASS_END_OF_INPUT
) {
1017 state
.AdvanceThroughSeparators();
1018 if (state
.mCurCharClass
== CHAR_CLASS_END_OF_INPUT
)
1021 PRInt32 specialWordLength
= state
.FindSpecialWord();
1022 if (specialWordLength
> 0) {
1023 mRealWords
.AppendElement(
1024 RealWord(aStart
+ state
.mDOMWordOffset
, specialWordLength
, PR_FALSE
));
1026 // skip the special word
1027 state
.mDOMWordOffset
+= specialWordLength
;
1028 if (state
.mDOMWordOffset
+ aStart
>= aEnd
)
1029 state
.mCurCharClass
= CHAR_CLASS_END_OF_INPUT
;
1031 state
.mCurCharClass
= state
.ClassifyCharacter(state
.mDOMWordOffset
, PR_TRUE
);
1035 // save the beginning of the word
1036 PRInt32 wordOffset
= state
.mDOMWordOffset
;
1038 // find the end of the word
1039 state
.AdvanceThroughWord();
1040 PRInt32 wordLen
= state
.mDOMWordOffset
- wordOffset
;
1041 mRealWords
.AppendElement(
1042 RealWord(aStart
+ wordOffset
, wordLen
,
1043 !state
.ShouldSkipWord(wordOffset
, wordLen
)));