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