2 * RichEdit - functions dealing with editor object
4 * Copyright 2004 by Krzysztof Foltman
5 * Copyright 2005 by Cihan Altinay
6 * Copyright 2005 by Phil Krylov
7 * Copyright 2008 Eric Pouech
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
54 - EM_GETLANGOPTIONS 2.0
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0 (only Y value valid)
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
94 - EM_SETBIDIOPTIONS 3.0
96 + EM_SETCHARFORMAT (partly done, no ANSI)
98 + EM_SETEVENTMASK (few notifications supported)
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETLANGOPTIONS 2.0
104 + EM_SETMODIFY (not sure if implementation is correct)
106 + EM_SETOPTIONS (partially implemented)
109 + EM_SETPASSWORDCHAR 2.0
110 - EM_SETPUNCTUATION 1.0asian
111 + EM_SETREADONLY no beep on modification attempt
113 + EM_SETRECTNP (EM_SETRECT without repainting)
115 + EM_SETSCROLLPOS 3.0
117 - EM_SETTARGETDEVICE (partial)
118 + EM_SETTEXTEX 3.0 (proper style?)
120 - EM_SETTYPOGRAPHYOPTIONS 3.0
121 + EM_SETUNDOLIMIT 2.0
122 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
123 - EM_SETWORDBREAKPROCEX
124 - EM_SETWORDWRAPMODE 1.0asian
126 + EM_SHOWSCROLLBAR 2.0
127 + EM_STOPGROUPTYPING 2.0
135 + WM_GETDLGCODE (the current implementation is incomplete)
136 + WM_GETTEXT (ANSI&Unicode)
137 + WM_GETTEXTLENGTH (ANSI version sucks)
140 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
142 - WM_STYLECHANGED (things like read-only flag)
147 * EN_CHANGE (sent from the wrong place)
164 * EN_UPDATE (sent from the wrong place)
172 + ES_DISABLENOSCROLL (scrollbar is always visible)
173 - ES_EX_NOCALLOLEINIT
175 - ES_MULTILINE (currently single line controls aren't supported)
177 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
183 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
190 * RICHED20 TODO (incomplete):
192 * - messages/styles/notifications listed above
193 * - add remaining CHARFORMAT/PARAFORMAT fields
194 * - right/center align should strip spaces from the beginning
195 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196 * - COM interface (looks like a major pain in the TODO list)
197 * - calculate heights of pictures (half-done)
198 * - horizontal scrolling (not even started)
199 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
201 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202 * - italic caret with italic fonts
204 * - most notifications aren't sent at all (the most important ones are)
205 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208 * - full justification
211 * - ListBox & ComboBox not implemented
213 * Bugs that are probably fixed, but not so easy to verify:
214 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217 * - caret shouldn't be displayed when selection isn't empty
218 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219 * - undo for setting default format (done, might be buggy)
220 * - styles might be not released properly (looks like they work like charm, but who knows?
227 #define NO_SHLWAPI_STREAM
233 #define STACK_SIZE_DEFAULT 100
234 #define STACK_SIZE_MAX 1000
236 #define TEXT_LIMIT_DEFAULT 32767
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
249 HANDLE me_heap = NULL;
251 static BOOL ME_ListBoxRegistered = FALSE;
252 static BOOL ME_ComboBoxRegistered = FALSE;
254 static inline int is_version_nt(void)
256 return !(GetVersion() & 0x80000000);
259 static ME_TextBuffer *ME_MakeText(void) {
261 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
263 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
264 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
270 p1->member.para.next_para = p2;
271 p2->member.para.prev_para = p1;
272 p2->member.para.nCharOfs = 0;
276 buf->pCharStyle = NULL;
282 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
284 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
287 TRACE("%08x %p\n", dwFormat, stream);
294 ME_StreamInFill(stream);
295 if (stream->editstream->dwError)
301 if (!(dwFormat & SF_UNICODE))
303 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
304 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
309 nWideChars = stream->dwSize >> 1;
310 pText = (WCHAR *)stream->buffer;
313 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
314 if (stream->dwSize == 0)
318 ME_CommitUndo(editor);
319 ME_UpdateRepaint(editor);
323 static void ME_RTFCharAttrHook(RTF_Info *info)
326 fmt.cbSize = sizeof(fmt);
330 switch(info->rtfMinor)
333 /* FIXME add more flags once they're implemented */
334 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
335 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
336 fmt.yHeight = 12*20; /* 12pt */
337 fmt.wWeight = FW_NORMAL;
338 fmt.bUnderlineType = CFU_UNDERLINENONE;
341 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
342 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
343 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
346 fmt.dwMask = CFM_ITALIC;
347 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
350 fmt.dwMask = CFM_UNDERLINETYPE;
351 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
353 case rtfDotUnderline:
354 fmt.dwMask = CFM_UNDERLINETYPE;
355 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
358 fmt.dwMask = CFM_UNDERLINETYPE;
359 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
361 case rtfWordUnderline:
362 fmt.dwMask = CFM_UNDERLINETYPE;
363 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
366 fmt.dwMask = CFM_UNDERLINETYPE;
367 fmt.bUnderlineType = CFU_UNDERLINENONE;
370 fmt.dwMask = CFM_STRIKEOUT;
371 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
375 case rtfSubScrShrink:
376 case rtfSuperScrShrink:
378 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
379 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
380 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
381 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
384 fmt.dwMask = CFM_HIDDEN;
385 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
388 fmt.dwMask = CFM_BACKCOLOR;
390 if (info->rtfParam == 0)
391 fmt.dwEffects = CFE_AUTOBACKCOLOR;
392 else if (info->rtfParam != rtfNoParam)
394 RTFColor *c = RTFGetColor(info, info->rtfParam);
395 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
399 fmt.dwMask = CFM_COLOR;
401 if (info->rtfParam == 0)
402 fmt.dwEffects = CFE_AUTOCOLOR;
403 else if (info->rtfParam != rtfNoParam)
405 RTFColor *c = RTFGetColor(info, info->rtfParam);
407 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
413 if (info->rtfParam != rtfNoParam)
415 RTFFont *f = RTFGetFont(info, info->rtfParam);
418 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
419 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
420 fmt.bCharSet = f->rtfFCharSet;
421 fmt.dwMask = CFM_FACE | CFM_CHARSET;
422 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
427 fmt.dwMask = CFM_SIZE;
428 if (info->rtfParam != rtfNoParam)
429 fmt.yHeight = info->rtfParam*10;
434 RTFFlushOutputBuffer(info);
435 /* FIXME too slow ? how come ? */
436 style2 = ME_ApplyStyle(info->style, &fmt);
437 ME_ReleaseStyle(info->style);
438 info->style = style2;
439 info->styleChanged = TRUE;
443 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
444 the same tags mean different things in different contexts */
445 static void ME_RTFParAttrHook(RTF_Info *info)
448 fmt.cbSize = sizeof(fmt);
451 switch(info->rtfMinor)
453 case rtfParDef: /* restores default paragraph attributes */
454 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
455 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
457 /* TODO: numbering, shading */
458 fmt.wAlignment = PFA_LEFT;
460 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
461 fmt.wBorderWidth = fmt.wBorders = 0;
462 fmt.wBorderSpace = 0;
463 fmt.bLineSpacingRule = 0;
464 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
465 fmt.dyLineSpacing = 0;
466 if (!info->editor->bEmulateVersion10) /* v4.1 */
468 if (info->tableDef && info->tableDef->tableRowStart &&
469 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
472 ME_DisplayItem *para;
473 /* We are just after a table row. */
474 RTFFlushOutputBuffer(info);
475 cursor = info->editor->pCursors[0];
476 para = ME_GetParagraph(cursor.pRun);
477 if (para == info->tableDef->tableRowStart->member.para.next_para
478 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
480 /* Since the table row end, no text has been inserted, and the \intbl
481 * control word has not be used. We can confirm that we are not in a
484 info->tableDef->tableRowStart = NULL;
485 info->canInheritInTbl = FALSE;
488 } else { /* v1.0 - v3.0 */
489 fmt.dwMask |= PFM_TABLE;
490 fmt.wEffects &= ~PFE_TABLE;
494 if (!info->editor->bEmulateVersion10) /* v4.1 */
496 while (info->rtfParam > info->nestingLevel) {
497 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
498 ZeroMemory(tableDef, sizeof(RTFTable));
499 tableDef->parent = info->tableDef;
500 info->tableDef = tableDef;
502 RTFFlushOutputBuffer(info);
503 if (tableDef->tableRowStart &&
504 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
506 ME_DisplayItem *para = tableDef->tableRowStart;
507 para = para->member.para.next_para;
508 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
509 tableDef->tableRowStart = para;
513 cursor = info->editor->pCursors[0];
514 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
515 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
516 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
519 info->nestingLevel++;
521 info->canInheritInTbl = FALSE;
526 if (!info->editor->bEmulateVersion10) /* v4.1 */
528 if (info->nestingLevel < 1)
533 info->tableDef = ALLOC_OBJ(RTFTable);
534 ZeroMemory(info->tableDef, sizeof(RTFTable));
536 tableDef = info->tableDef;
537 RTFFlushOutputBuffer(info);
538 if (tableDef->tableRowStart &&
539 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
541 ME_DisplayItem *para = tableDef->tableRowStart;
542 para = para->member.para.next_para;
543 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
544 tableDef->tableRowStart = para;
548 cursor = info->editor->pCursors[0];
549 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
550 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
551 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
553 info->nestingLevel = 1;
554 info->canInheritInTbl = TRUE;
557 } else { /* v1.0 - v3.0 */
558 fmt.dwMask |= PFM_TABLE;
559 fmt.wEffects |= PFE_TABLE;
564 ME_GetSelectionParaFormat(info->editor, &fmt);
565 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
566 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
567 fmt.dxOffset = -info->rtfParam;
570 ME_GetSelectionParaFormat(info->editor, &fmt);
571 fmt.dwMask = PFM_STARTINDENT;
572 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
575 fmt.dwMask = PFM_RIGHTINDENT;
576 fmt.dxRightIndent = info->rtfParam;
580 fmt.dwMask = PFM_ALIGNMENT;
581 fmt.wAlignment = PFA_LEFT;
584 fmt.dwMask = PFM_ALIGNMENT;
585 fmt.wAlignment = PFA_RIGHT;
588 fmt.dwMask = PFM_ALIGNMENT;
589 fmt.wAlignment = PFA_CENTER;
592 ME_GetSelectionParaFormat(info->editor, &fmt);
593 if (!(fmt.dwMask & PFM_TABSTOPS))
597 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
598 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
599 fmt.dwMask = PFM_TABSTOPS;
602 fmt.dwMask = PFM_KEEP;
603 fmt.wEffects = PFE_KEEP;
605 case rtfNoWidowControl:
606 fmt.dwMask = PFM_NOWIDOWCONTROL;
607 fmt.wEffects = PFE_NOWIDOWCONTROL;
610 fmt.dwMask = PFM_KEEPNEXT;
611 fmt.wEffects = PFE_KEEPNEXT;
614 fmt.dwMask = PFM_SPACEAFTER;
615 fmt.dySpaceAfter = info->rtfParam;
618 fmt.dwMask = PFM_SPACEBEFORE;
619 fmt.dySpaceBefore = info->rtfParam;
621 case rtfSpaceBetween:
622 fmt.dwMask = PFM_LINESPACING;
623 if ((int)info->rtfParam > 0)
625 fmt.dyLineSpacing = info->rtfParam;
626 fmt.bLineSpacingRule = 3;
630 fmt.dyLineSpacing = info->rtfParam;
631 fmt.bLineSpacingRule = 4;
633 case rtfSpaceMultiply:
634 fmt.dwMask = PFM_LINESPACING;
635 fmt.dyLineSpacing = info->rtfParam * 20;
636 fmt.bLineSpacingRule = 5;
639 fmt.dwMask = PFM_NUMBERING;
640 fmt.wNumbering = PFN_BULLET;
643 fmt.dwMask = PFM_NUMBERING;
644 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
646 case rtfParNumDecimal:
647 fmt.dwMask = PFM_NUMBERING;
648 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
650 case rtfParNumIndent:
651 fmt.dwMask = PFM_NUMBERINGTAB;
652 fmt.wNumberingTab = info->rtfParam;
654 case rtfParNumStartAt:
655 fmt.dwMask = PFM_NUMBERINGSTART;
656 fmt.wNumberingStart = info->rtfParam;
659 ME_GetSelectionParaFormat(info->editor, &fmt);
660 if (!(fmt.dwMask & PFM_BORDER))
662 fmt.wBorderSpace = 0;
663 fmt.wBorderWidth = 1;
667 fmt.dwMask = PFM_BORDER;
670 ME_GetSelectionParaFormat(info->editor, &fmt);
671 if (!(fmt.dwMask & PFM_BORDER))
673 fmt.wBorderSpace = 0;
674 fmt.wBorderWidth = 1;
678 fmt.dwMask = PFM_BORDER;
681 ME_GetSelectionParaFormat(info->editor, &fmt);
682 if (!(fmt.dwMask & PFM_BORDER))
684 fmt.wBorderSpace = 0;
685 fmt.wBorderWidth = 1;
689 fmt.dwMask = PFM_BORDER;
691 case rtfBorderBottom:
692 ME_GetSelectionParaFormat(info->editor, &fmt);
693 if (!(fmt.dwMask & PFM_BORDER))
695 fmt.wBorderSpace = 0;
696 fmt.wBorderWidth = 1;
700 fmt.dwMask = PFM_BORDER;
702 case rtfBorderSingle:
703 ME_GetSelectionParaFormat(info->editor, &fmt);
704 /* we assume that borders have been created before (RTF spec) */
705 fmt.wBorders &= ~0x700;
706 fmt.wBorders |= 1 << 8;
707 fmt.dwMask = PFM_BORDER;
710 ME_GetSelectionParaFormat(info->editor, &fmt);
711 /* we assume that borders have been created before (RTF spec) */
712 fmt.wBorders &= ~0x700;
713 fmt.wBorders |= 2 << 8;
714 fmt.dwMask = PFM_BORDER;
716 case rtfBorderShadow:
717 ME_GetSelectionParaFormat(info->editor, &fmt);
718 /* we assume that borders have been created before (RTF spec) */
719 fmt.wBorders &= ~0x700;
720 fmt.wBorders |= 10 << 8;
721 fmt.dwMask = PFM_BORDER;
723 case rtfBorderDouble:
724 ME_GetSelectionParaFormat(info->editor, &fmt);
725 /* we assume that borders have been created before (RTF spec) */
726 fmt.wBorders &= ~0x700;
727 fmt.wBorders |= 7 << 8;
728 fmt.dwMask = PFM_BORDER;
731 ME_GetSelectionParaFormat(info->editor, &fmt);
732 /* we assume that borders have been created before (RTF spec) */
733 fmt.wBorders &= ~0x700;
734 fmt.wBorders |= 11 << 8;
735 fmt.dwMask = PFM_BORDER;
738 ME_GetSelectionParaFormat(info->editor, &fmt);
739 /* we assume that borders have been created before (RTF spec) */
740 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
741 fmt.dwMask = PFM_BORDER;
744 ME_GetSelectionParaFormat(info->editor, &fmt);
745 /* we assume that borders have been created before (RTF spec) */
746 fmt.wBorderSpace = info->rtfParam;
747 fmt.dwMask = PFM_BORDER;
751 RTFFlushOutputBuffer(info);
752 /* FIXME too slow ? how come ?*/
753 ME_SetSelectionParaFormat(info->editor, &fmt);
757 static void ME_RTFTblAttrHook(RTF_Info *info)
759 switch (info->rtfMinor)
763 if (!info->tableDef) {
764 info->tableDef = ALLOC_OBJ(RTFTable);
765 ZeroMemory(info->tableDef, sizeof(RTFTable));
767 ZeroMemory(info->tableDef->cells, sizeof(info->tableDef->cells));
768 info->tableDef->numCellsDefined = 0;
775 info->tableDef = ALLOC_OBJ(RTFTable);
776 ZeroMemory(info->tableDef, sizeof(RTFTable));
778 if (info->tableDef->numCellsDefined >= MAX_TABLE_CELLS)
780 info->tableDef->cells[info->tableDef->numCellsDefined].rightBoundary = info->rtfParam;
782 /* Tab stops were used to store cell positions before v4.1 but v4.1
783 * still seems to set the tabstops without using them. */
784 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
785 PARAFORMAT2 *pFmt = para->member.para.pFmt;
786 int cellNum = info->tableDef->numCellsDefined;
787 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
788 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
790 info->tableDef->numCellsDefined++;
795 static void ME_RTFSpecialCharHook(RTF_Info *info)
797 RTFTable *tableDef = info->tableDef;
798 switch (info->rtfMinor)
801 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
803 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
807 RTFFlushOutputBuffer(info);
808 if (!info->editor->bEmulateVersion10) { /* v4.1 */
809 if (tableDef->tableRowStart)
811 if (!info->nestingLevel &&
812 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
814 ME_DisplayItem *para = tableDef->tableRowStart;
815 para = para->member.para.next_para;
816 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
817 tableDef->tableRowStart = para;
818 info->nestingLevel = 1;
820 ME_InsertTableCellFromCursor(info->editor);
822 } else { /* v1.0 - v3.0 */
823 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
824 PARAFORMAT2 *pFmt = para->member.para.pFmt;
825 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
826 tableDef->numCellsInserted < tableDef->numCellsDefined)
829 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
830 tableDef->numCellsInserted++;
835 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
837 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
840 ME_DisplayItem *para, *cell, *run;
845 RTFFlushOutputBuffer(info);
846 if (!info->editor->bEmulateVersion10) { /* v4.1 */
847 if (!tableDef->tableRowStart)
849 if (!info->nestingLevel &&
850 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
852 para = tableDef->tableRowStart;
853 para = para->member.para.next_para;
854 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
855 tableDef->tableRowStart = para;
856 info->nestingLevel++;
858 para = tableDef->tableRowStart;
859 cell = ME_FindItemFwd(para, diCell);
860 assert(cell && !cell->member.cell.prev_cell);
861 if (tableDef->numCellsDefined < 1)
863 /* 2000 twips appears to be the cell size that native richedit uses
864 * when no cell sizes are specified. */
865 const int defaultCellSize = 2000;
866 int nRightBoundary = defaultCellSize;
867 cell->member.cell.nRightBoundary = nRightBoundary;
868 while (cell->member.cell.next_cell) {
869 cell = cell->member.cell.next_cell;
870 nRightBoundary += defaultCellSize;
871 cell->member.cell.nRightBoundary = nRightBoundary;
873 para = ME_InsertTableCellFromCursor(info->editor);
874 cell = para->member.para.pCell;
875 cell->member.cell.nRightBoundary = nRightBoundary;
877 for (i = 0; i < tableDef->numCellsDefined; i++)
879 cell->member.cell.nRightBoundary = tableDef->cells[i].rightBoundary;
880 cell = cell->member.cell.next_cell;
883 para = ME_InsertTableCellFromCursor(info->editor);
884 cell = para->member.para.pCell;
887 /* Cell for table row delimiter is empty */
888 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
891 run = ME_FindItemFwd(cell, diRun);
892 if (info->editor->pCursors[0].pRun != run ||
893 info->editor->pCursors[0].nOffset)
896 /* Delete inserted cells that aren't defined. */
897 info->editor->pCursors[1].pRun = run;
898 info->editor->pCursors[1].nOffset = 0;
899 nOfs = ME_GetCursorOfs(info->editor, 1);
900 nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
901 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
904 para = ME_InsertTableRowEndFromCursor(info->editor);
905 info->nestingLevel--;
906 if (!info->nestingLevel)
908 if (info->canInheritInTbl) {
909 tableDef->tableRowStart = para;
911 while (info->tableDef) {
912 tableDef = info->tableDef;
913 info->tableDef = tableDef->parent;
918 info->tableDef = tableDef->parent;
921 } else { /* v1.0 - v3.0 */
923 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
924 PARAFORMAT2 *pFmt = para->member.para.pFmt;
925 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
928 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
929 tableDef->numCellsInserted++;
931 pFmt->cTabCount = tableDef->numCellsDefined;
932 if (!tableDef->numCellsDefined)
933 pFmt->wEffects &= ~PFE_TABLE;
934 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
935 tableDef->numCellsInserted = 0;
941 tableDef->numCellsInserted = 0;
946 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
949 LPOLEOBJECT lpObject = NULL;
950 LPSTORAGE lpStorage = NULL;
951 LPOLECLIENTSITE lpClientSite = NULL;
952 LPDATAOBJECT lpDataObject = NULL;
953 LPOLECACHE lpOleCache = NULL;
962 stgm.tymed = TYMED_ENHMF;
963 stgm.u.hEnhMetaFile = hemf;
964 fm.cfFormat = CF_ENHMETAFILE;
968 stgm.tymed = TYMED_GDI;
969 stgm.u.hBitmap = hbmp;
970 fm.cfFormat = CF_BITMAP;
972 stgm.pUnkForRelease = NULL;
975 fm.dwAspect = DVASPECT_CONTENT;
977 fm.tymed = stgm.tymed;
979 if (!info->lpRichEditOle)
981 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
984 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
986 /* FIXME: enable it when rich-edit properly implements this method */
987 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
988 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
990 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
991 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
992 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
993 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
994 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
998 reobject.cbStruct = sizeof(reobject);
999 reobject.cp = REO_CP_SELECTION;
1000 reobject.clsid = clsid;
1001 reobject.poleobj = lpObject;
1002 reobject.pstg = lpStorage;
1003 reobject.polesite = lpClientSite;
1004 /* convert from twips to .01 mm */
1005 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1006 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1007 reobject.dvaspect = DVASPECT_CONTENT;
1008 reobject.dwFlags = 0; /* FIXME */
1009 reobject.dwUser = 0;
1011 /* FIXME: could be simpler */
1012 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1015 if (lpObject) IOleObject_Release(lpObject);
1016 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1017 if (lpStorage) IStorage_Release(lpStorage);
1018 if (lpDataObject) IDataObject_Release(lpDataObject);
1019 if (lpOleCache) IOleCache_Release(lpOleCache);
1024 static void ME_RTFReadPictGroup(RTF_Info *info)
1027 BYTE* buffer = NULL;
1028 unsigned bufsz, bufidx;
1034 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1037 if (info->rtfClass == rtfEOF)
1040 /* fetch picture type */
1041 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1043 mfp.mm = info->rtfParam;
1046 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1048 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1051 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1053 gfx = gfx_enhmetafile;
1057 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1061 /* fetch picture attributes */
1065 if (info->rtfClass == rtfEOF)
1067 if (info->rtfClass == rtfText)
1069 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1071 ERR("Expected picture attribute (%d %d)\n",
1072 info->rtfClass, info->rtfMajor);
1075 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1077 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1079 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1081 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1083 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1084 sz.cx = info->rtfParam;
1085 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1086 sz.cy = info->rtfParam;
1088 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1090 /* fetch picture data */
1093 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1094 val = info->rtfMajor;
1095 for (flip = TRUE;; flip = !flip)
1098 if (info->rtfClass == rtfEOF)
1100 HeapFree(GetProcessHeap(), 0, buffer);
1101 return; /* Warn ?? */
1103 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1105 if (info->rtfClass != rtfText) goto skip_group;
1108 if (bufidx >= bufsz &&
1109 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1111 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1114 val = info->rtfMajor;
1116 if (flip) FIXME("wrong hex string\n");
1120 case gfx_enhmetafile:
1121 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1122 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1125 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1126 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1130 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1132 unsigned nc = bi->bmiHeader.biClrUsed;
1134 /* not quite right, especially for bitfields type of compression */
1135 if (!nc && bi->bmiHeader.biBitCount <= 8)
1136 nc = 1 << bi->bmiHeader.biBitCount;
1137 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1138 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1139 bi, DIB_RGB_COLORS)))
1140 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1147 HeapFree(GetProcessHeap(), 0, buffer);
1148 RTFRouteToken (info); /* feed "}" back to router */
1151 HeapFree(GetProcessHeap(), 0, buffer);
1153 RTFRouteToken(info); /* feed "}" back to router */
1156 /* for now, lookup the \result part and use it, whatever the object */
1157 static void ME_RTFReadObjectGroup(RTF_Info *info)
1162 if (info->rtfClass == rtfEOF)
1164 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1166 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1169 if (info->rtfClass == rtfEOF)
1171 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1175 while (RTFGetToken (info) != rtfEOF)
1177 if (info->rtfClass == rtfGroup)
1179 if (info->rtfMajor == rtfBeginGroup) level++;
1180 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1182 RTFRouteToken(info);
1185 else RTFSkipGroup(info);
1188 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1190 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1194 RTFRouteToken(info); /* feed "}" back to router */
1197 static void ME_RTFReadHook(RTF_Info *info) {
1198 switch(info->rtfClass)
1201 switch(info->rtfMajor)
1204 if (info->stackTop < maxStack) {
1205 info->stack[info->stackTop].fmt = info->style->fmt;
1206 info->stack[info->stackTop].codePage = info->codePage;
1207 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1210 info->styleChanged = FALSE;
1215 RTFFlushOutputBuffer(info);
1217 if (info->stackTop<=0) {
1218 info->rtfClass = rtfEOF;
1221 assert(info->stackTop >= 0);
1222 if (info->styleChanged)
1224 /* FIXME too slow ? how come ? */
1225 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1226 ME_ReleaseStyle(info->style);
1228 info->codePage = info->stack[info->stackTop].codePage;
1229 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1236 switch(info->rtfMajor)
1239 ME_RTFCharAttrHook(info);
1242 ME_RTFParAttrHook(info);
1245 ME_RTFTblAttrHook(info);
1247 case rtfSpecialChar:
1248 ME_RTFSpecialCharHook(info);
1256 ME_StreamInFill(ME_InStream *stream)
1258 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1259 (BYTE *)stream->buffer,
1260 sizeof(stream->buffer),
1261 (LONG *)&stream->dwSize);
1265 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1269 int from, to, to2, nUndoMode;
1270 int nEventMask = editor->nEventMask;
1271 ME_InStream inStream;
1272 BOOL invalidRTF = FALSE;
1274 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1275 editor->nEventMask = 0;
1277 ME_GetSelection(editor, &from, &to);
1278 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1279 style = ME_GetSelectionInsertStyle(editor);
1281 ME_InternalDeleteText(editor, from, to-from, FALSE);
1284 ME_DisplayItem *para_item;
1285 style = editor->pBuffer->pDefaultStyle;
1286 ME_AddRefStyle(style);
1287 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1288 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1290 ME_ClearTempStyle(editor);
1292 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1293 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1297 /* Back up undo mode to a local variable */
1298 nUndoMode = editor->nUndoMode;
1300 /* Only create an undo if SFF_SELECTION is set */
1301 if (!(format & SFF_SELECTION))
1302 editor->nUndoMode = umIgnore;
1304 inStream.editstream = stream;
1305 inStream.editstream->dwError = 0;
1306 inStream.dwSize = 0;
1307 inStream.dwUsed = 0;
1309 if (format & SF_RTF)
1311 /* Check if it's really RTF, and if it is not, use plain text */
1312 ME_StreamInFill(&inStream);
1313 if (!inStream.editstream->dwError)
1315 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1316 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1319 inStream.editstream->dwError = -16;
1324 if (!invalidRTF && !inStream.editstream->dwError)
1326 if (format & SF_RTF) {
1327 ME_DisplayItem *para;
1329 /* setup the RTF parser */
1330 memset(&parser, 0, sizeof parser);
1331 RTFSetEditStream(&parser, &inStream);
1332 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1333 parser.hwndEdit = editor->hWnd;
1334 parser.editor = editor;
1335 parser.style = style;
1336 WriterInit(&parser);
1338 RTFSetReadHook(&parser, ME_RTFReadHook);
1339 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1340 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1341 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1342 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1345 /* do the parsing */
1347 RTFFlushOutputBuffer(&parser);
1348 if (!editor->bEmulateVersion10) { /* v4.1 */
1349 if (parser.tableDef && parser.tableDef->tableRowStart)
1351 /* Delete any incomplete table row at the end of the rich text. */
1353 ME_DisplayItem *pCell;
1355 para = parser.tableDef->tableRowStart;
1357 parser.rtfMinor = rtfRow;
1358 /* Complete the table row before deleting it.
1359 * By doing it this way we will have the current paragraph format set
1360 * properly to reflect that is not in the complete table, and undo items
1361 * will be added for this change to the current paragraph format. */
1362 if (parser.nestingLevel > 0)
1364 while (parser.nestingLevel--)
1365 ME_RTFSpecialCharHook(&parser);
1366 } else if (parser.canInheritInTbl) {
1367 ME_RTFSpecialCharHook(&parser);
1369 if (parser.tableDef && parser.tableDef->tableRowStart &&
1370 para->member.para.nFlags & MEPF_ROWEND)
1372 para = para->member.para.next_para;
1374 pCell = para->member.para.pCell;
1376 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1377 editor->pCursors[1].nOffset = 0;
1378 nOfs = ME_GetCursorOfs(editor, 1);
1379 nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1380 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1381 parser.tableDef->tableRowStart = NULL;
1384 ME_CheckTablesForCorruption(editor);
1385 RTFDestroy(&parser);
1386 if (parser.lpRichEditOle)
1387 IRichEditOle_Release(parser.lpRichEditOle);
1389 if (!inStream.editstream->dwError && parser.stackTop > 0)
1390 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1392 /* Remove last line break, as mandated by tests. This is not affected by
1393 CR/LF counters, since RTF streaming presents only \para tokens, which
1394 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1398 ME_GetSelection(editor, &newfrom, &newto);
1399 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1400 WCHAR lastchar[3] = {'\0', '\0'};
1401 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1403 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1404 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1405 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1410 style = parser.style;
1412 else if (format & SF_TEXT)
1413 ME_StreamInText(editor, format, &inStream, style);
1415 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1416 ME_GetSelection(editor, &to, &to2);
1417 /* put the cursor at the top */
1418 if (!(format & SFF_SELECTION))
1419 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1422 /* Restore saved undo mode */
1423 editor->nUndoMode = nUndoMode;
1425 /* even if we didn't add an undo, we need to commit anything on the stack */
1426 ME_CommitUndo(editor);
1428 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1429 if (!(format & SFF_SELECTION))
1430 ME_EmptyUndoStack(editor);
1432 ME_ReleaseStyle(style);
1433 editor->nEventMask = nEventMask;
1434 ME_UpdateRepaint(editor);
1435 if (!(format & SFF_SELECTION)) {
1436 ME_ClearTempStyle(editor);
1438 HideCaret(editor->hWnd);
1439 ME_MoveCaret(editor);
1440 ShowCaret(editor->hWnd);
1441 ME_SendSelChange(editor);
1442 ME_SendRequestResize(editor, FALSE);
1448 typedef struct tagME_RTFStringStreamStruct
1453 } ME_RTFStringStreamStruct;
1455 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1457 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1460 count = min(cb, pStruct->length - pStruct->pos);
1461 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1462 pStruct->pos += count;
1468 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1471 ME_RTFStringStreamStruct data;
1473 data.string = string;
1474 data.length = strlen(string);
1476 es.dwCookie = (DWORD)&data;
1477 es.pfnCallback = ME_ReadFromRTFString;
1478 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1483 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1485 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1488 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1489 item = ME_FindItemFwd(item, diParagraph);
1494 nOffset -= item->member.para.nCharOfs;
1495 if (nItemType == diParagraph) {
1497 *nItemOffset = nOffset;
1502 item = ME_FindItemFwd(item, diRun);
1503 runLength = ME_StrLen(item->member.run.strText);
1504 if (item->member.run.nFlags & MERF_ENDPARA)
1505 runLength = item->member.run.nCR + item->member.run.nLF;
1506 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1508 nOffset -= item->member.run.nCharOfs;
1510 /* Special case: nOffset may not point exactly at the division between the
1511 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1512 into the next run, if one exists
1514 if ( item->member.run.nFlags & MERF_ENDPARA
1515 && nOffset == item->member.run.nCR
1516 && item->member.run.nLF > 0) {
1517 ME_DisplayItem *nextItem;
1518 nextItem = ME_FindItemFwd(item, diRun);
1525 *nItemOffset = nOffset;
1532 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1534 const int nLen = lstrlenW(text);
1535 const int nTextLen = ME_GetTextLength(editor);
1538 ME_DisplayItem *item;
1539 ME_DisplayItem *para;
1540 WCHAR wLastChar = ' ';
1542 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1543 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1545 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1546 FIXME("Flags 0x%08x not implemented\n",
1547 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1550 if (chrg->cpMax == -1)
1553 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1555 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1556 if (editor->bEmulateVersion10 && nMax == nTextLen)
1561 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1562 if (editor->bEmulateVersion10 && nMax < nMin)
1566 chrgText->cpMin = -1;
1567 chrgText->cpMax = -1;
1572 /* when searching up, if cpMin < cpMax, then instead of searching
1573 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1574 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1575 * case, it is always bigger than cpMin.
1577 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1581 nMax = nMin > nTextLen ? nTextLen : nMin;
1582 if (nMin < nSwap || chrg->cpMax == -1)
1588 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1591 chrgText->cpMin = chrgText->cpMax = -1;
1595 if (flags & FR_DOWN) /* Forward search */
1597 /* If possible, find the character before where the search starts */
1598 if ((flags & FR_WHOLEWORD) && nMin)
1601 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1605 chrgText->cpMin = chrgText->cpMax = -1;
1608 wLastChar = item->member.run.strText->szData[nStart];
1612 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1616 chrgText->cpMin = chrgText->cpMax = -1;
1620 para = ME_GetParagraph(item);
1622 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1624 ME_DisplayItem *pCurItem = item;
1625 int nCurStart = nStart;
1628 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1630 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1634 if (nMatched == nLen)
1636 ME_DisplayItem *pNextItem = pCurItem;
1637 int nNextStart = nCurStart;
1640 /* Check to see if next character is a whitespace */
1641 if (flags & FR_WHOLEWORD)
1643 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1645 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1646 nNextStart = -nMatched;
1650 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1654 if (isalnumW(wNextChar))
1658 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1661 chrgText->cpMin = nStart;
1662 chrgText->cpMax = nStart + nLen;
1664 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1667 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1669 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1670 para = ME_GetParagraph(pCurItem);
1671 nCurStart = -nMatched;
1675 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1680 if (nStart == ME_StrLen(item->member.run.strText))
1682 item = ME_FindItemFwd(item, diRun);
1683 para = ME_GetParagraph(item);
1688 else /* Backward search */
1690 /* If possible, find the character after where the search ends */
1691 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1694 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1698 chrgText->cpMin = chrgText->cpMax = -1;
1701 wLastChar = item->member.run.strText->szData[nEnd];
1705 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1709 chrgText->cpMin = chrgText->cpMax = -1;
1713 para = ME_GetParagraph(item);
1716 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1718 ME_DisplayItem *pCurItem = item;
1722 if (nCurEnd - nMatched == 0)
1724 pCurItem = ME_FindItemBack(pCurItem, diRun);
1725 para = ME_GetParagraph(pCurItem);
1726 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1729 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1731 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1735 if (nMatched == nLen)
1737 ME_DisplayItem *pPrevItem = pCurItem;
1738 int nPrevEnd = nCurEnd;
1741 /* Check to see if previous character is a whitespace */
1742 if (flags & FR_WHOLEWORD)
1744 if (nPrevEnd - nMatched == 0)
1746 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1748 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1752 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1756 if (isalnumW(wPrevChar))
1760 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1763 chrgText->cpMin = nStart;
1764 chrgText->cpMax = nStart + nLen;
1766 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1769 if (nCurEnd - nMatched == 0)
1771 pCurItem = ME_FindItemBack(pCurItem, diRun);
1772 /* Don't care about pCurItem becoming NULL here; it's already taken
1773 * care of in the exterior loop condition */
1774 para = ME_GetParagraph(pCurItem);
1775 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1779 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1786 item = ME_FindItemBack(item, diRun);
1787 para = ME_GetParagraph(item);
1788 nEnd = ME_StrLen(item->member.run.strText);
1792 TRACE("not found\n");
1794 chrgText->cpMin = chrgText->cpMax = -1;
1798 /* helper to send a msg filter notification */
1800 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1804 msgf.nmhdr.hwndFrom = editor->hWnd;
1805 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1806 msgf.nmhdr.code = EN_MSGFILTER;
1809 msgf.wParam = *wParam;
1810 msgf.lParam = *lParam;
1811 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1813 *wParam = msgf.wParam;
1814 *lParam = msgf.lParam;
1815 msgf.wParam = *wParam;
1821 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1823 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1824 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1826 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1827 editor->nSelectionType = stPosition;
1835 editor->nUDArrowX = -1;
1841 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1842 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1846 editor->nUDArrowX = -1;
1847 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1848 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1850 if (ME_IsSelection(editor))
1852 ME_DeleteSelection(editor);
1853 ME_CommitUndo(editor);
1855 else if (nKey == VK_DELETE)
1857 /* Delete stops group typing.
1858 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1859 ME_DeleteTextAtCursor(editor, 1, 1);
1860 ME_CommitUndo(editor);
1862 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1864 BOOL bDeletionSucceeded;
1865 /* Backspace can be grouped for a single undo */
1866 ME_ContinueCoalescingTransaction(editor);
1867 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
1868 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
1869 /* Deletion was prevented so the cursor is moved back to where it was.
1870 * (e.g. this happens when trying to delete cell boundaries)
1872 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
1874 ME_CommitCoalescingUndo(editor);
1878 ME_UpdateSelectionLinkAttribute(editor);
1879 ME_UpdateRepaint(editor);
1880 ME_SendRequestResize(editor, FALSE);
1884 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1885 editor->nUDArrowX = -1;
1892 chf.cbSize = sizeof(chf);
1894 ME_GetSelectionCharFormat(editor, &chf);
1895 ME_DumpStyleToBuf(&chf, buf);
1896 MessageBoxA(NULL, buf, "Style dump", MB_OK);
1900 ME_CheckCharOffsets(editor);
1907 /* Process the message and calculate the new click count.
1909 * returns: The click count if it is mouse down event, else returns 0. */
1910 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
1913 static int clickNum = 0;
1914 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
1917 if ((msg == WM_LBUTTONDBLCLK) ||
1918 (msg == WM_RBUTTONDBLCLK) ||
1919 (msg == WM_MBUTTONDBLCLK) ||
1920 (msg == WM_XBUTTONDBLCLK))
1922 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1925 if ((msg == WM_LBUTTONDOWN) ||
1926 (msg == WM_RBUTTONDOWN) ||
1927 (msg == WM_MBUTTONDOWN) ||
1928 (msg == WM_XBUTTONDOWN))
1930 static MSG prevClickMsg;
1932 clickMsg.hwnd = hWnd;
1933 clickMsg.message = msg;
1934 clickMsg.wParam = wParam;
1935 clickMsg.lParam = lParam;
1936 clickMsg.time = GetMessageTime();
1937 clickMsg.pt.x = (short)LOWORD(lParam);
1938 clickMsg.pt.y = (short)HIWORD(lParam);
1939 if ((clickNum != 0) &&
1940 (clickMsg.message == prevClickMsg.message) &&
1941 (clickMsg.hwnd == prevClickMsg.hwnd) &&
1942 (clickMsg.wParam == prevClickMsg.wParam) &&
1943 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
1944 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1945 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1951 prevClickMsg = clickMsg;
1958 static BOOL ME_SetCursor(ME_TextEditor *editor)
1963 DWORD messagePos = GetMessagePos();
1964 pt.x = (short)LOWORD(messagePos);
1965 pt.y = (short)HIWORD(messagePos);
1966 ScreenToClient(editor->hWnd, &pt);
1967 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1968 (pt.x < editor->selofs ||
1969 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
1974 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
1977 if (editor->AutoURLDetect_bEnable)
1981 ME_CursorFromCharOfs(editor, offset, &cursor);
1982 run = &cursor.pRun->member.run;
1983 if (editor->AutoURLDetect_bEnable &&
1984 run->style->fmt.dwMask & CFM_LINK &&
1985 run->style->fmt.dwEffects & CFE_LINK)
1987 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
1991 if (ME_IsSelection(editor))
1993 int selStart, selEnd;
1994 ME_GetSelection(editor, &selStart, &selEnd);
1995 if (selStart <= offset && selEnd >= offset) {
1996 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2001 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
2005 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2010 if(!editor->lpOleCallback)
2012 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2013 if(selrange.cpMin == selrange.cpMax)
2014 seltype |= SEL_EMPTY;
2017 /* FIXME: Handle objects */
2018 seltype |= SEL_TEXT;
2019 if(selrange.cpMax-selrange.cpMin > 1)
2020 seltype |= SEL_MULTICHAR;
2022 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2024 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2030 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
2031 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2034 ed->bEmulateVersion10 = FALSE;
2035 ed->pBuffer = ME_MakeText();
2036 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2037 ME_MakeFirstParagraph(ed);
2038 /* The four cursors are for:
2039 * 0 - The position where the caret is shown
2040 * 1 - The anchored end of the selection (for normal selection)
2041 * 2 & 3 - The anchored start and end respectively for word, line,
2042 * or paragraph selection.
2045 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2046 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2047 ed->pCursors[0].nOffset = 0;
2048 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2049 ed->pCursors[1].nOffset = 0;
2050 ed->pCursors[2] = ed->pCursors[0];
2051 ed->pCursors[3] = ed->pCursors[1];
2052 ed->nLastTotalLength = ed->nTotalLength = 0;
2056 ed->rgbBackColor = -1;
2057 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2058 ed->bCaretAtEnd = FALSE;
2060 ed->nModifyStep = 0;
2061 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2062 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2063 ed->nUndoStackSize = 0;
2064 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2065 ed->nUndoMode = umAddToUndo;
2066 ed->nParagraphs = 1;
2067 ed->nLastSelStart = ed->nLastSelEnd = 0;
2068 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2070 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
2071 ed->bHideSelection = FALSE;
2072 ed->nInvalidOfs = -1;
2073 ed->pfnWordBreak = NULL;
2074 ed->lpOleCallback = NULL;
2075 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2076 ed->AutoURLDetect_bEnable = FALSE;
2077 ed->bHaveFocus = FALSE;
2078 for (i=0; i<HFONT_CACHE_SIZE; i++)
2080 ed->pFontCache[i].nRefs = 0;
2081 ed->pFontCache[i].nAge = 0;
2082 ed->pFontCache[i].hFont = NULL;
2085 ME_CheckCharOffsets(ed);
2086 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
2087 ed->selofs = SELECTIONBAR_WIDTH;
2090 ed->nSelectionType = stPosition;
2092 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
2093 ed->cPasswordMask = '*';
2095 ed->cPasswordMask = 0;
2097 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2099 /* Default vertical scrollbar information */
2100 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2101 ed->vert_si.nMin = 0;
2102 ed->vert_si.nMax = 0;
2103 ed->vert_si.nPage = 0;
2104 ed->vert_si.nPos = 0;
2106 OleInitialize(NULL);
2111 typedef struct tagME_GlobalDestStruct
2115 } ME_GlobalDestStruct;
2117 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2119 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2124 pDest = (WORD *)lpBuff;
2125 pSrc = (WORD *)GlobalLock(pData->hData);
2126 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2127 pDest[i] = pSrc[pData->nLength+i];
2129 pData->nLength += i;
2131 GlobalUnlock(pData->hData);
2135 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2137 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2142 pSrc = (BYTE *)GlobalLock(pData->hData);
2143 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2144 pDest[i] = pSrc[pData->nLength+i];
2146 pData->nLength += i;
2148 GlobalUnlock(pData->hData);
2153 void ME_DestroyEditor(ME_TextEditor *editor)
2155 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2156 ME_DisplayItem *p = pFirst, *pNext = NULL;
2159 ME_ClearTempStyle(editor);
2160 ME_EmptyUndoStack(editor);
2163 ME_DestroyDisplayItem(p);
2166 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2167 for (i=0; i<HFONT_CACHE_SIZE; i++)
2169 if (editor->pFontCache[i].hFont)
2170 DeleteObject(editor->pFontCache[i].hFont);
2172 if (editor->rgbBackColor != -1)
2173 DeleteObject(editor->hbrBackground);
2174 if(editor->lpOleCallback)
2175 IUnknown_Release(editor->lpOleCallback);
2178 FREE_OBJ(editor->pBuffer);
2179 FREE_OBJ(editor->pCursors);
2184 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2189 case DLL_PROCESS_ATTACH:
2190 DisableThreadLibraryCalls(hinstDLL);
2191 me_heap = HeapCreate (0, 0x10000, 0);
2192 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2193 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2197 case DLL_PROCESS_DETACH:
2198 UnregisterClassW(RichEdit20W, 0);
2199 UnregisterClassW(RichEdit50W, 0);
2200 UnregisterClassA("RichEdit20A", 0);
2201 UnregisterClassA("RichEdit50A", 0);
2202 if (ME_ListBoxRegistered)
2203 UnregisterClassW(REListBox20W, 0);
2204 if (ME_ComboBoxRegistered)
2205 UnregisterClassW(REComboBox20W, 0);
2207 HeapDestroy (me_heap);
2215 #define UNSUPPORTED_MSG(e) \
2217 FIXME(#e ": stub\n"); \
2218 return DefWindowProcW(hWnd, msg, wParam, lParam);
2220 static const char * const edit_messages[] = {
2249 "EM_SETPASSWORDCHAR",
2250 "EM_EMPTYUNDOBUFFER",
2251 "EM_GETFIRSTVISIBLELINE",
2253 "EM_SETWORDBREAKPROC",
2254 "EM_GETWORDBREAKPROC",
2255 "EM_GETPASSWORDCHAR",
2263 static const char * const richedit_messages[] = {
2268 "EM_EXLINEFROMCHAR",
2274 "EM_GETOLEINTERFACE",
2284 "EM_SETOLECALLBACK",
2286 "EM_SETTARGETDEVICE",
2294 "EM_GETWORDBREAKPROCEX",
2295 "EM_SETWORDBREAKPROCEX",
2297 "EM_UNKNOWN_USER_83",
2302 "EM_STOPGROUPTYPING",
2306 "EM_GETAUTOURLDETECT",
2309 "EM_GETTEXTLENGTHEX",
2312 "EM_UNKNOWN_USER_98",
2313 "EM_UNKNOWN_USER_99",
2314 "EM_SETPUNCTUATION",
2315 "EM_GETPUNCTUATION",
2316 "EM_SETWORDWRAPMODE",
2317 "EM_GETWORDWRAPMODE",
2323 "EM_UNKNOWN_USER_109",
2324 "EM_UNKNOWN_USER_110",
2325 "EM_UNKNOWN_USER_111",
2326 "EM_UNKNOWN_USER_112",
2327 "EM_UNKNOWN_USER_113",
2328 "EM_UNKNOWN_USER_114",
2329 "EM_UNKNOWN_USER_115",
2330 "EM_UNKNOWN_USER_116",
2331 "EM_UNKNOWN_USER_117",
2332 "EM_UNKNOWN_USER_118",
2333 "EM_UNKNOWN_USER_119",
2334 "EM_SETLANGOPTIONS",
2335 "EM_GETLANGOPTIONS",
2336 "EM_GETIMECOMPMODE",
2340 "EM_SETIMEMODEBIAS",
2345 get_msg_name(UINT msg)
2347 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2348 return edit_messages[msg - EM_GETSEL];
2349 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2350 return richedit_messages[msg - EM_CANPASTE];
2354 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2355 LPARAM lParam, BOOL unicode)
2357 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2359 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2360 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2362 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2363 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2369 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2370 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2371 UNSUPPORTED_MSG(EM_FMTLINES)
2372 UNSUPPORTED_MSG(EM_FORMATRANGE)
2373 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2374 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2375 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2376 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2377 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2378 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2379 UNSUPPORTED_MSG(EM_GETREDONAME)
2380 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2381 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2382 UNSUPPORTED_MSG(EM_GETUNDONAME)
2383 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2384 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2385 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2386 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2387 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2388 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2389 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2390 UNSUPPORTED_MSG(EM_SETPALETTE)
2391 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2392 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2393 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2394 UNSUPPORTED_MSG(WM_STYLECHANGING)
2395 UNSUPPORTED_MSG(WM_STYLECHANGED)
2397 /* Messages specific to Richedit controls */
2400 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2402 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2405 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2406 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2408 int vk = (int)((LPMSG)lParam)->wParam;
2409 /* if style says we want return key */
2410 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2412 code |= DLGC_WANTMESSAGE;
2414 /* we always handle ctrl-tab */
2415 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2417 code |= DLGC_WANTMESSAGE;
2424 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2425 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2426 editor = ME_MakeEditor(hWnd);
2427 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2430 case EM_EMPTYUNDOBUFFER:
2431 ME_EmptyUndoStack(editor);
2435 /* Note: wParam/lParam can be NULL */
2437 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2438 PUINT pto = lParam ? (PUINT)lParam : &to;
2439 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2440 if ((*pfrom|*pto) & 0xFFFF0000)
2442 return MAKELONG(*pfrom,*pto);
2446 CHARRANGE *pRange = (CHARRANGE *)lParam;
2447 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2448 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2451 case EM_SETUNDOLIMIT:
2453 if ((int)wParam < 0)
2454 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2456 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2457 /* Setting a max stack size keeps wine from getting killed
2458 for hogging memory. Windows allocates all this memory at once, so
2459 no program would realistically set a value above our maximum. */
2460 return editor->nUndoLimit;
2463 return editor->pUndoStack != NULL;
2465 return editor->pRedoStack != NULL;
2466 case WM_UNDO: /* FIXME: actually not the same */
2468 return ME_Undo(editor);
2470 return ME_Redo(editor);
2473 /* these flags are equivalent to the ES_* counterparts */
2474 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2475 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2476 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2482 /* these flags are equivalent to ES_* counterparts
2483 * ECO_READONLY is already implemented in the code, only requires
2484 * setting the bit to work
2486 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2487 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2488 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2489 DWORD settings = mask & raw;
2505 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2507 if (settings & ECO_AUTOWORDSELECTION)
2508 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2509 if (settings & ECO_SELECTIONBAR)
2510 editor->selofs = SELECTIONBAR_WIDTH;
2513 ME_WrapMarkedParagraphs(editor);
2515 if (settings & ECO_VERTICAL)
2516 FIXME("ECO_VERTICAL not implemented yet!\n");
2517 if (settings & ECO_AUTOHSCROLL)
2518 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2519 if (settings & ECO_AUTOVSCROLL)
2520 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2521 if (settings & ECO_NOHIDESEL)
2522 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2523 if (settings & ECO_WANTRETURN)
2524 FIXME("ECO_WANTRETURN not implemented yet!\n");
2530 ME_InvalidateSelection(editor);
2531 ME_SetSelection(editor, wParam, lParam);
2532 ME_InvalidateSelection(editor);
2533 HideCaret(editor->hWnd);
2534 ME_ShowCaret(editor);
2535 ME_SendSelChange(editor);
2538 case EM_SETSCROLLPOS:
2540 POINT *point = (POINT *)lParam;
2541 ME_ScrollAbs(editor, point->y);
2544 case EM_AUTOURLDETECT:
2546 if (wParam==1 || wParam ==0)
2548 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2551 return E_INVALIDARG;
2553 case EM_GETAUTOURLDETECT:
2555 return editor->AutoURLDetect_bEnable;
2560 CHARRANGE range = *(CHARRANGE *)lParam;
2562 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2564 ME_InvalidateSelection(editor);
2565 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2566 ME_InvalidateSelection(editor);
2567 HideCaret(editor->hWnd);
2568 ME_ShowCaret(editor);
2569 ME_SendSelChange(editor);
2573 case EM_SHOWSCROLLBAR:
2575 ShowScrollBar(editor->hWnd, wParam, lParam);
2581 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2585 int oldModify = editor->nModifyStep;
2587 if (!pStruct) return 0;
2589 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2590 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2591 pStruct->flags, pStruct->codepage);
2593 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2594 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2595 len = wszText ? lstrlenW(wszText) : 0;
2597 if (pStruct->flags & ST_SELECTION) {
2598 ME_GetSelection(editor, &from, &to);
2599 style = ME_GetSelectionInsertStyle(editor);
2600 ME_InternalDeleteText(editor, from, to - from, FALSE);
2601 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2602 ME_StreamInRTFString(editor, 1, (char *)lParam);
2603 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2604 ME_ReleaseStyle(style);
2606 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2609 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2610 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2611 ME_StreamInRTFString(editor, 0, (char *)lParam);
2612 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2615 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2617 ME_CommitUndo(editor);
2618 if (!(pStruct->flags & ST_KEEPUNDO))
2620 editor->nModifyStep = oldModify;
2621 ME_EmptyUndoStack(editor);
2623 ME_UpdateRepaint(editor);
2626 case EM_SETBKGNDCOLOR:
2629 if (editor->rgbBackColor != -1) {
2630 DeleteObject(editor->hbrBackground);
2631 lColor = editor->rgbBackColor;
2633 else lColor = GetSysColor(COLOR_WINDOW);
2637 editor->rgbBackColor = -1;
2638 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2642 editor->rgbBackColor = lParam;
2643 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2645 if (editor->bRedraw)
2647 InvalidateRect(hWnd, NULL, TRUE);
2653 return editor->nModifyStep == 0 ? 0 : -1;
2657 editor->nModifyStep = 1;
2659 editor->nModifyStep = 0;
2663 case EM_SETREADONLY:
2665 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2667 nStyle |= ES_READONLY;
2669 nStyle &= ~ES_READONLY;
2670 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2673 case EM_SETEVENTMASK:
2675 DWORD nOldMask = editor->nEventMask;
2677 editor->nEventMask = lParam;
2680 case EM_GETEVENTMASK:
2681 return editor->nEventMask;
2682 case EM_SETCHARFORMAT:
2684 CHARFORMAT2W buf, *p;
2685 BOOL bRepaint = TRUE;
2686 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2687 if (p == NULL) return 0;
2689 ME_SetDefaultCharFormat(editor, p);
2690 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2691 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2693 } else if (wParam == SCF_ALL) {
2694 if (editor->mode & TM_PLAINTEXT)
2695 ME_SetDefaultCharFormat(editor, p);
2697 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2698 editor->nModifyStep = 1;
2700 } else if (editor->mode & TM_PLAINTEXT) {
2704 ME_GetSelection(editor, &from, &to);
2705 bRepaint = (from != to);
2706 ME_SetSelectionCharFormat(editor, p);
2707 if (from != to) editor->nModifyStep = 1;
2709 ME_CommitUndo(editor);
2711 ME_RewrapRepaint(editor);
2714 case EM_GETCHARFORMAT:
2716 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2717 if (dst->cbSize != sizeof(CHARFORMATA) &&
2718 dst->cbSize != sizeof(CHARFORMATW) &&
2719 dst->cbSize != sizeof(CHARFORMAT2A) &&
2720 dst->cbSize != sizeof(CHARFORMAT2W))
2722 tmp.cbSize = sizeof(tmp);
2724 ME_GetDefaultCharFormat(editor, &tmp);
2726 ME_GetSelectionCharFormat(editor, &tmp);
2727 ME_CopyToCFAny(dst, &tmp);
2730 case EM_SETPARAFORMAT:
2731 ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2732 ME_RewrapRepaint(editor);
2733 ME_CommitUndo(editor);
2735 case EM_GETPARAFORMAT:
2736 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2738 case EM_GETFIRSTVISIBLELINE:
2740 ME_DisplayItem *p = editor->pBuffer->pFirst;
2741 int y = ME_GetYScrollPos(editor);
2746 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2747 if (p->type == diTextEnd)
2749 if (p->type == diParagraph) {
2750 ypara = p->member.para.pt.y;
2753 ystart = ypara + p->member.row.pt.y;
2754 yend = ystart + p->member.row.nHeight;
2762 case EM_HIDESELECTION:
2764 editor->bHideSelection = (wParam != 0);
2765 ME_InvalidateSelection(editor);
2770 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2771 return TRUE; /* Should return false if a single line richedit control */
2776 ME_GetSelection(editor, &from, &to);
2777 ME_InternalDeleteText(editor, from, to-from, FALSE);
2778 ME_CommitUndo(editor);
2779 ME_UpdateRepaint(editor);
2786 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2787 size_t len = wszText ? lstrlenW(wszText) : 0;
2788 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2790 ME_GetSelection(editor, &from, &to);
2791 style = ME_GetSelectionInsertStyle(editor);
2792 ME_InternalDeleteText(editor, from, to-from, FALSE);
2793 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2794 ME_ReleaseStyle(style);
2795 /* drop temporary style if line end */
2797 * FIXME question: does abc\n mean: put abc,
2798 * clear temp style, put \n? (would require a change)
2800 if (len>0 && wszText[len-1] == '\n')
2801 ME_ClearTempStyle(editor);
2802 ME_EndToUnicode(unicode, wszText);
2803 ME_CommitUndo(editor);
2804 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2806 ME_EmptyUndoStack(editor);
2807 ME_UpdateRepaint(editor);
2810 case EM_SCROLLCARET:
2812 int top, bottom; /* row's edges relative to document top */
2814 ME_DisplayItem *para, *row;
2816 nPos = ME_GetYScrollPos(editor);
2817 row = ME_RowStart(editor->pCursors[0].pRun);
2818 para = ME_GetParagraph(row);
2819 top = para->member.para.pt.y + row->member.row.pt.y;
2820 bottom = top + row->member.row.nHeight;
2822 if (top < nPos) /* caret above window */
2823 ME_ScrollAbs(editor, top);
2824 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2825 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2833 BOOL bRepaint = LOWORD(lParam);
2836 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2837 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2839 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2840 ReleaseDC(hWnd, hDC);
2841 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2842 ME_SetDefaultCharFormat(editor, &fmt);
2844 ME_CommitUndo(editor);
2846 ME_RewrapRepaint(editor);
2851 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2854 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2855 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2857 /* Undocumented: WM_SETTEXT supports RTF text */
2858 ME_StreamInRTFString(editor, 0, (char *)lParam);
2862 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2863 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2864 if (lstrlenW(wszText) > 0)
2868 /* uses default style! */
2869 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2874 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2877 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2879 ME_EndToUnicode(unicode, wszText);
2883 TRACE("WM_SETTEXT - NULL\n");
2884 if (editor->AutoURLDetect_bEnable)
2886 ME_UpdateLinkAttribute(editor, 0, -1);
2888 ME_SetSelection(editor, 0, 0);
2889 editor->nModifyStep = 0;
2890 ME_CommitUndo(editor);
2891 ME_EmptyUndoStack(editor);
2892 ME_UpdateRepaint(editor);
2897 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2898 if (IsClipboardFormatAvailable(nRTFFormat))
2900 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2908 ME_GlobalDestStruct gds;
2909 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2912 if (IsClipboardFormatAvailable(nRTFFormat))
2913 cf = nRTFFormat, dwFormat = SF_RTF;
2914 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2915 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2919 if (!OpenClipboard(hWnd))
2921 gds.hData = GetClipboardData(cf);
2923 es.dwCookie = (DWORD)&gds;
2924 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2925 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2933 LPDATAOBJECT dataObj = NULL;
2937 if (editor->cPasswordMask)
2938 return 0; /* Copying or Cutting masked text isn't allowed */
2940 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2941 if(editor->lpOleCallback)
2942 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2943 if(FAILED(hr) || !dataObj)
2944 hr = ME_GetDataObject(editor, &range, &dataObj);
2946 hr = OleSetClipboard(dataObj);
2947 IDataObject_Release(dataObj);
2949 if (SUCCEEDED(hr) && msg == WM_CUT)
2951 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
2952 ME_CommitUndo(editor);
2953 ME_UpdateRepaint(editor);
2957 case WM_GETTEXTLENGTH:
2959 GETTEXTLENGTHEX how;
2961 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2962 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2963 how.codepage = unicode ? 1200 : CP_ACP;
2964 return ME_GetTextLengthEx(editor, &how);
2966 case EM_GETTEXTLENGTHEX:
2967 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2972 LPSTR bufferA = NULL;
2973 LPWSTR bufferW = NULL;
2976 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2978 bufferA = heap_alloc(wParam + 2);
2980 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2981 ex.flags = GT_USECRLF;
2982 ex.codepage = unicode ? 1200 : CP_ACP;
2983 ex.lpDefaultChar = NULL;
2984 ex.lpUsedDefChar = NULL;
2985 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2989 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2990 if (lstrlenW(bufferW) >= wParam) rc = 0;
2994 memcpy((LPSTR)lParam, bufferA, wParam);
2995 if (strlen(bufferA) >= wParam) rc = 0;
3003 GETTEXTEX *ex = (GETTEXTEX*)wParam;
3004 int nStart, nCount; /* in chars */
3006 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
3007 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
3009 if (ex->flags & GT_SELECTION)
3011 ME_GetSelection(editor, &nStart, &nCount);
3017 nCount = 0x7fffffff;
3019 if (ex->codepage == 1200)
3021 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
3022 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
3026 /* potentially each char may be a CR, why calculate the exact value with O(N) when
3027 we can just take a bigger buffer? :)
3028 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
3029 occurs only in richedit 2.0 mode, in which line breaks have only one CR
3031 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
3033 DWORD buflen = ex->cb;
3037 nCount = min(nCount, ex->cb - 1);
3038 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
3040 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
3041 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
3042 if (rc) rc--; /* do not count 0 terminator */
3051 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3052 ME_GetSelection(editor, &from, &to);
3053 tr.chrg.cpMin = from;
3055 tr.lpstrText = (WCHAR *)lParam;
3056 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
3058 case EM_GETSCROLLPOS:
3060 POINT *point = (POINT *)lParam;
3061 point->x = 0; /* FIXME side scrolling not implemented */
3062 point->y = ME_GetYScrollPos(editor);
3065 case EM_GETTEXTRANGE:
3067 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3068 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3069 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3070 editor->bEmulateVersion10, ME_GetTextLength(editor));
3072 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
3075 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
3076 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
3077 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
3078 /* FIXME this is a potential security hole (buffer overrun)
3079 if you know more about wchar->mbyte conversion please explain
3081 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
3088 ME_DisplayItem *run;
3089 const unsigned int nMaxChars = *(WORD *) lParam;
3090 unsigned int nCharsLeft = nMaxChars;
3091 char *dest = (char *) lParam;
3092 BOOL wroteNull = FALSE;
3094 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3095 unicode ? "Unicode" : "Ansi");
3097 run = ME_FindRowWithNumber(editor, wParam);
3101 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3102 && !(run->member.run.nFlags & MERF_ENDPARA))
3106 if (run->type != diRun)
3108 strText = run->member.run.strText;
3109 nCopy = min(nCharsLeft, strText->nLen);
3112 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
3114 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3115 nCharsLeft, NULL, NULL);
3116 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3117 nCharsLeft -= nCopy;
3120 /* append line termination, space allowing */
3123 if (run && (run->member.run.nFlags & MERF_ENDPARA))
3126 /* Write as many \r as encoded in end-of-paragraph, space allowing */
3127 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3129 *((WCHAR *)dest) = '\r';
3130 dest += unicode ? sizeof(WCHAR) : 1;
3132 /* Write as many \n as encoded in end-of-paragraph, space allowing */
3133 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3135 *((WCHAR *)dest) = '\n';
3136 dest += unicode ? sizeof(WCHAR) : 1;
3142 *((WCHAR *)dest) = '\0';
3150 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3151 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3153 case EM_GETLINECOUNT:
3155 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3158 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3160 while (item != editor->pBuffer->pLast)
3162 assert(item->type == diParagraph);
3163 prev_para = ME_FindItemBack(item, diRun);
3165 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3167 nRows += item->member.para.nRows;
3168 item = item->member.para.next_para;
3170 last_para = ME_FindItemBack(item, diRun);
3172 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3173 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3174 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3176 /* In 1.0 emulation, the last solitary \r at the very end of the text
3177 (if one exists) is NOT a line break.
3178 FIXME: this is an ugly hack. This should have a more regular model. */
3182 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3183 return max(1, nRows);
3185 case EM_LINEFROMCHAR:
3188 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3190 return ME_RowNumberFromCharOfs(editor, wParam);
3192 case EM_EXLINEFROMCHAR:
3195 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3197 return ME_RowNumberFromCharOfs(editor, lParam);
3201 ME_DisplayItem *item, *para;
3205 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3207 item = ME_FindRowWithNumber(editor, wParam);
3210 para = ME_GetParagraph(item);
3211 item = ME_FindItemFwd(item, diRun);
3212 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3213 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3218 ME_DisplayItem *item, *item_end;
3219 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3221 if (wParam > ME_GetTextLength(editor))
3225 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3228 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3229 item = ME_RowStart(item);
3230 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3231 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3232 if (item_end->type == diStartRow)
3233 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3236 ME_DisplayItem *endPara;
3238 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3239 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3240 endPara = ME_FindItemBack(endPara, diRun);
3242 assert(endPara->type == diRun);
3243 assert(endPara->member.run.nFlags & MERF_ENDPARA);
3244 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3246 nChars = nNextLineOfs - nThisLineOfs;
3247 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3250 case EM_EXLIMITTEXT:
3252 if ((int)lParam < 0)
3255 editor->nTextLimit = 65536;
3257 editor->nTextLimit = (int) lParam;
3263 editor->nTextLimit = 65536;
3265 editor->nTextLimit = (int) wParam;
3268 case EM_GETLIMITTEXT:
3270 return editor->nTextLimit;
3274 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3275 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3279 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3280 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3281 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3287 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3288 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3292 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3293 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3294 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3300 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3301 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3303 case EM_FINDTEXTEXW:
3305 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3306 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3309 if (!wParam || !lParam)
3311 *(int *)wParam = editor->nZoomNumerator;
3312 *(int *)lParam = editor->nZoomDenominator;
3315 return ME_SetZoom(editor, wParam, lParam);
3316 case EM_CHARFROMPOS:
3317 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3318 case EM_POSFROMCHAR:
3320 ME_DisplayItem *pRun;
3321 int nCharOfs, nOffset, nLength;
3326 /* detect which API version we're dealing with */
3327 if (wParam >= 0x40000)
3329 nLength = ME_GetTextLength(editor);
3331 if (nCharOfs < nLength) {
3332 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3333 assert(pRun->type == diRun);
3334 pt.y = pRun->member.run.pt.y;
3335 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3336 pt.y += ME_GetParagraph(pRun)->member.para.pt.y;
3339 pt.y = editor->pBuffer->pLast->member.para.pt.y;
3341 pt.x += editor->selofs;
3343 si.cbSize = sizeof(si);
3345 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3346 si.cbSize = sizeof(si);
3348 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3350 if (wParam >= 0x40000) {
3351 *(POINTL *)wParam = pt;
3353 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3359 GetClientRect(hWnd, &editor->rcFormat);
3360 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3361 { /* Squelch the default horizontal scrollbar it would make */
3362 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3365 si.cbSize = sizeof(si);
3366 si.fMask = SIF_PAGE | SIF_RANGE;
3367 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3368 si.fMask |= SIF_DISABLENOSCROLL;
3369 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3372 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3374 ME_CommitUndo(editor);
3375 ME_WrapMarkedParagraphs(editor);
3376 ME_MoveCaret(editor);
3380 ME_DestroyEditor(editor);
3381 SetWindowLongPtrW(hWnd, 0, 0);
3385 return ME_SetCursor(editor);
3387 case WM_LBUTTONDBLCLK:
3388 case WM_LBUTTONDOWN:
3390 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3391 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3392 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3395 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3396 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3398 ME_LinkNotify(editor,msg,wParam,lParam);
3399 if (!ME_SetCursor(editor)) goto do_default;
3403 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3404 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3406 if (GetCapture() == hWnd)
3407 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3408 ME_LinkNotify(editor,msg,wParam,lParam);
3409 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3410 if (GetCapture() == hWnd)
3411 ME_SetCursor(editor);
3414 if (GetCapture() == hWnd)
3416 if (editor->nSelectionType == stDocument)
3417 editor->nSelectionType = stPosition;
3418 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3419 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3423 ME_SetCursor(editor);
3424 ME_LinkNotify(editor,msg,wParam,lParam);
3428 case WM_RBUTTONDOWN:
3429 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3430 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3431 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3434 case WM_CONTEXTMENU:
3435 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3439 if (editor->bRedraw)
3444 hDC = BeginPaint(hWnd, &ps);
3445 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3446 EndPaint(hWnd, &ps);
3450 editor->bHaveFocus = TRUE;
3451 ME_ShowCaret(editor);
3452 ME_SendOldNotify(editor, EN_SETFOCUS);
3455 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3456 editor->bHaveFocus = FALSE;
3457 ME_HideCaret(editor);
3458 ME_SendOldNotify(editor, EN_KILLFOCUS);
3462 if (editor->bRedraw)
3464 HDC hDC = (HDC)wParam;
3466 if (GetUpdateRect(hWnd,&rc,TRUE))
3468 FillRect(hDC, &rc, editor->hbrBackground);
3474 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3477 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3478 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3482 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3483 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3485 if (ME_KeyDown(editor, LOWORD(wParam)))
3493 wstr = (WCHAR)wParam;
3496 CHAR charA = wParam;
3497 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3502 case 1: /* Ctrl-A */
3503 ME_SetSelection(editor, 0, -1);
3505 case 3: /* Ctrl-C */
3506 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3510 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3511 MessageBeep(MB_ICONERROR);
3512 return 0; /* FIXME really 0 ? */
3517 case 22: /* Ctrl-V */
3518 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3520 case 24: /* Ctrl-X */
3521 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3523 case 25: /* Ctrl-Y */
3524 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3526 case 26: /* Ctrl-Z */
3527 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3530 if (((unsigned)wstr)>=' '
3531 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3534 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
3535 ME_GetSelection(editor, &from, &to);
3537 /* v4.1 allows tabs to be inserted with ctrl key down */
3538 && !(ctrl_is_down && !editor->bEmulateVersion10)
3541 ME_Cursor cursor = editor->pCursors[0];
3542 ME_DisplayItem *para;
3543 BOOL bSelectedRow = FALSE;
3545 para = ME_GetParagraph(cursor.pRun);
3546 if (ME_IsSelection(editor) &&
3547 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3548 para->member.para.prev_para->type == diParagraph)
3550 para = para->member.para.prev_para;
3551 bSelectedRow = TRUE;
3553 if (ME_IsInTable(para))
3555 ME_TabPressedInTable(editor, bSelectedRow);
3556 ME_CommitUndo(editor);
3560 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3561 /* WM_CHAR is restricted to nTextLimit */
3562 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3564 ME_Style *style = ME_GetInsertStyle(editor, 0);
3565 ME_SaveTempStyle(editor);
3566 ME_ContinueCoalescingTransaction(editor);
3567 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3568 ME_InsertEndRowFromCursor(editor, 0);
3570 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3571 ME_ReleaseStyle(style);
3572 ME_CommitCoalescingUndo(editor);
3576 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3578 ME_UpdateRepaint(editor);
3585 if(wParam == UNICODE_NOCHAR) return TRUE;
3586 if(wParam <= 0x000fffff)
3588 if(wParam > 0xffff) /* convert to surrogates */
3591 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3592 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3594 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3599 case EM_STOPGROUPTYPING:
3600 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3602 case EM_SCROLL: /* fall through */
3608 origNPos = ME_GetYScrollPos(editor);
3611 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3612 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3613 if (lineHeight <= 0) lineHeight = 24;
3615 switch(LOWORD(wParam))
3618 ME_ScrollUp(editor,lineHeight);
3621 ME_ScrollDown(editor,lineHeight);
3624 ME_ScrollUp(editor,editor->sizeWindow.cy);
3627 ME_ScrollDown(editor,editor->sizeWindow.cy);
3630 case SB_THUMBPOSITION:
3631 ME_ScrollAbs(editor,HIWORD(wParam));
3634 if (msg == EM_SCROLL)
3635 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3641 UINT pulScrollLines;
3643 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3644 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3647 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3648 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3650 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3652 /* FIXME follow the original */
3653 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3659 *((RECT *)lParam) = editor->rcFormat;
3667 RECT *rc = (RECT *)lParam;
3671 editor->rcFormat.left += rc->left;
3672 editor->rcFormat.top += rc->top;
3673 editor->rcFormat.right += rc->right;
3674 editor->rcFormat.bottom += rc->bottom;
3678 editor->rcFormat = *rc;
3683 GetClientRect(hWnd, &editor->rcFormat);
3685 if (msg != EM_SETRECTNP)
3686 ME_RewrapRepaint(editor);
3689 case EM_REQUESTRESIZE:
3690 ME_SendRequestResize(editor, TRUE);
3693 if ((editor->bRedraw = wParam))
3694 ME_RewrapRepaint(editor);
3698 GetClientRect(hWnd, &editor->rcFormat);
3699 ME_RewrapRepaint(editor);
3700 return DefWindowProcW(hWnd, msg, wParam, lParam);
3702 /* IME messages to make richedit controls IME aware */
3703 case WM_IME_SETCONTEXT:
3704 case WM_IME_CONTROL:
3706 case WM_IME_COMPOSITIONFULL:
3708 case WM_IME_STARTCOMPOSITION:
3710 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3711 ME_DeleteSelection(editor);
3712 ME_CommitUndo(editor);
3713 ME_UpdateRepaint(editor);
3716 case WM_IME_COMPOSITION:
3720 ME_Style *style = ME_GetInsertStyle(editor, 0);
3721 hIMC = ImmGetContext(hWnd);
3722 ME_DeleteSelection(editor);
3723 ME_CommitUndo(editor);
3724 ME_SaveTempStyle(editor);
3725 if (lParam & GCS_RESULTSTR)
3727 LPWSTR lpCompStr = NULL;
3730 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3731 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3732 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3733 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3734 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3736 else if (lParam & GCS_COMPSTR)
3738 LPWSTR lpCompStr = NULL;
3741 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3742 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3743 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3744 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3746 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3747 ME_SetSelection(editor,editor->imeStartIndex,
3748 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3750 ME_ReleaseStyle(style);
3751 ME_UpdateRepaint(editor);
3754 case WM_IME_ENDCOMPOSITION:
3756 ME_DeleteSelection(editor);
3757 editor->imeStartIndex=-1;
3760 case EM_GETOLEINTERFACE:
3762 LPVOID *ppvObj = (LPVOID*) lParam;
3763 return CreateIRichEditOle(editor, ppvObj);
3765 case EM_GETPASSWORDCHAR:
3767 return editor->cPasswordMask;
3769 case EM_SETOLECALLBACK:
3770 if(editor->lpOleCallback)
3771 IUnknown_Release(editor->lpOleCallback);
3772 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3773 if(editor->lpOleCallback)
3774 IUnknown_AddRef(editor->lpOleCallback);
3776 case EM_GETWORDBREAKPROC:
3777 return (LRESULT)editor->pfnWordBreak;
3778 case EM_SETWORDBREAKPROC:
3780 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3782 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3783 return (LRESULT)pfnOld;
3785 case EM_SETTEXTMODE:
3790 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3793 /*Check for valid wParam*/
3794 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3795 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3796 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3800 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3802 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3803 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3805 /*FIXME: Currently no support for undo level and code page options*/
3806 editor->mode = (editor->mode & (~mask)) | changes;
3812 case EM_SETPASSWORDCHAR:
3814 editor->cPasswordMask = wParam;
3815 ME_RewrapRepaint(editor);
3818 case EM_SETTARGETDEVICE:
3821 BOOL new = (lParam == 0);
3822 if (editor->bWordWrap != new)
3824 editor->bWordWrap = new;
3825 ME_RewrapRepaint(editor);
3828 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3832 return DefWindowProcW(hWnd, msg, wParam, lParam);
3837 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3839 BOOL unicode = TRUE;
3841 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3842 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3845 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3848 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3850 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3853 /******************************************************************
3854 * RichEditANSIWndProc (RICHED20.10)
3856 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3858 return RichEditWndProcA(hWnd, msg, wParam, lParam);
3861 /******************************************************************
3862 * RichEdit10ANSIWndProc (RICHED20.9)
3864 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3868 /* FIXME: this is NOT the same as 2.0 version */
3869 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3870 if (msg == WM_NCCREATE)
3872 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3874 editor->bEmulateVersion10 = TRUE;
3875 editor->pBuffer->pLast->member.para.nCharOfs = 2;
3876 assert(editor->pBuffer->pLast->prev->type == diRun);
3877 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3878 editor->pBuffer->pLast->prev->member.run.nLF = 1;
3883 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3885 HWND hWnd = editor->hWnd;
3886 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3889 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3892 ME_Cursor tmpCursor;
3894 int nCharOfs; /* The start of the clicked text. Absolute character offset */
3899 x = (short)LOWORD(lParam);
3900 y = (short)HIWORD(lParam);
3901 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
3902 if (!isExact) return;
3904 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3905 tmpRun = &tmpCursor.pRun->member.run;
3907 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3908 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3909 { /* The clicked run has CFE_LINK set */
3910 info.nmhdr.hwndFrom = editor->hWnd;
3911 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3912 info.nmhdr.code = EN_LINK;
3914 info.wParam = wParam;
3915 info.lParam = lParam;
3916 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3917 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3918 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3922 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3924 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3927 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3928 item = item->member.para.next_para;
3931 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3932 item = item->member.para.next_para;
3939 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3941 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3943 WCHAR *pStart = buffer;
3950 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3951 if (editor->bEmulateVersion10) bCRLF = 0;
3955 int nLen = ME_StrLen(item->member.run.strText) - nStart;
3958 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3967 item = ME_FindItemFwd(item, diRun);
3970 while(nChars && item)
3972 int nLen = ME_StrLen(item->member.run.strText);
3973 if (item->member.run.nFlags & MERF_ENDPARA)
3974 nLen = item->member.run.nCR + item->member.run.nLF;
3978 if (item->member.run.nFlags & MERF_ENDCELL &&
3979 item->member.run.nFlags & MERF_ENDPARA)
3983 else if (item->member.run.nFlags & MERF_ENDPARA)
3985 if (!ME_FindItemFwd(item, diRun))
3986 /* No '\r' is appended to the last paragraph. */
3988 else if (bCRLF && nChars == 1) {
3994 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
3995 if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4000 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4010 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4012 while (nChars - i > 0 && i < item->member.run.nCR)
4014 buffer[i] = '\r'; i++;
4017 while (nChars - i - j > 0 && j < item->member.run.nLF)
4019 buffer[i+j] = '\n'; j++;
4025 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4032 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4036 item = ME_FindItemFwd(item, diRun);
4039 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4043 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4048 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4049 wcW.lpfnWndProc = RichEditWndProcW;
4051 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4052 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4054 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4055 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4056 wcW.lpszMenuName = NULL;
4058 if (is_version_nt())
4060 wcW.lpszClassName = RichEdit20W;
4061 if (!RegisterClassW(&wcW)) return FALSE;
4062 wcW.lpszClassName = RichEdit50W;
4063 if (!RegisterClassW(&wcW)) return FALSE;
4067 /* WNDCLASSA/W have the same layout */
4068 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4069 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4070 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4071 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4074 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4075 wcA.lpfnWndProc = RichEditWndProcA;
4077 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4078 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4080 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4081 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4082 wcA.lpszMenuName = NULL;
4083 wcA.lpszClassName = "RichEdit20A";
4084 if (!RegisterClassA(&wcA)) return FALSE;
4085 wcA.lpszClassName = "RichEdit50A";
4086 if (!RegisterClassA(&wcA)) return FALSE;
4091 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4092 /* FIXME: Not implemented */
4093 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4094 hWnd, msg, get_msg_name(msg), wParam, lParam);
4095 return DefWindowProcW(hWnd, msg, wParam, lParam);
4098 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4099 /* FIXME: Not implemented */
4100 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4101 hWnd, msg, get_msg_name(msg), wParam, lParam);
4102 return DefWindowProcW(hWnd, msg, wParam, lParam);
4105 /******************************************************************
4106 * REExtendedRegisterClass (RICHED20.8)
4108 * FIXME undocumented
4109 * Need to check for errors and implement controls and callbacks
4111 LRESULT WINAPI REExtendedRegisterClass(void)
4116 FIXME("semi stub\n");
4120 wcW.hInstance = NULL;
4123 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4124 wcW.lpszMenuName = NULL;
4126 if (!ME_ListBoxRegistered)
4128 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4129 wcW.lpfnWndProc = REListWndProc;
4130 wcW.lpszClassName = REListBox20W;
4131 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4134 if (!ME_ComboBoxRegistered)
4136 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4137 wcW.lpfnWndProc = REComboWndProc;
4138 wcW.lpszClassName = REComboBox20W;
4139 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4143 if (ME_ListBoxRegistered)
4145 if (ME_ComboBoxRegistered)
4151 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
4171 int curf_ef, link_ef, def_ef;
4172 int cur_prefx, prefx_cnt;
4173 int sel_min, sel_max;
4176 int URLmin, URLmax = 0;
4178 CHARFORMAT2W cur_format;
4179 CHARFORMAT2W default_format;
4181 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
4182 sel_min = ins_pt.cpMin;
4183 sel_max = ins_pt.cpMax;
4184 if (sel_min==sel_max)
4186 if (sel_min!=sel_max)
4187 car_pos = ME_GetTextLength(editor)+1;
4188 cur_format.cbSize = sizeof(cur_format);
4189 default_format.cbSize = sizeof(default_format);
4190 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
4191 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
4192 link.cbSize = sizeof(link);
4193 link.dwMask = CFM_LINK;
4194 link.dwEffects = CFE_LINK;
4195 curf_ef = cur_format.dwEffects & link.dwEffects;
4196 def_ef = default_format.dwEffects & link.dwEffects;
4197 link_ef = link.dwEffects & link.dwEffects;
4198 if (curf_ef == link_ef)
4200 if( curChar == '\n' || curChar=='\r' || curChar==' ')
4202 ME_SetSelection(editor, car_pos, car_pos);
4203 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
4208 if (curf_ef == def_ef)
4211 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
4212 while (cur_prefx<=prefx_cnt)
4216 ft.lpstrText = prefixes[cur_prefx].text;
4217 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
4218 URLmax=max(0, car_pos);
4219 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
4221 URLmax = ME_GetTextLength(editor)+1;
4223 ft.chrg.cpMin = URLmin;
4224 ft.chrg.cpMax = URLmax;
4225 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
4230 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
4231 ME_RewrapRepaint(editor);
4240 static BOOL isurlspecial(WCHAR c)
4242 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4243 return strchrW( special_chars, c ) != NULL;
4247 * This proc takes a selection, and scans it forward in order to select the span
4248 * of a possible URL candidate. A possible URL candidate must start with isalnum
4249 * or one of the following special characters: *|/\+%#@ and must consist entirely
4250 * of the characters allowed to start the URL, plus : (colon) which may occur
4251 * at most once, and not at either end.
4253 * sel_max == -1 indicates scan to end of text.
4255 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4256 int * candidate_min, int * candidate_max)
4258 ME_DisplayItem * item;
4259 ME_DisplayItem * para;
4261 BOOL foundColon = FALSE;
4262 WCHAR lastAcceptedChar = '\0';
4264 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4266 *candidate_min = *candidate_max = -1;
4267 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4268 if (!item) return FALSE;
4269 TRACE("nStart = %d\n", nStart);
4270 para = ME_GetParagraph(item);
4271 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4272 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4274 ME_DisplayItem * next_item;
4276 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4277 /* Find start of candidate */
4278 if (*candidate_min == -1) {
4279 while (nStart < ME_StrLen(item->member.run.strText) &&
4280 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4281 isurlspecial(item->member.run.strText->szData[nStart]))) {
4284 if (nStart < ME_StrLen(item->member.run.strText) &&
4285 (isalnumW(item->member.run.strText->szData[nStart]) ||
4286 isurlspecial(item->member.run.strText->szData[nStart]))) {
4287 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4288 lastAcceptedChar = item->member.run.strText->szData[nStart];
4293 /* Find end of candidate */
4294 if (*candidate_min >= 0) {
4295 while (nStart < ME_StrLen(item->member.run.strText) &&
4296 (isalnumW(item->member.run.strText->szData[nStart]) ||
4297 isurlspecial(item->member.run.strText->szData[nStart]) ||
4298 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4299 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4300 lastAcceptedChar = item->member.run.strText->szData[nStart];
4303 if (nStart < ME_StrLen(item->member.run.strText) &&
4304 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4305 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4306 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4308 if (lastAcceptedChar == ':') (*candidate_max)--;
4313 /* End of paragraph: skip it if before candidate span, or terminates
4314 current active span */
4315 if (*candidate_min >= 0) {
4316 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4317 if (lastAcceptedChar == ':') (*candidate_max)--;
4322 /* Reaching this point means no span was found, so get next span */
4323 next_item = ME_FindItemFwd(item, diRun);
4325 if (*candidate_min >= 0) {
4326 /* There are no further runs, so take end of text as end of candidate */
4327 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4328 if (lastAcceptedChar == ':') (*candidate_max)--;
4333 para = ME_GetParagraph(item);
4338 if (*candidate_min >= 0) {
4339 /* There are no further runs, so take end of text as end of candidate */
4340 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4341 if (lastAcceptedChar == ':') (*candidate_max)--;
4349 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4351 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4357 /* Code below depends on these being in decreasing length order! */
4371 LPWSTR bufferW = NULL;
4375 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4376 assert(sel_min <= sel_max);
4377 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4379 if (sel_max - sel_min < prefixes[i].length) continue;
4380 if (bufferW == NULL) {
4381 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4383 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4384 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4385 if (!lstrcmpW(bufW, bufferW))
4396 * This proc walks through the indicated selection and evaluates whether each
4397 * section identified by ME_FindNextURLCandidate and in-between sections have
4398 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4399 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4401 * Returns TRUE if at least one section was modified.
4403 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4405 BOOL modified = FALSE;
4408 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4415 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4417 /* Section before candidate is not an URL */
4418 beforeURL[0] = sel_min;
4419 beforeURL[1] = cMin;
4421 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4423 inURL[0] = cMin; inURL[1] = cMax;
4427 beforeURL[1] = cMax;
4428 inURL[0] = inURL[1] = -1;
4434 /* No more candidates until end of selection */
4435 beforeURL[0] = sel_min;
4436 beforeURL[1] = sel_max;
4437 inURL[0] = inURL[1] = -1;
4441 if (beforeURL[0] < beforeURL[1])
4443 /* CFE_LINK effect should be consistently unset */
4444 link.cbSize = sizeof(link);
4445 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4446 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4448 /* CFE_LINK must be unset from this range */
4449 memset(&link, 0, sizeof(CHARFORMAT2W));
4450 link.cbSize = sizeof(link);
4451 link.dwMask = CFM_LINK;
4453 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4457 if (inURL[0] < inURL[1])
4459 /* CFE_LINK effect should be consistently set */
4460 link.cbSize = sizeof(link);
4461 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4462 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4464 /* CFE_LINK must be set on this range */
4465 memset(&link, 0, sizeof(CHARFORMAT2W));
4466 link.cbSize = sizeof(link);
4467 link.dwMask = CFM_LINK;
4468 link.dwEffects = CFE_LINK;
4469 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4473 } while (sel_min < sel_max);
4477 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4479 ME_DisplayItem * startPara, * endPara;
4480 ME_DisplayItem * item;
4484 ME_GetSelection(editor, &from, &to);
4485 if (from > to) from ^= to, to ^=from, from ^= to;
4486 startPara = NULL; endPara = NULL;
4488 /* Find paragraph previous to the one that contains start cursor */
4489 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4491 startPara = ME_FindItemBack(item, diParagraph);
4492 item = ME_FindItemBack(startPara, diParagraph);
4493 if (item) startPara = item;
4496 /* Find paragraph that contains end cursor */
4497 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4499 endPara = ME_FindItemFwd(item, diParagraph);
4502 if (startPara && endPara) {
4503 ME_UpdateLinkAttribute(editor,
4504 startPara->member.para.nCharOfs,
4505 endPara->member.para.nCharOfs);
4506 } else if (startPara) {
4507 ME_UpdateLinkAttribute(editor,
4508 startPara->member.para.nCharOfs,