caret.c 48.8 KB
Newer Older
1 2 3 4
/*
 * RichEdit - Caret and selection functions.
 *
 * Copyright 2004 by Krzysztof Foltman
5
 * Copyright 2005 by Phil Krylov
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 24 25 26
 */


#include "editor.h"

WINE_DEFAULT_DEBUG_CHANNEL(richedit);

27 28 29 30 31 32 33
void ME_SetCursorToStart(ME_TextEditor *editor, ME_Cursor *cursor)
{
  cursor->pPara = editor->pBuffer->pFirst->member.para.next_para;
  cursor->pRun = ME_FindItemFwd(cursor->pPara, diRun);
  cursor->nOffset = 0;
}

34
static void ME_SetCursorToEnd(ME_TextEditor *editor, ME_Cursor *cursor, BOOL final_eop)
35 36 37
{
  cursor->pPara = editor->pBuffer->pLast->member.para.prev_para;
  cursor->pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
38
  cursor->nOffset = final_eop ? cursor->pRun->member.run.len : 0;
39 40 41
}


42
int ME_GetSelectionOfs(ME_TextEditor *editor, int *from, int *to)
43
{
44 45
  *from = ME_GetCursorOfs(&editor->pCursors[0]);
  *to =   ME_GetCursorOfs(&editor->pCursors[1]);
46

47 48 49 50
  if (*from > *to)
  {
    int tmp = *from;
    *from = *to;
51 52 53 54 55 56 57 58
    *to = tmp;
    return 1;
  }
  return 0;
}

int ME_GetSelection(ME_TextEditor *editor, ME_Cursor **from, ME_Cursor **to)
{
59 60 61 62 63 64 65 66 67 68 69 70 71
  int from_ofs = ME_GetCursorOfs( &editor->pCursors[0] );
  int to_ofs   = ME_GetCursorOfs( &editor->pCursors[1] );
  BOOL swap = (from_ofs > to_ofs);

  if (from_ofs == to_ofs)
  {
      /* If cursor[0] is at the beginning of a run and cursor[1] at the end
         of the prev run then we need to swap. */
      if (editor->pCursors[0].nOffset < editor->pCursors[1].nOffset)
          swap = TRUE;
  }

  if (!swap)
72 73 74 75 76 77 78 79
  {
    *from = &editor->pCursors[0];
    *to = &editor->pCursors[1];
    return 0;
  } else {
    *from = &editor->pCursors[1];
    *to = &editor->pCursors[0];
    return 1;
80 81 82 83 84
  }
}

int ME_GetTextLength(ME_TextEditor *editor)
{
85
  ME_Cursor cursor;
86
  ME_SetCursorToEnd(editor, &cursor, FALSE);
87
  return ME_GetCursorOfs(&cursor);
88 89
}

90

91
int ME_GetTextLengthEx(ME_TextEditor *editor, const GETTEXTLENGTHEX *how)
92 93
{
  int length;
94

95 96 97 98 99 100
  if (how->flags & GTL_PRECISE && how->flags & GTL_CLOSE)
    return E_INVALIDARG;
  if (how->flags & GTL_NUMCHARS && how->flags & GTL_NUMBYTES)
    return E_INVALIDARG;
  
  length = ME_GetTextLength(editor);
101

102
  if ((editor->styleFlags & ES_MULTILINE)
103 104
        && (how->flags & GTL_USECRLF)
        && !editor->bEmulateVersion10) /* Ignore GTL_USECRLF flag in 1.0 emulation */
105
    length += editor->nParagraphs - 1;
106 107 108 109

  if (how->flags & GTL_NUMBYTES ||
      (how->flags & GTL_PRECISE &&     /* GTL_PRECISE seems to imply GTL_NUMBYTES */
       !(how->flags & GTL_NUMCHARS)))  /* unless GTL_NUMCHARS is given */
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  {
    CPINFO cpinfo;
    
    if (how->codepage == 1200)
      return length * 2;
    if (how->flags & GTL_PRECISE)
      FIXME("GTL_PRECISE flag unsupported. Using GTL_CLOSE\n");
    if (GetCPInfo(how->codepage, &cpinfo))
      return length * cpinfo.MaxCharSize;
    ERR("Invalid codepage %u\n", how->codepage);
    return E_INVALIDARG;
  }
  return length; 
}

125 126 127 128 129 130 131 132
/******************************************************************
 *    set_selection_cursors
 *
 * Updates the selection cursors.
 *
 * Note that this does not invalidate either the old or the new selections.
 */
int set_selection_cursors(ME_TextEditor *editor, int from, int to)
133
{
134 135 136 137 138 139 140 141 142 143
  int selectionEnd = 0;
  const int len = ME_GetTextLength(editor);

  /* all negative values are effectively the same */
  if (from < 0)
    from = -1;
  if (to < 0)
    to = -1;

  /* select all */
144 145
  if (from == 0 && to == -1)
  {
146
    ME_SetCursorToStart(editor, &editor->pCursors[1]);
147
    ME_SetCursorToEnd(editor, &editor->pCursors[0], TRUE);
148
    return len + 1;
149
  }
150 151 152 153

  /* if both values are equal and also out of bound, that means to */
  /* put the selection at the end of the text */
  if ((from == to) && (to < 0 || to > len))
154
  {
155
    selectionEnd = 1;
156
  }
157
  else
158
  {
159 160 161 162 163
    /* if from is negative and to is positive then selection is */
    /* deselected and caret moved to end of the current selection */
    if (from < 0)
    {
      int start, end;
164
      ME_GetSelectionOfs(editor, &start, &end);
165 166
      if (start != end)
      {
167 168 169 170 171
          if (end > len)
          {
              editor->pCursors[0].nOffset = 0;
              end --;
          }
172 173
          editor->pCursors[1] = editor->pCursors[0];
      }
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      return end;
    }

    /* adjust to if it's a negative value */
    if (to < 0)
      to = len + 1;

    /* flip from and to if they are reversed */
    if (from>to)
    {
      int tmp = from;
      from = to;
      to = tmp;
    }

    /* after fiddling with the values, we find from > len && to > len */
    if (from > len)
      selectionEnd = 1;
    /* special case with to too big */
    else if (to > len)
      to = len + 1;
195
  }
196 197

  if (selectionEnd)
198
  {
199
    ME_SetCursorToEnd(editor, &editor->pCursors[0], FALSE);
200
    editor->pCursors[1] = editor->pCursors[0];
201
    return len;
202
  }
203

204
  ME_CursorFromCharOfs(editor, from, &editor->pCursors[1]);
205
  editor->pCursors[0] = editor->pCursors[1];
206
  ME_MoveCursorChars(editor, &editor->pCursors[0], to - from, FALSE);
207 208 209 210
  /* Selection is not allowed in the middle of an end paragraph run. */
  if (editor->pCursors[1].pRun->member.run.nFlags & MERF_ENDPARA)
    editor->pCursors[1].nOffset = 0;
  if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA)
211 212 213 214 215 216
  {
    if (to > len)
      editor->pCursors[0].nOffset = editor->pCursors[0].pRun->member.run.len;
    else
      editor->pCursors[0].nOffset = 0;
  }
217
  return to;
218 219 220
}


221 222
void ME_GetCursorCoordinates(ME_TextEditor *editor, ME_Cursor *pCursor,
                             int *x, int *y, int *height)
223
{
224 225
  ME_DisplayItem *row;
  ME_DisplayItem *run = pCursor->pRun;
226
  ME_DisplayItem *para = pCursor->pPara;
227 228
  ME_DisplayItem *pSizeRun = run;
  ME_Context c;
229
  int run_x;
230 231

  assert(height && x && y);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  assert(~para->member.para.nFlags & MEPF_REWRAP);
  assert(run && run->type == diRun);
  assert(para && para->type == diParagraph);

  row = ME_FindItemBack(run, diStartRowOrParagraph);
  assert(row && row->type == diStartRow);

  ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));

  if (!pCursor->nOffset)
  {
    ME_DisplayItem *prev = ME_FindItemBack(run, diRunOrParagraph);
    assert(prev);
    if (prev->type == diRun)
      pSizeRun = prev;
  }
  if (editor->bCaretAtEnd && !pCursor->nOffset &&
      run == ME_FindItemFwd(row, diRun))
  {
    ME_DisplayItem *tmp = ME_FindItemBack(row, diRunOrParagraph);
    assert(tmp);
    if (tmp->type == diRun)
    {
      row = ME_FindItemBack(tmp, diStartRow);
      pSizeRun = run = tmp;
      assert(run);
      assert(run->type == diRun);
259 260
    }
  }
