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