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