261
  run_x = ME_PointFromCharContext( &c, &run->member.run, pCursor->nOffset, TRUE );
262 263

  *height = pSizeRun->member.run.nAscent + pSizeRun->member.run.nDescent;
264
  *x = c.rcView.left + run->member.run.pt.x + run_x - editor->horz_si.nPos;
265 266 267 268 269
  *y = c.rcView.top + para->member.para.pt.y + row->member.row.nBaseline
       + run->member.run.pt.y - pSizeRun->member.run.nAscent
       - editor->vert_si.nPos;
  ME_DestroyContext(&c);
  return;
270 271
}

272
void create_caret(ME_TextEditor *editor)
273 274 275 276
{
  int x, y, height;

  ME_GetCursorCoordinates(editor, &editor->pCursors[0], &x, &y, &height);
277 278 279
  ITextHost_TxCreateCaret(editor->texthost, NULL, 0, height);
  editor->caret_height = height;
  editor->caret_hidden = TRUE;
280 281
}

282 283 284 285 286
void show_caret(ME_TextEditor *editor)
{
  ITextHost_TxShowCaret(editor->texthost, TRUE);
  editor->caret_hidden = FALSE;
}
287

288
void hide_caret(ME_TextEditor *editor)
289
{
290 291 292 293 294 295
  /* calls to HideCaret are cumulative; do so only once */
  if (!editor->caret_hidden)
  {
    ITextHost_TxShowCaret(editor->texthost, FALSE);
    editor->caret_hidden = TRUE;
  }
296 297
}

298
void update_caret(ME_TextEditor *editor)
299
{
300 301 302 303
  int x, y, height;

  if (!editor->bHaveFocus) return;
  if (!ME_IsSelection(editor))
304
  {
305 306 307 308 309
    ME_GetCursorCoordinates(editor, &editor->pCursors[0], &x, &y, &height);
    if (height != editor->caret_height) create_caret(editor);
    x = min(x, editor->rcFormat.right-1);
    ITextHost_TxSetCaretPos(editor->texthost, x, y);
    show_caret(editor);
310
  }
311 312
  else
    hide_caret(editor);
313 314
}

315 316
BOOL ME_InternalDeleteText(ME_TextEditor *editor, ME_Cursor *start,
                           int nChars, BOOL bForce)
317
{
318
  ME_Cursor c = *start;
319
  int nOfs = ME_GetCursorOfs(start), text_len = ME_GetTextLength( editor );
320
  int shift = 0;
321
  int totalChars = nChars;
322
  ME_DisplayItem *start_para;
323
  BOOL delete_all = FALSE;
324

325
  /* Prevent deletion past last end of paragraph run. */
326 327
  nChars = min(nChars, text_len - nOfs);
  if (nChars == text_len) delete_all = TRUE;
328
  start_para = c.pPara;
329 330 331

  if (!bForce)
  {
332
    ME_ProtectPartialTableDeletion(editor, &c, &nChars);
333 334 335 336
    if (nChars == 0)
      return FALSE;
  }

337 338 339
  while(nChars > 0)
  {
    ME_Run *run;
340 341 342
    ME_CursorFromCharOfs(editor, nOfs+nChars, &c);
    if (!c.nOffset &&
        nOfs+nChars == (c.pRun->member.run.nCharOfs
343
                        + c.pPara->member.para.nCharOfs))
344 345 346
    {
      /* We aren't deleting anything in this run, so we will go back to the
       * last run we are deleting text in. */
347
      ME_PrevRun(&c.pPara, &c.pRun, TRUE);
348
      c.nOffset = c.pRun->member.run.len;
349
    }
350 351
    run = &c.pRun->member.run;
    if (run->nFlags & MERF_ENDPARA) {
352
      int eollen = c.pRun->member.run.len;
353
      BOOL keepFirstParaFormat;
354

355 356
      if (!ME_FindItemFwd(c.pRun, diParagraph))
      {
357
        return TRUE;
358
      }
359 360
      keepFirstParaFormat = (totalChars == nChars && nChars <= eollen &&
                             run->nCharOfs);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
      if (!editor->bEmulateVersion10) /* v4.1 */
      {
        ME_DisplayItem *next_para = ME_FindItemFwd(c.pRun, diParagraphOrEnd);
        ME_DisplayItem *this_para = next_para->member.para.prev_para;

        /* The end of paragraph before a table row is only deleted if there
         * is nothing else on the line before it. */
        if (this_para == start_para &&
            next_para->member.para.nFlags & MEPF_ROWSTART)
        {
          /* If the paragraph will be empty, then it should be deleted, however
           * it still might have text right now which would inherit the
           * MEPF_STARTROW property if we joined it right now.
           * Instead we will delete it after the preceding text is deleted. */
          if (nOfs > this_para->member.para.nCharOfs) {
            /* Skip this end of line. */
            nChars -= (eollen < nChars) ? eollen : nChars;
            continue;
          }
          keepFirstParaFormat = TRUE;
        }
      }
383
      ME_JoinParagraphs(editor, c.pPara, keepFirstParaFormat);
384 385
      /* ME_SkipAndPropagateCharOffset(p->pRun, shift); */
      ME_CheckCharOffsets(editor);
386
      nChars -= (eollen < nChars) ? eollen : nChars;
387 388 389 390 391
      continue;
    }
    else
    {
      ME_Cursor cursor;
392
      int nCharsToDelete = min(nChars, c.nOffset);
393
      int i;
394 395 396

      c.nOffset -= nCharsToDelete;

397
      mark_para_rewrap(editor, ME_FindItemBack(c.pRun, diParagraph));
398

399 400
      cursor = c;
      /* nChars is the number of characters that should be deleted from the
401
         PRECEDING runs (these BEFORE cursor.pRun)
402
         nCharsToDelete is a number of chars to delete from THIS run */
403
      nChars -= nCharsToDelete;
404
      shift -= nCharsToDelete;
405
      TRACE("Deleting %d (remaining %d) chars at %d in %s (%d)\n",
406
        nCharsToDelete, nChars, c.nOffset,
407
        debugstr_run( run ), run->len);
408

409 410
      /* nOfs is a character offset (from the start of the document
         to the current (deleted) run */
411
      add_undo_insert_run( editor, nOfs + nChars, get_text( run, c.nOffset ), nCharsToDelete, run->nFlags, run->style );
412

413
      ME_StrDeleteV(run->para->text, run->nCharOfs + c.nOffset, nCharsToDelete);
414 415 416
      run->len -= nCharsToDelete;
      TRACE("Post deletion string: %s (%d)\n", debugstr_run( run ), run->len);
      TRACE("Shift value: %d\n", shift);
417

418 419
      /* update cursors (including c) */
      for (i=-1; i<editor->nCursors; i++) {
420
        ME_Cursor *pThisCur = editor->pCursors + i;
421 422 423 424 425 426 427 428
        if (i == -1) pThisCur = &c;
        if (pThisCur->pRun == cursor.pRun) {
          if (pThisCur->nOffset > cursor.nOffset) {
            if (pThisCur->nOffset-cursor.nOffset < nCharsToDelete)
              pThisCur->nOffset = cursor.nOffset;
            else
              pThisCur->nOffset -= nCharsToDelete;
            assert(pThisCur->nOffset >= 0);
429
            assert(pThisCur->nOffset <= run->len);
430
          }
431
          if (pThisCur->nOffset == run->len)
432 433 434 435 436 437 438
          {
            pThisCur->pRun = ME_FindItemFwd(pThisCur->pRun, diRunOrParagraphOrEnd);
            assert(pThisCur->pRun->type == diRun);
            pThisCur->nOffset = 0;
          }
        }
      }
439

440
      /* c = updated data now */
441

442 443 444 445 446
      if (c.pRun == cursor.pRun)
        ME_SkipAndPropagateCharOffset(c.pRun, shift);
      else
        ME_PropagateCharOffset(c.pRun, shift);

447
      if (!cursor.pRun->member.run.len)
448
      {
449
        TRACE("Removing empty run\n");
450 451 452
        ME_Remove(cursor.pRun);
        ME_DestroyDisplayItem(cursor.pRun);
      }
453

454 455 456 457 458 459 460
      shift = 0;
      /*
      ME_CheckCharOffsets(editor);
      */
      continue;
    }
  }
461
  if (delete_all) ME_SetDefaultParaFormat( editor, &start_para->member.para.fmt );
462
  return TRUE;
463 464
}

