dnsapi: Cast-qual warnings fix.
[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->nScrollPosY = 0;
1139   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1140   ed->bRedraw = TRUE;
1141   ed->bHideSelection = FALSE;
1142   ed->nInvalidOfs = -1;
1143   ed->pfnWordBreak = NULL;
1144   ed->lpOleCallback = NULL;
1145   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1146   GetClientRect(hWnd, &ed->rcFormat);
1147   for (i=0; i<HFONT_CACHE_SIZE; i++)
1148   {
1149     ed->pFontCache[i].nRefs = 0;
1150     ed->pFontCache[i].nAge = 0;
1151     ed->pFontCache[i].hFont = NULL;
1152   }
1153   
1154   if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
1155     FIXME("WS_HSCROLL requested, but horizontal scrolling isn't implemented yet.\n");
1156   ed->bScrollX = 0;  
1157   ed->bScrollY = GetWindowLongW(hWnd, GWL_STYLE) & WS_VSCROLL;
1158   
1159   ME_CheckCharOffsets(ed);
1160   
1161   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1162     ed->cPasswordMask = '*';
1163   else
1164     ed->cPasswordMask = 0;
1165   
1166   return ed;
1167 }
1168
1169 typedef struct tagME_GlobalDestStruct
1170 {
1171   HGLOBAL hData;
1172   int nLength;
1173 } ME_GlobalDestStruct;
1174
1175 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1176 {
1177   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1178   int i;
1179   WORD *pSrc, *pDest;
1180   
1181   cb = cb >> 1;
1182   pDest = (WORD *)lpBuff;
1183   pSrc = (WORD *)GlobalLock(pData->hData);
1184   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1185     pDest[i] = pSrc[pData->nLength+i];
1186   }    
1187   pData->nLength += i;
1188   *pcb = 2*i;
1189   GlobalUnlock(pData->hData);
1190   return 0;
1191 }
1192
1193 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1194 {
1195   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1196   int i;
1197   BYTE *pSrc, *pDest;
1198   
1199   pDest = lpBuff;
1200   pSrc = (BYTE *)GlobalLock(pData->hData);
1201   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1202     pDest[i] = pSrc[pData->nLength+i];
1203   }    
1204   pData->nLength += i;
1205   *pcb = i;
1206   GlobalUnlock(pData->hData);
1207   return 0;
1208 }
1209
1210
1211 void ME_DestroyEditor(ME_TextEditor *editor)
1212 {
1213   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1214   ME_DisplayItem *p = pFirst, *pNext = NULL;
1215   int i;
1216   
1217   ME_ClearTempStyle(editor);
1218   ME_EmptyUndoStack(editor);
1219   while(p) {
1220     pNext = p->next;
1221     ME_DestroyDisplayItem(p);    
1222     p = pNext;
1223   }
1224   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1225   for (i=0; i<HFONT_CACHE_SIZE; i++)
1226   {
1227     if (editor->pFontCache[i].hFont)
1228       DeleteObject(editor->pFontCache[i].hFont);
1229   }
1230   DeleteObject(editor->hbrBackground);
1231   if(editor->lpOleCallback)
1232     IUnknown_Release(editor->lpOleCallback);
1233
1234   FREE_OBJ(editor);
1235 }
1236
1237 static const WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
1238 static const WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
1239 static const WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
1240 static const WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
1241
1242 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1243 {
1244     TRACE("\n");
1245     switch (fdwReason)
1246     {
1247     case DLL_PROCESS_ATTACH:
1248       DisableThreadLibraryCalls(hinstDLL);
1249       me_heap = HeapCreate (0, 0x10000, 0);
1250       ME_RegisterEditorClass(hinstDLL);
1251       break;
1252
1253     case DLL_PROCESS_DETACH:
1254       UnregisterClassW(wszClassName, 0);
1255       UnregisterClassW(wszClassName50, 0);
1256       UnregisterClassA("RichEdit20A", 0);
1257       UnregisterClassA("RichEdit50A", 0);
1258       if (ME_ListBoxRegistered)
1259           UnregisterClassW(wszClassNameListBox, 0);
1260       if (ME_ComboBoxRegistered)
1261           UnregisterClassW(wszClassNameComboBox, 0);
1262       HeapDestroy (me_heap);
1263       me_heap = NULL;
1264       break;
1265     }
1266     return TRUE;
1267 }
1268
1269
1270 #define UNSUPPORTED_MSG(e) \
1271   case e: \
1272     FIXME(#e ": stub\n"); \
1273     return DefWindowProcW(hWnd, msg, wParam, lParam);
1274
1275 static const char * const edit_messages[] = {
1276   "EM_GETSEL",
1277   "EM_SETSEL",
1278   "EM_GETRECT",
1279   "EM_SETRECT",
1280   "EM_SETRECTNP",
1281   "EM_SCROLL",
1282   "EM_LINESCROLL",
1283   "EM_SCROLLCARET",
1284   "EM_GETMODIFY",
1285   "EM_SETMODIFY",
1286   "EM_GETLINECOUNT",
1287   "EM_LINEINDEX",
1288   "EM_SETHANDLE",
1289   "EM_GETHANDLE",
1290   "EM_GETTHUMB",
1291   "EM_UNKNOWN_BF",
1292   "EM_UNKNOWN_C0",
1293   "EM_LINELENGTH",
1294   "EM_REPLACESEL",
1295   "EM_UNKNOWN_C3",
1296   "EM_GETLINE",
1297   "EM_LIMITTEXT",
1298   "EM_CANUNDO",
1299   "EM_UNDO",
1300   "EM_FMTLINES",
1301   "EM_LINEFROMCHAR",
1302   "EM_UNKNOWN_CA",
1303   "EM_SETTABSTOPS",
1304   "EM_SETPASSWORDCHAR",
1305   "EM_EMPTYUNDOBUFFER",
1306   "EM_GETFIRSTVISIBLELINE",
1307   "EM_SETREADONLY",
1308   "EM_SETWORDBREAKPROC",
1309   "EM_GETWORDBREAKPROC",
1310   "EM_GETPASSWORDCHAR",
1311   "EM_SETMARGINS",
1312   "EM_GETMARGINS",
1313   "EM_GETLIMITTEXT",
1314   "EM_POSFROMCHAR",
1315   "EM_CHARFROMPOS"
1316 };
1317
1318 static const char * const richedit_messages[] = {
1319   "EM_CANPASTE",
1320   "EM_DISPLAYBAND",
1321   "EM_EXGETSEL",
1322   "EM_EXLIMITTEXT",
1323   "EM_EXLINEFROMCHAR",
1324   "EM_EXSETSEL",
1325   "EM_FINDTEXT",
1326   "EM_FORMATRANGE",
1327   "EM_GETCHARFORMAT",
1328   "EM_GETEVENTMASK",
1329   "EM_GETOLEINTERFACE",
1330   "EM_GETPARAFORMAT",
1331   "EM_GETSELTEXT",
1332   "EM_HIDESELECTION", 
1333   "EM_PASTESPECIAL",
1334   "EM_REQUESTRESIZE",
1335   "EM_SELECTIONTYPE",
1336   "EM_SETBKGNDCOLOR",
1337   "EM_SETCHARFORMAT",
1338   "EM_SETEVENTMASK",
1339   "EM_SETOLECALLBACK",
1340   "EM_SETPARAFORMAT",
1341   "EM_SETTARGETDEVICE",
1342   "EM_STREAMIN",
1343   "EM_STREAMOUT",
1344   "EM_GETTEXTRANGE",
1345   "EM_FINDWORDBREAK",
1346   "EM_SETOPTIONS",
1347   "EM_GETOPTIONS",
1348   "EM_FINDTEXTEX",
1349   "EM_GETWORDBREAKPROCEX",
1350   "EM_SETWORDBREAKPROCEX",
1351   "EM_SETUNDOLIMIT",
1352   "EM_UNKNOWN_USER_83",
1353   "EM_REDO",
1354   "EM_CANREDO",
1355   "EM_GETUNDONAME",
1356   "EM_GETREDONAME",
1357   "EM_STOPGROUPTYPING",
1358   "EM_SETTEXTMODE",
1359   "EM_GETTEXTMODE",
1360   "EM_AUTOURLDETECT",
1361   "EM_GETAUTOURLDETECT",
1362   "EM_SETPALETTE",
1363   "EM_GETTEXTEX",
1364   "EM_GETTEXTLENGTHEX",
1365   "EM_SHOWSCROLLBAR",
1366   "EM_SETTEXTEX",
1367   "EM_UNKNOWN_USER_98",
1368   "EM_UNKNOWN_USER_99",
1369   "EM_SETPUNCTUATION",
1370   "EM_GETPUNCTUATION",
1371   "EM_SETWORDWRAPMODE",
1372   "EM_GETWORDWRAPMODE",
1373   "EM_SETIMECOLOR",
1374   "EM_GETIMECOLOR",
1375   "EM_SETIMEOPTIONS",
1376   "EM_GETIMEOPTIONS",
1377   "EM_CONVPOSITION",
1378   "EM_UNKNOWN_USER_109",
1379   "EM_UNKNOWN_USER_110",
1380   "EM_UNKNOWN_USER_111",
1381   "EM_UNKNOWN_USER_112",
1382   "EM_UNKNOWN_USER_113",
1383   "EM_UNKNOWN_USER_114",
1384   "EM_UNKNOWN_USER_115",
1385   "EM_UNKNOWN_USER_116",
1386   "EM_UNKNOWN_USER_117",
1387   "EM_UNKNOWN_USER_118",
1388   "EM_UNKNOWN_USER_119",
1389   "EM_SETLANGOPTIONS",
1390   "EM_GETLANGOPTIONS",
1391   "EM_GETIMECOMPMODE",
1392   "EM_FINDTEXTW",
1393   "EM_FINDTEXTEXW",
1394   "EM_RECONVERSION",
1395   "EM_SETIMEMODEBIAS",
1396   "EM_GETIMEMODEBIAS"
1397 };
1398
1399 static const char *
1400 get_msg_name(UINT msg)
1401 {
1402   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1403     return edit_messages[msg - EM_GETSEL];
1404   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1405     return richedit_messages[msg - EM_CANPASTE];
1406   return "";
1407 }
1408
1409 /******************************************************************
1410  *        RichEditANSIWndProc (RICHED20.10)
1411  */
1412 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1413   SCROLLINFO si;
1414   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1415   
1416   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1417         hWnd, msg, get_msg_name(msg), wParam, lParam);
1418   
1419   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1420     ERR("RichEditANSIWndProc called with invalid hWnd %p - application bug?\n", hWnd);
1421     return 0; 
1422   }
1423
1424   switch(msg) {
1425   
1426   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1427   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1428   UNSUPPORTED_MSG(EM_FMTLINES)
1429   UNSUPPORTED_MSG(EM_FORMATRANGE)
1430   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1431   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1432   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1433   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1434   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1435   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1436   UNSUPPORTED_MSG(EM_GETREDONAME)
1437   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1438   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1439   UNSUPPORTED_MSG(EM_GETUNDONAME)
1440   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1441   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1442   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1443   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1444   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1445   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1446   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1447   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1448   UNSUPPORTED_MSG(EM_SETPALETTE)
1449   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1450   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1451   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1452   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1453   UNSUPPORTED_MSG(WM_STYLECHANGING)
1454   UNSUPPORTED_MSG(WM_STYLECHANGED)
1455 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1456     
1457 /* Messages specific to Richedit controls */
1458   
1459   case EM_STREAMIN:
1460    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1461   case EM_STREAMOUT:
1462    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1463   case WM_GETDLGCODE:
1464   {
1465     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1466     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1467       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1468     return code;
1469   }
1470   case WM_NCCREATE:
1471   {
1472     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1473     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1474     editor = ME_MakeEditor(hWnd);
1475     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1476     pcs = 0; /* ignore */
1477     return TRUE;
1478   }
1479   case EM_EMPTYUNDOBUFFER:
1480     ME_EmptyUndoStack(editor);
1481     return 0;
1482   case EM_GETSEL:
1483   {
1484     /* Note: wParam/lParam can be NULL */
1485     UINT from, to;
1486     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1487     PUINT pto = lParam ? (PUINT)lParam : &to;
1488     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1489     if ((*pfrom|*pto) & 0xFFFF0000)
1490       return -1;
1491     return MAKELONG(*pfrom,*pto);
1492   }
1493   case EM_EXGETSEL:
1494   {
1495     CHARRANGE *pRange = (CHARRANGE *)lParam;
1496     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1497     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1498     return 0;
1499   }
1500   case EM_SETUNDOLIMIT:
1501   {
1502     if ((int)wParam < 0)
1503       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1504     else
1505       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1506     /* Setting a max stack size keeps wine from getting killed 
1507       for hogging memory. Windows allocates all this memory at once, so
1508       no program would realistically set a value above our maxiumum. */  
1509     return editor->nUndoLimit;
1510   }
1511   case EM_CANUNDO:
1512     return editor->pUndoStack != NULL;
1513   case EM_CANREDO:
1514     return editor->pRedoStack != NULL;
1515   case WM_UNDO: /* FIXME: actually not the same */
1516   case EM_UNDO:
1517     ME_Undo(editor);
1518     return 0;
1519   case EM_REDO:
1520     ME_Redo(editor);
1521     return 0;
1522   case EM_GETOPTIONS:
1523   {
1524     /* these flags are equivalent to the ES_* counterparts */
1525     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1526                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1527     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1528
1529     return settings;
1530   }
1531   case EM_SETOPTIONS:
1532   {
1533     /* these flags are equivalent to ES_* counterparts                      
1534      * ECO_READONLY is already implemented in the code, only requires 
1535      * setting the bit to work                                        
1536      */
1537     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1538                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1539     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1540     DWORD settings = mask & raw;
1541
1542     switch(wParam)
1543     {
1544       case ECOOP_SET:
1545         settings = lParam;
1546         break;
1547       case ECOOP_OR:
1548         settings |= lParam;
1549         break;
1550       case ECOOP_AND:
1551         settings &= lParam;
1552         break;
1553       case ECOOP_XOR:
1554         settings ^= lParam;
1555     }
1556     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1557
1558     if (lParam & ECO_AUTOWORDSELECTION)
1559       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1560     if (lParam & ECO_SELECTIONBAR)
1561       FIXME("ECO_SELECTIONBAR not implemented yet!\n");
1562     if (lParam & ECO_VERTICAL)
1563       FIXME("ECO_VERTICAL not implemented yet!\n");
1564     if (lParam & ECO_AUTOHSCROLL)
1565       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1566     if (lParam & ECO_AUTOVSCROLL)
1567       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1568     if (lParam & ECO_NOHIDESEL)
1569       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1570     if (lParam & ECO_WANTRETURN)
1571       FIXME("ECO_WANTRETURN not implemented yet!\n");
1572
1573     return settings;
1574   }
1575   case EM_SETSEL:
1576   {
1577     ME_InvalidateSelection(editor);
1578     ME_SetSelection(editor, wParam, lParam);
1579     ME_InvalidateSelection(editor);
1580     ME_SendSelChange(editor);
1581     return 0;
1582   }
1583   case EM_SETSCROLLPOS:
1584   {
1585     POINT *point = (POINT *)lParam;
1586     /* Native behavior when point->y is too large is very odd / dosn't follow MSDN.
1587        This seems to be a pretty close approximation of what it does. */
1588     ME_Scroll(editor, 0, -(min(point->y, (editor->nTotalLength - 1)) - editor->nScrollPosY));
1589     return 0;
1590   }
1591   case EM_AUTOURLDETECT:
1592   {
1593     if (wParam==1 || wParam ==0) 
1594     {
1595         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1596         return 0;
1597     }
1598     return E_INVALIDARG;
1599   }
1600   case EM_GETAUTOURLDETECT:
1601   {
1602         return editor->AutoURLDetect_bEnable;
1603   }
1604   case EM_EXSETSEL:
1605   {
1606     int start, end;
1607     CHARRANGE range = *(CHARRANGE *)lParam;
1608
1609     TRACE("EM_EXSETSEL (%ld,%ld)\n", range.cpMin, range.cpMax);
1610
1611     /* if cpMin < 0, then selection is deselected and caret moved to end of
1612      * the current selection  */
1613     if (range.cpMin < 0)
1614     {
1615         ME_GetSelection(editor, &start, &end);
1616         range.cpMin = end;
1617         range.cpMax = end;
1618     }  
1619     else if (range.cpMax > ME_GetTextLength(editor) +1)
1620     {
1621       range.cpMax = ME_GetTextLength(editor) + 1;
1622     }
1623
1624     ME_InvalidateSelection(editor);
1625     ME_SetSelection(editor, range.cpMin, range.cpMax);
1626     ME_InvalidateSelection(editor);
1627     ME_SendSelChange(editor);
1628     
1629     return range.cpMax;
1630   }
1631   case EM_SHOWSCROLLBAR:
1632   {
1633     if (wParam == SB_VERT)
1634       editor->bScrollY = lParam;
1635     else if (wParam == SB_HORZ)
1636       editor->bScrollX = lParam;
1637     ME_UpdateScrollBar(editor);
1638     return 0;
1639   }
1640   case EM_SETTEXTEX:
1641   {
1642     LPWSTR wszText = (LPWSTR)lParam;
1643     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1644     size_t len = wszText ? lstrlenW(wszText) : 0;
1645     int from, to;
1646     ME_Style *style;
1647     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1648     if (pStruct->codepage != 1200) {
1649       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1650       return 0;
1651     }
1652     /* FIXME: this should support RTF strings too, according to MSDN */
1653     if (pStruct->flags & ST_SELECTION) {
1654       ME_GetSelection(editor, &from, &to);
1655       style = ME_GetSelectionInsertStyle(editor);
1656       ME_InternalDeleteText(editor, from, to - from);
1657       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1658       ME_ReleaseStyle(style);
1659     }
1660     else {
1661       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1662       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1663       len = 1;
1664     }
1665     ME_CommitUndo(editor);
1666     if (!(pStruct->flags & ST_KEEPUNDO))
1667       ME_EmptyUndoStack(editor);
1668     ME_UpdateRepaint(editor);
1669     return len;
1670   }
1671   case EM_SETBKGNDCOLOR:
1672   {
1673     LRESULT lColor = ME_GetBackColor(editor);
1674     if (editor->rgbBackColor != -1)
1675       DeleteObject(editor->hbrBackground);
1676     if (wParam)
1677     {
1678       editor->rgbBackColor = -1;
1679       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1680     }
1681     else
1682     {
1683       editor->rgbBackColor = lParam;
1684       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1685     }
1686     if (editor->bRedraw)
1687     {
1688       InvalidateRect(hWnd, NULL, TRUE);
1689       UpdateWindow(hWnd);
1690     }
1691     return lColor;
1692   }
1693   case EM_GETMODIFY:
1694     return editor->nModifyStep == 0 ? 0 : 1;
1695   case EM_SETMODIFY:
1696   {
1697     if (wParam)
1698       editor->nModifyStep = 0x80000000;
1699     else
1700       editor->nModifyStep = 0;
1701     
1702     return 0;
1703   }
1704   case EM_SETREADONLY:
1705   {
1706     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1707     if (wParam)
1708       nStyle |= ES_READONLY;
1709     else
1710       nStyle &= ~ES_READONLY;
1711     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1712     return 0;
1713   }
1714   case EM_SETEVENTMASK:
1715   {
1716     DWORD nOldMask = editor->nEventMask;
1717     
1718     editor->nEventMask = lParam;
1719     return nOldMask;
1720   }
1721   case EM_GETEVENTMASK:
1722     return editor->nEventMask;
1723   case EM_SETCHARFORMAT:
1724   {
1725     CHARFORMAT2W buf, *p;
1726     BOOL bRepaint = TRUE;
1727     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1728     if (!wParam || (editor->mode & TM_PLAINTEXT))
1729       ME_SetDefaultCharFormat(editor, p);
1730     else if (wParam == (SCF_WORD | SCF_SELECTION))
1731       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1732     else if (wParam == SCF_ALL)
1733       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1734     else {
1735       int from, to;
1736       ME_GetSelection(editor, &from, &to);
1737       bRepaint = (from != to);
1738       ME_SetSelectionCharFormat(editor, p);
1739     }
1740     ME_CommitUndo(editor);
1741     if (bRepaint)
1742       ME_UpdateRepaint(editor);
1743     return 0;
1744   }
1745   case EM_GETCHARFORMAT:
1746   {
1747     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1748     if (dst->cbSize != sizeof(CHARFORMATA) &&
1749         dst->cbSize != sizeof(CHARFORMATW) &&
1750         dst->cbSize != sizeof(CHARFORMAT2A) &&
1751         dst->cbSize != sizeof(CHARFORMAT2W))
1752       return 0;
1753     tmp.cbSize = sizeof(tmp);
1754     if (!wParam)
1755       ME_GetDefaultCharFormat(editor, &tmp);
1756     else
1757       ME_GetSelectionCharFormat(editor, &tmp);
1758     ME_CopyToCFAny(dst, &tmp);
1759     return tmp.dwMask;
1760   }
1761   case EM_SETPARAFORMAT:
1762     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1763     ME_UpdateRepaint(editor);
1764     ME_CommitUndo(editor);
1765     return 0;
1766   case EM_GETPARAFORMAT:
1767     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1768     return 0;
1769   case EM_GETFIRSTVISIBLELINE:
1770   {
1771     ME_DisplayItem *p = editor->pBuffer->pFirst;
1772     int y = editor->nScrollPosY;
1773     int ypara = 0;
1774     int count = 0;
1775     int ystart, yend;
1776     while(p) {
1777       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1778       if (p->type == diTextEnd)
1779         break;
1780       if (p->type == diParagraph) {
1781         ypara = p->member.para.nYPos;
1782         continue;
1783       }
1784       ystart = ypara + p->member.row.nYPos;
1785       yend = ystart + p->member.row.nHeight;
1786       if (y < yend) {
1787         break;
1788       }
1789       count++;
1790     }
1791     return count;
1792   }
1793   case EM_HIDESELECTION:
1794   {
1795      editor->bHideSelection = (wParam != 0);
1796      ME_InvalidateSelection(editor);
1797      return 0;
1798   }
1799   case EM_LINESCROLL:
1800   {
1801     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1802     nPos += 8 * lParam; /* FIXME follow the original */
1803     if (nPos>=nEnd)
1804       nPos = nEnd;
1805     if (nPos<0)
1806       nPos = 0;
1807     if (nPos != editor->nScrollPosY) {
1808       int dy = editor->nScrollPosY - nPos;
1809       editor->nScrollPosY = nPos;
1810       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1811       if (editor->bRedraw)
1812       {
1813         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1814         UpdateWindow(hWnd);
1815       }
1816     }
1817     return TRUE; /* Should return false if a single line richedit control */
1818   }
1819   case WM_CLEAR:
1820   {
1821     int from, to;
1822     ME_GetSelection(editor, &from, &to);
1823     ME_InternalDeleteText(editor, from, to-from);
1824     ME_CommitUndo(editor);
1825     ME_UpdateRepaint(editor);
1826     return 0;
1827   }
1828   case EM_REPLACESEL:
1829   {
1830     int from, to;
1831     ME_Style *style;
1832     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1833     size_t len = lstrlenW(wszText);
1834     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1835     
1836     ME_GetSelection(editor, &from, &to);
1837     style = ME_GetSelectionInsertStyle(editor);
1838     ME_InternalDeleteText(editor, from, to-from);
1839     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1840     ME_ReleaseStyle(style);
1841     ME_EndToUnicode(hWnd, wszText);
1842     /* drop temporary style if line end */
1843     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1844     if (len>0 && wszText[len-1] == '\n')
1845       ME_ClearTempStyle(editor);
1846       
1847     ME_CommitUndo(editor);
1848     if (!wParam)
1849       ME_EmptyUndoStack(editor);
1850     ME_UpdateRepaint(editor);
1851     return 0;
1852   }
1853   case EM_SCROLLCARET:
1854   {
1855     int top, bottom; /* row's edges relative to document top */
1856     ME_DisplayItem *para, *row;
1857
1858     row = ME_RowStart(editor->pCursors[0].pRun);
1859     para = ME_GetParagraph(row);
1860     top = para->member.para.nYPos + row->member.row.nYPos;
1861     bottom = top + row->member.row.nHeight;
1862
1863     if ((top < editor->nScrollPosY)
1864         || (editor->nScrollPosY + editor->sizeWindow.cy < bottom))
1865     {
1866       int dy;
1867       int prevScrollPosY = editor->nScrollPosY;
1868
1869       if (top < editor->nScrollPosY) /* caret above window */
1870         editor->nScrollPosY = top;
1871       else /* caret below window */
1872         editor->nScrollPosY = bottom - editor->sizeWindow.cy;
1873
1874       if (editor->nScrollPosY < 0)
1875         editor->nScrollPosY = 0;
1876
1877       dy = prevScrollPosY - editor->nScrollPosY;
1878       SetScrollPos(hWnd, SB_VERT, editor->nScrollPosY, TRUE);
1879       if (editor->bRedraw)
1880       {
1881         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1882         UpdateWindow(hWnd);
1883       }
1884     }
1885
1886     return 0;
1887   }
1888   case WM_SETFONT:
1889   {
1890     LOGFONTW lf;
1891     CHARFORMAT2W fmt;
1892     HDC hDC;
1893     BOOL bRepaint = LOWORD(lParam);
1894     
1895     if (!wParam)
1896       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1897     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1898     hDC = GetDC(hWnd);
1899     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1900     ReleaseDC(hWnd, hDC);   
1901     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1902     ME_SetDefaultCharFormat(editor, &fmt);
1903
1904     ME_CommitUndo(editor);
1905     if (bRepaint)
1906       ME_UpdateRepaint(editor);
1907     return 0;
1908   }
1909   case WM_SETTEXT:
1910   {
1911     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1912     if (lParam)
1913     {
1914       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1915       if (!IsWindowUnicode(hWnd) && !strncmp((char *)lParam, "{\\rtf", 5))
1916       {
1917         /* Undocumented: WM_SETTEXT supports RTF text */
1918         ME_StreamInRTFString(editor, 0, (char *)lParam);
1919       }
1920       else
1921       {
1922         LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1923         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1924         if (lstrlenW(wszText) > 0)
1925         {
1926           /* uses default style! */
1927           ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1928         }
1929         ME_EndToUnicode(hWnd, wszText);
1930       }
1931     }
1932     else
1933       TRACE("WM_SETTEXT - NULL\n");
1934     ME_CommitUndo(editor);
1935     ME_EmptyUndoStack(editor);
1936     ME_SetSelection(editor, 0, 0);
1937     ME_UpdateRepaint(editor);
1938     return 0;
1939   }
1940   case EM_CANPASTE:
1941   {
1942     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1943     if (IsClipboardFormatAvailable(nRTFFormat))
1944       return TRUE;
1945     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1946       return TRUE;
1947     return FALSE;
1948   }
1949   case WM_PASTE:
1950   {    
1951     DWORD dwFormat = 0;
1952     EDITSTREAM es;
1953     ME_GlobalDestStruct gds;
1954     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1955     UINT cf = 0;
1956
1957     if (IsClipboardFormatAvailable(nRTFFormat))
1958       cf = nRTFFormat, dwFormat = SF_RTF;
1959     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1960       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1961     else
1962       return 0;
1963
1964     if (!OpenClipboard(hWnd))
1965       return 0;
1966     gds.hData = GetClipboardData(cf);
1967     gds.nLength = 0;
1968     es.dwCookie = (DWORD)&gds;
1969     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1970     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
1971
1972     CloseClipboard();
1973     return 0;
1974   }
1975   case WM_CUT:
1976   case WM_COPY:
1977   {
1978     LPDATAOBJECT dataObj = NULL;
1979     CHARRANGE range;
1980     HRESULT hr = S_OK;
1981     
1982     if (editor->cPasswordMask)
1983       return 0; /* Copying or Cutting masked text isn't allowed */
1984     
1985     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
1986     if(editor->lpOleCallback)
1987         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
1988     if(FAILED(hr) || !dataObj)
1989         hr = ME_GetDataObject(editor, &range, &dataObj);
1990     if(SUCCEEDED(hr)) {
1991         hr = OleSetClipboard(dataObj);
1992         IDataObject_Release(dataObj);
1993     }
1994     if (SUCCEEDED(hr) && msg == WM_CUT)
1995     {
1996       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
1997       ME_CommitUndo(editor);
1998       ME_UpdateRepaint(editor);
1999     }
2000     return 0;
2001   }
2002   case WM_GETTEXTLENGTH:
2003     return ME_GetTextLength(editor);
2004   case EM_GETTEXTLENGTHEX:
2005     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2006   case WM_GETTEXT:
2007   {
2008     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2009     tr.chrg.cpMin = 0;
2010     tr.chrg.cpMax = wParam-1;
2011     tr.lpstrText = (WCHAR *)lParam;
2012     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2013   }
2014   case EM_GETTEXTEX:
2015   {
2016     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2017     int nStart, nCount;
2018
2019     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2020       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2021
2022     if (ex->flags & GT_SELECTION)
2023     {
2024       ME_GetSelection(editor, &nStart, &nCount);
2025       nCount -= nStart;
2026       nCount = min(nCount, ex->cb - 1);
2027     }
2028     else
2029     {
2030       nStart = 0;
2031       nCount = ex->cb - 1;
2032     }
2033     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
2034     {
2035       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2036       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2037     }
2038     else
2039     {
2040       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2041         we can just take a bigger buffer? :) */
2042       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2043       LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (crlfmul*nCount + 1) * sizeof(WCHAR));
2044       DWORD buflen = ex->cb;
2045       LRESULT rc;
2046       DWORD flags = 0;
2047
2048       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2049       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2050
2051       HeapFree(GetProcessHeap(),0,buffer);
2052       return rc;
2053     }
2054   }
2055   case EM_GETSELTEXT:
2056   {
2057     int from, to;
2058     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2059     ME_GetSelection(editor, &from, &to);
2060     tr.chrg.cpMin = from;
2061     tr.chrg.cpMax = to;
2062     tr.lpstrText = (WCHAR *)lParam;
2063     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2064   }
2065   case EM_GETSCROLLPOS:
2066   {
2067       POINT *point = (POINT *)lParam;
2068       point->x = 0; /* FIXME side scrolling not implemented */
2069       point->y = editor->nScrollPosY;
2070       return 1;
2071   }
2072   case EM_GETTEXTRANGE:
2073   {
2074     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2075     TRACE("EM_GETTEXTRANGE min=%ld max=%ld unicode=%d emul1.0=%d length=%d\n",
2076       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
2077       editor->bEmulateVersion10, ME_GetTextLength(editor));
2078     if (IsWindowUnicode(hWnd))
2079       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2080     else
2081     {
2082       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2083       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2084       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2085       /* FIXME this is a potential security hole (buffer overrun) 
2086          if you know more about wchar->mbyte conversion please explain
2087       */
2088       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2089       FREE_OBJ(p);
2090       return nChars;
2091     }
2092   }
2093   case EM_GETLINE:
2094   {
2095     ME_DisplayItem *run;
2096     const BOOL bUnicode = IsWindowUnicode(hWnd);
2097     const unsigned int nMaxChars = *(WORD *) lParam;
2098     unsigned int nEndChars, nCharsLeft = nMaxChars;
2099     char *dest = (char *) lParam;
2100     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2101     we need to know how if we have the extra \n or not */
2102     int nLF = editor->bEmulateVersion10;
2103
2104     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2105           bUnicode ? "Unicode" : "Ansi");
2106
2107     run = ME_FindRowWithNumber(editor, wParam);
2108     if (run == NULL)
2109       return 0;
2110
2111     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2112            && !(run->member.run.nFlags & MERF_ENDPARA))
2113     {
2114       unsigned int nCopy;
2115       ME_String *strText;
2116       if (run->type != diRun)
2117         break;
2118       strText = run->member.run.strText;
2119       nCopy = min(nCharsLeft, strText->nLen);
2120
2121       if (bUnicode)
2122         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2123       else
2124         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2125                                     nCharsLeft, NULL, NULL);
2126       dest += nCopy * (bUnicode ? sizeof(WCHAR) : 1);
2127       nCharsLeft -= nCopy;
2128     }
2129
2130     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2131     nEndChars = min(nCharsLeft, 2 + nLF);
2132     nCharsLeft -= nEndChars;
2133     if (bUnicode)
2134     {
2135       const WCHAR src[] = {'\r', '\0'};
2136       const WCHAR src10[] = {'\r', '\n', '\0'};
2137       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2138     }
2139     else
2140       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2141
2142     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2143
2144     if (nEndChars == 2 + nLF)
2145       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2146     else
2147       return nMaxChars - nCharsLeft;
2148   }
2149   case EM_GETLINECOUNT:
2150   {
2151     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2152     int nRows = 0;
2153
2154     while (item != editor->pBuffer->pLast)
2155     {
2156       assert(item->type == diParagraph);
2157       nRows += item->member.para.nRows;
2158       item = item->member.para.next_para;
2159     }
2160     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2161     return max(1, nRows);
2162   }
2163   case EM_LINEFROMCHAR:
2164   {
2165     if (wParam == -1)
2166       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2167     else
2168       return ME_RowNumberFromCharOfs(editor, wParam);
2169   }
2170   case EM_EXLINEFROMCHAR:
2171   {
2172     if (lParam == -1)
2173       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2174     else    
2175       return ME_RowNumberFromCharOfs(editor, lParam);
2176   }
2177   case EM_LINEINDEX:
2178   {
2179     ME_DisplayItem *item, *para;
2180     int nCharOfs;
2181     
2182     if (wParam == -1)
2183       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2184     else
2185       item = ME_FindRowWithNumber(editor, wParam);
2186     if (!item)
2187       return -1;
2188     para = ME_GetParagraph(item);
2189     item = ME_FindItemFwd(item, diRun);
2190     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2191     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2192     return nCharOfs;
2193   }
2194   case EM_LINELENGTH:
2195   {
2196     ME_DisplayItem *item, *item_end;
2197     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2198     
2199     if (wParam > ME_GetTextLength(editor))
2200       return 0;
2201     if (wParam == -1)
2202     {
2203       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2204       return 0;
2205     }
2206     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2207     item = ME_RowStart(item);
2208     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2209     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2210     if (item_end->type == diStartRow)
2211       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2212     else
2213       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2214        - (editor->bEmulateVersion10?2:1);
2215     nChars = nNextLineOfs - nThisLineOfs;
2216     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
2217     return nChars;
2218   }
2219   case EM_EXLIMITTEXT:
2220   {
2221     if (wParam != 0 || lParam < 0)
2222      return 0;
2223     if (lParam == 0)
2224       editor->nTextLimit = 65536;
2225     else
2226       editor->nTextLimit = (int) lParam;
2227     return 0;
2228   }
2229   case EM_GETLIMITTEXT:
2230   {
2231     return editor->nTextLimit;
2232   }
2233   case EM_FINDTEXT:
2234   {
2235     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2236     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2237     WCHAR *tmp;
2238     
2239     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2240       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2241     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2242   }
2243   case EM_FINDTEXTEX:
2244   {
2245     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2246     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2247     WCHAR *tmp;
2248     
2249     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2250       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2251     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2252   }
2253   case EM_FINDTEXTW:
2254   {
2255     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2256     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2257   }
2258   case EM_FINDTEXTEXW:
2259   {
2260     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2261     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2262   }
2263   case EM_GETZOOM:
2264     if (!wParam || !lParam)
2265       return FALSE;
2266     *(int *)wParam = editor->nZoomNumerator;
2267     *(int *)lParam = editor->nZoomDenominator;
2268     return TRUE;
2269   case EM_SETZOOM:
2270     return ME_SetZoom(editor, wParam, lParam);
2271   case EM_CHARFROMPOS:
2272     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2273   case EM_POSFROMCHAR:
2274   {
2275     ME_DisplayItem *pRun;
2276     int nCharOfs, nOffset, nLength;
2277     POINTL pt = {0,0};
2278     
2279     nCharOfs = wParam; 
2280     /* detect which API version we're dealing with */
2281     if (wParam >= 0x40000)
2282         nCharOfs = lParam;
2283     nLength = ME_GetTextLength(editor);
2284     
2285     if (nCharOfs < nLength) { 
2286         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2287         assert(pRun->type == diRun);
2288         pt.y = pRun->member.run.pt.y;
2289         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2290         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2291     } else {
2292         pt.x = 0;
2293         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2294     }
2295     if (wParam >= 0x40000) {
2296         *(POINTL *)wParam = pt;
2297     }
2298     return MAKELONG( pt.x, pt.y );
2299   }
2300   case WM_CREATE:
2301     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2302     { /* Squelch the default horizontal scrollbar it would make */
2303       si.cbSize = sizeof(SCROLLINFO);
2304       si.fMask = SIF_POS | SIF_RANGE;
2305       si.nMax = 0;
2306       si.nMin = 0;
2307       si.nPos = 0;
2308       SetScrollInfo(hWnd, SB_HORZ, &si, FALSE);
2309     }     
2310     ME_CommitUndo(editor);
2311     ME_WrapMarkedParagraphs(editor);
2312     ME_MoveCaret(editor);
2313     return 0;
2314   case WM_DESTROY:
2315     ME_DestroyEditor(editor);
2316     SetWindowLongPtrW(hWnd, 0, 0);
2317     return 0;
2318   case WM_LBUTTONDOWN:
2319     SetFocus(hWnd);
2320     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2321     SetCapture(hWnd);
2322     ME_LinkNotify(editor,msg,wParam,lParam);
2323     break;
2324   case WM_MOUSEMOVE:
2325     if (GetCapture() == hWnd)
2326       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2327     ME_LinkNotify(editor,msg,wParam,lParam);
2328     break;
2329   case WM_LBUTTONUP:
2330     if (GetCapture() == hWnd)
2331       ReleaseCapture();
2332     ME_LinkNotify(editor,msg,wParam,lParam);
2333     break;
2334   case WM_LBUTTONDBLCLK:
2335     ME_LinkNotify(editor,msg,wParam,lParam);
2336     ME_SelectWord(editor);
2337     break;
2338   case WM_CONTEXTMENU:
2339     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2340       goto do_default;
2341     break;
2342   case WM_PAINT:
2343     if (editor->bRedraw)
2344     {
2345       HDC hDC;
2346       PAINTSTRUCT ps;
2347
2348       hDC = BeginPaint(hWnd, &ps);
2349       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2350       EndPaint(hWnd, &ps);
2351     }
2352     break;
2353   case WM_SETFOCUS:
2354     ME_ShowCaret(editor);
2355     ME_SendOldNotify(editor, EN_SETFOCUS);
2356     return 0;
2357   case WM_KILLFOCUS:
2358     ME_HideCaret(editor);
2359     ME_SendOldNotify(editor, EN_KILLFOCUS);
2360     return 0;
2361   case WM_ERASEBKGND:
2362   {
2363     if (editor->bRedraw)
2364     {
2365       HDC hDC = (HDC)wParam;
2366       RECT rc;
2367       if (GetUpdateRect(hWnd,&rc,TRUE))
2368       {
2369         FillRect(hDC, &rc, editor->hbrBackground);
2370       }
2371     }
2372     return 1;
2373   }
2374   case WM_COMMAND:
2375     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2376     return 0;
2377   case WM_KEYDOWN:
2378     if (ME_KeyDown(editor, LOWORD(wParam)))
2379       return 0;
2380     goto do_default;
2381   case WM_CHAR: 
2382   {
2383     WCHAR wstr = LOWORD(wParam);
2384     if (editor->AutoURLDetect_bEnable)
2385       ME_AutoURLDetect(editor, wstr);
2386         
2387     switch (wstr)
2388     {
2389     case 1: /* Ctrl-A */
2390       ME_SetSelection(editor, 0, -1);
2391       return 0;
2392     case 3: /* Ctrl-C */
2393       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2394       return 0;
2395     }
2396     
2397     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2398       MessageBeep(MB_ICONERROR);
2399       return 0; /* FIXME really 0 ? */
2400     }
2401
2402     switch (wstr)
2403     {
2404     case 22: /* Ctrl-V */
2405       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2406       return 0;
2407     case 24: /* Ctrl-X */
2408       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2409       return 0;
2410     case 25: /* Ctrl-Y */
2411       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2412       return 0;
2413     case 26: /* Ctrl-Z */
2414       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2415       return 0;
2416     }
2417     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
2418       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2419       ME_Style *style = ME_GetInsertStyle(editor, 0);
2420       ME_SaveTempStyle(editor);
2421       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2422       ME_ReleaseStyle(style);
2423       ME_CommitUndo(editor);
2424       ME_UpdateRepaint(editor);
2425     }
2426     return 0;
2427   }
2428   case EM_SCROLL: /* fall through */
2429   case WM_VSCROLL: 
2430   {
2431     int nEnd;
2432     int nPos = editor->nScrollPosY;
2433     int origNPos = nPos;
2434     int lineHeight = 24;
2435     si.cbSize = sizeof(SCROLLINFO);
2436     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
2437     GetScrollInfo(hWnd, SB_VERT, &si);
2438     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2439         lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2440     if (lineHeight <= 0) lineHeight = 24;
2441     switch(LOWORD(wParam)) {
2442     case SB_LINEUP:
2443       nPos -= lineHeight;
2444       if (nPos<0) nPos = 0;
2445       break;
2446     case SB_LINEDOWN:
2447     {
2448       nEnd = editor->nTotalLength - editor->sizeWindow.cy;
2449       if (nEnd < 0) nEnd = 0;
2450       nPos += lineHeight;
2451       if (nPos>=nEnd) nPos = nEnd;
2452       break;
2453     }
2454     case SB_PAGEUP:
2455       nPos -= editor->sizeWindow.cy;
2456       if (nPos<0) nPos = 0;
2457       break;
2458     case SB_PAGEDOWN:
2459       nEnd = editor->nTotalLength - editor->sizeWindow.cy;
2460       if (nEnd < 0) nEnd = 0;
2461       nPos += editor->sizeWindow.cy;
2462       if (nPos>=nEnd) nPos = nEnd;
2463       break;
2464     case SB_THUMBTRACK:
2465     case SB_THUMBPOSITION:
2466       nPos = si.nTrackPos;
2467       break;
2468     }
2469     if (nPos != editor->nScrollPosY) {
2470       int dy = editor->nScrollPosY - nPos;
2471       editor->nScrollPosY = nPos;
2472       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
2473       if (editor->bRedraw)
2474       {
2475         ScrollWindow(hWnd, 0, dy, NULL, NULL);
2476         UpdateWindow(hWnd);
2477       }
2478     }
2479     if (msg == EM_SCROLL)
2480       return 0x00010000 | (((nPos - origNPos)/lineHeight) & 0xffff);
2481     break;
2482   }
2483   case WM_MOUSEWHEEL:
2484   {
2485     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
2486     UINT pulScrollLines;
2487     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2488     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
2489     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2490       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
2491     if (nPos>=nEnd)
2492       nPos = nEnd;
2493     if (nPos<0)
2494       nPos = 0;
2495     if (nPos != editor->nScrollPosY) {
2496       int dy = editor->nScrollPosY - nPos;
2497       editor->nScrollPosY = nPos;
2498       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
2499       if (editor->bRedraw)
2500       {
2501         ScrollWindow(hWnd, 0, dy, NULL, NULL);
2502         UpdateWindow(hWnd);
2503       }
2504     }
2505     break;
2506   }
2507   case EM_GETRECT:
2508   {
2509     *((RECT *)lParam) = editor->rcFormat;
2510     return 0;
2511   }
2512   case EM_SETRECT:
2513   case EM_SETRECTNP:
2514   {
2515     if (lParam)
2516     {
2517       RECT *rc = (RECT *)lParam;
2518       
2519       if (wParam)
2520       {
2521         editor->rcFormat.left += rc->left;
2522         editor->rcFormat.top += rc->top;
2523         editor->rcFormat.right += rc->right;
2524         editor->rcFormat.bottom += rc->bottom;
2525       }
2526       else
2527       {
2528         editor->rcFormat = *rc;
2529       }
2530     }
2531     else
2532     {
2533       GetClientRect(hWnd, &editor->rcFormat);
2534     }
2535     if (msg != EM_SETRECTNP)
2536       ME_RewrapRepaint(editor);
2537     return 0;
2538   }
2539   case EM_REQUESTRESIZE:
2540     ME_SendRequestResize(editor, TRUE);
2541     return 0;
2542   case WM_SETREDRAW:
2543     editor->bRedraw = wParam;
2544     return 0;
2545   case WM_SIZE:
2546   {
2547     GetClientRect(hWnd, &editor->rcFormat);
2548     ME_RewrapRepaint(editor);
2549     return DefWindowProcW(hWnd, msg, wParam, lParam);
2550   }
2551   case EM_GETOLEINTERFACE:
2552   {
2553     LPVOID *ppvObj = (LPVOID*) lParam;
2554     return CreateIRichEditOle(editor, ppvObj);
2555   }
2556   case EM_GETPASSWORDCHAR:
2557   {
2558     return editor->cPasswordMask;
2559   }
2560   case EM_SETOLECALLBACK:
2561     if(editor->lpOleCallback)
2562       IUnknown_Release(editor->lpOleCallback);
2563     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2564     if(editor->lpOleCallback)
2565       IUnknown_AddRef(editor->lpOleCallback);
2566     return TRUE;
2567   case EM_GETWORDBREAKPROC:
2568     return (LRESULT)editor->pfnWordBreak;
2569   case EM_SETWORDBREAKPROC:
2570   {
2571     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2572
2573     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2574     return (LRESULT)pfnOld;
2575   }
2576   case EM_SETTEXTMODE:
2577   {
2578     LRESULT ret;
2579     int mask = 0;
2580     int changes = 0;
2581     if ((ret = RichEditANSIWndProc(hWnd, WM_GETTEXTLENGTH, 0, 0)) == 0)
2582     {
2583       /*Check for valid wParam*/
2584       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2585           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2586           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2587         return 1;
2588       else
2589       {
2590         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2591         {
2592           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2593           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2594         }
2595         /*FIXME: Currently no support for undo level and code page options*/ 
2596         editor->mode = (editor->mode & (~mask)) | changes;
2597         return 0;
2598       }
2599     }
2600     return ret;
2601   }
2602   case EM_SETPASSWORDCHAR:
2603   {
2604     editor->cPasswordMask = wParam;
2605     ME_RewrapRepaint(editor);
2606     return 0;
2607   }
2608   default:
2609   do_default:
2610     return DefWindowProcW(hWnd, msg, wParam, lParam);
2611   }
2612   return 0L;
2613 }
2614
2615
2616 /******************************************************************
2617  *        RichEdit10ANSIWndProc (RICHED20.9)
2618  */
2619 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2620 {
2621   LRESULT result;
2622   
2623   /* FIXME: this is NOT the same as 2.0 version */
2624   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2625   if (msg == WM_NCCREATE)
2626   {
2627     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2628     
2629     editor->bEmulateVersion10 = TRUE;
2630     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2631   }
2632   return result;
2633 }
2634
2635 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2636 {
2637   HWND hWnd = editor->hWnd;
2638   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2639 }
2640
2641 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2642 {
2643   int x,y;
2644   ME_Cursor tmpCursor;
2645   ME_Run *tmpRun;
2646   BOOL bNothing;
2647   ENLINK info;
2648   x = (short)LOWORD(lParam);
2649   y = (short)HIWORD(lParam);
2650   ME_FindPixelPos(editor, x, y, &tmpCursor, &bNothing);
2651   tmpRun = &tmpCursor.pRun->member.run;
2652         
2653   if ((tmpRun->style->fmt.dwMask & CFM_LINK) 
2654     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2655   { /* The clicked run has CFE_LINK set */
2656     info.nmhdr.hwndFrom = editor->hWnd;
2657     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2658     info.nmhdr.code = EN_LINK;
2659     info.msg = msg;
2660     info.wParam = wParam;
2661     info.lParam = lParam;
2662     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2663     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2664     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2665   }  
2666 }
2667
2668 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2669 {
2670   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2671   int i = 0;
2672   
2673   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2674     item = item->member.para.next_para;
2675   if (!item)
2676     return 0;
2677   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2678     item = item->member.para.next_para;
2679     i++;
2680   }
2681   return i;
2682 }
2683
2684
2685 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2686 {
2687   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2688   int nWritten = 0;
2689   WCHAR *pStart = buffer;
2690   
2691   if (!item) {
2692     *buffer = L'\0';
2693     return 0;
2694   }
2695   
2696   if (nStart)
2697   {
2698     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2699     if (nLen > nChars)
2700       nLen = nChars;
2701     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2702     nChars -= nLen;
2703     nWritten += nLen;
2704     if (!nChars)
2705       return nWritten;
2706     buffer += nLen;
2707     nStart = 0;
2708     item = ME_FindItemFwd(item, diRun);
2709   }
2710   
2711   while(nChars && item)
2712   {
2713     int nLen = ME_StrLen(item->member.run.strText);
2714     if (nLen > nChars)
2715       nLen = nChars;
2716
2717     if (item->member.run.nFlags & MERF_ENDPARA)
2718     {
2719       if (!ME_FindItemFwd(item, diRun))
2720         /* No '\r' is appended to the last paragraph. */
2721         nLen = 0;
2722       else {
2723         *buffer = '\r';
2724         if (bCRLF)
2725         {
2726           *(++buffer) = '\n';
2727           nWritten++;
2728         }
2729         assert(nLen == 1);
2730         /* our end paragraph consists of 2 characters now */
2731         if (editor->bEmulateVersion10)
2732           nChars--;
2733       }
2734     }
2735     else
2736       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2737     nChars -= nLen;
2738     nWritten += nLen;
2739     buffer += nLen;    
2740       
2741     if (!nChars)
2742     {
2743       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2744       *buffer = L'\0';
2745       return nWritten;
2746     }
2747     item = ME_FindItemFwd(item, diRun);
2748   }
2749   *buffer = L'\0';
2750   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2751   return nWritten;  
2752 }
2753
2754 void ME_RegisterEditorClass(HINSTANCE hInstance)
2755 {
2756   BOOL bResult;
2757   WNDCLASSW wcW;
2758   WNDCLASSA wcA;
2759   
2760   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2761   wcW.lpfnWndProc = RichEditANSIWndProc;
2762   wcW.cbClsExtra = 0;
2763   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2764   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2765   wcW.hIcon = NULL;
2766   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2767   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2768   wcW.lpszMenuName = NULL;
2769   wcW.lpszClassName = wszClassName;
2770   bResult = RegisterClassW(&wcW);  
2771   assert(bResult);
2772   wcW.lpszClassName = wszClassName50;
2773   bResult = RegisterClassW(&wcW);  
2774   assert(bResult);
2775
2776   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2777   wcA.lpfnWndProc = RichEditANSIWndProc;
2778   wcA.cbClsExtra = 0;
2779   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2780   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2781   wcA.hIcon = NULL;
2782   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2783   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2784   wcA.lpszMenuName = NULL;
2785   wcA.lpszClassName = "RichEdit20A";
2786   bResult = RegisterClassA(&wcA);  
2787   assert(bResult);
2788   wcA.lpszClassName = "RichEdit50A";
2789   bResult = RegisterClassA(&wcA);  
2790   assert(bResult);
2791 }
2792
2793 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2794   /* FIXME: Not implemented */
2795   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2796         hWnd, msg, get_msg_name(msg), wParam, lParam);
2797   return DefWindowProcW(hWnd, msg, wParam, lParam);
2798 }
2799
2800 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2801   /* FIXME: Not implemented */
2802   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2803         hWnd, msg, get_msg_name(msg), wParam, lParam);
2804   return DefWindowProcW(hWnd, msg, wParam, lParam);
2805 }
2806
2807 /******************************************************************
2808  *        REExtendedRegisterClass (RICHED20.8)
2809  *
2810  * FIXME undocumented
2811  * Need to check for errors and implement controls and callbacks 
2812  */
2813 LRESULT WINAPI REExtendedRegisterClass(void)
2814 {
2815   WNDCLASSW wcW;
2816   UINT result;
2817
2818   FIXME("semi stub\n");
2819
2820   wcW.cbClsExtra = 0;
2821   wcW.cbWndExtra = 4;
2822   wcW.hInstance = NULL;
2823   wcW.hIcon = NULL;
2824   wcW.hCursor = NULL;
2825   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2826   wcW.lpszMenuName = NULL;
2827
2828   if (!ME_ListBoxRegistered)
2829   {
2830       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2831       wcW.lpfnWndProc = REListWndProc;
2832       wcW.lpszClassName = wszClassNameListBox;
2833       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2834   }
2835
2836   if (!ME_ComboBoxRegistered)
2837   {
2838       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2839       wcW.lpfnWndProc = REComboWndProc;
2840       wcW.lpszClassName = wszClassNameComboBox;
2841       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2842   }
2843
2844   result = 0;
2845   if (ME_ListBoxRegistered)
2846       result += 1;
2847   if (ME_ComboBoxRegistered)
2848       result += 2;
2849
2850   return result;
2851 }
2852
2853 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
2854 {
2855   struct prefix_s {
2856     const char *text;
2857     int length;
2858   } prefixes[12] = {
2859     {"http:", 5},
2860     {"file:", 6},
2861     {"mailto:", 8},
2862     {"ftp:", 5},
2863     {"https:", 7},
2864     {"gopher:", 8},
2865     {"nntp:", 6},
2866     {"prospero:", 10},
2867     {"telnet:", 8},
2868     {"news:", 6},
2869     {"wais:", 6},
2870     {"www.", 5}
2871   };
2872   CHARRANGE ins_pt;
2873   int curf_ef, link_ef, def_ef;
2874   int cur_prefx, prefx_cnt;
2875   int sel_min, sel_max;
2876   int car_pos = 0;
2877   int text_pos=-1;
2878   int URLmin, URLmax = 0;
2879   CHARRANGE url;
2880   FINDTEXTA ft;
2881   CHARFORMAT2W cur_format;
2882   CHARFORMAT2W default_format;
2883   CHARFORMAT2W link;
2884   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
2885   sel_min = ins_pt.cpMin;
2886   sel_max = ins_pt.cpMax;
2887   if (sel_min==sel_max) 
2888     car_pos = sel_min;
2889   if (sel_min!=sel_max)
2890     car_pos = ME_GetTextLength(editor)+1;   
2891   cur_format.cbSize = sizeof(cur_format);
2892   default_format.cbSize = sizeof(default_format);
2893   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
2894   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
2895   link.cbSize = sizeof(link);
2896   link.dwMask = CFM_LINK;
2897   link.dwEffects = CFE_LINK;
2898   curf_ef = cur_format.dwEffects & link.dwEffects;
2899   def_ef = default_format.dwEffects & link.dwEffects;
2900   link_ef = link.dwEffects & link.dwEffects;
2901   if (curf_ef == link_ef) 
2902   {
2903     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
2904     {
2905       ME_SetSelection(editor, car_pos, car_pos);
2906       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
2907       text_pos=-1;
2908       return 0;
2909     }
2910   }
2911   if (curf_ef == def_ef)
2912   {
2913     cur_prefx = 0;
2914     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
2915     while (cur_prefx<=prefx_cnt) 
2916     {
2917       if (text_pos == -1) 
2918       {
2919         ft.lpstrText = prefixes[cur_prefx].text;
2920         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
2921         URLmax=max(0, car_pos);
2922         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
2923         {
2924         URLmax = ME_GetTextLength(editor)+1;
2925         }
2926         ft.chrg.cpMin = URLmin;
2927         ft.chrg.cpMax = URLmax;
2928         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
2929         cur_prefx++;
2930       }
2931       if (text_pos != -1) 
2932       {
2933         url.cpMin=text_pos;
2934         url.cpMax=car_pos-1;
2935         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
2936         ME_Repaint(editor);
2937         break;
2938       }
2939     }
2940   }
2941   return 0;
2942 }