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