465
BOOL ME_DeleteTextAtCursor(ME_TextEditor *editor, int nCursor, int nChars)
466
{
467
  assert(nCursor>=0 && nCursor<editor->nCursors);
468 469
  /* text operations set modified state */
  editor->nModifyStep = 1;
470
  return ME_InternalDeleteText(editor, &editor->pCursors[nCursor],
471
                               nChars, FALSE);
472 473
}

474
static ME_DisplayItem *
475 476 477 478 479 480 481 482 483 484
ME_InternalInsertTextFromCursor(ME_TextEditor *editor, int nCursor,
                                const WCHAR *str, int len, ME_Style *style,
                                int flags)
{
  ME_Cursor *p = &editor->pCursors[nCursor];

  editor->bCaretAtEnd = FALSE;
  
  assert(p->pRun->type == diRun);
  
485
  return ME_InsertRunAtCursor(editor, p, style, str, len, flags);
486 487
}

488 489 490 491 492 493 494 495 496
static struct re_object* create_re_object(const REOBJECT *reo)
{
  struct re_object *reobj = heap_alloc(sizeof(*reobj));

  if (!reobj)
  {
    WARN("Fail to allocate re_object.\n");
    return NULL;
  }
497
  ME_CopyReObject(&reobj->obj, reo, REO_GETOBJ_ALL_INTERFACES);
498 499
  return reobj;
}
500

501
void ME_InsertOLEFromCursor(ME_TextEditor *editor, const REOBJECT* reo, int nCursor)
502
{
503 504 505
  ME_Style              *pStyle = ME_GetInsertStyle(editor, nCursor);
  ME_DisplayItem        *di;
  WCHAR                 space = ' ';
506 507
  ME_DisplayItem        *di_prev = NULL;
  struct re_object      *reobj_prev = NULL;
508 509 510 511 512
  
  /* FIXME no no no */
  if (ME_IsSelection(editor))
    ME_DeleteSelection(editor);

513 514
  di = ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
                                       MERF_GRAPHICS);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  di->member.run.reobj = create_re_object(reo);

  di_prev = di;
  while (ME_PrevRun(NULL, &di_prev, TRUE))
  {
    if (di_prev->member.run.reobj)
    {
      reobj_prev = di_prev->member.run.reobj;
      break;
    }
  }
  if (reobj_prev)
    list_add_after(&reobj_prev->entry, &di->member.run.reobj->entry);
  else
    list_add_head(&editor->reobj_list, &di->member.run.reobj->entry);

531
  ME_ReleaseStyle(pStyle);
532 533 534
}


535 536 537 538 539 540 541 542 543
void ME_InsertEndRowFromCursor(ME_TextEditor *editor, int nCursor)
{
  ME_Style              *pStyle = ME_GetInsertStyle(editor, nCursor);
  WCHAR                 space = ' ';

  /* FIXME no no no */
  if (ME_IsSelection(editor))
    ME_DeleteSelection(editor);

544 545
  ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
                                  MERF_ENDROW);
546
  ME_ReleaseStyle(pStyle);
547 548
}

549

550 551 552 553 554
void ME_InsertTextFromCursor(ME_TextEditor *editor, int nCursor, 
  const WCHAR *str, int len, ME_Style *style)
{
  const WCHAR *pos;
  ME_Cursor *p = NULL;
555
  int oldLen;
556 557 558 559 560

  /* FIXME really HERE ? */
  if (ME_IsSelection(editor))
    ME_DeleteSelection(editor);

561 562
  /* FIXME: is this too slow? */
  /* Didn't affect performance for WM_SETTEXT (around 50sec/30K) */
563
  oldLen = ME_GetTextLength(editor);
564

565 566 567
  /* text operations set modified state */
  editor->nModifyStep = 1;

568 569 570 571 572
  assert(style);

  assert(nCursor>=0 && nCursor<editor->nCursors);
  if (len == -1)
    len = lstrlenW(str);
573 574 575 576 577

  /* grow the text limit to fit our text */
  if(editor->nTextLimit < oldLen +len)
    editor->nTextLimit = oldLen + len;

578 579
  pos = str;

580 581 582
  while (len)
  {
    /* FIXME this sucks - no respect for unicode (what else can be a line separator in unicode?) */
583
    while(pos - str < len && *pos != '\r' && *pos != '\n' && *pos != '\t')
584
      pos++;
585

586 587 588 589
    if (pos != str) { /* handle text */
      ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
    } else if (*pos == '\t') { /* handle tabs */
      WCHAR tab = '\t';
590 591
      ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, style, MERF_TAB);
      pos++;
592
    } else { /* handle EOLs */
593
      ME_DisplayItem *tp, *end_run, *run, *prev;
594
      int eol_len = 0;
595

596 597 598 599
      /* Check if new line is allowed for this control */
      if (!(editor->styleFlags & ES_MULTILINE))
        break;

600 601 602 603
      /* Find number of CR and LF in end of paragraph run */
      if (*pos =='\r')
      {
        if (len > 1 && pos[1] == '\n')
604
          eol_len = 2;
605
        else if (len > 2 && pos[1] == '\r' && pos[2] == '\n')
606 607 608
          eol_len = 3;
        else
          eol_len = 1;
609
      } else {
610
        assert(*pos == '\n');
611
        eol_len = 1;
612
      }
613
      pos += eol_len;
614

615
      if (!editor->bEmulateVersion10 && eol_len == 3)
616 617 618 619 620
      {
        /* handle special \r\r\n sequence (richedit 2.x and higher only) */
        WCHAR space = ' ';
        ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, style, 0);
      } else {
621
        const WCHAR cr = '\r', *eol_str = str;
622

623 624 625 626
        if (!editor->bEmulateVersion10)
        {
          eol_str = &cr;
          eol_len = 1;
627
        }
628 629

        p = &editor->pCursors[nCursor];
630 631 632 633 634 635 636 637 638 639 640 641

        if (p->nOffset == p->pRun->member.run.len)
        {
           run = ME_FindItemFwd( p->pRun, diRun );
           if (!run) run = p->pRun;
        }
        else
        {
          if (p->nOffset) ME_SplitRunSimple(editor, p);
          run = p->pRun;
        }

642
        tp = ME_SplitParagraph(editor, run, style, eol_str, eol_len, 0);
643

644
        end_run = ME_FindItemBack(tp, diRun);
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

        /* Move any cursors that were at the end of the previous run to the beginning of the new para */
        prev = ME_FindItemBack( end_run, diRun );
        if (prev)
        {
          int i;
          for (i = 0; i < editor->nCursors; i++)
          {
            if (editor->pCursors[i].pRun == prev &&
                editor->pCursors[i].nOffset == prev->member.run.len)
            {
              editor->pCursors[i].pPara = tp;
              editor->pCursors[i].pRun = run;
              editor->pCursors[i].nOffset = 0;
            }
          }
        }

663
      }
664
    }
665 666
    len -= pos - str;
    str = pos;
667 668 669
  }
}

670
/* Move the cursor nRelOfs characters (either forwards or backwards)
671
 * If final_eop is TRUE, allow moving the cursor to the end of the final eop.
672 673 674
 *
 * returns the actual number of characters moved.
 **/
