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