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