675
int ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *cursor, int nRelOfs, BOOL final_eop)
676
{
677 678
  cursor->nOffset += nRelOfs;
  if (cursor->nOffset < 0)
679
  {
680 681
    cursor->nOffset += cursor->pRun->member.run.nCharOfs;
    if (cursor->nOffset >= 0)
682
    {
683
      /* new offset in the same paragraph */
684
      do {
685 686 687 688
        cursor->pRun = ME_FindItemBack(cursor->pRun, diRun);
      } while (cursor->nOffset < cursor->pRun->member.run.nCharOfs);
      cursor->nOffset -= cursor->pRun->member.run.nCharOfs;
      return nRelOfs;
689
    }
690

691 692
    cursor->nOffset += cursor->pPara->member.para.nCharOfs;
    if (cursor->nOffset <= 0)
693
    {
694 695 696 697 698
      /* moved to the start of the text */
      nRelOfs -= cursor->nOffset;
      ME_SetCursorToStart(editor, cursor);
      return nRelOfs;
    }
699

700 701 702 703 704 705 706 707 708 709 710
    /* new offset in a previous paragraph */
    do {
      cursor->pPara = cursor->pPara->member.para.prev_para;
    } while (cursor->nOffset < cursor->pPara->member.para.nCharOfs);
    cursor->nOffset -= cursor->pPara->member.para.nCharOfs;

    cursor->pRun = ME_FindItemBack(cursor->pPara->member.para.next_para, diRun);
    while (cursor->nOffset < cursor->pRun->member.run.nCharOfs) {
      cursor->pRun = ME_FindItemBack(cursor->pRun, diRun);
    }
    cursor->nOffset -= cursor->pRun->member.run.nCharOfs;
711
  } else if (cursor->nOffset >= cursor->pRun->member.run.len) {
712 713 714 715 716 717 718 719 720
    ME_DisplayItem *next_para;
    int new_offset;

    new_offset = ME_GetCursorOfs(cursor);
    next_para = cursor->pPara->member.para.next_para;
    if (new_offset < next_para->member.para.nCharOfs)
    {
      /* new offset in the same paragraph */
      do {
721
        cursor->nOffset -= cursor->pRun->member.run.len;
722
        cursor->pRun = ME_FindItemFwd(cursor->pRun, diRun);
723
      } while (cursor->nOffset >= cursor->pRun->member.run.len);
724
      return nRelOfs;
725
    }
726

727
    if (new_offset >= ME_GetTextLength(editor) + (final_eop ? 1 : 0))
728 729
    {
      /* new offset at the end of the text */
730 731
      ME_SetCursorToEnd(editor, cursor, final_eop);
      nRelOfs -= new_offset - (ME_GetTextLength(editor) + (final_eop ? 1 : 0));
732 733 734 735
      return nRelOfs;
    }

    /* new offset in a following paragraph */
736
    do {
737 738 739 740 741 742
      cursor->pPara = next_para;
      next_para = next_para->member.para.next_para;
    } while (new_offset >= next_para->member.para.nCharOfs);

    cursor->nOffset = new_offset - cursor->pPara->member.para.nCharOfs;
    cursor->pRun = ME_FindItemFwd(cursor->pPara, diRun);
743
    while (cursor->nOffset >= cursor->pRun->member.run.len)
744
    {
745
      cursor->nOffset -= cursor->pRun->member.run.len;
746
      cursor->pRun = ME_FindItemFwd(cursor->pRun, diRun);
747
    }
748 749
  } /* else new offset is in the same run */
  return nRelOfs;
750 751
}

752

753
BOOL
754 755 756
ME_MoveCursorWords(ME_TextEditor *editor, ME_Cursor *cursor, int nRelOfs)
{
  ME_DisplayItem *pRun = cursor->pRun, *pOtherRun;
757
  ME_DisplayItem *pPara = cursor->pPara;
758
  int nOffset = cursor->nOffset;
759

760 761 762 763 764
  if (nRelOfs == -1)
  {
    /* Backward movement */
    while (TRUE)
    {
765 766
      nOffset = ME_CallWordBreakProc(editor, get_text( &pRun->member.run, 0 ),
                                     pRun->member.run.len, nOffset, WB_MOVEWORDLEFT);
767
      if (nOffset)
768 769 770 771
        break;
      pOtherRun = ME_FindItemBack(pRun, diRunOrParagraph);
      if (pOtherRun->type == diRun)
      {
772 773
        if (ME_CallWordBreakProc(editor, get_text( &pOtherRun->member.run, 0 ),
                                 pOtherRun->member.run.len,
774
                                 pOtherRun->member.run.len - 1,
775 776 777
                                 WB_ISDELIMITER)
            && !(pRun->member.run.nFlags & MERF_ENDPARA)
            && !(cursor->pRun == pRun && cursor->nOffset == 0)
778 779
            && !ME_CallWordBreakProc(editor, get_text( &pRun->member.run, 0 ),
                                     pRun->member.run.len, 0,
780 781 782
                                     WB_ISDELIMITER))
          break;
        pRun = pOtherRun;
783
        nOffset = pOtherRun->member.run.len;
784 785 786 787 788
      }
      else if (pOtherRun->type == diParagraph)
      {
        if (cursor->pRun == pRun && cursor->nOffset == 0)
        {
789
          pPara = pOtherRun;
790
          /* Skip empty start of table row paragraph */
791 792
          if (pPara->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART)
            pPara = pPara->member.para.prev_para;
793
          /* Paragraph breaks are treated as separate words */
794
          if (pPara->member.para.prev_para->type == diTextStart)
795
            return FALSE;
796

797
          pRun = ME_FindItemBack(pPara, diRun);
798
          pPara = pPara->member.para.prev_para;
799 800 801 802 803 804 805 806 807 808 809 810
        }
        break;
      }
    }
  }
  else
  {
    /* Forward movement */
    BOOL last_delim = FALSE;
    
    while (TRUE)
    {
811 812
      if (last_delim && !ME_CallWordBreakProc(editor, get_text( &pRun->member.run, 0 ),
                                              pRun->member.run.len, nOffset, WB_ISDELIMITER))
813
        break;
814 815
      nOffset = ME_CallWordBreakProc(editor, get_text( &pRun->member.run, 0 ),
                                     pRun->member.run.len, nOffset, WB_MOVEWORDRIGHT);
816
      if (nOffset < pRun->member.run.len)
817 818 819 820
        break;
      pOtherRun = ME_FindItemFwd(pRun, diRunOrParagraphOrEnd);
      if (pOtherRun->type == diRun)
      {
821 822
        last_delim = ME_CallWordBreakProc(editor, get_text( &pRun->member.run, 0 ),
                                          pRun->member.run.len, nOffset - 1, WB_ISDELIMITER);
823 824 825 826 827
        pRun = pOtherRun;
        nOffset = 0;
      }
      else if (pOtherRun->type == diParagraph)
      {
828 829
        if (pOtherRun->member.para.nFlags & MEPF_ROWSTART)
            pOtherRun = pOtherRun->member.para.next_para;
830 831 832 833
        if (cursor->pRun == pRun) {
          pPara = pOtherRun;
          pRun = ME_FindItemFwd(pPara, diRun);
        }
834 835 836 837 838 839 840 841 842 843 844 845
        nOffset = 0;
        break;
      }
      else /* diTextEnd */
      {
        if (cursor->pRun == pRun)
          return FALSE;
        nOffset = 0;
        break;
      }
    }
  }
846
  cursor->pPara = pPara;
847 848 849 850
  cursor->pRun = pRun;
  cursor->nOffset = nOffset;
  return TRUE;
}
851

852

