public string getWordsBeforeLastSentence()
{
string lastSentenceString = "";
Word.Range range = Globals.ThisAddIn.Application.Selection.Range;
range.Start = range.End;
string temp = "";
bool isWordBeforeLastSentence = false;
bool isSpecialKey = false;
bool isNewLine = false;
bool isSpaceForLastCharacter = false;
bool isFullStop = false;
String[] exceptionalWords = { "mr.", "ms.", "mrs.", "mdm.", "prof.", "dr."};
do
{
// Move the start range index by one letter (left)
// This is to check the word before the current cursor
range.MoveStart(Word.WdUnits.wdCharacter, -1);
temp = range.Text;
if (temp != null)
{
// Check if the word is before last sentence or at the beginning of the document (null)
isSpecialKey = (temp.Trim().Equals("!")
|| temp.Trim().Equals("?")
|| temp.Trim().Equals("."));
isNewLine = temp.Equals("\r");
isFullStop = temp.Trim().Equals(".");
isWordBeforeLastSentence = (!isNewLine && (!isSpecialKey || (isSpecialKey && !isSpaceForLastCharacter)));
if (isFullStop)
{
range.MoveStart(Word.WdUnits.wdWord, -1);
temp = range.Text;
for (int i = 0; i<exceptionalWords.Count(); i++)
{
if(temp.ToLower().Equals(exceptionalWords[i].ToLower())){
isWordBeforeLastSentence = true;
break;
}
}
range.End = range.Start;
range.MoveEnd(Word.WdUnits.wdCharacter, 1);
}
}
else
{
isWordBeforeLastSentence = false;
}
if (isWordBeforeLastSentence)
lastSentenceString = temp + lastSentenceString;
// Move the end range index by one letter (left)
range.MoveEnd(Word.WdUnits.wdCharacter, -1);
if (temp != null && temp.Equals(" "))
{
isSpaceForLastCharacter = true;
}
else
{
isSpaceForLastCharacter = false;
}
} while (isWordBeforeLastSentence);
return lastSentenceString;
}