comctl32: Update Polish translation.
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Cihan Altinay
6  * Copyright 2005 by Phil Krylov
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /* 
24   API implementation status:
25   
26   Messages (ANSI versions not done yet)
27   + EM_AUTOURLDETECT 2.0
28   + EM_CANPASTE
29   + EM_CANREDO 2.0
30   + EM_CANUNDO
31   + EM_CHARFROMPOS
32   - EM_DISPLAYBAND
33   + EM_EMPTYUNDOBUFFER
34   + EM_EXGETSEL
35   + EM_EXLIMITTEXT
36   + EM_EXLINEFROMCHAR
37   + EM_EXSETSEL
38   + EM_FINDTEXT (only FR_DOWN flag implemented)
39   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
40   - EM_FINDWORDBREAK
41   - EM_FMTLINES
42   - EM_FORMATRANGE
43   + EM_GETAUTOURLDETECT 2.0
44   - EM_GETBIDIOPTIONS 3.0
45   - EM_GETCHARFORMAT (partly done)
46   - EM_GETEDITSTYLE
47   + EM_GETEVENTMASK
48   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
49   - EM_GETIMECOLOR 1.0asian
50   - EM_GETIMECOMPMODE 2.0
51   - EM_GETIMEOPTIONS 1.0asian
52   - EM_GETIMESTATUS
53   - EM_GETLANGOPTIONS 2.0
54   + EM_GETLIMITTEXT
55   + EM_GETLINE
56   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
57   + EM_GETMODIFY
58   - EM_GETOLEINTERFACE
59   + EM_GETOPTIONS
60   + EM_GETPARAFORMAT
61   + EM_GETPASSWORDCHAR 2.0
62   - EM_GETPUNCTUATION 1.0asian
63   + EM_GETRECT
64   - EM_GETREDONAME 2.0
65   + EM_GETSEL
66   + EM_GETSELTEXT (ANSI&Unicode)
67   + EM_GETSCROLLPOS 3.0 (only Y value valid)
68 ! - EM_GETTHUMB
69   - EM_GETTEXTEX 2.0
70   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
71   - EM_GETTEXTMODE 2.0
72 ? + EM_GETTEXTRANGE (ANSI&Unicode)
73   - EM_GETTYPOGRAPHYOPTIONS 3.0
74   - EM_GETUNDONAME
75   + EM_GETWORDBREAKPROC
76   - EM_GETWORDBREAKPROCEX
77   - EM_GETWORDWRAPMODE 1.0asian
78   + EM_GETZOOM 3.0
79   + EM_HIDESELECTION
80   - EM_LIMITTEXT
81   + EM_LINEFROMCHAR
82   + EM_LINEINDEX
83   + EM_LINELENGTH
84   + EM_LINESCROLL
85   - EM_PASTESPECIAL
86   + EM_POSFROMCHAR
87   + EM_REDO 2.0
88   + EM_REQUESTRESIZE
89   + EM_REPLACESEL (proper style?) ANSI&Unicode
90   + EM_SCROLL
91   + EM_SCROLLCARET
92   - EM_SELECTIONTYPE
93   - EM_SETBIDIOPTIONS 3.0
94   + EM_SETBKGNDCOLOR
95   + EM_SETCHARFORMAT (partly done, no ANSI)
96   - EM_SETEDITSTYLE
97   + EM_SETEVENTMASK (few notifications supported)
98   - EM_SETFONTSIZE
99   - EM_SETIMECOLOR 1.0asian
100   - EM_SETIMEOPTIONS 1.0asian
101   - EM_SETLANGOPTIONS 2.0
102   - EM_SETLIMITTEXT
103   + EM_SETMODIFY (not sure if implementation is correct)
104   - EM_SETOLECALLBACK
105   + EM_SETOPTIONS (partially implemented)
106   - EM_SETPALETTE 2.0
107   + EM_SETPARAFORMAT
108   + EM_SETPASSWORDCHAR 2.0
109   - EM_SETPUNCTUATION 1.0asian
110   + EM_SETREADONLY no beep on modification attempt
111   + EM_SETRECT
112   + EM_SETRECTNP (EM_SETRECT without repainting)
113   + EM_SETSEL
114   + EM_SETSCROLLPOS 3.0
115   - EM_SETTABSTOPS 3.0
116   - EM_SETTARGETDEVICE
117   + EM_SETTEXTEX 3.0 (unicode only, no rich text insertion handling, proper style?)
118   - EM_SETTEXTMODE 2.0
119   - EM_SETTYPOGRAPHYOPTIONS 3.0
120   + EM_SETUNDOLIMIT 2.0
121   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
122   - EM_SETWORDBREAKPROCEX
123   - EM_SETWORDWRAPMODE 1.0asian
124   + EM_SETZOOM 3.0
125   + EM_SHOWSCROLLBAR 2.0
126   - EM_STOPGROUPTYPING 2.0
127   + EM_STREAMIN
128   + EM_STREAMOUT
129   + EM_UNDO
130   + WM_CHAR
131   + WM_CLEAR
132   + WM_COPY
133   + WM_CUT
134   + WM_GETDLGCODE (the current implementation is incomplete)
135   + WM_GETTEXT (ANSI&Unicode)
136   + WM_GETTEXTLENGTH (ANSI version sucks)
137   + WM_PASTE
138   + WM_SETFONT
139   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
140   - WM_STYLECHANGING
141   - WM_STYLECHANGED (things like read-only flag)
142   - WM_UNICHAR
143   
144   Notifications
145   
146   * EN_CHANGE (sent from the wrong place)
147   - EN_CORRECTTEXT
148   - EN_DROPFILES
149   - EN_ERRSPACE
150   - EN_HSCROLL
151   - EN_IMECHANGE
152   + EN_KILLFOCUS
153   - EN_LINK
154   - EN_MAXTEXT
155   - EN_MSGFILTER
156   - EN_OLEOPFAILED
157   - EN_PROTECTED
158   + EN_REQUESTRESIZE
159   - EN_SAVECLIPBOARD
160   + EN_SELCHANGE 
161   + EN_SETFOCUS
162   - EN_STOPNOUNDO
163   * EN_UPDATE (sent from the wrong place)
164   - EN_VSCROLL
165   
166   Styles
167   
168   - ES_AUTOHSCROLL
169   - ES_AUTOVSCROLL
170   - ES_CENTER
171   + ES_DISABLENOSCROLL (scrollbar is always visible)
172   - ES_EX_NOCALLOLEINIT
173   - ES_LEFT
174   - ES_MULTILINE (currently single line controls aren't supported)
175   - ES_NOIME
176   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
177   - ES_RIGHT
178   - ES_SAVESEL
179   - ES_SELFIME
180   - ES_SUNKEN
181   - ES_VERTICAL
182   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
183   - WS_SETFONT
184   - WS_HSCROLL
185   + WS_VSCROLL
186 */
187
188 /*
189  * RICHED20 TODO (incomplete):
190  *
191  * - messages/styles/notifications listed above 
192  * - Undo coalescing 
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)
200  * - find/replace
201  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202  * - italic caret with italic fonts
203  * - IME
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
209  * - hyphenation
210  * - tables
211  * - ListBox & ComboBox not implemented
212  *
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?
221  *
222  */
223
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM 
228 #include "shlwapi.h"
229 #include "imm.h"
230 #include "textserv.h"
231 #include "rtf.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 int me_debug = 0;
241 HANDLE me_heap = NULL;
242
243 static BOOL ME_ListBoxRegistered = FALSE;
244 static BOOL ME_ComboBoxRegistered = FALSE;
245
246 static ME_TextBuffer *ME_MakeText(void) {
247   
248   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
249
250   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
251   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
252   
253   p1->prev = NULL;
254   p1->next = p2;
255   p2->prev = p1;
256   p2->next = NULL;
257   p1->member.para.next_para = p2;
258   p2->member.para.prev_para = p1;
259   p2->member.para.nCharOfs = 0;  
260   
261   buf->pFirst = p1;
262   buf->pLast = p2;
263   buf->pCharStyle = NULL;
264   
265   return buf;
266 }
267
268
269 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
270 {
271   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
272   WCHAR *pText;
273   
274   TRACE("%08lx %p\n", dwFormat, stream);
275   
276   do {
277     long nWideChars = 0;
278
279     if (!stream->dwSize)
280     {
281       ME_StreamInFill(stream);
282       if (stream->editstream->dwError)
283         break;
284       if (!stream->dwSize)
285         break;
286     }
287       
288     if (!(dwFormat & SF_UNICODE))
289     {
290       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
291       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
292       pText = wszText;
293     }
294     else
295     {
296       nWideChars = stream->dwSize >> 1;
297       pText = (WCHAR *)stream->buffer;
298     }
299     
300     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
301     if (stream->dwSize == 0)
302       break;
303     stream->dwSize = 0;
304   } while(1);
305   ME_CommitUndo(editor);
306   ME_UpdateRepaint(editor);
307   return 0;
308 }
309
310 static void ME_RTFCharAttrHook(RTF_Info *info)
311 {
312   CHARFORMAT2W fmt;
313   fmt.cbSize = sizeof(fmt);
314   fmt.dwMask = 0;
315   fmt.dwEffects = 0;
316
317   switch(info->rtfMinor)
318   {
319     case rtfPlain:
320       /* FIXME add more flags once they're implemented */
321       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
322       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
323       fmt.yHeight = 12*20; /* 12pt */
324       fmt.wWeight = 400;
325       break;
326     case rtfBold:
327       fmt.dwMask = CFM_BOLD;
328       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
329       break;
330     case rtfItalic:
331       fmt.dwMask = CFM_ITALIC;
332       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
333       break;
334     case rtfUnderline:
335       fmt.dwMask = CFM_UNDERLINE;
336       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
337       fmt.bUnderlineType = CFU_CF1UNDERLINE;
338       break;
339     case rtfNoUnderline:
340       fmt.dwMask = CFM_UNDERLINE;
341       fmt.dwEffects = 0;
342       break;
343     case rtfStrikeThru:
344       fmt.dwMask = CFM_STRIKEOUT;
345       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
346       break;
347     case rtfSubScript:
348     case rtfSuperScript:
349     case rtfSubScrShrink:
350     case rtfSuperScrShrink:
351     case rtfNoSuperSub:
352       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
353       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
354       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
355       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
356       break;
357     case rtfInvisible:
358       fmt.dwMask = CFM_HIDDEN;
359       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
360       break;
361     case rtfBackColor:
362       fmt.dwMask = CFM_BACKCOLOR;
363       fmt.dwEffects = 0;
364       if (info->rtfParam == 0)
365         fmt.dwEffects = CFE_AUTOBACKCOLOR;
366       else if (info->rtfParam != rtfNoParam)
367       {
368         RTFColor *c = RTFGetColor(info, info->rtfParam);
369         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
370       }
371       break;
372     case rtfForeColor:
373       fmt.dwMask = CFM_COLOR;
374       fmt.dwEffects = 0;
375       if (info->rtfParam == 0)
376         fmt.dwEffects = CFE_AUTOCOLOR;
377       else if (info->rtfParam != rtfNoParam)
378       {
379         RTFColor *c = RTFGetColor(info, info->rtfParam);
380         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
381       }
382       break;
383     case rtfFontNum:
384       if (info->rtfParam != rtfNoParam)
385       {
386         RTFFont *f = RTFGetFont(info, info->rtfParam);
387         if (f)
388         {
389           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
390           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
391           fmt.bCharSet = f->rtfFCharSet;
392           fmt.dwMask = CFM_FACE | CFM_CHARSET;
393         }
394       }
395       break;
396     case rtfFontSize:
397       fmt.dwMask = CFM_SIZE;
398       if (info->rtfParam != rtfNoParam)
399         fmt.yHeight = info->rtfParam*10;
400       break;
401   }
402   if (fmt.dwMask) {
403     ME_Style *style2;
404     RTFFlushOutputBuffer(info);
405     /* FIXME too slow ? how come ? */
406     style2 = ME_ApplyStyle(info->style, &fmt);
407     ME_ReleaseStyle(info->style);
408     info->style = style2;
409     info->styleChanged = TRUE;
410   }
411 }
412
413 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
414    the same tags mean different things in different contexts */
415 static void ME_RTFParAttrHook(RTF_Info *info)
416 {
417   PARAFORMAT2 fmt;
418   fmt.cbSize = sizeof(fmt);
419   fmt.dwMask = 0;
420   
421   switch(info->rtfMinor)
422   {
423   case rtfParDef: /* restores default paragraph attributes */
424     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
425     fmt.wAlignment = PFA_LEFT;
426     fmt.cTabCount = 0;
427     fmt.dxOffset = fmt.dxStartIndent = 0;
428     RTFFlushOutputBuffer(info);
429     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
430     break;
431   case rtfInTable:
432   {
433     ME_DisplayItem *para;
434     
435     RTFFlushOutputBuffer(info);
436     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
437     assert(para->member.para.pCells);
438     para->member.para.bTable = TRUE;
439     return;
440   }
441   case rtfFirstIndent:
442     ME_GetSelectionParaFormat(info->editor, &fmt);
443     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
444     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
445     fmt.dxOffset = -info->rtfParam;
446     break;
447   case rtfLeftIndent:
448     ME_GetSelectionParaFormat(info->editor, &fmt);
449     fmt.dwMask = PFM_STARTINDENT;
450     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
451     break;
452   case rtfRightIndent:
453     fmt.dwMask = PFM_RIGHTINDENT;
454     fmt.dxRightIndent = info->rtfParam;
455     break;
456   case rtfQuadLeft:
457   case rtfQuadJust:
458     fmt.dwMask = PFM_ALIGNMENT;
459     fmt.wAlignment = PFA_LEFT;
460     break;
461   case rtfQuadRight:
462     fmt.dwMask = PFM_ALIGNMENT;
463     fmt.wAlignment = PFA_RIGHT;
464     break;
465   case rtfQuadCenter:
466     fmt.dwMask = PFM_ALIGNMENT;
467     fmt.wAlignment = PFA_CENTER;
468     break;
469   case rtfTabPos:
470     ME_GetSelectionParaFormat(info->editor, &fmt);
471     if (!(fmt.dwMask & PFM_TABSTOPS))
472     {
473       fmt.dwMask |= PFM_TABSTOPS;
474       fmt.cTabCount = 0;
475     }
476     if (fmt.cTabCount < MAX_TAB_STOPS)
477       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
478     break;
479   }  
480   if (fmt.dwMask) {
481     RTFFlushOutputBuffer(info);
482     /* FIXME too slow ? how come ?*/
483     ME_SetSelectionParaFormat(info->editor, &fmt);
484   }
485 }
486
487 static void ME_RTFTblAttrHook(RTF_Info *info)
488 {
489   ME_DisplayItem *para;
490   
491   switch (info->rtfMinor)
492   {
493     case rtfRowDef:
494       RTFFlushOutputBuffer(info);
495       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
496       
497       /* Release possibly inherited cell definitions */
498       ME_DestroyTableCellList(para);
499       
500       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
501       para->member.para.pCells->nRightBoundary = 0;
502       para->member.para.pCells->next = NULL;
503       para->member.para.pLastCell = para->member.para.pCells;
504       break;
505     case rtfCellPos:
506       RTFFlushOutputBuffer(info);
507       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
508       
509       if (para->member.para.pLastCell->nRightBoundary)
510       {
511         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
512         
513         pCell->next = NULL;
514         para->member.para.pLastCell->next = pCell;
515         para->member.para.pLastCell = pCell;
516       }
517       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
518       break;
519   }
520 }
521
522 static void ME_RTFReadHook(RTF_Info *info) {
523   switch(info->rtfClass)
524   {
525     case rtfGroup:
526       switch(info->rtfMajor)
527       {
528         case rtfBeginGroup:
529           if (info->stackTop < maxStack) {
530             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
531             info->stack[info->stackTop].codePage = info->codePage;
532             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
533           }
534           info->stackTop++;
535           info->styleChanged = FALSE;
536           break;
537         case rtfEndGroup:
538         {
539           ME_Style *s;
540           RTFFlushOutputBuffer(info);
541           if (info->stackTop<=1) {
542             info->rtfClass = rtfEOF;
543             return;
544           }
545           info->stackTop--;
546           assert(info->stackTop >= 0);
547           if (info->styleChanged)
548           {
549             /* FIXME too slow ? how come ? */
550             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
551             ME_ReleaseStyle(info->style);
552             info->style = s;
553             info->codePage = info->stack[info->stackTop].codePage;
554             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
555           }
556           break;
557         }
558       }
559       break;
560     case rtfControl:
561       switch(info->rtfMajor)
562       {
563         case rtfCharAttr:
564           ME_RTFCharAttrHook(info);
565           break;
566         case rtfParAttr:
567           ME_RTFParAttrHook(info);
568           break;
569         case rtfTblAttr:
570           ME_RTFTblAttrHook(info);
571           break;
572         case rtfSpecialChar:
573           if (info->rtfMinor == rtfCell)
574           {
575             RTFFlushOutputBuffer(info);
576             ME_InsertTableCellFromCursor(info->editor, 0);
577           }
578       }
579       break;
580   }
581 }
582
583 void
584 ME_StreamInFill(ME_InStream *stream)
585 {
586   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
587                                                                 (BYTE *)stream->buffer,
588                                                                 sizeof(stream->buffer),
589                                                                 (LONG *)&stream->dwSize);
590   stream->dwUsed = 0;
591 }
592
593 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
594 {
595   RTF_Info parser;
596   ME_Style *style;
597   int from, to, to2, nUndoMode;
598   ME_UndoItem *pUI;
599   int nEventMask = editor->nEventMask;
600   ME_InStream inStream;
601
602   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
603   editor->nEventMask = 0;
604   
605   ME_GetSelection(editor, &from, &to);
606   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
607     style = ME_GetSelectionInsertStyle(editor);
608
609     ME_InternalDeleteText(editor, from, to-from);
610   }
611   else {
612     style = editor->pBuffer->pDefaultStyle;
613     ME_AddRefStyle(style);
614     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
615     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
616     from = to = 0;
617     ME_ClearTempStyle(editor);
618     /* FIXME restore default paragraph formatting ! */
619   }
620   
621   nUndoMode = editor->nUndoMode;
622   editor->nUndoMode = umIgnore;
623
624   inStream.editstream = stream;
625   inStream.editstream->dwError = 0;
626   inStream.dwSize = 0;
627   inStream.dwUsed = 0;
628
629   if (format & SF_RTF)
630   {
631     /* Check if it's really RTF, and if it is not, use plain text */
632     ME_StreamInFill(&inStream);
633     if (!inStream.editstream->dwError)
634     {
635       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
636       {
637         format &= ~SF_RTF;
638         format |= SF_TEXT;
639       }
640     }
641   }
642
643   if (!inStream.editstream->dwError)
644   {
645     if (format & SF_RTF) {
646       /* setup the RTF parser */
647       memset(&parser, 0, sizeof parser);
648       RTFSetEditStream(&parser, &inStream);
649       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
650       parser.hwndEdit = editor->hWnd;
651       parser.editor = editor;
652       parser.style = style;
653       WriterInit(&parser);
654       RTFInit(&parser);
655       RTFSetReadHook(&parser, ME_RTFReadHook);
656       BeginFile(&parser);
657   
658       /* do the parsing */
659       RTFRead(&parser);
660       RTFFlushOutputBuffer(&parser);
661       RTFDestroy(&parser);
662
663       style = parser.style;
664     }
665     else if (format & SF_TEXT)
666       ME_StreamInText(editor, format, &inStream, style);
667     else
668       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
669     ME_GetSelection(editor, &to, &to2);
670     /* put the cursor at the top */
671     if (!(format & SFF_SELECTION))
672       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
673   }
674   
675   editor->nUndoMode = nUndoMode;
676   if (format & SFF_SELECTION)
677   {
678     pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
679     TRACE("from %d to %d\n", from, to);
680     if (pUI && from < to)
681     {
682       pUI->nStart = from;
683       pUI->nLen = to-from;
684     }
685     ME_CommitUndo(editor);
686   }
687   else
688   {
689     ME_EmptyUndoStack(editor);
690   }
691
692   ME_ReleaseStyle(style); 
693   editor->nEventMask = nEventMask;
694   if (editor->bRedraw)
695   {
696     ME_UpdateRepaint(editor);
697   }
698   if (!(format & SFF_SELECTION)) {
699     ME_ClearTempStyle(editor);
700   }
701   ME_MoveCaret(editor);
702   ME_SendSelChange(editor);
703   ME_SendRequestResize(editor, FALSE);
704
705   return 0;
706 }
707
708
709 typedef struct tagME_RTFStringStreamStruct
710 {
711   char *string;
712   int pos;
713   int length;
714 } ME_RTFStringStreamStruct;
715
716 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
717 {
718   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
719   int count;
720
721   count = min(cb, pStruct->length - pStruct->pos);
722   memmove(lpBuff, pStruct->string + pStruct->pos, count);
723   pStruct->pos += count;
724   *pcb = count;
725   return 0;
726 }
727
728 static void
729 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
730 {
731   EDITSTREAM es;
732   ME_RTFStringStreamStruct data;
733
734   data.string = string;
735   data.length = strlen(string);
736   data.pos = 0;
737   es.dwCookie = (DWORD)&data;
738   es.pfnCallback = ME_ReadFromRTFString;
739   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
740 }
741
742
743 ME_DisplayItem *
744 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
745 {
746   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
747   
748   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
749     item = ME_FindItemFwd(item, diParagraph);
750
751   if (!item)
752     return item;
753
754   nOffset -= item->member.para.nCharOfs;
755   if (nItemType == diParagraph) {
756     if (nItemOffset)
757       *nItemOffset = nOffset;
758     return item;
759   }
760   
761   do {
762     item = ME_FindItemFwd(item, diRun);
763   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
764   if (item) {
765     nOffset -= item->member.run.nCharOfs;
766     if (nItemOffset)
767       *nItemOffset = nOffset;
768   }
769   return item;
770 }
771
772
773 static int
774 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
775 {
776   const int nLen = lstrlenW(text);
777   const int nTextLen = ME_GetTextLength(editor);
778   int nStart, nEnd;
779   int nMin, nMax;
780   ME_DisplayItem *item;
781   ME_DisplayItem *para;
782   WCHAR wLastChar = ' ';
783
784   TRACE("flags==0x%08lx, chrg->cpMin==%ld, chrg->cpMax==%ld text==%s\n",
785         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
786   
787   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
788     FIXME("Flags 0x%08lx not implemented\n",
789         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
790
791   nMin = chrg->cpMin;
792   if (chrg->cpMax == -1)
793     nMax = nTextLen;
794   else
795     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
796   
797   /* when searching up, if cpMin < cpMax, then instead of searching
798    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
799    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
800    * case, it is always bigger than cpMin.
801    */
802   if (!(flags & FR_DOWN))
803   {
804     int nSwap = nMax;
805
806     nMax = nMin > nTextLen ? nTextLen : nMin;
807     if (nMin < nSwap || chrg->cpMax == -1)
808       nMin = 0;
809     else
810       nMin = nSwap;
811   }
812
813   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
814   {
815     if (chrgText)
816       chrgText->cpMin = chrgText->cpMax = -1;
817     return -1;
818   }
819  
820   if (flags & FR_DOWN) /* Forward search */
821   {
822     /* If possible, find the character before where the search starts */
823     if ((flags & FR_WHOLEWORD) && nMin)
824     {
825       nStart = nMin - 1;
826       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
827       if (!item)
828       {
829         if (chrgText)
830           chrgText->cpMin = chrgText->cpMax = -1;
831         return -1;
832       }
833       wLastChar = item->member.run.strText->szData[nStart];
834     }
835
836     nStart = nMin;
837     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
838     if (!item)
839     {
840       if (chrgText)
841         chrgText->cpMin = chrgText->cpMax = -1;
842       return -1;
843     }
844
845     para = ME_GetParagraph(item);
846     while (item
847            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
848     {
849       ME_DisplayItem *pCurItem = item;
850       int nCurStart = nStart;
851       int nMatched = 0;
852     
853       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
854       {
855         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
856           break;
857
858         nMatched++;
859         if (nMatched == nLen)
860         {
861           ME_DisplayItem *pNextItem = pCurItem;
862           int nNextStart = nCurStart;
863           WCHAR wNextChar;
864
865           /* Check to see if next character is a whitespace */
866           if (flags & FR_WHOLEWORD)
867           {
868             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
869             {
870               pNextItem = ME_FindItemFwd(pCurItem, diRun);
871               nNextStart = -nMatched;
872             }
873
874             if (pNextItem)
875               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
876             else
877               wNextChar = ' ';
878
879             if (isalnumW(wNextChar))
880               break;
881           }
882
883           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
884           if (chrgText)
885           {
886             chrgText->cpMin = nStart;
887             chrgText->cpMax = nStart + nLen;
888           }
889           TRACE("found at %d-%d\n", nStart, nStart + nLen);
890           return nStart;
891         }
892         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
893         {
894           pCurItem = ME_FindItemFwd(pCurItem, diRun);
895           para = ME_GetParagraph(pCurItem);
896           nCurStart = -nMatched;
897         }
898       }
899       if (pCurItem)
900         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
901       else
902         wLastChar = ' ';
903
904       nStart++;
905       if (nStart == ME_StrLen(item->member.run.strText))
906       {
907         item = ME_FindItemFwd(item, diRun);
908         para = ME_GetParagraph(item);
909         nStart = 0;
910       }
911     }
912   }
913   else /* Backward search */
914   {
915     /* If possible, find the character after where the search ends */
916     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
917     {
918       nEnd = nMax + 1;
919       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
920       if (!item)
921       {
922         if (chrgText)
923           chrgText->cpMin = chrgText->cpMax = -1;
924         return -1;
925       }
926       wLastChar = item->member.run.strText->szData[nEnd];
927     }
928
929     nEnd = nMax;
930     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
931     if (!item)
932     {
933       if (chrgText)
934         chrgText->cpMin = chrgText->cpMax = -1;
935       return -1;
936     }
937     
938     para = ME_GetParagraph(item);
939     
940     while (item
941            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
942     {
943       ME_DisplayItem *pCurItem = item;
944       int nCurEnd = nEnd;
945       int nMatched = 0;
946       
947       if (nCurEnd - nMatched == 0)
948       {
949         pCurItem = ME_FindItemBack(pCurItem, diRun);
950         para = ME_GetParagraph(pCurItem);
951         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
952       }
953       
954       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
955       {
956         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
957           break;
958
959         nMatched++;
960         if (nMatched == nLen)
961         {
962           ME_DisplayItem *pPrevItem = pCurItem;
963           int nPrevEnd = nCurEnd;
964           WCHAR wPrevChar;
965
966           /* Check to see if previous character is a whitespace */
967           if (flags & FR_WHOLEWORD)
968           {
969             if (nPrevEnd - nMatched == 0)
970             {
971               pPrevItem = ME_FindItemBack(pCurItem, diRun);
972               if (pPrevItem)
973                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
974             }
975
976             if (pPrevItem)
977               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
978             else
979               wPrevChar = ' ';
980
981             if (isalnumW(wPrevChar))
982               break;
983           }
984
985           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
986           if (chrgText)
987           {
988             chrgText->cpMin = nStart;
989             chrgText->cpMax = nStart + nLen;
990           }
991           TRACE("found at %d-%d\n", nStart, nStart + nLen);
992           return nStart;
993         }
994         if (nCurEnd - nMatched == 0)
995         {
996           pCurItem = ME_FindItemBack(pCurItem, diRun);
997           /* Don't care about pCurItem becoming NULL here; it's already taken
998            * care of in the exterior loop condition */
999           para = ME_GetParagraph(pCurItem);
1000           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1001         }
1002       }
1003       if (pCurItem)
1004         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1005       else
1006         wLastChar = ' ';
1007
1008       nEnd--;
1009       if (nEnd < 0)
1010       {
1011         item = ME_FindItemBack(item, diRun);
1012         para = ME_GetParagraph(item);
1013         nEnd = ME_StrLen(item->member.run.strText);
1014       }
1015     }
1016   }
1017   TRACE("not found\n");
1018   if (chrgText)
1019     chrgText->cpMin = chrgText->cpMax = -1;
1020   return -1;
1021 }
1022
1023
1024 static BOOL
1025 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1026 {
1027   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1028   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1029   
1030   switch (nKey)
1031   {
1032     case VK_LEFT:
1033     case VK_RIGHT:
1034     case VK_UP:
1035     case VK_DOWN:
1036     case VK_HOME:
1037     case VK_END:
1038     case VK_PRIOR:
1039     case VK_NEXT:
1040       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1041       return TRUE;
1042     case VK_BACK:
1043     case VK_DELETE:
1044       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1045       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1046         return FALSE;
1047       if (ME_IsSelection(editor))
1048         ME_DeleteSelection(editor);
1049       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1050         ME_DeleteTextAtCursor(editor, 1, 1);
1051       else
1052         return TRUE;
1053       ME_CommitUndo(editor);
1054       ME_UpdateRepaint(editor);
1055       ME_SendRequestResize(editor, FALSE);
1056       return TRUE;
1057
1058     default:
1059       if (ctrl_is_down)
1060       {
1061         if (nKey == 'W')
1062         {
1063           CHARFORMAT2W chf;
1064           char buf[2048];
1065           chf.cbSize = sizeof(chf);
1066           
1067           ME_GetSelectionCharFormat(editor, &chf);
1068           ME_DumpStyleToBuf(&chf, buf);
1069           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1070         }
1071         if (nKey == 'Q')
1072         {
1073           ME_CheckCharOffsets(editor);
1074         }
1075       }
1076   }
1077   return FALSE;
1078 }
1079
1080 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1081 {
1082   CHARRANGE selrange;
1083   HMENU menu;
1084   int seltype = 0;
1085   if(!editor->lpOleCallback)
1086     return FALSE;
1087   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1088   if(selrange.cpMin == selrange.cpMax)
1089     seltype |= SEL_EMPTY;
1090   else
1091   {
1092     /* FIXME: Handle objects */
1093     seltype |= SEL_TEXT;
1094     if(selrange.cpMax-selrange.cpMin > 1)
1095       seltype |= SEL_MULTICHAR;
1096   }
1097   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1098   {
1099     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1100     DestroyMenu(menu);
1101   }
1102   return TRUE;
1103 }
1104
1105 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1106   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1107   HDC hDC;
1108   int i;
1109   ed->hWnd = hWnd;
1110   ed->bEmulateVersion10 = FALSE;
1111   ed->pBuffer = ME_MakeText();
1112   hDC = GetDC(hWnd);
1113   ME_MakeFirstParagraph(hDC, ed->pBuffer);
1114   ReleaseDC(hWnd, hDC);
1115   ed->bCaretShown = FALSE;
1116   ed->nCursors = 3;
1117   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1118   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1119   ed->pCursors[0].nOffset = 0;
1120   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1121   ed->pCursors[1].nOffset = 0;
1122   ed->nLastTotalLength = ed->nTotalLength = 0;
1123   ed->nUDArrowX = -1;
1124   ed->nSequence = 0;
1125   ed->rgbBackColor = -1;
1126   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1127   ed->bCaretAtEnd = FALSE;
1128   ed->nEventMask = 0;
1129   ed->nModifyStep = 0;
1130   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1131   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1132   ed->nUndoStackSize = 0;
1133   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1134   ed->nUndoMode = umAddToUndo;
1135   ed->nParagraphs = 1;
1136   ed->nLastSelStart = ed->nLastSelEnd = 0;
1137   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1138   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1139   ed->bRedraw = TRUE;
1140   ed->bHideSelection = FALSE;
1141   ed->nInvalidOfs = -1;
1142   ed->pfnWordBreak = NULL;
1143   ed->lpOleCallback = NULL;
1144   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1145   GetClientRect(hWnd, &ed->rcFormat);
1146   for (i=0; i<HFONT_CACHE_SIZE; i++)
1147   {
1148     ed->pFontCache[i].nRefs = 0;
1149     ed->pFontCache[i].nAge = 0;
1150     ed->pFontCache[i].hFont = NULL;
1151   }
1152   
1153   ME_CheckCharOffsets(ed);
1154   
1155   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1156     ed->cPasswordMask = '*';
1157   else
1158     ed->cPasswordMask = 0;
1159   
1160   return ed;
1161 }
1162
1163 typedef struct tagME_GlobalDestStruct
1164 {
1165   HGLOBAL hData;
1166   int nLength;
1167 } ME_GlobalDestStruct;
1168
1169 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1170 {
1171   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1172   int i;
1173   WORD *pSrc, *pDest;
1174   
1175   cb = cb >> 1;
1176   pDest = (WORD *)lpBuff;
1177   pSrc = (WORD *)GlobalLock(pData->hData);
1178   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1179     pDest[i] = pSrc[pData->nLength+i];
1180   }    
1181   pData->nLength += i;
1182   *pcb = 2*i;
1183   GlobalUnlock(pData->hData);
1184   return 0;
1185 }
1186
1187 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1188 {
1189   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1190   int i;
1191   BYTE *pSrc, *pDest;
1192   
1193   pDest = lpBuff;
1194   pSrc = (BYTE *)GlobalLock(pData->hData);
1195   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1196     pDest[i] = pSrc[pData->nLength+i];
1197   }    
1198   pData->nLength += i;
1199   *pcb = i;
1200   GlobalUnlock(pData->hData);
1201   return 0;
1202 }
1203
1204
1205 void ME_DestroyEditor(ME_TextEditor *editor)
1206 {
1207   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1208   ME_DisplayItem *p = pFirst, *pNext = NULL;
1209   int i;
1210   
1211   ME_ClearTempStyle(editor);
1212   ME_EmptyUndoStack(editor);
1213   while(p) {
1214     pNext = p->next;
1215     ME_DestroyDisplayItem(p);    
1216     p = pNext;
1217   }
1218   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1219   for (i=0; i<HFONT_CACHE_SIZE; i++)
1220   {
1221     if (editor->pFontCache[i].hFont)
1222       DeleteObject(editor->pFontCache[i].hFont);
1223   }
1224   DeleteObject(editor->hbrBackground);
1225   if(editor->lpOleCallback)
1226     IUnknown_Release(editor->lpOleCallback);
1227
1228   FREE_OBJ(editor);
1229 }
1230
1231 static const WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
1232 static const WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
1233 static const WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
1234 static const WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
1235
1236 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1237 {
1238     TRACE("\n");
1239     switch (fdwReason)
1240     {
1241     case DLL_PROCESS_ATTACH:
1242       DisableThreadLibraryCalls(hinstDLL);
1243       me_heap = HeapCreate (0, 0x10000, 0);
1244       ME_RegisterEditorClass(hinstDLL);
1245       break;
1246
1247     case DLL_PROCESS_DETACH:
1248       UnregisterClassW(wszClassName, 0);
1249       UnregisterClassW(wszClassName50, 0);
1250       UnregisterClassA("RichEdit20A", 0);
1251       UnregisterClassA("RichEdit50A", 0);
1252       if (ME_ListBoxRegistered)
1253           UnregisterClassW(wszClassNameListBox, 0);
1254       if (ME_ComboBoxRegistered)
1255           UnregisterClassW(wszClassNameComboBox, 0);
1256       HeapDestroy (me_heap);
1257       me_heap = NULL;
1258       break;
1259     }
1260     return TRUE;
1261 }
1262
1263
1264 #define UNSUPPORTED_MSG(e) \
1265   case e: \
1266     FIXME(#e ": stub\n"); \
1267     return DefWindowProcW(hWnd, msg, wParam, lParam);
1268
1269 static const char * const edit_messages[] = {
1270   "EM_GETSEL",
1271   "EM_SETSEL",
1272   "EM_GETRECT",
1273   "EM_SETRECT",
1274   "EM_SETRECTNP",
1275   "EM_SCROLL",
1276   "EM_LINESCROLL",
1277   "EM_SCROLLCARET",
1278   "EM_GETMODIFY",
1279   "EM_SETMODIFY",
1280   "EM_GETLINECOUNT",
1281   "EM_LINEINDEX",
1282   "EM_SETHANDLE",
1283   "EM_GETHANDLE",
1284   "EM_GETTHUMB",
1285   "EM_UNKNOWN_BF",
1286   "EM_UNKNOWN_C0",
1287   "EM_LINELENGTH",
1288   "EM_REPLACESEL",
1289   "EM_UNKNOWN_C3",
1290   "EM_GETLINE",
1291   "EM_LIMITTEXT",
1292   "EM_CANUNDO",
1293   "EM_UNDO",
1294   "EM_FMTLINES",
1295   "EM_LINEFROMCHAR",
1296   "EM_UNKNOWN_CA",
1297   "EM_SETTABSTOPS",
1298   "EM_SETPASSWORDCHAR",
1299   "EM_EMPTYUNDOBUFFER",
1300   "EM_GETFIRSTVISIBLELINE",
1301   "EM_SETREADONLY",
1302   "EM_SETWORDBREAKPROC",
1303   "EM_GETWORDBREAKPROC",
1304   "EM_GETPASSWORDCHAR",
1305   "EM_SETMARGINS",
1306   "EM_GETMARGINS",
1307   "EM_GETLIMITTEXT",
1308   "EM_POSFROMCHAR",
1309   "EM_CHARFROMPOS"
1310 };
1311
1312 static const char * const richedit_messages[] = {
1313   "EM_CANPASTE",
1314   "EM_DISPLAYBAND",
1315   "EM_EXGETSEL",
1316   "EM_EXLIMITTEXT",
1317   "EM_EXLINEFROMCHAR",
1318   "EM_EXSETSEL",
1319   "EM_FINDTEXT",
1320   "EM_FORMATRANGE",
1321   "EM_GETCHARFORMAT",
1322   "EM_GETEVENTMASK",
1323   "EM_GETOLEINTERFACE",
1324   "EM_GETPARAFORMAT",
1325   "EM_GETSELTEXT",
1326   "EM_HIDESELECTION", 
1327   "EM_PASTESPECIAL",
1328   "EM_REQUESTRESIZE",
1329   "EM_SELECTIONTYPE",
1330   "EM_SETBKGNDCOLOR",
1331   "EM_SETCHARFORMAT",
1332   "EM_SETEVENTMASK",
1333   "EM_SETOLECALLBACK",
1334   "EM_SETPARAFORMAT",
1335   "EM_SETTARGETDEVICE",
1336   "EM_STREAMIN",
1337   "EM_STREAMOUT",
1338   "EM_GETTEXTRANGE",
1339   "EM_FINDWORDBREAK",
1340   "EM_SETOPTIONS",
1341   "EM_GETOPTIONS",
1342   "EM_FINDTEXTEX",
1343   "EM_GETWORDBREAKPROCEX",
1344   "EM_SETWORDBREAKPROCEX",
1345   "EM_SETUNDOLIMIT",
1346   "EM_UNKNOWN_USER_83",
1347   "EM_REDO",
1348   "EM_CANREDO",
1349   "EM_GETUNDONAME",
1350   "EM_GETREDONAME",
1351   "EM_STOPGROUPTYPING",
1352   "EM_SETTEXTMODE",
1353   "EM_GETTEXTMODE",
1354   "EM_AUTOURLDETECT",
1355   "EM_GETAUTOURLDETECT",
1356   "EM_SETPALETTE",
1357   "EM_GETTEXTEX",
1358   "EM_GETTEXTLENGTHEX",
1359   "EM_SHOWSCROLLBAR",
1360   "EM_SETTEXTEX",
1361   "EM_UNKNOWN_USER_98",
1362   "EM_UNKNOWN_USER_99",
1363   "EM_SETPUNCTUATION",
1364   "EM_GETPUNCTUATION",
1365   "EM_SETWORDWRAPMODE",
1366   "EM_GETWORDWRAPMODE",
1367   "EM_SETIMECOLOR",
1368   "EM_GETIMECOLOR",
1369   "EM_SETIMEOPTIONS",
1370   "EM_GETIMEOPTIONS",
1371   "EM_CONVPOSITION",
1372   "EM_UNKNOWN_USER_109",
1373   "EM_UNKNOWN_USER_110",
1374   "EM_UNKNOWN_USER_111",
1375   "EM_UNKNOWN_USER_112",
1376   "EM_UNKNOWN_USER_113",
1377   "EM_UNKNOWN_USER_114",
1378   "EM_UNKNOWN_USER_115",
1379   "EM_UNKNOWN_USER_116",
1380   "EM_UNKNOWN_USER_117",
1381   "EM_UNKNOWN_USER_118",
1382   "EM_UNKNOWN_USER_119",
1383   "EM_SETLANGOPTIONS",
1384   "EM_GETLANGOPTIONS",
1385   "EM_GETIMECOMPMODE",
1386   "EM_FINDTEXTW",
1387   "EM_FINDTEXTEXW",
1388   "EM_RECONVERSION",
1389   "EM_SETIMEMODEBIAS",
1390   "EM_GETIMEMODEBIAS"
1391 };
1392
1393 static const char *
1394 get_msg_name(UINT msg)
1395 {
1396   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1397     return edit_messages[msg - EM_GETSEL];
1398   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1399     return richedit_messages[msg - EM_CANPASTE];
1400   return "";
1401 }
1402
1403 /******************************************************************
1404  *        RichEditANSIWndProc (RICHED20.10)
1405  */
1406 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1407   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1408   
1409   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1410         hWnd, msg, get_msg_name(msg), wParam, lParam);
1411   
1412   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1413     ERR("RichEditANSIWndProc called with invalid hWnd %p - application bug?\n", hWnd);
1414     return 0; 
1415   }
1416
1417   switch(msg) {
1418   
1419   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1420   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1421   UNSUPPORTED_MSG(EM_FMTLINES)
1422   UNSUPPORTED_MSG(EM_FORMATRANGE)
1423   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1424   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1425   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1426   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1427   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1428   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1429   UNSUPPORTED_MSG(EM_GETREDONAME)
1430   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1431   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1432   UNSUPPORTED_MSG(EM_GETUNDONAME)
1433   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1434   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1435   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1436   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1437   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1438   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1439   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1440   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1441   UNSUPPORTED_MSG(EM_SETPALETTE)
1442   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1443   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1444   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1445   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1446   UNSUPPORTED_MSG(WM_STYLECHANGING)
1447   UNSUPPORTED_MSG(WM_STYLECHANGED)
1448 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1449     
1450 /* Messages specific to Richedit controls */
1451   
1452   case EM_STREAMIN:
1453    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1454   case EM_STREAMOUT:
1455    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1456   case WM_GETDLGCODE:
1457   {
1458     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1459     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1460       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1461     return code;
1462   }
1463   case WM_NCCREATE:
1464   {
1465     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1466     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1467     editor = ME_MakeEditor(hWnd);
1468     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1469     pcs = 0; /* ignore */
1470     return TRUE;
1471   }
1472   case EM_EMPTYUNDOBUFFER:
1473     ME_EmptyUndoStack(editor);
1474     return 0;
1475   case EM_GETSEL:
1476   {
1477     /* Note: wParam/lParam can be NULL */
1478     UINT from, to;
1479     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1480     PUINT pto = lParam ? (PUINT)lParam : &to;
1481     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1482     if ((*pfrom|*pto) & 0xFFFF0000)
1483       return -1;
1484     return MAKELONG(*pfrom,*pto);
1485   }
1486   case EM_EXGETSEL:
1487   {
1488     CHARRANGE *pRange = (CHARRANGE *)lParam;
1489     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1490     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1491     return 0;
1492   }
1493   case EM_SETUNDOLIMIT:
1494   {
1495     if ((int)wParam < 0)
1496       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1497     else
1498       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1499     /* Setting a max stack size keeps wine from getting killed 
1500       for hogging memory. Windows allocates all this memory at once, so
1501       no program would realistically set a value above our maxiumum. */  
1502     return editor->nUndoLimit;
1503   }
1504   case EM_CANUNDO:
1505     return editor->pUndoStack != NULL;
1506   case EM_CANREDO:
1507     return editor->pRedoStack != NULL;
1508   case WM_UNDO: /* FIXME: actually not the same */
1509   case EM_UNDO:
1510     ME_Undo(editor);
1511     return 0;
1512   case EM_REDO:
1513     ME_Redo(editor);
1514     return 0;
1515   case EM_GETOPTIONS:
1516   {
1517     /* these flags are equivalent to the ES_* counterparts */
1518     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1519                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1520     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1521
1522     return settings;
1523   }
1524   case EM_SETOPTIONS:
1525   {
1526     /* these flags are equivalent to ES_* counterparts                      
1527      * ECO_READONLY is already implemented in the code, only requires 
1528      * setting the bit to work                                        
1529      */
1530     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1531                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1532     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1533     DWORD settings = mask & raw;
1534
1535     switch(wParam)
1536     {
1537       case ECOOP_SET:
1538         settings = lParam;
1539         break;
1540       case ECOOP_OR:
1541         settings |= lParam;
1542         break;
1543       case ECOOP_AND:
1544         settings &= lParam;
1545         break;
1546       case ECOOP_XOR:
1547         settings ^= lParam;
1548     }
1549     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1550
1551     if (lParam & ECO_AUTOWORDSELECTION)
1552       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1553     if (lParam & ECO_SELECTIONBAR)
1554       FIXME("ECO_SELECTIONBAR not implemented yet!\n");
1555     if (lParam & ECO_VERTICAL)
1556       FIXME("ECO_VERTICAL not implemented yet!\n");
1557     if (lParam & ECO_AUTOHSCROLL)
1558       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1559     if (lParam & ECO_AUTOVSCROLL)
1560       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1561     if (lParam & ECO_NOHIDESEL)
1562       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1563     if (lParam & ECO_WANTRETURN)
1564       FIXME("ECO_WANTRETURN not implemented yet!\n");
1565
1566     return settings;
1567   }
1568   case EM_SETSEL:
1569   {
1570     ME_InvalidateSelection(editor);
1571     ME_SetSelection(editor, wParam, lParam);
1572     ME_InvalidateSelection(editor);
1573     ME_SendSelChange(editor);
1574     return 0;
1575   }
1576   case EM_SETSCROLLPOS:
1577   {
1578     POINT *point = (POINT *)lParam;
1579     ME_ScrollAbs(editor, point->y);
1580     return 0;
1581   }
1582   case EM_AUTOURLDETECT:
1583   {
1584     if (wParam==1 || wParam ==0) 
1585     {
1586         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1587         return 0;
1588     }
1589     return E_INVALIDARG;
1590   }
1591   case EM_GETAUTOURLDETECT:
1592   {
1593     return editor->AutoURLDetect_bEnable;
1594   }
1595   case EM_EXSETSEL:
1596   {
1597     int start, end;
1598     CHARRANGE range = *(CHARRANGE *)lParam;
1599
1600     TRACE("EM_EXSETSEL (%ld,%ld)\n", range.cpMin, range.cpMax);
1601
1602     /* if cpMin < 0, then selection is deselected and caret moved to end of
1603      * the current selection  */
1604     if (range.cpMin < 0)
1605     {
1606         ME_GetSelection(editor, &start, &end);
1607         range.cpMin = end;
1608         range.cpMax = end;
1609     }  
1610     else if (range.cpMax > ME_GetTextLength(editor) +1)
1611     {
1612       range.cpMax = ME_GetTextLength(editor) + 1;
1613     }
1614
1615     ME_InvalidateSelection(editor);
1616     ME_SetSelection(editor, range.cpMin, range.cpMax);
1617     ME_InvalidateSelection(editor);
1618     ME_SendSelChange(editor);
1619     
1620     return range.cpMax;
1621   }
1622   case EM_SHOWSCROLLBAR:
1623   {
1624     ShowScrollBar(editor->hWnd, wParam, lParam);
1625     return 0;
1626   }
1627   case EM_SETTEXTEX:
1628   {
1629     LPWSTR wszText = (LPWSTR)lParam;
1630     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1631     size_t len = wszText ? lstrlenW(wszText) : 0;
1632     int from, to;
1633     ME_Style *style;
1634     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1635     if (pStruct->codepage != 1200) {
1636       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1637       return 0;
1638     }
1639     /* FIXME: this should support RTF strings too, according to MSDN */
1640     if (pStruct->flags & ST_SELECTION) {
1641       ME_GetSelection(editor, &from, &to);
1642       style = ME_GetSelectionInsertStyle(editor);
1643       ME_InternalDeleteText(editor, from, to - from);
1644       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1645       ME_ReleaseStyle(style);
1646     }
1647     else {
1648       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1649       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1650       len = 1;
1651     }
1652     ME_CommitUndo(editor);
1653     if (!(pStruct->flags & ST_KEEPUNDO))
1654       ME_EmptyUndoStack(editor);
1655     ME_UpdateRepaint(editor);
1656     return len;
1657   }
1658   case EM_SETBKGNDCOLOR:
1659   {
1660     LRESULT lColor = ME_GetBackColor(editor);
1661     if (editor->rgbBackColor != -1)
1662       DeleteObject(editor->hbrBackground);
1663     if (wParam)
1664     {
1665       editor->rgbBackColor = -1;
1666       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1667     }
1668     else
1669     {
1670       editor->rgbBackColor = lParam;
1671       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1672     }
1673     if (editor->bRedraw)
1674     {
1675       InvalidateRect(hWnd, NULL, TRUE);
1676       UpdateWindow(hWnd);
1677     }
1678     return lColor;
1679   }
1680   case EM_GETMODIFY:
1681     return editor->nModifyStep == 0 ? 0 : 1;
1682   case EM_SETMODIFY:
1683   {
1684     if (wParam)
1685       editor->nModifyStep = 0x80000000;
1686     else
1687       editor->nModifyStep = 0;
1688     
1689     return 0;
1690   }
1691   case EM_SETREADONLY:
1692   {
1693     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1694     if (wParam)
1695       nStyle |= ES_READONLY;
1696     else
1697       nStyle &= ~ES_READONLY;
1698     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1699     return 0;
1700   }
1701   case EM_SETEVENTMASK:
1702   {
1703     DWORD nOldMask = editor->nEventMask;
1704     
1705     editor->nEventMask = lParam;
1706     return nOldMask;
1707   }
1708   case EM_GETEVENTMASK:
1709     return editor->nEventMask;
1710   case EM_SETCHARFORMAT:
1711   {
1712     CHARFORMAT2W buf, *p;
1713     BOOL bRepaint = TRUE;
1714     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1715     if (!wParam || (editor->mode & TM_PLAINTEXT))
1716       ME_SetDefaultCharFormat(editor, p);
1717     else if (wParam == (SCF_WORD | SCF_SELECTION))
1718       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1719     else if (wParam == SCF_ALL)
1720       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1721     else {
1722       int from, to;
1723       ME_GetSelection(editor, &from, &to);
1724       bRepaint = (from != to);
1725       ME_SetSelectionCharFormat(editor, p);
1726     }
1727     ME_CommitUndo(editor);
1728     if (bRepaint)
1729       ME_UpdateRepaint(editor);
1730     return 0;
1731   }
1732   case EM_GETCHARFORMAT:
1733   {
1734     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1735     if (dst->cbSize != sizeof(CHARFORMATA) &&
1736         dst->cbSize != sizeof(CHARFORMATW) &&
1737         dst->cbSize != sizeof(CHARFORMAT2A) &&
1738         dst->cbSize != sizeof(CHARFORMAT2W))
1739       return 0;
1740     tmp.cbSize = sizeof(tmp);
1741     if (!wParam)
1742       ME_GetDefaultCharFormat(editor, &tmp);
1743     else
1744       ME_GetSelectionCharFormat(editor, &tmp);
1745     ME_CopyToCFAny(dst, &tmp);
1746     return tmp.dwMask;
1747   }
1748   case EM_SETPARAFORMAT:
1749     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1750     ME_UpdateRepaint(editor);
1751     ME_CommitUndo(editor);
1752     return 0;
1753   case EM_GETPARAFORMAT:
1754     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1755     return 0;
1756   case EM_GETFIRSTVISIBLELINE:
1757   {
1758     ME_DisplayItem *p = editor->pBuffer->pFirst;
1759     int y = ME_GetYScrollPos(editor);
1760     int ypara = 0;
1761     int count = 0;
1762     int ystart, yend;
1763     while(p) {
1764       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1765       if (p->type == diTextEnd)
1766         break;
1767       if (p->type == diParagraph) {
1768         ypara = p->member.para.nYPos;
1769         continue;
1770       }
1771       ystart = ypara + p->member.row.nYPos;
1772       yend = ystart + p->member.row.nHeight;
1773       if (y < yend) {
1774         break;
1775       }
1776       count++;
1777     }
1778     return count;
1779   }
1780   case EM_HIDESELECTION:
1781   {
1782      editor->bHideSelection = (wParam != 0);
1783      ME_InvalidateSelection(editor);
1784      return 0;
1785   }
1786   case EM_LINESCROLL:
1787   {
1788     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1789     return TRUE; /* Should return false if a single line richedit control */
1790   }
1791   case WM_CLEAR:
1792   {
1793     int from, to;
1794     ME_GetSelection(editor, &from, &to);
1795     ME_InternalDeleteText(editor, from, to-from);
1796     ME_CommitUndo(editor);
1797     ME_UpdateRepaint(editor);
1798     return 0;
1799   }
1800   case EM_REPLACESEL:
1801   {
1802     int from, to;
1803     ME_Style *style;
1804     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1805     size_t len = lstrlenW(wszText);
1806     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1807     
1808     ME_GetSelection(editor, &from, &to);
1809     style = ME_GetSelectionInsertStyle(editor);
1810     ME_InternalDeleteText(editor, from, to-from);
1811     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1812     ME_ReleaseStyle(style);
1813     ME_EndToUnicode(hWnd, wszText);
1814     /* drop temporary style if line end */
1815     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1816     if (len>0 && wszText[len-1] == '\n')
1817       ME_ClearTempStyle(editor);
1818       
1819     ME_CommitUndo(editor);
1820     if (!wParam)
1821       ME_EmptyUndoStack(editor);
1822     ME_UpdateRepaint(editor);
1823     return 0;
1824   }
1825   case EM_SCROLLCARET:
1826   {
1827     int top, bottom; /* row's edges relative to document top */
1828     int nPos;
1829     ME_DisplayItem *para, *row;
1830     
1831     nPos = ME_GetYScrollPos(editor);
1832     row = ME_RowStart(editor->pCursors[0].pRun);
1833     para = ME_GetParagraph(row);
1834     top = para->member.para.nYPos + row->member.row.nYPos;
1835     bottom = top + row->member.row.nHeight;
1836     
1837     if (top < nPos) /* caret above window */
1838       ME_ScrollAbs(editor,  top);
1839     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1840       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1841     return 0;
1842   }
1843   case WM_SETFONT:
1844   {
1845     LOGFONTW lf;
1846     CHARFORMAT2W fmt;
1847     HDC hDC;
1848     BOOL bRepaint = LOWORD(lParam);
1849     
1850     if (!wParam)
1851       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1852     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1853     hDC = GetDC(hWnd);
1854     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1855     ReleaseDC(hWnd, hDC);   
1856     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1857     ME_SetDefaultCharFormat(editor, &fmt);
1858
1859     ME_CommitUndo(editor);
1860     if (bRepaint)
1861       ME_UpdateRepaint(editor);
1862     return 0;
1863   }
1864   case WM_SETTEXT:
1865   {
1866     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1867     if (lParam)
1868     {
1869       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1870       if (!IsWindowUnicode(hWnd) && !strncmp((char *)lParam, "{\\rtf", 5))
1871       {
1872         /* Undocumented: WM_SETTEXT supports RTF text */
1873         ME_StreamInRTFString(editor, 0, (char *)lParam);
1874       }
1875       else
1876       {
1877         LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1878         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1879         if (lstrlenW(wszText) > 0)
1880         {
1881           /* uses default style! */
1882           ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1883         }
1884         ME_EndToUnicode(hWnd, wszText);
1885       }
1886     }
1887     else
1888       TRACE("WM_SETTEXT - NULL\n");
1889     ME_CommitUndo(editor);
1890     ME_EmptyUndoStack(editor);
1891     ME_SetSelection(editor, 0, 0);
1892     ME_UpdateRepaint(editor);
1893     return 0;
1894   }
1895   case EM_CANPASTE:
1896   {
1897     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1898     if (IsClipboardFormatAvailable(nRTFFormat))
1899       return TRUE;
1900     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1901       return TRUE;
1902     return FALSE;
1903   }
1904   case WM_PASTE:
1905   {    
1906     DWORD dwFormat = 0;
1907     EDITSTREAM es;
1908     ME_GlobalDestStruct gds;
1909     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1910     UINT cf = 0;
1911
1912     if (IsClipboardFormatAvailable(nRTFFormat))
1913       cf = nRTFFormat, dwFormat = SF_RTF;
1914     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1915       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1916     else
1917       return 0;
1918
1919     if (!OpenClipboard(hWnd))
1920       return 0;
1921     gds.hData = GetClipboardData(cf);
1922     gds.nLength = 0;
1923     es.dwCookie = (DWORD)&gds;
1924     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1925     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
1926
1927     CloseClipboard();
1928     return 0;
1929   }
1930   case WM_CUT:
1931   case WM_COPY:
1932   {
1933     LPDATAOBJECT dataObj = NULL;
1934     CHARRANGE range;
1935     HRESULT hr = S_OK;
1936     
1937     if (editor->cPasswordMask)
1938       return 0; /* Copying or Cutting masked text isn't allowed */
1939     
1940     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
1941     if(editor->lpOleCallback)
1942         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
1943     if(FAILED(hr) || !dataObj)
1944         hr = ME_GetDataObject(editor, &range, &dataObj);
1945     if(SUCCEEDED(hr)) {
1946         hr = OleSetClipboard(dataObj);
1947         IDataObject_Release(dataObj);
1948     }
1949     if (SUCCEEDED(hr) && msg == WM_CUT)
1950     {
1951       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
1952       ME_CommitUndo(editor);
1953       ME_UpdateRepaint(editor);
1954     }
1955     return 0;
1956   }
1957   case WM_GETTEXTLENGTH:
1958     return ME_GetTextLength(editor);
1959   case EM_GETTEXTLENGTHEX:
1960     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1961   case WM_GETTEXT:
1962   {
1963     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1964     tr.chrg.cpMin = 0;
1965     tr.chrg.cpMax = wParam-1;
1966     tr.lpstrText = (WCHAR *)lParam;
1967     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1968   }
1969   case EM_GETTEXTEX:
1970   {
1971     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1972     int nStart, nCount;
1973
1974     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1975       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1976
1977     if (ex->flags & GT_SELECTION)
1978     {
1979       ME_GetSelection(editor, &nStart, &nCount);
1980       nCount -= nStart;
1981       nCount = min(nCount, ex->cb - 1);
1982     }
1983     else
1984     {
1985       nStart = 0;
1986       nCount = ex->cb - 1;
1987     }
1988     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1989     {
1990       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1991       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1992     }
1993     else
1994     {
1995       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1996         we can just take a bigger buffer? :) */
1997       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1998       LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (crlfmul*nCount + 1) * sizeof(WCHAR));
1999       DWORD buflen = ex->cb;
2000       LRESULT rc;
2001       DWORD flags = 0;
2002
2003       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2004       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2005
2006       HeapFree(GetProcessHeap(),0,buffer);
2007       return rc;
2008     }
2009   }
2010   case EM_GETSELTEXT:
2011   {
2012     int from, to;
2013     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2014     ME_GetSelection(editor, &from, &to);
2015     tr.chrg.cpMin = from;
2016     tr.chrg.cpMax = to;
2017     tr.lpstrText = (WCHAR *)lParam;
2018     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2019   }
2020   case EM_GETSCROLLPOS:
2021   {
2022       POINT *point = (POINT *)lParam;
2023       point->x = 0; /* FIXME side scrolling not implemented */
2024       point->y = ME_GetYScrollPos(editor);
2025       return 1;
2026   }
2027   case EM_GETTEXTRANGE:
2028   {
2029     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2030     TRACE("EM_GETTEXTRANGE min=%ld max=%ld unicode=%d emul1.0=%d length=%d\n",
2031       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
2032       editor->bEmulateVersion10, ME_GetTextLength(editor));
2033     if (IsWindowUnicode(hWnd))
2034       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2035     else
2036     {
2037       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2038       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2039       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2040       /* FIXME this is a potential security hole (buffer overrun) 
2041          if you know more about wchar->mbyte conversion please explain
2042       */
2043       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2044       FREE_OBJ(p);
2045       return nChars;
2046     }
2047   }
2048   case EM_GETLINE:
2049   {
2050     ME_DisplayItem *run;
2051     const BOOL bUnicode = IsWindowUnicode(hWnd);
2052     const unsigned int nMaxChars = *(WORD *) lParam;
2053     unsigned int nEndChars, nCharsLeft = nMaxChars;
2054     char *dest = (char *) lParam;
2055     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2056     we need to know how if we have the extra \n or not */
2057     int nLF = editor->bEmulateVersion10;
2058
2059     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2060           bUnicode ? "Unicode" : "Ansi");
2061
2062     run = ME_FindRowWithNumber(editor, wParam);
2063     if (run == NULL)
2064       return 0;
2065
2066     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2067            && !(run->member.run.nFlags & MERF_ENDPARA))
2068     {
2069       unsigned int nCopy;
2070       ME_String *strText;
2071       if (run->type != diRun)
2072         break;
2073       strText = run->member.run.strText;
2074       nCopy = min(nCharsLeft, strText->nLen);
2075
2076       if (bUnicode)
2077         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2078       else
2079         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2080                                     nCharsLeft, NULL, NULL);
2081       dest += nCopy * (bUnicode ? sizeof(WCHAR) : 1);
2082       nCharsLeft -= nCopy;
2083     }
2084
2085     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2086     nEndChars = min(nCharsLeft, 2 + nLF);
2087     nCharsLeft -= nEndChars;
2088     if (bUnicode)
2089     {
2090       const WCHAR src[] = {'\r', '\0'};
2091       const WCHAR src10[] = {'\r', '\n', '\0'};
2092       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2093     }
2094     else
2095       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2096
2097     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2098
2099     if (nEndChars == 2 + nLF)
2100       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2101     else
2102       return nMaxChars - nCharsLeft;
2103   }
2104   case EM_GETLINECOUNT:
2105   {
2106     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2107     int nRows = 0;
2108
2109     while (item != editor->pBuffer->pLast)
2110     {
2111       assert(item->type == diParagraph);
2112       nRows += item->member.para.nRows;
2113       item = item->member.para.next_para;
2114     }
2115     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2116     return max(1, nRows);
2117   }
2118   case EM_LINEFROMCHAR:
2119   {
2120     if (wParam == -1)
2121       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2122     else
2123       return ME_RowNumberFromCharOfs(editor, wParam);
2124   }
2125   case EM_EXLINEFROMCHAR:
2126   {
2127     if (lParam == -1)
2128       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2129     else    
2130       return ME_RowNumberFromCharOfs(editor, lParam);
2131   }
2132   case EM_LINEINDEX:
2133   {
2134     ME_DisplayItem *item, *para;
2135     int nCharOfs;
2136     
2137     if (wParam == -1)
2138       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2139     else
2140       item = ME_FindRowWithNumber(editor, wParam);
2141     if (!item)
2142       return -1;
2143     para = ME_GetParagraph(item);
2144     item = ME_FindItemFwd(item, diRun);
2145     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2146     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2147     return nCharOfs;
2148   }
2149   case EM_LINELENGTH:
2150   {
2151     ME_DisplayItem *item, *item_end;
2152     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2153     
2154     if (wParam > ME_GetTextLength(editor))
2155       return 0;
2156     if (wParam == -1)
2157     {
2158       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2159       return 0;
2160     }
2161     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2162     item = ME_RowStart(item);
2163     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2164     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2165     if (item_end->type == diStartRow)
2166       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2167     else
2168       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2169        - (editor->bEmulateVersion10?2:1);
2170     nChars = nNextLineOfs - nThisLineOfs;
2171     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
2172     return nChars;
2173   }
2174   case EM_EXLIMITTEXT:
2175   {
2176     if (wParam != 0 || lParam < 0)
2177      return 0;
2178     if (lParam == 0)
2179       editor->nTextLimit = 65536;
2180     else
2181       editor->nTextLimit = (int) lParam;
2182     return 0;
2183   }
2184   case EM_GETLIMITTEXT:
2185   {
2186     return editor->nTextLimit;
2187   }
2188   case EM_FINDTEXT:
2189   {
2190     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2191     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2192     WCHAR *tmp;
2193     
2194     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2195       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2196     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2197   }
2198   case EM_FINDTEXTEX:
2199   {
2200     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2201     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2202     WCHAR *tmp;
2203     
2204     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2205       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2206     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2207   }
2208   case EM_FINDTEXTW:
2209   {
2210     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2211     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2212   }
2213   case EM_FINDTEXTEXW:
2214   {
2215     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2216     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2217   }
2218   case EM_GETZOOM:
2219     if (!wParam || !lParam)
2220       return FALSE;
2221     *(int *)wParam = editor->nZoomNumerator;
2222     *(int *)lParam = editor->nZoomDenominator;
2223     return TRUE;
2224   case EM_SETZOOM:
2225     return ME_SetZoom(editor, wParam, lParam);
2226   case EM_CHARFROMPOS:
2227     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2228   case EM_POSFROMCHAR:
2229   {
2230     ME_DisplayItem *pRun;
2231     int nCharOfs, nOffset, nLength;
2232     POINTL pt = {0,0};
2233     
2234     nCharOfs = wParam; 
2235     /* detect which API version we're dealing with */
2236     if (wParam >= 0x40000)
2237         nCharOfs = lParam;
2238     nLength = ME_GetTextLength(editor);
2239     
2240     if (nCharOfs < nLength) { 
2241         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2242         assert(pRun->type == diRun);
2243         pt.y = pRun->member.run.pt.y;
2244         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2245         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2246     } else {
2247         pt.x = 0;
2248         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2249     }
2250     if (wParam >= 0x40000) {
2251         *(POINTL *)wParam = pt;
2252     }
2253     return MAKELONG( pt.x, pt.y );
2254   }
2255   case WM_CREATE:
2256     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2257     { /* Squelch the default horizontal scrollbar it would make */
2258       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2259     }
2260     ME_CommitUndo(editor);
2261     ME_WrapMarkedParagraphs(editor);
2262     ME_MoveCaret(editor);
2263     return 0;
2264   case WM_DESTROY:
2265     ME_DestroyEditor(editor);
2266     SetWindowLongPtrW(hWnd, 0, 0);
2267     return 0;
2268   case WM_LBUTTONDOWN:
2269     SetFocus(hWnd);
2270     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2271     SetCapture(hWnd);
2272     ME_LinkNotify(editor,msg,wParam,lParam);
2273     break;
2274   case WM_MOUSEMOVE:
2275     if (GetCapture() == hWnd)
2276       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2277     ME_LinkNotify(editor,msg,wParam,lParam);
2278     break;
2279   case WM_LBUTTONUP:
2280     if (GetCapture() == hWnd)
2281       ReleaseCapture();
2282     ME_LinkNotify(editor,msg,wParam,lParam);
2283     break;
2284   case WM_LBUTTONDBLCLK:
2285     ME_LinkNotify(editor,msg,wParam,lParam);
2286     ME_SelectWord(editor);
2287     break;
2288   case WM_CONTEXTMENU:
2289     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2290       goto do_default;
2291     break;
2292   case WM_PAINT:
2293     if (editor->bRedraw)
2294     {
2295       HDC hDC;
2296       PAINTSTRUCT ps;
2297
2298       hDC = BeginPaint(hWnd, &ps);
2299       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2300       EndPaint(hWnd, &ps);
2301     }
2302     break;
2303   case WM_SETFOCUS:
2304     ME_ShowCaret(editor);
2305     ME_SendOldNotify(editor, EN_SETFOCUS);
2306     return 0;
2307   case WM_KILLFOCUS:
2308     ME_HideCaret(editor);
2309     ME_SendOldNotify(editor, EN_KILLFOCUS);
2310     return 0;
2311   case WM_ERASEBKGND:
2312   {
2313     if (editor->bRedraw)
2314     {
2315       HDC hDC = (HDC)wParam;
2316       RECT rc;
2317       if (GetUpdateRect(hWnd,&rc,TRUE))
2318       {
2319         FillRect(hDC, &rc, editor->hbrBackground);
2320       }
2321     }
2322     return 1;
2323   }
2324   case WM_COMMAND:
2325     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2326     return 0;
2327   case WM_KEYDOWN:
2328     if (ME_KeyDown(editor, LOWORD(wParam)))
2329       return 0;
2330     goto do_default;
2331   case WM_CHAR: 
2332   {
2333     WCHAR wstr = LOWORD(wParam);
2334     if (editor->AutoURLDetect_bEnable)
2335       ME_AutoURLDetect(editor, wstr);
2336         
2337     switch (wstr)
2338     {
2339     case 1: /* Ctrl-A */
2340       ME_SetSelection(editor, 0, -1);
2341       return 0;
2342     case 3: /* Ctrl-C */
2343       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2344       return 0;
2345     }
2346     
2347     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2348       MessageBeep(MB_ICONERROR);
2349       return 0; /* FIXME really 0 ? */
2350     }
2351
2352     switch (wstr)
2353     {
2354     case 22: /* Ctrl-V */
2355       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2356       return 0;
2357     case 24: /* Ctrl-X */
2358       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2359       return 0;
2360     case 25: /* Ctrl-Y */
2361       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2362       return 0;
2363     case 26: /* Ctrl-Z */
2364       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2365       return 0;
2366     }
2367     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
2368       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2369       ME_Style *style = ME_GetInsertStyle(editor, 0);
2370       ME_SaveTempStyle(editor);
2371       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2372       ME_ReleaseStyle(style);
2373       ME_CommitUndo(editor);
2374       ME_UpdateRepaint(editor);
2375     }
2376     return 0;
2377   }
2378   case EM_SCROLL: /* fall through */
2379   case WM_VSCROLL: 
2380   {
2381     int origNPos;
2382     int lineHeight;
2383     
2384     origNPos = ME_GetYScrollPos(editor);
2385     lineHeight = 24;
2386     
2387     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2388       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2389     if (lineHeight <= 0) lineHeight = 24;
2390     
2391     switch(LOWORD(wParam)) 
2392     {
2393       case SB_LINEUP:
2394         ME_ScrollUp(editor,lineHeight);
2395         break;
2396       case SB_LINEDOWN:
2397         ME_ScrollDown(editor,lineHeight);
2398         break;
2399       case SB_PAGEUP:
2400         ME_ScrollUp(editor,editor->sizeWindow.cy);
2401         break;
2402       case SB_PAGEDOWN:
2403         ME_ScrollDown(editor,editor->sizeWindow.cy);
2404         break;
2405       case SB_THUMBTRACK:
2406       case SB_THUMBPOSITION:
2407         ME_ScrollAbs(editor,HIWORD(wParam));
2408         break;
2409     }
2410     if (msg == EM_SCROLL)
2411       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2412     break;
2413   }
2414   case WM_MOUSEWHEEL:
2415   {
2416     int gcWheelDelta;
2417     UINT pulScrollLines;
2418     
2419     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2420     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2421     
2422     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2423     {
2424       /* FIXME follow the original */
2425       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2426     }
2427     break;
2428   }
2429   case EM_GETRECT:
2430   {
2431     *((RECT *)lParam) = editor->rcFormat;
2432     return 0;
2433   }
2434   case EM_SETRECT:
2435   case EM_SETRECTNP:
2436   {
2437     if (lParam)
2438     {
2439       RECT *rc = (RECT *)lParam;
2440       
2441       if (wParam)
2442       {
2443         editor->rcFormat.left += rc->left;
2444         editor->rcFormat.top += rc->top;
2445         editor->rcFormat.right += rc->right;
2446         editor->rcFormat.bottom += rc->bottom;
2447       }
2448       else
2449       {
2450         editor->rcFormat = *rc;
2451       }
2452     }
2453     else
2454     {
2455       GetClientRect(hWnd, &editor->rcFormat);
2456     }
2457     if (msg != EM_SETRECTNP)
2458       ME_RewrapRepaint(editor);
2459     return 0;
2460   }
2461   case EM_REQUESTRESIZE:
2462     ME_SendRequestResize(editor, TRUE);
2463     return 0;
2464   case WM_SETREDRAW:
2465     editor->bRedraw = wParam;
2466     return 0;
2467   case WM_SIZE:
2468   {
2469     GetClientRect(hWnd, &editor->rcFormat);
2470     ME_RewrapRepaint(editor);
2471     return DefWindowProcW(hWnd, msg, wParam, lParam);
2472   }
2473   case EM_GETOLEINTERFACE:
2474   {
2475     LPVOID *ppvObj = (LPVOID*) lParam;
2476     return CreateIRichEditOle(editor, ppvObj);
2477   }
2478   case EM_GETPASSWORDCHAR:
2479   {
2480     return editor->cPasswordMask;
2481   }
2482   case EM_SETOLECALLBACK:
2483     if(editor->lpOleCallback)
2484       IUnknown_Release(editor->lpOleCallback);
2485     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2486     if(editor->lpOleCallback)
2487       IUnknown_AddRef(editor->lpOleCallback);
2488     return TRUE;
2489   case EM_GETWORDBREAKPROC:
2490     return (LRESULT)editor->pfnWordBreak;
2491   case EM_SETWORDBREAKPROC:
2492   {
2493     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2494
2495     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2496     return (LRESULT)pfnOld;
2497   }
2498   case EM_SETTEXTMODE:
2499   {
2500     LRESULT ret;
2501     int mask = 0;
2502     int changes = 0;
2503     if ((ret = RichEditANSIWndProc(hWnd, WM_GETTEXTLENGTH, 0, 0)) == 0)
2504     {
2505       /*Check for valid wParam*/
2506       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2507           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2508           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2509         return 1;
2510       else
2511       {
2512         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2513         {
2514           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2515           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2516         }
2517         /*FIXME: Currently no support for undo level and code page options*/ 
2518         editor->mode = (editor->mode & (~mask)) | changes;
2519         return 0;
2520       }
2521     }
2522     return ret;
2523   }
2524   case EM_SETPASSWORDCHAR:
2525   {
2526     editor->cPasswordMask = wParam;
2527     ME_RewrapRepaint(editor);
2528     return 0;
2529   }
2530   default:
2531   do_default:
2532     return DefWindowProcW(hWnd, msg, wParam, lParam);
2533   }
2534   return 0L;
2535 }
2536
2537
2538 /******************************************************************
2539  *        RichEdit10ANSIWndProc (RICHED20.9)
2540  */
2541 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2542 {
2543   LRESULT result;
2544   
2545   /* FIXME: this is NOT the same as 2.0 version */
2546   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2547   if (msg == WM_NCCREATE)
2548   {
2549     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2550     
2551     editor->bEmulateVersion10 = TRUE;
2552     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2553   }
2554   return result;
2555 }
2556
2557 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2558 {
2559   HWND hWnd = editor->hWnd;
2560   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2561 }
2562
2563 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2564 {
2565   int x,y;
2566   ME_Cursor tmpCursor;
2567   ME_Run *tmpRun;
2568   BOOL bNothing;
2569   ENLINK info;
2570   x = (short)LOWORD(lParam);
2571   y = (short)HIWORD(lParam);
2572   ME_FindPixelPos(editor, x, y, &tmpCursor, &bNothing);
2573   tmpRun = &tmpCursor.pRun->member.run;
2574         
2575   if ((tmpRun->style->fmt.dwMask & CFM_LINK) 
2576     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2577   { /* The clicked run has CFE_LINK set */
2578     info.nmhdr.hwndFrom = editor->hWnd;
2579     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2580     info.nmhdr.code = EN_LINK;
2581     info.msg = msg;
2582     info.wParam = wParam;
2583     info.lParam = lParam;
2584     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2585     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2586     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2587   }  
2588 }
2589
2590 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2591 {
2592   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2593   int i = 0;
2594   
2595   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2596     item = item->member.para.next_para;
2597   if (!item)
2598     return 0;
2599   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2600     item = item->member.para.next_para;
2601     i++;
2602   }
2603   return i;
2604 }
2605
2606
2607 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2608 {
2609   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2610   int nWritten = 0;
2611   WCHAR *pStart = buffer;
2612   
2613   if (!item) {
2614     *buffer = L'\0';
2615     return 0;
2616   }
2617   
2618   if (nStart)
2619   {
2620     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2621     if (nLen > nChars)
2622       nLen = nChars;
2623     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2624     nChars -= nLen;
2625     nWritten += nLen;
2626     if (!nChars)
2627       return nWritten;
2628     buffer += nLen;
2629     nStart = 0;
2630     item = ME_FindItemFwd(item, diRun);
2631   }
2632   
2633   while(nChars && item)
2634   {
2635     int nLen = ME_StrLen(item->member.run.strText);
2636     if (nLen > nChars)
2637       nLen = nChars;
2638
2639     if (item->member.run.nFlags & MERF_ENDPARA)
2640     {
2641       if (!ME_FindItemFwd(item, diRun))
2642         /* No '\r' is appended to the last paragraph. */
2643         nLen = 0;
2644       else {
2645         *buffer = '\r';
2646         if (bCRLF)
2647         {
2648           *(++buffer) = '\n';
2649           nWritten++;
2650         }
2651         assert(nLen == 1);
2652         /* our end paragraph consists of 2 characters now */
2653         if (editor->bEmulateVersion10)
2654           nChars--;
2655       }
2656     }
2657     else
2658       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2659     nChars -= nLen;
2660     nWritten += nLen;
2661     buffer += nLen;    
2662       
2663     if (!nChars)
2664     {
2665       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2666       *buffer = L'\0';
2667       return nWritten;
2668     }
2669     item = ME_FindItemFwd(item, diRun);
2670   }
2671   *buffer = L'\0';
2672   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2673   return nWritten;  
2674 }
2675
2676 void ME_RegisterEditorClass(HINSTANCE hInstance)
2677 {
2678   BOOL bResult;
2679   WNDCLASSW wcW;
2680   WNDCLASSA wcA;
2681   
2682   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2683   wcW.lpfnWndProc = RichEditANSIWndProc;
2684   wcW.cbClsExtra = 0;
2685   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2686   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2687   wcW.hIcon = NULL;
2688   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2689   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2690   wcW.lpszMenuName = NULL;
2691   wcW.lpszClassName = wszClassName;
2692   bResult = RegisterClassW(&wcW);  
2693   assert(bResult);
2694   wcW.lpszClassName = wszClassName50;
2695   bResult = RegisterClassW(&wcW);  
2696   assert(bResult);
2697
2698   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2699   wcA.lpfnWndProc = RichEditANSIWndProc;
2700   wcA.cbClsExtra = 0;
2701   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2702   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2703   wcA.hIcon = NULL;
2704   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2705   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2706   wcA.lpszMenuName = NULL;
2707   wcA.lpszClassName = "RichEdit20A";
2708   bResult = RegisterClassA(&wcA);  
2709   assert(bResult);
2710   wcA.lpszClassName = "RichEdit50A";
2711   bResult = RegisterClassA(&wcA);  
2712   assert(bResult);
2713 }
2714
2715 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2716   /* FIXME: Not implemented */
2717   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2718         hWnd, msg, get_msg_name(msg), wParam, lParam);
2719   return DefWindowProcW(hWnd, msg, wParam, lParam);
2720 }
2721
2722 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2723   /* FIXME: Not implemented */
2724   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2725         hWnd, msg, get_msg_name(msg), wParam, lParam);
2726   return DefWindowProcW(hWnd, msg, wParam, lParam);
2727 }
2728
2729 /******************************************************************
2730  *        REExtendedRegisterClass (RICHED20.8)
2731  *
2732  * FIXME undocumented
2733  * Need to check for errors and implement controls and callbacks 
2734  */
2735 LRESULT WINAPI REExtendedRegisterClass(void)
2736 {
2737   WNDCLASSW wcW;
2738   UINT result;
2739
2740   FIXME("semi stub\n");
2741
2742   wcW.cbClsExtra = 0;
2743   wcW.cbWndExtra = 4;
2744   wcW.hInstance = NULL;
2745   wcW.hIcon = NULL;
2746   wcW.hCursor = NULL;
2747   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2748   wcW.lpszMenuName = NULL;
2749
2750   if (!ME_ListBoxRegistered)
2751   {
2752       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2753       wcW.lpfnWndProc = REListWndProc;
2754       wcW.lpszClassName = wszClassNameListBox;
2755       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2756   }
2757
2758   if (!ME_ComboBoxRegistered)
2759   {
2760       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2761       wcW.lpfnWndProc = REComboWndProc;
2762       wcW.lpszClassName = wszClassNameComboBox;
2763       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2764   }
2765
2766   result = 0;
2767   if (ME_ListBoxRegistered)
2768       result += 1;
2769   if (ME_ComboBoxRegistered)
2770       result += 2;
2771
2772   return result;
2773 }
2774
2775 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
2776 {
2777   struct prefix_s {
2778     const char *text;
2779     int length;
2780   } prefixes[12] = {
2781     {"http:", 5},
2782     {"file:", 6},
2783     {"mailto:", 8},
2784     {"ftp:", 5},
2785     {"https:", 7},
2786     {"gopher:", 8},
2787     {"nntp:", 6},
2788     {"prospero:", 10},
2789     {"telnet:", 8},
2790     {"news:", 6},
2791     {"wais:", 6},
2792     {"www.", 5}
2793   };
2794   CHARRANGE ins_pt;
2795   int curf_ef, link_ef, def_ef;
2796   int cur_prefx, prefx_cnt;
2797   int sel_min, sel_max;
2798   int car_pos = 0;
2799   int text_pos=-1;
2800   int URLmin, URLmax = 0;
2801   CHARRANGE url;
2802   FINDTEXTA ft;
2803   CHARFORMAT2W cur_format;
2804   CHARFORMAT2W default_format;
2805   CHARFORMAT2W link;
2806   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
2807   sel_min = ins_pt.cpMin;
2808   sel_max = ins_pt.cpMax;
2809   if (sel_min==sel_max) 
2810     car_pos = sel_min;
2811   if (sel_min!=sel_max)
2812     car_pos = ME_GetTextLength(editor)+1;   
2813   cur_format.cbSize = sizeof(cur_format);
2814   default_format.cbSize = sizeof(default_format);
2815   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
2816   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
2817   link.cbSize = sizeof(link);
2818   link.dwMask = CFM_LINK;
2819   link.dwEffects = CFE_LINK;
2820   curf_ef = cur_format.dwEffects & link.dwEffects;
2821   def_ef = default_format.dwEffects & link.dwEffects;
2822   link_ef = link.dwEffects & link.dwEffects;
2823   if (curf_ef == link_ef) 
2824   {
2825     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
2826     {
2827       ME_SetSelection(editor, car_pos, car_pos);
2828       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
2829       text_pos=-1;
2830       return 0;
2831     }
2832   }
2833   if (curf_ef == def_ef)
2834   {
2835     cur_prefx = 0;
2836     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
2837     while (cur_prefx<=prefx_cnt) 
2838     {
2839       if (text_pos == -1) 
2840       {
2841         ft.lpstrText = prefixes[cur_prefx].text;
2842         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
2843         URLmax=max(0, car_pos);
2844         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
2845         {
2846         URLmax = ME_GetTextLength(editor)+1;
2847         }
2848         ft.chrg.cpMin = URLmin;
2849         ft.chrg.cpMax = URLmax;
2850         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
2851         cur_prefx++;
2852       }
2853       if (text_pos != -1) 
2854       {
2855         url.cpMin=text_pos;
2856         url.cpMax=car_pos-1;
2857         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
2858         ME_RewrapRepaint(editor);
2859         break;
2860       }
2861     }
2862   }
2863   return 0;
2864 }