853
static void
854
ME_SelectByType(ME_TextEditor *editor, ME_SelectionType selectionType)
855
{
856 857
  /* pCursor[0] is the end of the selection
   * pCursor[1] is the start of the selection (or the position selection anchor)
858 859 860 861 862 863 864 865 866 867
   * pCursor[2] and [3] are the selection anchors that are backed up
   * so they are kept when the selection changes for drag selection.
   */

  editor->nSelectionType = selectionType;
  switch(selectionType)
  {
    case stPosition:
      break;
    case stWord:
868 869 870
      ME_MoveCursorWords(editor, &editor->pCursors[0], +1);
      editor->pCursors[1] = editor->pCursors[0];
      ME_MoveCursorWords(editor, &editor->pCursors[1], -1);
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
      break;
    case stLine:
    case stParagraph:
    {
      ME_DisplayItem *pItem;
      ME_DIType fwdSearchType, backSearchType;
      if (selectionType == stParagraph) {
          backSearchType = diParagraph;
          fwdSearchType = diParagraphOrEnd;
      } else {
          backSearchType = diStartRow;
          fwdSearchType = diStartRowOrParagraphOrEnd;
      }
      pItem = ME_FindItemFwd(editor->pCursors[0].pRun, fwdSearchType);
      assert(pItem);
      if (pItem->type == diTextEnd)
887
          editor->pCursors[0].pRun = ME_FindItemBack(pItem, diRun);
888
      else
889
          editor->pCursors[0].pRun = ME_FindItemFwd(pItem, diRun);
890
      editor->pCursors[0].pPara = ME_GetParagraph(editor->pCursors[0].pRun);
891 892 893 894
      editor->pCursors[0].nOffset = 0;

      pItem = ME_FindItemBack(pItem, backSearchType);
      editor->pCursors[1].pRun = ME_FindItemFwd(pItem, diRun);
895
      editor->pCursors[1].pPara = ME_GetParagraph(editor->pCursors[1].pRun);
896 897 898
      editor->pCursors[1].nOffset = 0;
      break;
    }
899 900 901
    case stDocument:
      /* Select everything with cursor anchored from the start of the text */
      editor->nSelectionType = stDocument;
902
      ME_SetCursorToStart(editor, &editor->pCursors[1]);
903
      ME_SetCursorToEnd(editor, &editor->pCursors[0], FALSE);
904
      break;
905 906 907 908 909
    default: assert(0);
  }
  /* Store the anchor positions for extending the selection. */
  editor->pCursors[2] = editor->pCursors[0];
  editor->pCursors[3] = editor->pCursors[1];
910 911
}

912
int ME_GetCursorOfs(const ME_Cursor *cursor)
913
{
914 915
  return cursor->pPara->member.para.nCharOfs
         + cursor->pRun->member.run.nCharOfs + cursor->nOffset;
916 917
}

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
/* Helper function for ME_FindPixelPos to find paragraph within tables */
static ME_DisplayItem* ME_FindPixelPosInTableRow(int x, int y,
                                                 ME_DisplayItem *para)
{
  ME_DisplayItem *cell, *next_cell;
  assert(para->member.para.nFlags & MEPF_ROWSTART);
  cell = para->member.para.next_para->member.para.pCell;
  assert(cell);

  /* find the cell we are in */
  while ((next_cell = cell->member.cell.next_cell) != NULL) {
    if (x < next_cell->member.cell.pt.x)
    {
      para = ME_FindItemFwd(cell, diParagraph);
      /* Found the cell, but there might be multiple paragraphs in
       * the cell, so need to search down the cell for the paragraph. */
      while (cell == para->member.para.pCell) {
        if (y < para->member.para.pt.y + para->member.para.nHeight)
        {
          if (para->member.para.nFlags & MEPF_ROWSTART)
            return ME_FindPixelPosInTableRow(x, y, para);
          else
            return para;
        }
        para = para->member.para.next_para;
      }
      /* Past the end of the cell, so go back to the last cell paragraph */
      return para->member.para.prev_para;
    }
    cell = next_cell;
  }
  /* Return table row delimiter */
  para = ME_FindItemFwd(cell, diParagraph);
  assert(para->member.para.nFlags & MEPF_ROWEND);
952 953
  assert(para->member.para.fmt.dwMask & PFM_TABLEROWDELIMITER);
  assert(para->member.para.fmt.wEffects & PFE_TABLEROWDELIMITER);
954 955 956
  return para;
}

957
static BOOL ME_FindRunInRow(ME_TextEditor *editor, ME_DisplayItem *pRow,
958
                            int x, ME_Cursor *cursor, BOOL *pbCaretAtEnd)
959
{
960
  ME_DisplayItem *pNext, *pLastRun;
961 962 963 964 965 966 967 968
  ME_Row *row = &pRow->member.row;
  BOOL exact = TRUE;

  if (x < row->pt.x)
  {
      x = row->pt.x;
      exact = FALSE;
  }
969 970 971 972 973 974 975
  pNext = ME_FindItemFwd(pRow, diRunOrStartRow);
  assert(pNext->type == diRun);
  if (pbCaretAtEnd) *pbCaretAtEnd = FALSE;
  cursor->nOffset = 0;
  do {
    int run_x = pNext->member.run.pt.x;
    int width = pNext->member.run.nWidth;
976

977 978
    if (x >= run_x && x < run_x+width)
    {
979
      cursor->nOffset = ME_CharFromPoint(editor, x-run_x, &pNext->member.run, TRUE, TRUE);
980 981
      cursor->pRun = pNext;
      cursor->pPara = ME_GetParagraph( cursor->pRun );
982
      return exact;
983 984 985 986 987 988
    }
    pLastRun = pNext;
    pNext = ME_FindItemFwd(pNext, diRunOrStartRow);
  } while(pNext && pNext->type == diRun);

  if ((pLastRun->member.run.nFlags & MERF_ENDPARA) == 0)
989
  {
990 991
    cursor->pRun = ME_FindItemFwd(pNext, diRun);
    if (pbCaretAtEnd) *pbCaretAtEnd = TRUE;
992
  }
993 994 995 996 997
  else
    cursor->pRun = pLastRun;

  cursor->pPara = ME_GetParagraph( cursor->pRun );
  return FALSE;
998 999
}

1000 1001 1002 1003 1004
/* Finds the run and offset from the pixel position.
 *
 * x & y are pixel positions in virtual coordinates into the rich edit control,
 * so client coordinates must first be adjusted by the scroll position.
 *
1005 1006
 * If final_eop is TRUE consider the final end-of-paragraph.
 *
1007 1008 1009 1010
 * returns TRUE if the result was exactly under the cursor, otherwise returns
 * FALSE, and result is set to the closest position to the coordinates.
 */
static BOOL ME_FindPixelPos(ME_TextEditor *editor, int x, int y,
1011
                            ME_Cursor *result, BOOL *is_eol, BOOL final_eop)
1012 1013
{
  ME_DisplayItem *p = editor->pBuffer->pFirst->member.para.next_para;
1014
  BOOL isExact = TRUE;
1015

1016 1017 1018
  x -= editor->rcFormat.left;
  y -= editor->rcFormat.top;

1019
  if (is_eol)
1020
    *is_eol = FALSE;
1021

1022 1023
  /* find paragraph */
  for (; p != editor->pBuffer->pLast; p = p->member.para.next_para)
1024
  {
1025
    assert(p->type == diParagraph);
1026
    if (y < p->member.para.pt.y + p->member.para.nHeight)
1027
    {
1028 1029 1030
      if (p->member.para.nFlags & MEPF_ROWSTART)
        p = ME_FindPixelPosInTableRow(x, y, p);
      y -= p->member.para.pt.y;
1031
      p = ME_FindItemFwd(p, diStartRow);
1032
      break;
1033 1034
    } else if (p->member.para.nFlags & MEPF_ROWSTART) {
      p = ME_GetTableRowEnd(p);
1035
    }
1036 1037 1038 1039 1040 1041
  }
  /* find row */
  for (; p != editor->pBuffer->pLast; )
  {
    ME_DisplayItem *pp;
    assert(p->type == diStartRow);
1042
    if (y < p->member.row.pt.y + p->member.row.nHeight) break;
1043
    pp = ME_FindItemFwd(p, diStartRow);
1044
    if (!pp) break;
1045 1046
    p = pp;
  }
1047
  if (p == editor->pBuffer->pLast && !final_eop)
1048 1049 1050 1051
  {
    /* The position is below the last paragraph, so the last row will be used
     * rather than the end of the text, so the x position will be used to
     * determine the offset closest to the pixel position. */
1052
    isExact = FALSE;
1053
    p = ME_FindItemBack(p, diStartRow);
1054
    if (!p) p = editor->pBuffer->pLast;
1055
  }
1056 1057 1058 1059 1060 1061

  assert( p->type == diStartRow || p == editor->pBuffer->pLast );

  if( p->type == diStartRow )
      return ME_FindRunInRow( editor, p, x, result, is_eol ) && isExact;

1062
  ME_SetCursorToEnd(editor, result, TRUE);
1063
  return FALSE;
1064 1065
}

1066

