richedit: Improve efficiency of ME_IsCandidateAnURL.
[wine] / dlls / riched20 / caret.c
1 /*
2  * RichEdit - Caret and selection functions.
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Phil Krylov
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22
23 #include "editor.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
26
27 static BOOL
28 ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs);
29
30 int ME_GetSelectionOfs(ME_TextEditor *editor, int *from, int *to)
31 {
32   *from = ME_GetCursorOfs(&editor->pCursors[0]);
33   *to =   ME_GetCursorOfs(&editor->pCursors[1]);
34
35   if (*from > *to)
36   {
37     int tmp = *from;
38     *from = *to;
39     *to = tmp;
40     return 1;
41   }
42   return 0;
43 }
44
45 int ME_GetSelection(ME_TextEditor *editor, ME_Cursor **from, ME_Cursor **to)
46 {
47   if (ME_GetCursorOfs(&editor->pCursors[0]) < ME_GetCursorOfs(&editor->pCursors[1]))
48   {
49     *from = &editor->pCursors[0];
50     *to = &editor->pCursors[1];
51     return 0;
52   } else {
53     *from = &editor->pCursors[1];
54     *to = &editor->pCursors[0];
55     return 1;
56   }
57 }
58
59 int ME_GetTextLength(ME_TextEditor *editor)
60 {
61   ME_DisplayItem *pLast = editor->pBuffer->pLast;
62   return ME_CharOfsFromRunOfs(editor, pLast->member.para.prev_para,
63                               ME_FindItemBack(pLast, diRun), 0);
64 }
65
66
67 int ME_GetTextLengthEx(ME_TextEditor *editor, const GETTEXTLENGTHEX *how)
68 {
69   int length;
70
71   if (how->flags & GTL_PRECISE && how->flags & GTL_CLOSE)
72     return E_INVALIDARG;
73   if (how->flags & GTL_NUMCHARS && how->flags & GTL_NUMBYTES)
74     return E_INVALIDARG;
75   
76   length = ME_GetTextLength(editor);
77
78   if ((editor->styleFlags & ES_MULTILINE)
79         && (how->flags & GTL_USECRLF)
80         && !editor->bEmulateVersion10) /* Ignore GTL_USECRLF flag in 1.0 emulation */
81     length += editor->nParagraphs - 1;
82   
83   if (how->flags & GTL_NUMBYTES)
84   {
85     CPINFO cpinfo;
86     
87     if (how->codepage == 1200)
88       return length * 2;
89     if (how->flags & GTL_PRECISE)
90       FIXME("GTL_PRECISE flag unsupported. Using GTL_CLOSE\n");
91     if (GetCPInfo(how->codepage, &cpinfo))
92       return length * cpinfo.MaxCharSize;
93     ERR("Invalid codepage %u\n", how->codepage);
94     return E_INVALIDARG;
95   }
96   return length; 
97 }
98
99
100 int ME_SetSelection(ME_TextEditor *editor, int from, int to)
101 {
102   int selectionEnd = 0;
103   const int len = ME_GetTextLength(editor);
104
105   /* all negative values are effectively the same */
106   if (from < 0)
107     from = -1;
108   if (to < 0)
109     to = -1;
110
111   /* select all */
112   if (from == 0 && to == -1)
113   {
114     editor->pCursors[1].pPara = editor->pBuffer->pFirst->member.para.next_para;
115     editor->pCursors[1].pRun = ME_FindItemFwd(editor->pCursors[1].pPara, diRun);
116     editor->pCursors[1].nOffset = 0;
117     editor->pCursors[0].pPara = editor->pBuffer->pLast->member.para.prev_para;
118     editor->pCursors[0].pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
119     editor->pCursors[0].nOffset = 0;
120     ME_InvalidateSelection(editor);
121     ME_ClearTempStyle(editor);
122     return len + 1;
123   }
124
125   /* if both values are equal and also out of bound, that means to */
126   /* put the selection at the end of the text */
127   if ((from == to) && (to < 0 || to > len))
128   {
129     selectionEnd = 1;
130   }
131   else
132   {
133     /* if from is negative and to is positive then selection is */
134     /* deselected and caret moved to end of the current selection */
135     if (from < 0)
136     {
137       int start, end;
138       ME_GetSelectionOfs(editor, &start, &end);
139       editor->pCursors[1] = editor->pCursors[0];
140       ME_Repaint(editor);
141       ME_ClearTempStyle(editor);
142       return end;
143     }
144
145     /* adjust to if it's a negative value */
146     if (to < 0)
147       to = len + 1;
148
149     /* flip from and to if they are reversed */
150     if (from>to)
151     {
152       int tmp = from;
153       from = to;
154       to = tmp;
155     }
156
157     /* after fiddling with the values, we find from > len && to > len */
158     if (from > len)
159       selectionEnd = 1;
160     /* special case with to too big */
161     else if (to > len)
162       to = len + 1;
163   }
164
165   if (selectionEnd)
166   {
167     editor->pCursors[0].pPara = editor->pBuffer->pLast->member.para.prev_para;
168     editor->pCursors[0].pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
169     editor->pCursors[0].nOffset = 0;
170     editor->pCursors[1] = editor->pCursors[0];
171     ME_InvalidateSelection(editor);
172     ME_ClearTempStyle(editor);
173     return len;
174   }
175
176   ME_CursorFromCharOfs(editor, from, &editor->pCursors[1]);
177   ME_CursorFromCharOfs(editor, to, &editor->pCursors[0]);
178   /* Selection is not allowed in the middle of an end paragraph run. */
179   if (editor->pCursors[1].pRun->member.run.nFlags & MERF_ENDPARA)
180     editor->pCursors[1].nOffset = 0;
181   if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA)
182     editor->pCursors[0].nOffset = 0;
183   return to;
184 }
185
186
187 static void
188 ME_GetCursorCoordinates(ME_TextEditor *editor, ME_Cursor *pCursor,
189                         int *x, int *y, int *height)
190 {
191   ME_DisplayItem *row;
192   ME_DisplayItem *run = pCursor->pRun;
193   ME_DisplayItem *para = pCursor->pPara;
194   ME_DisplayItem *pSizeRun = run;
195   ME_Context c;
196   SIZE sz = {0, 0};
197
198   assert(height && x && y);
199   assert(~para->member.para.nFlags & MEPF_REWRAP);
200   assert(run && run->type == diRun);
201   assert(para && para->type == diParagraph);
202
203   row = ME_FindItemBack(run, diStartRowOrParagraph);
204   assert(row && row->type == diStartRow);
205
206   ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
207
208   if (!pCursor->nOffset)
209   {
210     ME_DisplayItem *prev = ME_FindItemBack(run, diRunOrParagraph);
211     assert(prev);
212     if (prev->type == diRun)
213       pSizeRun = prev;
214   }
215   if (editor->bCaretAtEnd && !pCursor->nOffset &&
216       run == ME_FindItemFwd(row, diRun))
217   {
218     ME_DisplayItem *tmp = ME_FindItemBack(row, diRunOrParagraph);
219     assert(tmp);
220     if (tmp->type == diRun)
221     {
222       row = ME_FindItemBack(tmp, diStartRow);
223       pSizeRun = run = tmp;
224       assert(run);
225       assert(run->type == diRun);
226       sz = ME_GetRunSize(&c, &para->member.para,
227                          &run->member.run, run->member.run.strText->nLen,
228                          row->member.row.nLMargin);
229     }
230   }
231   if (pCursor->nOffset) {
232     sz = ME_GetRunSize(&c, &para->member.para, &run->member.run,
233                        pCursor->nOffset, row->member.row.nLMargin);
234   }
235
236   *height = pSizeRun->member.run.nAscent + pSizeRun->member.run.nDescent;
237   *x = c.rcView.left + run->member.run.pt.x + sz.cx - editor->horz_si.nPos;
238   *y = c.rcView.top + para->member.para.pt.y + row->member.row.nBaseline
239        + run->member.run.pt.y - pSizeRun->member.run.nAscent
240        - editor->vert_si.nPos;
241   ME_DestroyContext(&c);
242   return;
243 }
244
245
246 void
247 ME_MoveCaret(ME_TextEditor *editor)
248 {
249   int x, y, height;
250
251   ME_GetCursorCoordinates(editor, &editor->pCursors[0], &x, &y, &height);
252   if(editor->bHaveFocus && !ME_IsSelection(editor))
253   {
254     x = min(x, editor->rcFormat.right-1);
255     ITextHost_TxCreateCaret(editor->texthost, NULL, 0, height);
256     ITextHost_TxSetCaretPos(editor->texthost, x, y);
257   }
258 }
259
260
261 void ME_ShowCaret(ME_TextEditor *ed)
262 {
263   ME_MoveCaret(ed);
264   if(ed->bHaveFocus && !ME_IsSelection(ed))
265     ITextHost_TxShowCaret(ed->texthost, TRUE);
266 }
267
268 void ME_HideCaret(ME_TextEditor *ed)
269 {
270   if(!ed->bHaveFocus || ME_IsSelection(ed))
271   {
272     ITextHost_TxShowCaret(ed->texthost, FALSE);
273     DestroyCaret();
274   }
275 }
276
277 BOOL ME_InternalDeleteText(ME_TextEditor *editor, int nOfs, int nChars,
278                            BOOL bForce)
279 {
280   ME_Cursor c;
281   int shift = 0;
282   int totalChars = nChars;
283   ME_DisplayItem *start_para;
284
285   /* Prevent deletion past last end of paragraph run. */
286   nChars = min(nChars, ME_GetTextLength(editor) - nOfs);
287
288   ME_CursorFromCharOfs(editor, nOfs, &c);
289   start_para = c.pPara;
290
291   if (!bForce)
292   {
293     ME_ProtectPartialTableDeletion(editor, nOfs, &nChars);
294     if (nChars == 0)
295       return FALSE;
296   }
297
298   while(nChars > 0)
299   {
300     ME_Run *run;
301     ME_CursorFromCharOfs(editor, nOfs+nChars, &c);
302     if (!c.nOffset &&
303         nOfs+nChars == (c.pRun->member.run.nCharOfs
304                         + c.pPara->member.para.nCharOfs))
305     {
306       /* We aren't deleting anything in this run, so we will go back to the
307        * last run we are deleting text in. */
308       c.pRun = ME_FindItemBack(c.pRun, diRun);
309       c.pPara = ME_GetParagraph(c.pRun);
310       c.nOffset = c.pRun->member.run.strText->nLen;
311     }
312     run = &c.pRun->member.run;
313     if (run->nFlags & MERF_ENDPARA) {
314       int eollen = c.pRun->member.run.strText->nLen;
315       BOOL keepFirstParaFormat;
316
317       if (!ME_FindItemFwd(c.pRun, diParagraph))
318       {
319         return TRUE;
320       }
321       keepFirstParaFormat = (totalChars == nChars && nChars <= eollen &&
322                              run->nCharOfs);
323       if (!editor->bEmulateVersion10) /* v4.1 */
324       {
325         ME_DisplayItem *next_para = ME_FindItemFwd(c.pRun, diParagraphOrEnd);
326         ME_DisplayItem *this_para = next_para->member.para.prev_para;
327
328         /* The end of paragraph before a table row is only deleted if there
329          * is nothing else on the line before it. */
330         if (this_para == start_para &&
331             next_para->member.para.nFlags & MEPF_ROWSTART)
332         {
333           /* If the paragraph will be empty, then it should be deleted, however
334            * it still might have text right now which would inherit the
335            * MEPF_STARTROW property if we joined it right now.
336            * Instead we will delete it after the preceding text is deleted. */
337           if (nOfs > this_para->member.para.nCharOfs) {
338             /* Skip this end of line. */
339             nChars -= (eollen < nChars) ? eollen : nChars;
340             continue;
341           }
342           keepFirstParaFormat = TRUE;
343         }
344       }
345       ME_JoinParagraphs(editor, c.pPara, keepFirstParaFormat);
346       /* ME_SkipAndPropagateCharOffset(p->pRun, shift); */
347       ME_CheckCharOffsets(editor);
348       nChars -= (eollen < nChars) ? eollen : nChars;
349       continue;
350     }
351     else
352     {
353       ME_Cursor cursor;
354       int nCharsToDelete = min(nChars, c.nOffset);
355       int i;
356
357       c.nOffset -= nCharsToDelete;
358
359       ME_FindItemBack(c.pRun, diParagraph)->member.para.nFlags |= MEPF_REWRAP;
360
361       cursor = c;
362       /* nChars is the number of characters that should be deleted from the
363          PRECEDING runs (these BEFORE cursor.pRun)
364          nCharsToDelete is a number of chars to delete from THIS run */
365       nChars -= nCharsToDelete;
366       shift -= nCharsToDelete;
367       TRACE("Deleting %d (remaning %d) chars at %d in '%s' (%d)\n",
368         nCharsToDelete, nChars, c.nOffset,
369         debugstr_w(run->strText->szData), run->strText->nLen);
370
371       if (!c.nOffset && run->strText->nLen == nCharsToDelete)
372       {
373         /* undo = reinsert whole run */
374         /* nOfs is a character offset (from the start of the document
375            to the current (deleted) run */
376         ME_UndoItem *pUndo = ME_AddUndoItem(editor, diUndoInsertRun, c.pRun);
377         if (pUndo)
378           pUndo->di.member.run.nCharOfs = nOfs+nChars;
379       }
380       else
381       {
382         /* undo = reinsert partial run */
383         ME_UndoItem *pUndo = ME_AddUndoItem(editor, diUndoInsertRun, c.pRun);
384         if (pUndo) {
385           ME_DestroyString(pUndo->di.member.run.strText);
386           pUndo->di.member.run.nCharOfs = nOfs+nChars;
387           pUndo->di.member.run.strText = ME_MakeStringN(run->strText->szData+c.nOffset, nCharsToDelete);
388         }
389       }
390       TRACE("Post deletion string: %s (%d)\n", debugstr_w(run->strText->szData), run->strText->nLen);
391       TRACE("Shift value: %d\n", shift);
392       ME_StrDeleteV(run->strText, c.nOffset, nCharsToDelete);
393
394       /* update cursors (including c) */
395       for (i=-1; i<editor->nCursors; i++) {
396         ME_Cursor *pThisCur = editor->pCursors + i;
397         if (i == -1) pThisCur = &c;
398         if (pThisCur->pRun == cursor.pRun) {
399           if (pThisCur->nOffset > cursor.nOffset) {
400             if (pThisCur->nOffset-cursor.nOffset < nCharsToDelete)
401               pThisCur->nOffset = cursor.nOffset;
402             else
403               pThisCur->nOffset -= nCharsToDelete;
404             assert(pThisCur->nOffset >= 0);
405             assert(pThisCur->nOffset <= run->strText->nLen);
406           }
407           if (pThisCur->nOffset == run->strText->nLen)
408           {
409             pThisCur->pRun = ME_FindItemFwd(pThisCur->pRun, diRunOrParagraphOrEnd);
410             assert(pThisCur->pRun->type == diRun);
411             pThisCur->nOffset = 0;
412           }
413         }
414       }
415
416       /* c = updated data now */
417
418       if (c.pRun == cursor.pRun)
419         ME_SkipAndPropagateCharOffset(c.pRun, shift);
420       else
421         ME_PropagateCharOffset(c.pRun, shift);
422
423       if (!cursor.pRun->member.run.strText->nLen)
424       {
425         TRACE("Removing useless run\n");
426         ME_Remove(cursor.pRun);
427         ME_DestroyDisplayItem(cursor.pRun);
428       }
429
430       shift = 0;
431       /*
432       ME_CheckCharOffsets(editor);
433       */
434       continue;
435     }
436   }
437   return TRUE;
438 }
439
440 BOOL ME_DeleteTextAtCursor(ME_TextEditor *editor, int nCursor, int nChars)
441 {  
442   assert(nCursor>=0 && nCursor<editor->nCursors);
443   /* text operations set modified state */
444   editor->nModifyStep = 1;
445   return ME_InternalDeleteText(editor, ME_GetCursorOfs(&editor->pCursors[nCursor]),
446                                nChars, FALSE);
447 }
448
449 static ME_DisplayItem *
450 ME_InternalInsertTextFromCursor(ME_TextEditor *editor, int nCursor,
451                                 const WCHAR *str, int len, ME_Style *style,
452                                 int flags)
453 {
454   ME_Cursor *p = &editor->pCursors[nCursor];
455
456   editor->bCaretAtEnd = FALSE;
457   
458   assert(p->pRun->type == diRun);
459   
460   return ME_InsertRunAtCursor(editor, p, style, str, len, flags);
461 }
462
463
464 void ME_InsertOLEFromCursor(ME_TextEditor *editor, const REOBJECT* reo, int nCursor)
465 {
466   ME_Style              *pStyle = ME_GetInsertStyle(editor, nCursor);
467   ME_DisplayItem        *di;
468   WCHAR                 space = ' ';
469   
470   /* FIXME no no no */
471   if (ME_IsSelection(editor))
472     ME_DeleteSelection(editor);
473
474   di = ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
475                                        MERF_GRAPHICS);
476   di->member.run.ole_obj = ALLOC_OBJ(*reo);
477   ME_CopyReObject(di->member.run.ole_obj, reo);
478   ME_ReleaseStyle(pStyle);
479 }
480
481
482 void ME_InsertEndRowFromCursor(ME_TextEditor *editor, int nCursor)
483 {
484   ME_Style              *pStyle = ME_GetInsertStyle(editor, nCursor);
485   ME_DisplayItem        *di;
486   WCHAR                 space = ' ';
487
488   /* FIXME no no no */
489   if (ME_IsSelection(editor))
490     ME_DeleteSelection(editor);
491
492   di = ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
493                                        MERF_ENDROW);
494   ME_ReleaseStyle(pStyle);
495 }
496
497
498 void ME_InsertTextFromCursor(ME_TextEditor *editor, int nCursor, 
499   const WCHAR *str, int len, ME_Style *style)
500 {
501   const WCHAR *pos;
502   ME_Cursor *p = NULL;
503   int oldLen;
504
505   /* FIXME really HERE ? */
506   if (ME_IsSelection(editor))
507     ME_DeleteSelection(editor);
508
509   /* FIXME: is this too slow? */
510   /* Didn't affect performance for WM_SETTEXT (around 50sec/30K) */
511   oldLen = ME_GetTextLength(editor);
512
513   /* text operations set modified state */
514   editor->nModifyStep = 1;
515
516   assert(style);
517
518   assert(nCursor>=0 && nCursor<editor->nCursors);
519   if (len == -1)
520     len = lstrlenW(str);
521
522   /* grow the text limit to fit our text */
523   if(editor->nTextLimit < oldLen +len)
524     editor->nTextLimit = oldLen + len;
525
526   pos = str;
527
528   while (len)
529   {
530     /* FIXME this sucks - no respect for unicode (what else can be a line separator in unicode?) */
531     while(pos - str < len && *pos != '\r' && *pos != '\n' && *pos != '\t')
532       pos++;
533
534     if (pos != str) { /* handle text */
535       ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
536     } else if (*pos == '\t') { /* handle tabs */
537       WCHAR tab = '\t';
538       ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, style, MERF_TAB);
539       pos++;
540     } else { /* handle EOLs */
541       ME_DisplayItem *tp, *end_run;
542       ME_Style *tmp_style;
543       int eol_len = 0;
544
545       /* Find number of CR and LF in end of paragraph run */
546       if (*pos =='\r')
547       {
548         if (len > 1 && pos[1] == '\n')
549           eol_len = 2;
550         else if (len > 2 && pos[1] == '\r' && pos[2] == '\n')
551           eol_len = 3;
552         else
553           eol_len = 1;
554       } else {
555         assert(*pos == '\n');
556         eol_len = 1;
557       }
558       pos += eol_len;
559
560       if (!editor->bEmulateVersion10 && eol_len == 3)
561       {
562         /* handle special \r\r\n sequence (richedit 2.x and higher only) */
563         WCHAR space = ' ';
564         ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, style, 0);
565       } else {
566         ME_String *eol_str;
567
568         if (!editor->bEmulateVersion10) {
569           WCHAR cr = '\r';
570           eol_str = ME_MakeStringN(&cr, 1);
571         } else {
572           eol_str = ME_MakeStringN(str, eol_len);
573         }
574
575         p = &editor->pCursors[nCursor];
576         if (p->nOffset) {
577           ME_SplitRunSimple(editor, p->pRun, p->nOffset);
578           p = &editor->pCursors[nCursor];
579         }
580         tmp_style = ME_GetInsertStyle(editor, nCursor);
581         /* ME_SplitParagraph increases style refcount */
582         tp = ME_SplitParagraph(editor, p->pRun, p->pRun->member.run.style, eol_str, 0);
583         p->pRun = ME_FindItemFwd(tp, diRun);
584         p->pPara = ME_GetParagraph(p->pRun);
585         end_run = ME_FindItemBack(tp, diRun);
586         ME_ReleaseStyle(end_run->member.run.style);
587         end_run->member.run.style = tmp_style;
588         p->nOffset = 0;
589       }
590     }
591     len -= pos - str;
592     str = pos;
593   }
594 }
595
596
597 static BOOL
598 ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
599 {
600   ME_DisplayItem *pRun = pCursor->pRun;
601
602   if (nRelOfs == -1)
603   {
604     if (!pCursor->nOffset)
605     {
606       ME_DisplayItem *pPara = pCursor->pPara;
607       do {
608         pRun = ME_FindItemBack(pRun, diRunOrParagraph);
609         assert(pRun);
610         switch (pRun->type)
611         {
612           case diRun:
613             break;
614           case diParagraph:
615             pPara = pRun;
616             if (pPara->member.para.prev_para->type == diTextStart)
617               return FALSE;
618             pRun = ME_FindItemBack(pPara, diRunOrParagraph);
619             pPara = pPara->member.para.prev_para;
620             /* every paragraph ought to have at least one run */
621             assert(pRun && pRun->type == diRun);
622             assert(pRun->member.run.nFlags & MERF_ENDPARA);
623             break;
624           default:
625             assert(pRun->type != diRun && pRun->type != diParagraph);
626             return FALSE;
627         }
628       } while (RUN_IS_HIDDEN(&pRun->member.run) ||
629                pRun->member.run.nFlags & MERF_HIDDEN);
630       pCursor->pPara = pPara;
631       pCursor->pRun = pRun;
632       if (pRun->member.run.nFlags & MERF_ENDPARA)
633         pCursor->nOffset = 0;
634       else
635         pCursor->nOffset = pRun->member.run.strText->nLen;
636     }
637
638     if (pCursor->nOffset)
639       pCursor->nOffset = pCursor->nOffset + nRelOfs;
640     return TRUE;
641   }
642   else
643   {
644     if (!(pRun->member.run.nFlags & MERF_ENDPARA))
645     {
646       int new_ofs = pCursor->nOffset + nRelOfs;
647
648       if (new_ofs < pRun->member.run.strText->nLen)
649       {
650         pCursor->nOffset = new_ofs;
651         return TRUE;
652       }
653     }
654     do {
655       pRun = ME_FindItemFwd(pRun, diRun);
656     } while (pRun && (RUN_IS_HIDDEN(&pRun->member.run) ||
657                       pRun->member.run.nFlags & MERF_HIDDEN));
658     if (pRun)
659     {
660       pCursor->pPara = ME_GetParagraph(pRun);
661       pCursor->pRun = pRun;
662       pCursor->nOffset = 0;
663       return TRUE;
664     }
665   }
666   return FALSE;
667 }
668
669
670 static BOOL
671 ME_MoveCursorWords(ME_TextEditor *editor, ME_Cursor *cursor, int nRelOfs)
672 {
673   ME_DisplayItem *pRun = cursor->pRun, *pOtherRun;
674   int nOffset = cursor->nOffset;
675   
676   if (nRelOfs == -1)
677   {
678     /* Backward movement */
679     while (TRUE)
680     {
681       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
682                                      nOffset, WB_MOVEWORDLEFT);
683       if (nOffset)
684         break;
685       pOtherRun = ME_FindItemBack(pRun, diRunOrParagraph);
686       if (pOtherRun->type == diRun)
687       {
688         if (ME_CallWordBreakProc(editor, pOtherRun->member.run.strText,
689                                  pOtherRun->member.run.strText->nLen - 1,
690                                  WB_ISDELIMITER)
691             && !(pRun->member.run.nFlags & MERF_ENDPARA)
692             && !(cursor->pRun == pRun && cursor->nOffset == 0)
693             && !ME_CallWordBreakProc(editor, pRun->member.run.strText, 0,
694                                      WB_ISDELIMITER))
695           break;
696         pRun = pOtherRun;
697         nOffset = pOtherRun->member.run.strText->nLen;
698       }
699       else if (pOtherRun->type == diParagraph)
700       {
701         if (cursor->pRun == pRun && cursor->nOffset == 0)
702         {
703           /* Skip empty start of table row paragraph */
704           if (pOtherRun->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART)
705             pOtherRun = pOtherRun->member.para.prev_para;
706           /* Paragraph breaks are treated as separate words */
707           if (pOtherRun->member.para.prev_para->type == diTextStart)
708             return FALSE;
709
710           pRun = ME_FindItemBack(pOtherRun, diRun);
711         }
712         break;
713       }
714     }
715   }
716   else
717   {
718     /* Forward movement */
719     BOOL last_delim = FALSE;
720     
721     while (TRUE)
722     {
723       if (last_delim && !ME_CallWordBreakProc(editor, pRun->member.run.strText,
724                                               nOffset, WB_ISDELIMITER))
725         break;
726       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
727                                      nOffset, WB_MOVEWORDRIGHT);
728       if (nOffset < pRun->member.run.strText->nLen)
729         break;
730       pOtherRun = ME_FindItemFwd(pRun, diRunOrParagraphOrEnd);
731       if (pOtherRun->type == diRun)
732       {
733         last_delim = ME_CallWordBreakProc(editor, pRun->member.run.strText,
734                                           nOffset - 1, WB_ISDELIMITER);
735         pRun = pOtherRun;
736         nOffset = 0;
737       }
738       else if (pOtherRun->type == diParagraph)
739       {
740         if (pOtherRun->member.para.nFlags & MEPF_ROWSTART)
741             pOtherRun = pOtherRun->member.para.next_para;
742         if (cursor->pRun == pRun)
743           pRun = ME_FindItemFwd(pOtherRun, diRun);
744         nOffset = 0;
745         break;
746       }
747       else /* diTextEnd */
748       {
749         if (cursor->pRun == pRun)
750           return FALSE;
751         nOffset = 0;
752         break;
753       }
754     }
755   }
756   cursor->pPara = ME_GetParagraph(pRun);
757   cursor->pRun = pRun;
758   cursor->nOffset = nOffset;
759   return TRUE;
760 }
761
762
763 static void
764 ME_SelectByType(ME_TextEditor *editor, ME_SelectionType selectionType)
765 {
766   /* pCursor[0] is the end of the selection
767    * pCursor[1] is the start of the selection (or the position selection anchor)
768    * pCursor[2] and [3] are the selection anchors that are backed up
769    * so they are kept when the selection changes for drag selection.
770    */
771
772   editor->nSelectionType = selectionType;
773   switch(selectionType)
774   {
775     case stPosition:
776       break;
777     case stWord:
778       ME_MoveCursorWords(editor, &editor->pCursors[0], +1);
779       editor->pCursors[1] = editor->pCursors[0];
780       ME_MoveCursorWords(editor, &editor->pCursors[1], -1);
781       break;
782     case stLine:
783     case stParagraph:
784     {
785       ME_DisplayItem *pItem;
786       ME_DIType fwdSearchType, backSearchType;
787       if (selectionType == stParagraph) {
788           backSearchType = diParagraph;
789           fwdSearchType = diParagraphOrEnd;
790       } else {
791           backSearchType = diStartRow;
792           fwdSearchType = diStartRowOrParagraphOrEnd;
793       }
794       pItem = ME_FindItemFwd(editor->pCursors[0].pRun, fwdSearchType);
795       assert(pItem);
796       if (pItem->type == diTextEnd)
797           editor->pCursors[0].pRun = ME_FindItemBack(pItem, diRun);
798       else
799           editor->pCursors[0].pRun = ME_FindItemFwd(pItem, diRun);
800       editor->pCursors[0].pPara = ME_GetParagraph(editor->pCursors[0].pRun);
801       editor->pCursors[0].nOffset = 0;
802
803       pItem = ME_FindItemBack(pItem, backSearchType);
804       editor->pCursors[1].pRun = ME_FindItemFwd(pItem, diRun);
805       editor->pCursors[1].pPara = ME_GetParagraph(editor->pCursors[1].pRun);
806       editor->pCursors[1].nOffset = 0;
807       break;
808     }
809     case stDocument:
810       /* Select everything with cursor anchored from the start of the text */
811       editor->nSelectionType = stDocument;
812       editor->pCursors[1].pPara = editor->pBuffer->pFirst->member.para.next_para;
813       editor->pCursors[1].pRun = ME_FindItemFwd(editor->pCursors[1].pPara, diRun);
814       editor->pCursors[1].nOffset = 0;
815       editor->pCursors[0].pPara = editor->pBuffer->pLast->member.para.prev_para;
816       editor->pCursors[0].pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
817       editor->pCursors[0].nOffset = 0;
818       break;
819     default: assert(0);
820   }
821   /* Store the anchor positions for extending the selection. */
822   editor->pCursors[2] = editor->pCursors[0];
823   editor->pCursors[3] = editor->pCursors[1];
824 }
825
826 int ME_GetCursorOfs(const ME_Cursor *cursor)
827 {
828   return cursor->pPara->member.para.nCharOfs
829          + cursor->pRun->member.run.nCharOfs + cursor->nOffset;
830 }
831
832 /* Helper function for ME_FindPixelPos to find paragraph within tables */
833 static ME_DisplayItem* ME_FindPixelPosInTableRow(int x, int y,
834                                                  ME_DisplayItem *para)
835 {
836   ME_DisplayItem *cell, *next_cell;
837   assert(para->member.para.nFlags & MEPF_ROWSTART);
838   cell = para->member.para.next_para->member.para.pCell;
839   assert(cell);
840
841   /* find the cell we are in */
842   while ((next_cell = cell->member.cell.next_cell) != NULL) {
843     if (x < next_cell->member.cell.pt.x)
844     {
845       para = ME_FindItemFwd(cell, diParagraph);
846       /* Found the cell, but there might be multiple paragraphs in
847        * the cell, so need to search down the cell for the paragraph. */
848       while (cell == para->member.para.pCell) {
849         if (y < para->member.para.pt.y + para->member.para.nHeight)
850         {
851           if (para->member.para.nFlags & MEPF_ROWSTART)
852             return ME_FindPixelPosInTableRow(x, y, para);
853           else
854             return para;
855         }
856         para = para->member.para.next_para;
857       }
858       /* Past the end of the cell, so go back to the last cell paragraph */
859       return para->member.para.prev_para;
860     }
861     cell = next_cell;
862   }
863   /* Return table row delimiter */
864   para = ME_FindItemFwd(cell, diParagraph);
865   assert(para->member.para.nFlags & MEPF_ROWEND);
866   assert(para->member.para.pFmt->dwMask & PFM_TABLEROWDELIMITER);
867   assert(para->member.para.pFmt->wEffects & PFE_TABLEROWDELIMITER);
868   return para;
869 }
870
871 static BOOL ME_ReturnFoundPos(ME_TextEditor *editor, ME_DisplayItem *found,
872                                ME_Cursor *result, int rx, BOOL isExact)
873 {
874   assert(found);
875   assert(found->type == diRun);
876   if ((found->member.run.nFlags & MERF_ENDPARA) || rx < 0)
877     rx = 0;
878   result->pRun = found;
879   result->nOffset = ME_CharFromPointCursor(editor, rx, &found->member.run);
880   if (editor->pCursors[0].nOffset == found->member.run.strText->nLen && rx)
881   {
882     result->pRun = ME_FindItemFwd(editor->pCursors[0].pRun, diRun);
883     result->nOffset = 0;
884   }
885   result->pPara = ME_GetParagraph(result->pRun);
886   return isExact;
887 }
888
889 /* Finds the run and offset from the pixel position.
890  *
891  * x & y are pixel positions in virtual coordinates into the rich edit control,
892  * so client coordinates must first be adjusted by the scroll position.
893  *
894  * returns TRUE if the result was exactly under the cursor, otherwise returns
895  * FALSE, and result is set to the closest position to the coordinates.
896  */
897 static BOOL ME_FindPixelPos(ME_TextEditor *editor, int x, int y,
898                             ME_Cursor *result, BOOL *is_eol)
899 {
900   ME_DisplayItem *p = editor->pBuffer->pFirst->member.para.next_para;
901   ME_DisplayItem *last = NULL;
902   int rx = 0;
903   BOOL isExact = TRUE;
904
905   x -= editor->rcFormat.left;
906   y -= editor->rcFormat.top;
907
908   if (is_eol)
909     *is_eol = 0;
910
911   /* find paragraph */
912   for (; p != editor->pBuffer->pLast; p = p->member.para.next_para)
913   {
914     assert(p->type == diParagraph);
915     if (y < p->member.para.pt.y + p->member.para.nHeight)
916     {
917       if (p->member.para.nFlags & MEPF_ROWSTART)
918         p = ME_FindPixelPosInTableRow(x, y, p);
919       y -= p->member.para.pt.y;
920       p = ME_FindItemFwd(p, diStartRow);
921       break;
922     } else if (p->member.para.nFlags & MEPF_ROWSTART) {
923       p = ME_GetTableRowEnd(p);
924     }
925   }
926   /* find row */
927   for (; p != editor->pBuffer->pLast; )
928   {
929     ME_DisplayItem *pp;
930     assert(p->type == diStartRow);
931     if (y < p->member.row.pt.y + p->member.row.nHeight)
932     {
933         p = ME_FindItemFwd(p, diRun);
934         break;
935     }
936     pp = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
937     if (pp->type != diStartRow)
938     {
939         p = ME_FindItemFwd(p, diRun);
940         break;
941     }
942     p = pp;
943   }
944   if (p == editor->pBuffer->pLast)
945   {
946     /* The position is below the last paragraph, so the last row will be used
947      * rather than the end of the text, so the x position will be used to
948      * determine the offset closest to the pixel position. */
949     isExact = FALSE;
950     p = ME_FindItemBack(p, diStartRow);
951     if (p != NULL){
952       p = ME_FindItemFwd(p, diRun);
953     }
954     else
955     {
956       p = editor->pBuffer->pLast;
957     }
958   }
959   for (; p != editor->pBuffer->pLast; p = p->next)
960   {
961     switch (p->type)
962     {
963     case diRun:
964       rx = x - p->member.run.pt.x;
965       if (rx < p->member.run.nWidth)
966         return ME_ReturnFoundPos(editor, p, result, rx, isExact);
967       break;
968     case diStartRow:
969       isExact = FALSE;
970       p = ME_FindItemFwd(p, diRun);
971       if (is_eol) *is_eol = 1;
972       rx = 0; /* FIXME not sure */
973       return ME_ReturnFoundPos(editor, p, result, rx, isExact);
974     case diCell:
975     case diParagraph:
976     case diTextEnd:
977       isExact = FALSE;
978       rx = 0; /* FIXME not sure */
979       p = last;
980       return ME_ReturnFoundPos(editor, p, result, rx, isExact);
981     default: assert(0);
982     }
983     last = p;
984   }
985   result->pRun = ME_FindItemBack(p, diRun);
986   result->pPara = ME_GetParagraph(result->pRun);
987   result->nOffset = 0;
988   assert(result->pRun->member.run.nFlags & MERF_ENDPARA);
989   return FALSE;
990 }
991
992
993 /* Returns the character offset closest to the pixel position
994  *
995  * x & y are pixel positions in client coordinates.
996  *
997  * isExact will be set to TRUE if the run is directly under the pixel
998  * position, FALSE if it not, unless isExact is set to NULL.
999  */
1000 int ME_CharFromPos(ME_TextEditor *editor, int x, int y, BOOL *isExact)
1001 {
1002   ME_Cursor cursor;
1003   RECT rc;
1004   BOOL bResult;
1005
1006   ITextHost_TxGetClientRect(editor->texthost, &rc);
1007   if (x < 0 || y < 0 || x >= rc.right || y >= rc.bottom) {
1008     if (isExact) *isExact = FALSE;
1009     return -1;
1010   }
1011   x += editor->horz_si.nPos;
1012   y += editor->vert_si.nPos;
1013   bResult = ME_FindPixelPos(editor, x, y, &cursor, NULL);
1014   if (isExact) *isExact = bResult;
1015   return cursor.pPara->member.para.nCharOfs
1016          + cursor.pRun->member.run.nCharOfs + cursor.nOffset;
1017 }
1018
1019
1020
1021 /* Extends the selection with a word, line, or paragraph selection type.
1022  *
1023  * The selection is anchored by editor->pCursors[2-3] such that the text
1024  * between the anchors will remain selected, and one end will be extended.
1025  *
1026  * editor->pCursors[0] should have the position to extend the selection to
1027  * before this function is called.
1028  *
1029  * Nothing will be done if editor->nSelectionType equals stPosition.
1030  */
1031 static void ME_ExtendAnchorSelection(ME_TextEditor *editor)
1032 {
1033   ME_Cursor tmp_cursor;
1034   int curOfs, anchorStartOfs, anchorEndOfs;
1035   if (editor->nSelectionType == stPosition || editor->nSelectionType == stDocument)
1036       return;
1037   curOfs = ME_GetCursorOfs(&editor->pCursors[0]);
1038   anchorStartOfs = ME_GetCursorOfs(&editor->pCursors[3]);
1039   anchorEndOfs = ME_GetCursorOfs(&editor->pCursors[2]);
1040
1041   tmp_cursor = editor->pCursors[0];
1042   editor->pCursors[0] = editor->pCursors[2];
1043   editor->pCursors[1] = editor->pCursors[3];
1044   if (curOfs < anchorStartOfs)
1045   {
1046       /* Extend the left side of selection */
1047       editor->pCursors[1] = tmp_cursor;
1048       if (editor->nSelectionType == stWord)
1049           ME_MoveCursorWords(editor, &editor->pCursors[1], -1);
1050       else
1051       {
1052           ME_DisplayItem *pItem;
1053           ME_DIType searchType = ((editor->nSelectionType == stLine) ?
1054                                   diStartRowOrParagraph:diParagraph);
1055           pItem = ME_FindItemBack(editor->pCursors[1].pRun, searchType);
1056           editor->pCursors[1].pRun = ME_FindItemFwd(pItem, diRun);
1057           editor->pCursors[1].pPara = ME_GetParagraph(editor->pCursors[1].pRun);
1058           editor->pCursors[1].nOffset = 0;
1059       }
1060   }
1061   else if (curOfs >= anchorEndOfs)
1062   {
1063       /* Extend the right side of selection */
1064       editor->pCursors[0] = tmp_cursor;
1065       if (editor->nSelectionType == stWord)
1066           ME_MoveCursorWords(editor, &editor->pCursors[0], +1);
1067       else
1068       {
1069           ME_DisplayItem *pItem;
1070           ME_DIType searchType = ((editor->nSelectionType == stLine) ?
1071                                   diStartRowOrParagraphOrEnd:diParagraphOrEnd);
1072           pItem = ME_FindItemFwd(editor->pCursors[0].pRun, searchType);
1073           if (pItem->type == diTextEnd)
1074               editor->pCursors[0].pRun = ME_FindItemBack(pItem, diRun);
1075           else
1076               editor->pCursors[0].pRun = ME_FindItemFwd(pItem, diRun);
1077           editor->pCursors[0].pPara = ME_GetParagraph(editor->pCursors[0].pRun);
1078           editor->pCursors[0].nOffset = 0;
1079       }
1080   }
1081 }
1082
1083 void ME_LButtonDown(ME_TextEditor *editor, int x, int y, int clickNum)
1084 {
1085   ME_Cursor tmp_cursor;
1086   int is_selection = 0;
1087   BOOL is_shift;
1088
1089   editor->nUDArrowX = -1;
1090
1091   x += editor->horz_si.nPos;
1092   y += editor->vert_si.nPos;
1093
1094   tmp_cursor = editor->pCursors[0];
1095   is_selection = ME_IsSelection(editor);
1096   is_shift = GetKeyState(VK_SHIFT) < 0;
1097
1098   ME_FindPixelPos(editor, x, y, &editor->pCursors[0], &editor->bCaretAtEnd);
1099
1100   if (x >= editor->rcFormat.left || is_shift)
1101   {
1102     if (clickNum > 1)
1103     {
1104       editor->pCursors[1] = editor->pCursors[0];
1105       if (is_shift) {
1106           if (x >= editor->rcFormat.left)
1107               ME_SelectByType(editor, stWord);
1108           else
1109               ME_SelectByType(editor, stParagraph);
1110       } else if (clickNum % 2 == 0) {
1111           ME_SelectByType(editor, stWord);
1112       } else {
1113           ME_SelectByType(editor, stParagraph);
1114       }
1115     }
1116     else if (!is_shift)
1117     {
1118       editor->nSelectionType = stPosition;
1119       editor->pCursors[1] = editor->pCursors[0];
1120     }
1121     else if (!is_selection)
1122     {
1123       editor->nSelectionType = stPosition;
1124       editor->pCursors[1] = tmp_cursor;
1125     }
1126     else if (editor->nSelectionType != stPosition)
1127     {
1128       ME_ExtendAnchorSelection(editor);
1129     }
1130   }
1131   else
1132   {
1133     if (clickNum < 2) {
1134         ME_SelectByType(editor, stLine);
1135     } else if (clickNum % 2 == 0 || is_shift) {
1136         ME_SelectByType(editor, stParagraph);
1137     } else {
1138         ME_SelectByType(editor, stDocument);
1139     }
1140   }
1141   ME_InvalidateSelection(editor);
1142   ITextHost_TxShowCaret(editor->texthost, FALSE);
1143   ME_ShowCaret(editor);
1144   ME_ClearTempStyle(editor);
1145   ME_SendSelChange(editor);
1146 }
1147
1148 void ME_MouseMove(ME_TextEditor *editor, int x, int y)
1149 {
1150   ME_Cursor tmp_cursor;
1151
1152   if (editor->nSelectionType == stDocument)
1153       return;
1154   x += editor->horz_si.nPos;
1155   y += editor->vert_si.nPos;
1156
1157   tmp_cursor = editor->pCursors[0];
1158   /* FIXME: do something with the return value of ME_FindPixelPos */
1159   ME_FindPixelPos(editor, x, y, &tmp_cursor, &editor->bCaretAtEnd);
1160
1161   ME_InvalidateSelection(editor);
1162   editor->pCursors[0] = tmp_cursor;
1163   ME_ExtendAnchorSelection(editor);
1164
1165   if (editor->nSelectionType != stPosition &&
1166       memcmp(&editor->pCursors[1], &editor->pCursors[3], sizeof(ME_Cursor)))
1167   {
1168       /* The scroll the cursor towards the other end, since it was the one
1169        * extended by ME_ExtendAnchorSelection */
1170       ME_EnsureVisible(editor, &editor->pCursors[1]);
1171   } else {
1172       ME_EnsureVisible(editor, &editor->pCursors[0]);
1173   }
1174
1175   ME_InvalidateSelection(editor);
1176   ITextHost_TxShowCaret(editor->texthost, FALSE);
1177   ME_ShowCaret(editor);
1178   ME_SendSelChange(editor);
1179 }
1180
1181 static ME_DisplayItem *ME_FindRunInRow(ME_TextEditor *editor, ME_DisplayItem *pRow, 
1182                                 int x, int *pOffset, int *pbCaretAtEnd)
1183 {
1184   ME_DisplayItem *pNext, *pLastRun;
1185   pNext = ME_FindItemFwd(pRow, diRunOrStartRow);
1186   assert(pNext->type == diRun);
1187   pLastRun = pNext;
1188   if (pbCaretAtEnd) *pbCaretAtEnd = FALSE;
1189   if (pOffset) *pOffset = 0;
1190   do {
1191     int run_x = pNext->member.run.pt.x;
1192     int width = pNext->member.run.nWidth;
1193     if (x < run_x)
1194     {
1195       return pNext;
1196     }
1197     if (x >= run_x && x < run_x+width)
1198     {
1199       int ch = ME_CharFromPointCursor(editor, x-run_x, &pNext->member.run);
1200       ME_String *s = pNext->member.run.strText;
1201       if (ch < s->nLen) {
1202         if (pOffset)
1203           *pOffset = ch;
1204         return pNext;          
1205       }
1206     }
1207     pLastRun = pNext;
1208     pNext = ME_FindItemFwd(pNext, diRunOrStartRow);
1209   } while(pNext && pNext->type == diRun);
1210   
1211   if ((pLastRun->member.run.nFlags & MERF_ENDPARA) == 0)
1212   {
1213     pNext = ME_FindItemFwd(pNext, diRun);
1214     if (pbCaretAtEnd) *pbCaretAtEnd = TRUE;
1215     return pNext;
1216   } else {
1217     return pLastRun;
1218   }
1219 }
1220
1221 static int ME_GetXForArrow(ME_TextEditor *editor, ME_Cursor *pCursor)
1222 {
1223   ME_DisplayItem *pRun = pCursor->pRun;
1224   int x;
1225
1226   if (editor->nUDArrowX != -1)
1227     x = editor->nUDArrowX;
1228   else {
1229     if (editor->bCaretAtEnd)
1230     {
1231       pRun = ME_FindItemBack(pRun, diRun);
1232       assert(pRun);
1233       x = pRun->member.run.pt.x + pRun->member.run.nWidth;
1234     }
1235     else {
1236       x = pRun->member.run.pt.x;
1237       x += ME_PointFromChar(editor, &pRun->member.run, pCursor->nOffset);
1238     }
1239     editor->nUDArrowX = x;
1240   }
1241   return x;
1242 }
1243
1244
1245 static void
1246 ME_MoveCursorLines(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
1247 {
1248   ME_DisplayItem *pRun = pCursor->pRun;
1249   ME_DisplayItem *pItem, *pOldPara, *pNewPara;
1250   int x = ME_GetXForArrow(editor, pCursor);
1251
1252   if (editor->bCaretAtEnd && !pCursor->nOffset)
1253     pRun = ME_FindItemBack(pRun, diRun);
1254   if (!pRun)
1255     return;
1256   pOldPara = ME_GetParagraph(pRun);
1257   if (nRelOfs == -1)
1258   {
1259     /* start of this row */
1260     pItem = ME_FindItemBack(pRun, diStartRow);
1261     assert(pItem);
1262     /* start of the previous row */
1263     pItem = ME_FindItemBack(pItem, diStartRow);
1264     if (!pItem)
1265       return; /* row not found - ignore */
1266     pNewPara = ME_GetParagraph(pItem);
1267     if (pOldPara->member.para.nFlags & MEPF_ROWEND ||
1268         (pOldPara->member.para.pCell &&
1269          pOldPara->member.para.pCell != pNewPara->member.para.pCell))
1270     {
1271       /* Brought out of a cell */
1272       pNewPara = ME_GetTableRowStart(pOldPara)->member.para.prev_para;
1273       if (pNewPara->type == diTextStart)
1274         return; /* At the top, so don't go anywhere. */
1275       pItem = ME_FindItemFwd(pNewPara, diStartRow);
1276     }
1277     if (pNewPara->member.para.nFlags & MEPF_ROWEND)
1278     {
1279       /* Brought into a table row */
1280       ME_Cell *cell = &ME_FindItemBack(pNewPara, diCell)->member.cell;
1281       while (x < cell->pt.x && cell->prev_cell)
1282         cell = &cell->prev_cell->member.cell;
1283       if (cell->next_cell) /* else - we are still at the end of the row */
1284         pItem = ME_FindItemBack(cell->next_cell, diStartRow);
1285     }
1286   }
1287   else
1288   {
1289     /* start of the next row */
1290     pItem = ME_FindItemFwd(pRun, diStartRow);
1291     if (!pItem)
1292       return; /* row not found - ignore */
1293     pNewPara = ME_GetParagraph(pItem);
1294     if (pOldPara->member.para.nFlags & MEPF_ROWSTART ||
1295         (pOldPara->member.para.pCell &&
1296          pOldPara->member.para.pCell != pNewPara->member.para.pCell))
1297     {
1298       /* Brought out of a cell */
1299       pNewPara = ME_GetTableRowEnd(pOldPara)->member.para.next_para;
1300       if (pNewPara->type == diTextEnd)
1301         return; /* At the bottom, so don't go anywhere. */
1302       pItem = ME_FindItemFwd(pNewPara, diStartRow);
1303     }
1304     if (pNewPara->member.para.nFlags & MEPF_ROWSTART)
1305     {
1306       /* Brought into a table row */
1307       ME_DisplayItem *cell = ME_FindItemFwd(pNewPara, diCell);
1308       while (cell->member.cell.next_cell &&
1309              x >= cell->member.cell.next_cell->member.cell.pt.x)
1310         cell = cell->member.cell.next_cell;
1311       pItem = ME_FindItemFwd(cell, diStartRow);
1312     }
1313   }
1314   if (!pItem)
1315   {
1316     /* row not found - ignore */
1317     return;
1318   }
1319   pCursor->pRun = ME_FindRunInRow(editor, pItem, x, &pCursor->nOffset, &editor->bCaretAtEnd);
1320   pCursor->pPara = ME_GetParagraph(pCursor->pRun);
1321   assert(pCursor->pRun);
1322   assert(pCursor->pRun->type == diRun);
1323 }
1324
1325 static void ME_ArrowPageUp(ME_TextEditor *editor, ME_Cursor *pCursor)
1326 {
1327   ME_DisplayItem *p = ME_FindItemFwd(editor->pBuffer->pFirst, diStartRow);
1328
1329   if (editor->vert_si.nPos < p->member.row.nHeight)
1330   {
1331     pCursor->pPara = editor->pBuffer->pFirst->member.para.next_para;
1332     pCursor->pRun = ME_FindItemFwd(pCursor->pPara, diRun);
1333     pCursor->nOffset = 0;
1334     editor->bCaretAtEnd = FALSE;
1335     /* Native clears seems to clear this x value on page up at the top
1336      * of the text, but not on page down at the end of the text.
1337      * Doesn't make sense, but we try to be bug for bug compatible. */
1338     editor->nUDArrowX = -1;
1339   } else {
1340     ME_DisplayItem *pRun = pCursor->pRun;
1341     ME_DisplayItem *pLast;
1342     int x, y, ys, yd, yp, yprev;
1343     int yOldScrollPos = editor->vert_si.nPos;
1344
1345     x = ME_GetXForArrow(editor, pCursor);
1346     if (!pCursor->nOffset && editor->bCaretAtEnd)
1347       pRun = ME_FindItemBack(pRun, diRun);
1348
1349     p = ME_FindItemBack(pRun, diStartRowOrParagraph);
1350     assert(p->type == diStartRow);
1351     yp = ME_FindItemBack(p, diParagraph)->member.para.pt.y;
1352     yprev = ys = y = yp + p->member.row.pt.y;
1353
1354     ME_ScrollUp(editor, editor->sizeWindow.cy);
1355     /* Only move the cursor by the amount scrolled. */
1356     yd = y + editor->vert_si.nPos - yOldScrollPos;
1357     pLast = p;
1358
1359     do {
1360       p = ME_FindItemBack(p, diStartRowOrParagraph);
1361       if (!p)
1362         break;
1363       if (p->type == diParagraph) { /* crossing paragraphs */
1364         if (p->member.para.prev_para == NULL)
1365           break;
1366         yp = p->member.para.prev_para->member.para.pt.y;
1367         continue;
1368       }
1369       y = yp + p->member.row.pt.y;
1370       if (y < yd)
1371         break;
1372       pLast = p;
1373       yprev = y;
1374     } while(1);
1375
1376     pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset,
1377                                     &editor->bCaretAtEnd);
1378     pCursor->pPara = ME_GetParagraph(pCursor->pRun);
1379   }
1380   assert(pCursor->pRun);
1381   assert(pCursor->pRun->type == diRun);
1382 }
1383
1384 static void ME_ArrowPageDown(ME_TextEditor *editor, ME_Cursor *pCursor)
1385 {
1386   ME_DisplayItem *pLast;
1387   int x, y;
1388
1389   /* Find y position of the last row */
1390   pLast = editor->pBuffer->pLast;
1391   y = pLast->member.para.prev_para->member.para.pt.y
1392       + ME_FindItemBack(pLast, diStartRow)->member.row.pt.y;
1393
1394   x = ME_GetXForArrow(editor, pCursor);
1395
1396   if (editor->vert_si.nPos >= y - editor->sizeWindow.cy)
1397   {
1398     pCursor->pPara = editor->pBuffer->pLast->member.para.prev_para;
1399     pCursor->pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
1400     pCursor->nOffset = 0;
1401     editor->bCaretAtEnd = FALSE;
1402   } else {
1403     ME_DisplayItem *pRun = pCursor->pRun;
1404     ME_DisplayItem *p;
1405     int ys, yd, yp, yprev;
1406     int yOldScrollPos = editor->vert_si.nPos;
1407
1408     if (!pCursor->nOffset && editor->bCaretAtEnd)
1409       pRun = ME_FindItemBack(pRun, diRun);
1410
1411     p = ME_FindItemBack(pRun, diStartRowOrParagraph);
1412     assert(p->type == diStartRow);
1413     yp = ME_FindItemBack(p, diParagraph)->member.para.pt.y;
1414     yprev = ys = y = yp + p->member.row.pt.y;
1415
1416     /* For native richedit controls:
1417      * v1.0 - v3.1 can only scroll down as far as the scrollbar lets us
1418      * v4.1 can scroll past this position here. */
1419     ME_ScrollDown(editor, editor->sizeWindow.cy);
1420     /* Only move the cursor by the amount scrolled. */
1421     yd = y + editor->vert_si.nPos - yOldScrollPos;
1422     pLast = p;
1423
1424     do {
1425       p = ME_FindItemFwd(p, diStartRowOrParagraph);
1426       if (!p)
1427         break;
1428       if (p->type == diParagraph) {
1429         yp = p->member.para.pt.y;
1430         continue;
1431       }
1432       y = yp + p->member.row.pt.y;
1433       if (y >= yd)
1434         break;
1435       pLast = p;
1436       yprev = y;
1437     } while(1);
1438
1439     pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset,
1440                                     &editor->bCaretAtEnd);
1441     pCursor->pPara = ME_GetParagraph(pCursor->pRun);
1442   }
1443   assert(pCursor->pRun);
1444   assert(pCursor->pRun->type == diRun);
1445 }
1446
1447 static void ME_ArrowHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1448 {
1449   ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diStartRow);
1450   if (pRow) {
1451     ME_DisplayItem *pRun;
1452     if (editor->bCaretAtEnd && !pCursor->nOffset) {
1453       pRow = ME_FindItemBack(pRow, diStartRow);
1454       if (!pRow)
1455         return;
1456     }
1457     pRun = ME_FindItemFwd(pRow, diRun);
1458     if (pRun) {
1459       pCursor->pRun = pRun;
1460       assert(pCursor->pPara == ME_GetParagraph(pRun));
1461       pCursor->nOffset = 0;
1462     }
1463   }
1464   editor->bCaretAtEnd = FALSE;
1465 }
1466
1467 static void ME_ArrowCtrlHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1468 {
1469   pCursor->pPara = editor->pBuffer->pFirst->member.para.next_para;
1470   pCursor->pRun = ME_FindItemFwd(pCursor->pPara, diRun);
1471   pCursor->nOffset = 0;
1472   editor->bCaretAtEnd = FALSE;
1473 }
1474
1475 static void ME_ArrowEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1476 {
1477   ME_DisplayItem *pRow;
1478
1479   if (editor->bCaretAtEnd && !pCursor->nOffset)
1480     return;
1481
1482   pRow = ME_FindItemFwd(pCursor->pRun, diStartRowOrParagraphOrEnd);
1483   assert(pRow);
1484   if (pRow->type == diStartRow) {
1485     ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
1486     assert(pRun);
1487     pCursor->pRun = pRun;
1488     assert(pCursor->pPara == ME_GetParagraph(pCursor->pRun));
1489     pCursor->nOffset = 0;
1490     editor->bCaretAtEnd = TRUE;
1491     return;
1492   }
1493   pCursor->pRun = ME_FindItemBack(pRow, diRun);
1494   assert(pCursor->pRun && pCursor->pRun->member.run.nFlags & MERF_ENDPARA);
1495   assert(pCursor->pPara == ME_GetParagraph(pCursor->pRun));
1496   pCursor->nOffset = 0;
1497   editor->bCaretAtEnd = FALSE;
1498 }
1499
1500 static void ME_ArrowCtrlEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1501 {
1502   pCursor->pPara = editor->pBuffer->pLast->member.para.prev_para;
1503   pCursor->pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
1504   assert(pCursor->pRun->member.run.nFlags & MERF_ENDPARA);
1505   pCursor->nOffset = 0;
1506   editor->bCaretAtEnd = FALSE;
1507 }
1508
1509 BOOL ME_IsSelection(ME_TextEditor *editor)
1510 {
1511   return editor->pCursors[0].pRun != editor->pCursors[1].pRun ||
1512          editor->pCursors[0].nOffset != editor->pCursors[1].nOffset;
1513 }
1514
1515 void ME_DeleteSelection(ME_TextEditor *editor)
1516 {
1517   int from, to;
1518   int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
1519   ME_DeleteTextAtCursor(editor, nStartCursor, to - from);
1520 }
1521
1522 ME_Style *ME_GetSelectionInsertStyle(ME_TextEditor *editor)
1523 {
1524   return ME_GetInsertStyle(editor, 0);
1525 }
1526
1527 void ME_SendSelChange(ME_TextEditor *editor)
1528 {
1529   SELCHANGE sc;
1530
1531   if (!(editor->nEventMask & ENM_SELCHANGE))
1532     return;
1533
1534   sc.nmhdr.code = EN_SELCHANGE;
1535   ME_GetSelectionOfs(editor, &sc.chrg.cpMin, &sc.chrg.cpMax);
1536   sc.seltyp = SEL_EMPTY;
1537   if (sc.chrg.cpMin != sc.chrg.cpMax)
1538     sc.seltyp |= SEL_TEXT;
1539   if (sc.chrg.cpMin < sc.chrg.cpMax+1) /* what were RICHEDIT authors thinking ? */
1540     sc.seltyp |= SEL_MULTICHAR;
1541   TRACE("cpMin=%d cpMax=%d seltyp=%d (%s %s)\n",
1542     sc.chrg.cpMin, sc.chrg.cpMax, sc.seltyp,
1543     (sc.seltyp & SEL_TEXT) ? "SEL_TEXT" : "",
1544     (sc.seltyp & SEL_MULTICHAR) ? "SEL_MULTICHAR" : "");
1545   if (sc.chrg.cpMin != editor->notified_cr.cpMin || sc.chrg.cpMax != editor->notified_cr.cpMax)
1546   {
1547     ME_ClearTempStyle(editor);
1548
1549     editor->notified_cr = sc.chrg;
1550     ITextHost_TxNotify(editor->texthost, sc.nmhdr.code, &sc);
1551   }
1552 }
1553
1554 BOOL
1555 ME_ArrowKey(ME_TextEditor *editor, int nVKey, BOOL extend, BOOL ctrl)
1556 {
1557   int nCursor = 0;
1558   ME_Cursor *p = &editor->pCursors[nCursor];
1559   ME_Cursor tmp_curs = *p;
1560   BOOL success = FALSE;
1561
1562   ME_CheckCharOffsets(editor);
1563   switch(nVKey) {
1564     case VK_LEFT:
1565       editor->bCaretAtEnd = 0;
1566       if (ctrl)
1567         success = ME_MoveCursorWords(editor, &tmp_curs, -1);
1568       else
1569         success = ME_MoveCursorChars(editor, &tmp_curs, -1);
1570       break;
1571     case VK_RIGHT:
1572       editor->bCaretAtEnd = 0;
1573       if (ctrl)
1574         success = ME_MoveCursorWords(editor, &tmp_curs, +1);
1575       else
1576         success = ME_MoveCursorChars(editor, &tmp_curs, +1);
1577       break;
1578     case VK_UP:
1579       ME_MoveCursorLines(editor, &tmp_curs, -1);
1580       break;
1581     case VK_DOWN:
1582       ME_MoveCursorLines(editor, &tmp_curs, +1);
1583       break;
1584     case VK_PRIOR:
1585       ME_ArrowPageUp(editor, &tmp_curs);
1586       break;
1587     case VK_NEXT:
1588       ME_ArrowPageDown(editor, &tmp_curs);
1589       break;
1590     case VK_HOME: {
1591       if (ctrl)
1592         ME_ArrowCtrlHome(editor, &tmp_curs);
1593       else
1594         ME_ArrowHome(editor, &tmp_curs);
1595       editor->bCaretAtEnd = 0;
1596       break;
1597     }
1598     case VK_END:
1599       if (ctrl)
1600         ME_ArrowCtrlEnd(editor, &tmp_curs);
1601       else
1602         ME_ArrowEnd(editor, &tmp_curs);
1603       break;
1604   }
1605
1606   if (!extend)
1607     editor->pCursors[1] = tmp_curs;
1608   *p = tmp_curs;
1609
1610   ME_InvalidateSelection(editor);
1611   ME_Repaint(editor);
1612   ITextHost_TxShowCaret(editor->texthost, FALSE);
1613   ME_EnsureVisible(editor, &tmp_curs);
1614   ME_ShowCaret(editor);
1615   ME_SendSelChange(editor);
1616   return success;
1617 }