1067
/* Sets the cursor to the position closest to the pixel position
1068 1069 1070 1071 1072
 *
 * x & y are pixel positions in client coordinates.
 *
 * isExact will be set to TRUE if the run is directly under the pixel
 * position, FALSE if it not, unless isExact is set to NULL.
1073 1074 1075
 *
 * return FALSE if outside client area and the cursor is not set,
 * otherwise TRUE is returned.
1076
 */
1077 1078
BOOL ME_CharFromPos(ME_TextEditor *editor, int x, int y,
                    ME_Cursor *cursor, BOOL *isExact)
1079 1080
{
  RECT rc;
1081
  BOOL bResult;
1082

1083
  ITextHost_TxGetClientRect(editor->texthost, &rc);
1084 1085
  if (x < 0 || y < 0 || x >= rc.right || y >= rc.bottom) {
    if (isExact) *isExact = FALSE;
1086
    return FALSE;
1087
  }
1088 1089
  x += editor->horz_si.nPos;
  y += editor->vert_si.nPos;
1090
  bResult = ME_FindPixelPos(editor, x, y, cursor, NULL, FALSE);
1091
  if (isExact) *isExact = bResult;
1092
  return TRUE;
1093 1094
}

1095 1096


1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
/* Extends the selection with a word, line, or paragraph selection type.
 *
 * The selection is anchored by editor->pCursors[2-3] such that the text
 * between the anchors will remain selected, and one end will be extended.
 *
 * editor->pCursors[0] should have the position to extend the selection to
 * before this function is called.
 *
 * Nothing will be done if editor->nSelectionType equals stPosition.
 */
static void ME_ExtendAnchorSelection(ME_TextEditor *editor)
{
  ME_Cursor tmp_cursor;
  int curOfs, anchorStartOfs, anchorEndOfs;
1111
  if (editor->nSelectionType == stPosition || editor->nSelectionType == stDocument)
1112
      return;
1113 1114 1115
  curOfs = ME_GetCursorOfs(&editor->pCursors[0]);
  anchorStartOfs = ME_GetCursorOfs(&editor->pCursors[3]);
  anchorEndOfs = ME_GetCursorOfs(&editor->pCursors[2]);
1116 1117 1118 1119 1120 1121 1122

  tmp_cursor = editor->pCursors[0];
  editor->pCursors[0] = editor->pCursors[2];
  editor->pCursors[1] = editor->pCursors[3];
  if (curOfs < anchorStartOfs)
  {
      /* Extend the left side of selection */
1123
      editor->pCursors[1] = tmp_cursor;
1124
      if (editor->nSelectionType == stWord)
1125
          ME_MoveCursorWords(editor, &editor->pCursors[1], -1);
1126 1127 1128
      else
      {
          ME_DisplayItem *pItem;
1129 1130
          ME_DIType searchType = ((editor->nSelectionType == stLine) ?
                                  diStartRowOrParagraph:diParagraph);
1131 1132
          pItem = ME_FindItemBack(editor->pCursors[1].pRun, searchType);
          editor->pCursors[1].pRun = ME_FindItemFwd(pItem, diRun);
1133
          editor->pCursors[1].pPara = ME_GetParagraph(editor->pCursors[1].pRun);
1134
          editor->pCursors[1].nOffset = 0;
1135 1136 1137 1138 1139
      }
  }
  else if (curOfs >= anchorEndOfs)
  {
      /* Extend the right side of selection */
1140
      editor->pCursors[0] = tmp_cursor;
1141
      if (editor->nSelectionType == stWord)
1142
          ME_MoveCursorWords(editor, &editor->pCursors[0], +1);
1143 1144 1145
      else
      {
          ME_DisplayItem *pItem;
1146 1147
          ME_DIType searchType = ((editor->nSelectionType == stLine) ?
                                  diStartRowOrParagraphOrEnd:diParagraphOrEnd);
1148
          pItem = ME_FindItemFwd(editor->pCursors[0].pRun, searchType);
1149
          if (pItem->type == diTextEnd)
1150
              editor->pCursors[0].pRun = ME_FindItemBack(pItem, diRun);
1151
          else
1152
              editor->pCursors[0].pRun = ME_FindItemFwd(pItem, diRun);
1153
          editor->pCursors[0].pPara = ME_GetParagraph(editor->pCursors[0].pRun);
1154
          editor->pCursors[0].nOffset = 0;
1155 1156 1157
      }
  }
}
1158

1159
void ME_LButtonDown(ME_TextEditor *editor, int x, int y, int clickNum)
1160 1161
{
  ME_Cursor tmp_cursor;
1162
  BOOL is_selection = FALSE, is_shift;
1163

1164
  editor->nUDArrowX = -1;
1165 1166 1167

  x += editor->horz_si.nPos;
  y += editor->vert_si.nPos;
1168 1169 1170

  tmp_cursor = editor->pCursors[0];
  is_selection = ME_IsSelection(editor);
1171
  is_shift = GetKeyState(VK_SHIFT) < 0;
1172

1173
  ME_FindPixelPos(editor, x, y, &editor->pCursors[0], &editor->bCaretAtEnd, FALSE);
1174

1175
  if (x >= editor->rcFormat.left || is_shift)
1176
  {
1177 1178 1179
    if (clickNum > 1)
    {
      editor->pCursors[1] = editor->pCursors[0];
1180
      if (is_shift) {
1181
          if (x >= editor->rcFormat.left)
1182 1183 1184 1185
              ME_SelectByType(editor, stWord);
          else
              ME_SelectByType(editor, stParagraph);
      } else if (clickNum % 2 == 0) {
1186
          ME_SelectByType(editor, stWord);
1187
      } else {
1188
          ME_SelectByType(editor, stParagraph);
1189
      }
1190
    }
1191
    else if (!is_shift)
1192
    {
1193
      editor->nSelectionType = stPosition;
1194 1195
      editor->pCursors[1] = editor->pCursors[0];
    }
1196 1197 1198
    else if (!is_selection)
    {
      editor->nSelectionType = stPosition;
1199
      editor->pCursors[1] = tmp_cursor;
1200 1201 1202 1203
    }
    else if (editor->nSelectionType != stPosition)
    {
      ME_ExtendAnchorSelection(editor);
1204
    }
1205 1206 1207
  }
  else
  {
1208 1209
    if (clickNum < 2) {
        ME_SelectByType(editor, stLine);
1210
    } else if (clickNum % 2 == 0 || is_shift) {
1211
        ME_SelectByType(editor, stParagraph);
1212 1213
    } else {
        ME_SelectByType(editor, stDocument);
1214
    }
1215
  }
1216
  ME_InvalidateSelection(editor);
1217
  update_caret(editor);
1218
  ME_SendSelChange(editor);
1219 1220 1221 1222 1223
}

void ME_MouseMove(ME_TextEditor *editor, int x, int y)
{
  ME_Cursor tmp_cursor;
1224

1225 1226
  if (editor->nSelectionType == stDocument)
      return;
1227 1228
  x += editor->horz_si.nPos;
  y += editor->vert_si.nPos;
1229 1230

  tmp_cursor = editor->pCursors[0];
1231
  /* FIXME: do something with the return value of ME_FindPixelPos */
1232
  ME_FindPixelPos(editor, x, y, &tmp_cursor, &editor->bCaretAtEnd, TRUE);
1233

1234
  ME_InvalidateSelection(editor);
1235 1236 1237 1238 1239
  editor->pCursors[0] = tmp_cursor;
  ME_ExtendAnchorSelection(editor);

  if (editor->nSelectionType != stPosition &&
      memcmp(&editor->pCursors[1], &editor->pCursors[3], sizeof(ME_Cursor)))
1240
  {
1241
      /* The scroll the cursor towards the other end, since it was the one
1242
       * extended by ME_ExtendAnchorSelection */
1243
      ME_EnsureVisible(editor, &editor->pCursors[1]);
1244
  } else {
1245
      ME_EnsureVisible(editor, &editor->pCursors[0]);
1246 1247
  }

1248
  ME_InvalidateSelection(editor);
1249
  update_caret(editor);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  ME_SendSelChange(editor);
}

static int ME_GetXForArrow(ME_TextEditor *editor, ME_Cursor *pCursor)
{
  ME_DisplayItem *pRun = pCursor->pRun;
  int x;

  if (editor->nUDArrowX != -1)
    x = editor->nUDArrowX;
  else {
    if (editor->bCaretAtEnd)
    {
      pRun = ME_FindItemBack(pRun, diRun);
      assert(pRun);
      x = pRun->member.run.pt.x + pRun->member.run.nWidth;
    }
    else {
      x = pRun->member.run.pt.x;
1269
      x += ME_PointFromChar(editor, &pRun->member.run, pCursor->nOffset, TRUE);
1270 1271 1272 1273 1274 1275
    }
    editor->nUDArrowX = x;
  }
  return x;
}

1276 1277

static void
1278
ME_MoveCursorLines(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs, BOOL extend)
1279 1280
{
  ME_DisplayItem *pRun = pCursor->pRun;
1281 1282
  ME_DisplayItem *pOldPara = pCursor->pPara;
  ME_DisplayItem *pItem, *pNewPara;
1283
  int x = ME_GetXForArrow(editor, pCursor);
1284

1285
  if (editor->bCaretAtEnd && !pCursor->nOffset)
1286
    if (!ME_PrevRun(&pOldPara, &pRun, TRUE))
1287 1288
      return;

1289
  if (nRelOfs == -1)
1290
  {
1291 1292 1293 1294 1295
    /* start of this row */
    pItem = ME_FindItemBack(pRun, diStartRow);
    assert(pItem);
    /* start of the previous row */
    pItem = ME_FindItemBack(pItem, diStartRow);
1296 1297 1298 1299 1300 1301
    if (!pItem) /* row not found */
    {
      if (extend)
        ME_SetCursorToStart(editor, pCursor);
      return;
    }
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    pNewPara = ME_GetParagraph(pItem);
    if (pOldPara->member.para.nFlags & MEPF_ROWEND ||
        (pOldPara->member.para.pCell &&
         pOldPara->member.para.pCell != pNewPara->member.para.pCell))
    {
      /* Brought out of a cell */
      pNewPara = ME_GetTableRowStart(pOldPara)->member.para.prev_para;
      if (pNewPara->type == diTextStart)
        return; /* At the top, so don't go anywhere. */
      pItem = ME_FindItemFwd(pNewPara, diStartRow);
    }
    if (pNewPara->member.para.nFlags & MEPF_ROWEND)
    {
      /* Brought into a table row */
      ME_Cell *cell = &ME_FindItemBack(pNewPara, diCell)->member.cell;
      while (x < cell->pt.x && cell->prev_cell)
        cell = &cell->prev_cell->member.cell;
      if (cell->next_cell) /* else - we are still at the end of the row */
        pItem = ME_FindItemBack(cell->next_cell, diStartRow);
    }
1322 1323 1324 1325 1326
  }
  else
  {
    /* start of the next row */
    pItem = ME_FindItemFwd(pRun, diStartRow);
1327 1328 1329 1330 1331 1332
    if (!pItem) /* row not found */
    {
      if (extend)
        ME_SetCursorToEnd(editor, pCursor, TRUE);
      return;
    }
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
    pNewPara = ME_GetParagraph(pItem);
    if (pOldPara->member.para.nFlags & MEPF_ROWSTART ||
        (pOldPara->member.para.pCell &&
         pOldPara->member.para.pCell != pNewPara->member.para.pCell))
    {
      /* Brought out of a cell */
      pNewPara = ME_GetTableRowEnd(pOldPara)->member.para.next_para;
      if (pNewPara->type == diTextEnd)
        return; /* At the bottom, so don't go anywhere. */
      pItem = ME_FindItemFwd(pNewPara, diStartRow);
    }
    if (pNewPara->member.para.nFlags & MEPF_ROWSTART)
    {
      /* Brought into a table row */
      ME_DisplayItem *cell = ME_FindItemFwd(pNewPara, diCell);
      while (cell->member.cell.next_cell &&
             x >= cell->member.cell.next_cell->member.cell.pt.x)
        cell = cell->member.cell.next_cell;
      pItem = ME_FindItemFwd(cell, diStartRow);
    }
1353 1354 1355
  }
  if (!pItem)
  {
1356
    /* row not found - ignore */
1357 1358
    return;
  }
1359
  ME_FindRunInRow(editor, pItem, x, pCursor, &editor->bCaretAtEnd);
1360 1361 1362 1363
  assert(pCursor->pRun);
  assert(pCursor->pRun->type == diRun);
}

1364
static void ME_ArrowPageUp(ME_TextEditor *editor, ME_Cursor *pCursor)
1365
{
1366
  ME_DisplayItem *p = ME_FindItemFwd(editor->pBuffer->pFirst, diStartRow);
1367

1368
  if (editor->vert_si.nPos < p->member.row.nHeight)
1369
  {
1370
    ME_SetCursorToStart(editor, pCursor);
1371 1372 1373 1374 1375 1376 1377 1378
    editor->bCaretAtEnd = FALSE;
    /* Native clears seems to clear this x value on page up at the top
     * of the text, but not on page down at the end of the text.
     * Doesn't make sense, but we try to be bug for bug compatible. */
    editor->nUDArrowX = -1;
  } else {
    ME_DisplayItem *pRun = pCursor->pRun;
    ME_DisplayItem *pLast;
1379
    int x, y, yd, yp;
1380
    int yOldScrollPos = editor->vert_si.nPos;
1381

1382 1383 1384
    x = ME_GetXForArrow(editor, pCursor);
    if (!pCursor->nOffset && editor->bCaretAtEnd)
      pRun = ME_FindItemBack(pRun, diRun);
1385

1386 1387 1388
    p = ME_FindItemBack(pRun, diStartRowOrParagraph);
    assert(p->type == diStartRow);
    yp = ME_FindItemBack(p, diParagraph)->member.para.pt.y;
1389
    y = yp + p->member.row.pt.y;
1390

1391 1392 1393 1394
    ME_ScrollUp(editor, editor->sizeWindow.cy);
    /* Only move the cursor by the amount scrolled. */
    yd = y + editor->vert_si.nPos - yOldScrollPos;
    pLast = p;
1395

1396 1397 1398
    do {
      p = ME_FindItemBack(p, diStartRowOrParagraph);
      if (!p)
1399
        break;
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
      if (p->type == diParagraph) { /* crossing paragraphs */
        if (p->member.para.prev_para == NULL)
          break;
        yp = p->member.para.prev_para->member.para.pt.y;
        continue;
      }
      y = yp + p->member.row.pt.y;
      if (y < yd)
        break;
      pLast = p;
    } while(1);
1411

1412
    ME_FindRunInRow(editor, pLast, x, pCursor, &editor->bCaretAtEnd);
1413 1414 1415 1416 1417
  }
  assert(pCursor->pRun);
  assert(pCursor->pRun->type == diRun);
}

1418
static void ME_ArrowPageDown(ME_TextEditor *editor, ME_Cursor *pCursor)
1419
{
1420 1421 1422 1423 1424 1425 1426
  ME_DisplayItem *pLast;
  int x, y;

  /* Find y position of the last row */
  pLast = editor->pBuffer->pLast;
  y = pLast->member.para.prev_para->member.para.pt.y
      + ME_FindItemBack(pLast, diStartRow)->member.row.pt.y;
1427

1428
  x = ME_GetXForArrow(editor, pCursor);
1429

1430 1431
  if (editor->vert_si.nPos >= y - editor->sizeWindow.cy)
  {
1432
    ME_SetCursorToEnd(editor, pCursor, FALSE);
1433 1434 1435 1436
    editor->bCaretAtEnd = FALSE;
  } else {
    ME_DisplayItem *pRun = pCursor->pRun;
    ME_DisplayItem *p;
1437
    int yd, yp;
1438
    int yOldScrollPos = editor->vert_si.nPos;
1439

1440 1441 1442 1443 1444 1445
    if (!pCursor->nOffset && editor->bCaretAtEnd)
      pRun = ME_FindItemBack(pRun, diRun);

    p = ME_FindItemBack(pRun, diStartRowOrParagraph);
    assert(p->type == diStartRow);
    yp = ME_FindItemBack(p, diParagraph)->member.para.pt.y;
1446
    y = yp + p->member.row.pt.y;
1447 1448 1449 1450 1451 1452 1453

    /* For native richedit controls:
     * v1.0 - v3.1 can only scroll down as far as the scrollbar lets us
     * v4.1 can scroll past this position here. */
    ME_ScrollDown(editor, editor->sizeWindow.cy);
    /* Only move the cursor by the amount scrolled. */
    yd = y + editor->vert_si.nPos - yOldScrollPos;
1454
    pLast = p;
1455

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    do {
      p = ME_FindItemFwd(p, diStartRowOrParagraph);
      if (!p)
        break;
      if (p->type == diParagraph) {
        yp = p->member.para.pt.y;
        continue;
      }
      y = yp + p->member.row.pt.y;
      if (y >= yd)
        break;
      pLast = p;
    } while(1);

1470
    ME_FindRunInRow(editor, pLast, x, pCursor, &editor->bCaretAtEnd);
1471 1472 1473 1474 1475
  }
  assert(pCursor->pRun);
  assert(pCursor->pRun->type == diRun);
}

1476
static void ME_ArrowHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
{
  ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diStartRow);
  if (pRow) {
    ME_DisplayItem *pRun;
    if (editor->bCaretAtEnd && !pCursor->nOffset) {
      pRow = ME_FindItemBack(pRow, diStartRow);
      if (!pRow)
        return;
    }
    pRun = ME_FindItemFwd(pRow, diRun);
    if (pRun) {
      pCursor->pRun = pRun;
1489
      assert(pCursor->pPara == ME_GetParagraph(pRun));
1490 1491 1492 1493 1494 1495
      pCursor->nOffset = 0;
    }
  }
  editor->bCaretAtEnd = FALSE;
}

1496
static void ME_ArrowCtrlHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1497
{
1498
  ME_SetCursorToStart(editor, pCursor);
1499
  editor->bCaretAtEnd = FALSE;
1500 1501
}

1502
static void ME_ArrowEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1503 1504
{
  ME_DisplayItem *pRow;
1505

1506 1507
  if (editor->bCaretAtEnd && !pCursor->nOffset)
    return;
1508

1509 1510 1511 1512 1513 1514
  pRow = ME_FindItemFwd(pCursor->pRun, diStartRowOrParagraphOrEnd);
  assert(pRow);
  if (pRow->type == diStartRow) {
    ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
    assert(pRun);
    pCursor->pRun = pRun;
1515
    assert(pCursor->pPara == ME_GetParagraph(pCursor->pRun));
1516
    pCursor->nOffset = 0;
1517
    editor->bCaretAtEnd = TRUE;
1518 1519 1520 1521
    return;
  }
  pCursor->pRun = ME_FindItemBack(pRow, diRun);
  assert(pCursor->pRun && pCursor->pRun->member.run.nFlags & MERF_ENDPARA);
1522
  assert(pCursor->pPara == ME_GetParagraph(pCursor->pRun));
1523 1524 1525
  pCursor->nOffset = 0;
  editor->bCaretAtEnd = FALSE;
}
1526

1527
static void ME_ArrowCtrlEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1528
{
1529
  ME_SetCursorToEnd(editor, pCursor, FALSE);
1530 1531 1532 1533 1534
  editor->bCaretAtEnd = FALSE;
}

BOOL ME_IsSelection(ME_TextEditor *editor)
{
1535 1536
  return editor->pCursors[0].pRun != editor->pCursors[1].pRun ||
         editor->pCursors[0].nOffset != editor->pCursors[1].nOffset;
1537 1538 1539 1540 1541
}

void ME_DeleteSelection(ME_TextEditor *editor)
{
  int from, to;
1542
  int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
1543
  int nEndCursor = nStartCursor ^ 1;
1544
  ME_DeleteTextAtCursor(editor, nStartCursor, to - from);
1545
  editor->pCursors[nEndCursor] = editor->pCursors[nStartCursor];
1546 1547
}

1548 1549
ME_Style *ME_GetSelectionInsertStyle(ME_TextEditor *editor)
{
1550
  return ME_GetInsertStyle(editor, 0);
1551 1552
}

1553 1554 1555
void ME_SendSelChange(ME_TextEditor *editor)
{
  SELCHANGE sc;
1556

1557 1558
  sc.nmhdr.hwndFrom = NULL;
  sc.nmhdr.idFrom = 0;
1559
  sc.nmhdr.code = EN_SELCHANGE;
1560
  ME_GetSelectionOfs(editor, &sc.chrg.cpMin, &sc.chrg.cpMax);
1561 1562 1563
  sc.seltyp = SEL_EMPTY;
  if (sc.chrg.cpMin != sc.chrg.cpMax)
    sc.seltyp |= SEL_TEXT;
1564
  if (sc.chrg.cpMin < sc.chrg.cpMax+1) /* what were RICHEDIT authors thinking ? */
1565
    sc.seltyp |= SEL_MULTICHAR;
1566

1567 1568
  if (sc.chrg.cpMin != editor->notified_cr.cpMin || sc.chrg.cpMax != editor->notified_cr.cpMax)
  {
1569 1570
    ME_ClearTempStyle(editor);

1571
    editor->notified_cr = sc.chrg;
1572 1573 1574 1575 1576 1577 1578 1579 1580

    if (editor->nEventMask & ENM_SELCHANGE)
    {
      TRACE("cpMin=%d cpMax=%d seltyp=%d (%s %s)\n",
            sc.chrg.cpMin, sc.chrg.cpMax, sc.seltyp,
            (sc.seltyp & SEL_TEXT) ? "SEL_TEXT" : "",
            (sc.seltyp & SEL_MULTICHAR) ? "SEL_MULTICHAR" : "");
      ITextHost_TxNotify(editor->texthost, sc.nmhdr.code, &sc);
    }
1581
  }
1582 1583
}

1584
BOOL
1585
ME_ArrowKey(ME_TextEditor *editor, int nVKey, BOOL extend, BOOL ctrl)
1586 1587 1588 1589
{
  int nCursor = 0;
  ME_Cursor *p = &editor->pCursors[nCursor];
  ME_Cursor tmp_curs = *p;
1590
  BOOL success = FALSE;
1591

1592
  ME_CheckCharOffsets(editor);
1593
  switch(nVKey) {
1594
    case VK_LEFT:
1595
      editor->bCaretAtEnd = FALSE;
1596 1597 1598
      if (ctrl)
        success = ME_MoveCursorWords(editor, &tmp_curs, -1);
      else
1599
        success = ME_MoveCursorChars(editor, &tmp_curs, -1, extend);
1600 1601
      break;
    case VK_RIGHT:
1602
      editor->bCaretAtEnd = FALSE;
1603 1604 1605
      if (ctrl)
        success = ME_MoveCursorWords(editor, &tmp_curs, +1);
      else
1606
        success = ME_MoveCursorChars(editor, &tmp_curs, +1, extend);
1607
      break;
1608
    case VK_UP:
1609
      ME_MoveCursorLines(editor, &tmp_curs, -1, extend);
1610
      break;
1611
    case VK_DOWN:
1612
      ME_MoveCursorLines(editor, &tmp_curs, +1, extend);
1613
      break;
1614
    case VK_PRIOR:
1615 1616
      ME_ArrowPageUp(editor, &tmp_curs);
      break;
1617
    case VK_NEXT:
1618 1619
      ME_ArrowPageDown(editor, &tmp_curs);
      break;
1620
    case VK_HOME: {
1621
      if (ctrl)
1622
        ME_ArrowCtrlHome(editor, &tmp_curs);
1623
      else
1624
        ME_ArrowHome(editor, &tmp_curs);
1625
      editor->bCaretAtEnd = FALSE;
1626
      break;
1627
    }
1628
    case VK_END:
1629
      if (ctrl)
1630
        ME_ArrowCtrlEnd(editor, &tmp_curs);
1631
      else
1632 1633
        ME_ArrowEnd(editor, &tmp_curs);
      break;
1634
  }
1635

1636 1637 1638
  if (!extend)
    editor->pCursors[1] = tmp_curs;
  *p = tmp_curs;
1639

1640 1641
  ME_InvalidateSelection(editor);
  ME_Repaint(editor);
1642
  hide_caret(editor);
1643
  ME_EnsureVisible(editor, &tmp_curs);
1644
  update_caret(editor);
1645 1646
  ME_SendSelChange(editor);
  return success;
1647
}