~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/riched20/editor.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  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  * Copyright 2008 Eric Pouech
  8  *
  9  * This library is free software; you can redistribute it and/or
 10  * modify it under the terms of the GNU Lesser General Public
 11  * License as published by the Free Software Foundation; either
 12  * version 2.1 of the License, or (at your option) any later version.
 13  *
 14  * This library is distributed in the hope that it will be useful,
 15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 17  * Lesser General Public License for more details.
 18  *
 19  * You should have received a copy of the GNU Lesser General Public
 20  * License along with this library; if not, write to the Free Software
 21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 22  */
 23 
 24 /* 
 25   API implementation status:
 26   
 27   Messages (ANSI versions not done yet)
 28   + EM_AUTOURLDETECT 2.0
 29   + EM_CANPASTE
 30   + EM_CANREDO 2.0
 31   + EM_CANUNDO
 32   + EM_CHARFROMPOS
 33   - EM_DISPLAYBAND
 34   + EM_EMPTYUNDOBUFFER
 35   + EM_EXGETSEL
 36   + EM_EXLIMITTEXT
 37   + EM_EXLINEFROMCHAR
 38   + EM_EXSETSEL
 39   + EM_FINDTEXT (only FR_DOWN flag implemented)
 40   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
 41   - EM_FINDWORDBREAK
 42   - EM_FMTLINES
 43   - EM_FORMATRANGE
 44   + EM_GETAUTOURLDETECT 2.0
 45   - EM_GETBIDIOPTIONS 3.0
 46   - EM_GETCHARFORMAT (partly done)
 47   - EM_GETEDITSTYLE
 48   + EM_GETEVENTMASK
 49   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
 50   - EM_GETIMECOLOR 1.0asian
 51   - EM_GETIMECOMPMODE 2.0
 52   - EM_GETIMEOPTIONS 1.0asian
 53   - EM_GETIMESTATUS
 54   - EM_GETLANGOPTIONS 2.0
 55   + EM_GETLIMITTEXT
 56   + EM_GETLINE
 57   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
 58   + EM_GETMODIFY
 59   - EM_GETOLEINTERFACE
 60   + EM_GETOPTIONS
 61   + EM_GETPARAFORMAT
 62   + EM_GETPASSWORDCHAR 2.0
 63   - EM_GETPUNCTUATION 1.0asian
 64   + EM_GETRECT
 65   - EM_GETREDONAME 2.0
 66   + EM_GETSEL
 67   + EM_GETSELTEXT (ANSI&Unicode)
 68   + EM_GETSCROLLPOS 3.0 (only Y value valid)
 69 ! - EM_GETTHUMB
 70   + EM_GETTEXTEX 2.0
 71   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
 72   - EM_GETTEXTMODE 2.0
 73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
 74   - EM_GETTYPOGRAPHYOPTIONS 3.0
 75   - EM_GETUNDONAME
 76   + EM_GETWORDBREAKPROC
 77   - EM_GETWORDBREAKPROCEX
 78   - EM_GETWORDWRAPMODE 1.0asian
 79   + EM_GETZOOM 3.0
 80   + EM_HIDESELECTION
 81   + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
 82   + EM_LINEFROMCHAR
 83   + EM_LINEINDEX
 84   + EM_LINELENGTH
 85   + EM_LINESCROLL
 86   - EM_PASTESPECIAL
 87   + EM_POSFROMCHAR
 88   + EM_REDO 2.0
 89   + EM_REQUESTRESIZE
 90   + EM_REPLACESEL (proper style?) ANSI&Unicode
 91   + EM_SCROLL
 92   + EM_SCROLLCARET
 93   - EM_SELECTIONTYPE
 94   - EM_SETBIDIOPTIONS 3.0
 95   + EM_SETBKGNDCOLOR
 96   + EM_SETCHARFORMAT (partly done, no ANSI)
 97   - EM_SETEDITSTYLE
 98   + EM_SETEVENTMASK (few notifications supported)
 99   - EM_SETFONTSIZE
100   - EM_SETIMECOLOR 1.0asian
101   - EM_SETIMEOPTIONS 1.0asian
102   - EM_SETLANGOPTIONS 2.0
103   - EM_SETLIMITTEXT
104   + EM_SETMODIFY (not sure if implementation is correct)
105   - EM_SETOLECALLBACK
106   + EM_SETOPTIONS (partially implemented)
107   - EM_SETPALETTE 2.0
108   + EM_SETPARAFORMAT
109   + EM_SETPASSWORDCHAR 2.0
110   - EM_SETPUNCTUATION 1.0asian
111   + EM_SETREADONLY no beep on modification attempt
112   + EM_SETRECT
113   + EM_SETRECTNP (EM_SETRECT without repainting)
114   + EM_SETSEL
115   + EM_SETSCROLLPOS 3.0
116   - EM_SETTABSTOPS 3.0
117   - EM_SETTARGETDEVICE (partial)
118   + EM_SETTEXTEX 3.0 (proper style?)
119   - EM_SETTEXTMODE 2.0
120   - EM_SETTYPOGRAPHYOPTIONS 3.0
121   + EM_SETUNDOLIMIT 2.0
122   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
123   - EM_SETWORDBREAKPROCEX
124   - EM_SETWORDWRAPMODE 1.0asian
125   + EM_SETZOOM 3.0
126   + EM_SHOWSCROLLBAR 2.0
127   + EM_STOPGROUPTYPING 2.0
128   + EM_STREAMIN
129   + EM_STREAMOUT
130   + EM_UNDO
131   + WM_CHAR
132   + WM_CLEAR
133   + WM_COPY
134   + WM_CUT
135   + WM_GETDLGCODE (the current implementation is incomplete)
136   + WM_GETTEXT (ANSI&Unicode)
137   + WM_GETTEXTLENGTH (ANSI version sucks)
138   + WM_PASTE
139   + WM_SETFONT
140   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
141   - WM_STYLECHANGING
142   - WM_STYLECHANGED (things like read-only flag)
143   - WM_UNICHAR
144   
145   Notifications
146   
147   * EN_CHANGE (sent from the wrong place)
148   - EN_CORRECTTEXT
149   - EN_DROPFILES
150   - EN_ERRSPACE
151   - EN_HSCROLL
152   - EN_IMECHANGE
153   + EN_KILLFOCUS
154   - EN_LINK
155   - EN_MAXTEXT
156   - EN_MSGFILTER
157   - EN_OLEOPFAILED
158   - EN_PROTECTED
159   + EN_REQUESTRESIZE
160   - EN_SAVECLIPBOARD
161   + EN_SELCHANGE 
162   + EN_SETFOCUS
163   - EN_STOPNOUNDO
164   * EN_UPDATE (sent from the wrong place)
165   - EN_VSCROLL
166   
167   Styles
168   
169   - ES_AUTOHSCROLL
170   - ES_AUTOVSCROLL
171   - ES_CENTER
172   + ES_DISABLENOSCROLL (scrollbar is always visible)
173   - ES_EX_NOCALLOLEINIT
174   - ES_LEFT
175   - ES_MULTILINE (currently single line controls aren't supported)
176   - ES_NOIME
177   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
178   - ES_RIGHT
179   - ES_SAVESEL
180   - ES_SELFIME
181   - ES_SUNKEN
182   - ES_VERTICAL
183   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
184   - WS_SETFONT
185   - WS_HSCROLL
186   + WS_VSCROLL
187 */
188 
189 /*
190  * RICHED20 TODO (incomplete):
191  *
192  * - messages/styles/notifications listed above 
193  * - add remaining CHARFORMAT/PARAFORMAT fields
194  * - right/center align should strip spaces from the beginning
195  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196  * - COM interface (looks like a major pain in the TODO list)
197  * - calculate heights of pictures (half-done)
198  * - horizontal scrolling (not even started)
199  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
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 "rtf.h"
230 #include "imm.h"
231 #include "res.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 static BOOL ME_RegisterEditorClass(HINSTANCE);
241 
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','','W', 0};
246 static HCURSOR hLeft;
247 
248 int me_debug = 0;
249 HANDLE me_heap = NULL;
250 
251 static BOOL ME_ListBoxRegistered = FALSE;
252 static BOOL ME_ComboBoxRegistered = FALSE;
253 
254 static inline int is_version_nt(void)
255 {
256     return !(GetVersion() & 0x80000000);
257 }
258 
259 static ME_TextBuffer *ME_MakeText(void) {
260   
261   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
262 
263   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
264   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
265   
266   p1->prev = NULL;
267   p1->next = p2;
268   p2->prev = p1;
269   p2->next = NULL;
270   p1->member.para.next_para = p2;
271   p2->member.para.prev_para = p1;
272   p2->member.para.nCharOfs = 0;  
273   
274   buf->pFirst = p1;
275   buf->pLast = p2;
276   buf->pCharStyle = NULL;
277   
278   return buf;
279 }
280 
281 
282 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
283 {
284   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
285   WCHAR *pText;
286   
287   TRACE("%08x %p\n", dwFormat, stream);
288   
289   do {
290     long nWideChars = 0;
291 
292     if (!stream->dwSize)
293     {
294       ME_StreamInFill(stream);
295       if (stream->editstream->dwError)
296         break;
297       if (!stream->dwSize)
298         break;
299     }
300       
301     if (!(dwFormat & SF_UNICODE))
302     {
303       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
304       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
305       pText = wszText;
306     }
307     else
308     {
309       nWideChars = stream->dwSize >> 1;
310       pText = (WCHAR *)stream->buffer;
311     }
312     
313     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
314     if (stream->dwSize == 0)
315       break;
316     stream->dwSize = 0;
317   } while(1);
318   ME_CommitUndo(editor);
319   ME_UpdateRepaint(editor);
320   return 0;
321 }
322 
323 static void ME_RTFCharAttrHook(RTF_Info *info)
324 {
325   CHARFORMAT2W fmt;
326   fmt.cbSize = sizeof(fmt);
327   fmt.dwMask = 0;
328   fmt.dwEffects = 0;
329 
330   switch(info->rtfMinor)
331   {
332     case rtfPlain:
333       /* FIXME add more flags once they're implemented */
334       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
335       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
336       fmt.yHeight = 12*20; /* 12pt */
337       fmt.wWeight = FW_NORMAL;
338       fmt.bUnderlineType = CFU_UNDERLINENONE;
339       break;
340     case rtfBold:
341       fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
342       fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
343       fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
344       break;
345     case rtfItalic:
346       fmt.dwMask = CFM_ITALIC;
347       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
348       break;
349     case rtfUnderline:
350       fmt.dwMask = CFM_UNDERLINETYPE;
351       fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
352       break;
353     case rtfDotUnderline:
354       fmt.dwMask = CFM_UNDERLINETYPE;
355       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
356       break;
357     case rtfDbUnderline:
358       fmt.dwMask = CFM_UNDERLINETYPE;
359       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
360       break;
361     case rtfWordUnderline:
362       fmt.dwMask = CFM_UNDERLINETYPE;
363       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
364       break;
365     case rtfNoUnderline:
366       fmt.dwMask = CFM_UNDERLINETYPE;
367       fmt.bUnderlineType = CFU_UNDERLINENONE;
368       break;
369     case rtfStrikeThru:
370       fmt.dwMask = CFM_STRIKEOUT;
371       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
372       break;
373     case rtfSubScript:
374     case rtfSuperScript:
375     case rtfSubScrShrink:
376     case rtfSuperScrShrink:
377     case rtfNoSuperSub:
378       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
379       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
380       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
381       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
382       break;
383     case rtfInvisible:
384       fmt.dwMask = CFM_HIDDEN;
385       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
386       break;
387     case rtfBackColor:
388       fmt.dwMask = CFM_BACKCOLOR;
389       fmt.dwEffects = 0;
390       if (info->rtfParam == 0)
391         fmt.dwEffects = CFE_AUTOBACKCOLOR;
392       else if (info->rtfParam != rtfNoParam)
393       {
394         RTFColor *c = RTFGetColor(info, info->rtfParam);
395         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
396       }
397       break;
398     case rtfForeColor:
399       fmt.dwMask = CFM_COLOR;
400       fmt.dwEffects = 0;
401       if (info->rtfParam == 0)
402         fmt.dwEffects = CFE_AUTOCOLOR;
403       else if (info->rtfParam != rtfNoParam)
404       {
405         RTFColor *c = RTFGetColor(info, info->rtfParam);
406         if (c)
407           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
408         else
409           fmt.crTextColor = 0;
410       }
411       break;
412     case rtfFontNum:
413       if (info->rtfParam != rtfNoParam)
414       {
415         RTFFont *f = RTFGetFont(info, info->rtfParam);
416         if (f)
417         {
418           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
419           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
420           fmt.bCharSet = f->rtfFCharSet;
421           fmt.dwMask = CFM_FACE | CFM_CHARSET;
422           fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
423         }
424       }
425       break;
426     case rtfFontSize:
427       fmt.dwMask = CFM_SIZE;
428       if (info->rtfParam != rtfNoParam)
429         fmt.yHeight = info->rtfParam*10;
430       break;
431   }
432   if (fmt.dwMask) {
433     ME_Style *style2;
434     RTFFlushOutputBuffer(info);
435     /* FIXME too slow ? how come ? */
436     style2 = ME_ApplyStyle(info->style, &fmt);
437     ME_ReleaseStyle(info->style);
438     info->style = style2;
439     info->styleChanged = TRUE;
440   }
441 }
442 
443 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
444    the same tags mean different things in different contexts */
445 static void ME_RTFParAttrHook(RTF_Info *info)
446 {
447   PARAFORMAT2 fmt;
448   fmt.cbSize = sizeof(fmt);
449   fmt.dwMask = 0;
450   
451   switch(info->rtfMinor)
452   {
453   case rtfParDef: /* restores default paragraph attributes */
454     fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS | PFM_OFFSET |
455         PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE | PFM_STARTINDENT | PFM_TABLE;
456     /* TODO: numbering, shading */
457     fmt.wAlignment = PFA_LEFT;
458     fmt.cTabCount = 0;
459     fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
460     fmt.wBorderWidth = fmt.wBorders = 0;
461     fmt.wBorderSpace = 0;
462     fmt.bLineSpacingRule = 0;
463     fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
464     fmt.dyLineSpacing = 0;
465     fmt.wEffects &= ~PFE_TABLE;
466     break;
467   case rtfInTable:
468   {
469     ME_DisplayItem *para;
470     
471     RTFFlushOutputBuffer(info);
472     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
473     assert(para->member.para.pCells);
474     fmt.dwMask |= PFM_TABLE;
475     fmt.wEffects |= PFE_TABLE;
476     break;
477   }
478   case rtfFirstIndent:
479     ME_GetSelectionParaFormat(info->editor, &fmt);
480     fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
481     fmt.dxStartIndent += info->rtfParam;
482     fmt.dxOffset = -info->rtfParam;
483     break;
484   case rtfLeftIndent:
485     /* we assume rtfLeftIndent is always specified before rtfFirstIndent */
486     ME_GetSelectionParaFormat(info->editor, &fmt);
487     fmt.dwMask |= PFM_STARTINDENT;
488     fmt.dxStartIndent = info->rtfParam;
489     fmt.dxOffset = 0;
490     break;
491   case rtfRightIndent:
492     fmt.dwMask = PFM_RIGHTINDENT;
493     fmt.dxRightIndent = info->rtfParam;
494     break;
495   case rtfQuadLeft:
496   case rtfQuadJust:
497     fmt.dwMask = PFM_ALIGNMENT;
498     fmt.wAlignment = PFA_LEFT;
499     break;
500   case rtfQuadRight:
501     fmt.dwMask = PFM_ALIGNMENT;
502     fmt.wAlignment = PFA_RIGHT;
503     break;
504   case rtfQuadCenter:
505     fmt.dwMask = PFM_ALIGNMENT;
506     fmt.wAlignment = PFA_CENTER;
507     break;
508   case rtfTabPos:
509     ME_GetSelectionParaFormat(info->editor, &fmt);
510     if (!(fmt.dwMask & PFM_TABSTOPS))
511     {
512       fmt.dwMask |= PFM_TABSTOPS;
513       fmt.cTabCount = 0;
514     }
515     if (fmt.cTabCount < MAX_TAB_STOPS)
516       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
517     break;
518   case rtfKeep:
519     fmt.dwMask = PFM_KEEP;
520     fmt.wEffects = PFE_KEEP;
521     break;
522   case rtfNoWidowControl:
523     fmt.dwMask = PFM_NOWIDOWCONTROL;
524     fmt.wEffects = PFE_NOWIDOWCONTROL;
525     break;
526   case rtfKeepNext:
527     fmt.dwMask = PFM_KEEPNEXT;
528     fmt.wEffects = PFE_KEEPNEXT;
529     break;
530   case rtfSpaceAfter:
531     fmt.dwMask = PFM_SPACEAFTER;
532     fmt.dySpaceAfter = info->rtfParam;
533     break;
534   case rtfSpaceBefore:
535     fmt.dwMask = PFM_SPACEBEFORE;
536     fmt.dySpaceBefore = info->rtfParam;
537     break;
538   case rtfSpaceBetween:
539     fmt.dwMask = PFM_LINESPACING;
540     if ((int)info->rtfParam > 0)
541     {
542       fmt.dyLineSpacing = info->rtfParam;
543       fmt.bLineSpacingRule = 3;
544     }
545     else
546     {
547       fmt.dyLineSpacing = info->rtfParam;
548       fmt.bLineSpacingRule = 4;
549     }
550   case rtfSpaceMultiply:
551     fmt.dwMask = PFM_LINESPACING;
552     fmt.dyLineSpacing = info->rtfParam * 20;
553     fmt.bLineSpacingRule = 5;
554     break;
555   case rtfParBullet:
556     fmt.dwMask = PFM_NUMBERING;
557     fmt.wNumbering = PFN_BULLET;
558     break;
559   case rtfParSimple:
560     fmt.dwMask = PFM_NUMBERING;
561     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
562     break;
563   case rtfParNumDecimal:
564     fmt.dwMask = PFM_NUMBERING;
565     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
566     break;
567   case rtfParNumIndent:
568     fmt.dwMask = PFM_NUMBERINGTAB;
569     fmt.wNumberingTab = info->rtfParam;
570     break;
571   case rtfParNumStartAt:
572     fmt.dwMask = PFM_NUMBERINGSTART;
573     fmt.wNumberingStart = info->rtfParam;
574     break;
575   case rtfBorderLeft:
576     ME_GetSelectionParaFormat(info->editor, &fmt);
577     if (!(fmt.dwMask & PFM_BORDER))
578     {
579       fmt.dwMask |= PFM_BORDER;
580       fmt.wBorderSpace = 0;
581       fmt.wBorderWidth = 1;
582       fmt.wBorders = 0;
583     }
584     fmt.wBorders |= 1;
585     break;
586   case rtfBorderRight:
587     ME_GetSelectionParaFormat(info->editor, &fmt);
588     if (!(fmt.dwMask & PFM_BORDER))
589     {
590       fmt.dwMask |= PFM_BORDER;
591       fmt.wBorderSpace = 0;
592       fmt.wBorderWidth = 1;
593       fmt.wBorders = 0;
594     }
595     fmt.wBorders |= 2;
596     break;
597   case rtfBorderTop:
598     ME_GetSelectionParaFormat(info->editor, &fmt);
599     if (!(fmt.dwMask & PFM_BORDER))
600     {
601       fmt.dwMask |= PFM_BORDER;
602       fmt.wBorderSpace = 0;
603       fmt.wBorderWidth = 1;
604       fmt.wBorders = 0;
605     }
606     fmt.wBorders |= 4;
607     break;
608   case rtfBorderBottom:
609     ME_GetSelectionParaFormat(info->editor, &fmt);
610     if (!(fmt.dwMask & PFM_BORDER))
611     {
612       fmt.dwMask |= PFM_BORDER;
613       fmt.wBorderSpace = 0;
614       fmt.wBorderWidth = 1;
615       fmt.wBorders = 0;
616     }
617     fmt.wBorders |= 8;
618     break;
619   case rtfBorderSingle:
620     ME_GetSelectionParaFormat(info->editor, &fmt);
621     /* we assume that borders have been created before (RTF spec) */
622     fmt.wBorders &= ~0x700;
623     fmt.wBorders |= 1 << 8;
624     break;
625   case rtfBorderThick:
626     ME_GetSelectionParaFormat(info->editor, &fmt);
627     /* we assume that borders have been created before (RTF spec) */
628     fmt.wBorders &= ~0x700;
629     fmt.wBorders |= 2 << 8;
630     break;
631   case rtfBorderShadow:
632     ME_GetSelectionParaFormat(info->editor, &fmt);
633     /* we assume that borders have been created before (RTF spec) */
634     fmt.wBorders &= ~0x700;
635     fmt.wBorders |= 10 << 8;
636     break;
637   case rtfBorderDouble:
638     ME_GetSelectionParaFormat(info->editor, &fmt);
639     /* we assume that borders have been created before (RTF spec) */
640     fmt.wBorders &= ~0x700;
641     fmt.wBorders |= 7 << 8;
642     break;
643   case rtfBorderDot:
644     ME_GetSelectionParaFormat(info->editor, &fmt);
645     /* we assume that borders have been created before (RTF spec) */
646     fmt.wBorders &= ~0x700;
647     fmt.wBorders |= 11 << 8;
648     break;
649   case rtfBorderWidth:
650     ME_GetSelectionParaFormat(info->editor, &fmt);
651     /* we assume that borders have been created before (RTF spec) */
652     fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
653     break;
654   case rtfBorderSpace:
655     ME_GetSelectionParaFormat(info->editor, &fmt);
656     /* we assume that borders have been created before (RTF spec) */
657     fmt.wBorderSpace = info->rtfParam;
658     break;
659   }  
660   if (fmt.dwMask) {
661     RTFFlushOutputBuffer(info);
662     /* FIXME too slow ? how come ?*/
663     ME_SetSelectionParaFormat(info->editor, &fmt);
664   }
665 }
666 
667 static void ME_RTFTblAttrHook(RTF_Info *info)
668 {
669   ME_DisplayItem *para;
670   
671   switch (info->rtfMinor)
672   {
673     case rtfRowDef:
674       RTFFlushOutputBuffer(info);
675       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
676       
677       /* Release possibly inherited cell definitions */
678       ME_DestroyTableCellList(para);
679       
680       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
681       para->member.para.pCells->nRightBoundary = 0;
682       para->member.para.pCells->next = NULL;
683       para->member.para.pLastCell = para->member.para.pCells;
684       break;
685     case rtfCellPos:
686       RTFFlushOutputBuffer(info);
687       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
688       
689       if (para->member.para.pLastCell->nRightBoundary)
690       {
691         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
692         
693         pCell->next = NULL;
694         para->member.para.pLastCell->next = pCell;
695         para->member.para.pLastCell = pCell;
696       }
697       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
698       break;
699   }
700 }
701 
702 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
703                                   const SIZEL* sz)
704 {
705   LPOLEOBJECT         lpObject = NULL;
706   LPSTORAGE           lpStorage = NULL;
707   LPOLECLIENTSITE     lpClientSite = NULL;
708   LPDATAOBJECT        lpDataObject = NULL;
709   LPOLECACHE          lpOleCache = NULL;
710   STGMEDIUM           stgm;
711   FORMATETC           fm;
712   CLSID               clsid;
713   BOOL                ret = FALSE;
714   DWORD               conn;
715 
716   if (hemf)
717   {
718       stgm.tymed = TYMED_ENHMF;
719       stgm.u.hEnhMetaFile = hemf;
720       fm.cfFormat = CF_ENHMETAFILE;
721   }
722   else if (hbmp)
723   {
724       stgm.tymed = TYMED_GDI;
725       stgm.u.hBitmap = hbmp;
726       fm.cfFormat = CF_BITMAP;
727   }
728   stgm.pUnkForRelease = NULL;
729 
730   fm.ptd = NULL;
731   fm.dwAspect = DVASPECT_CONTENT;
732   fm.lindex = -1;
733   fm.tymed = stgm.tymed;
734 
735   if (!info->lpRichEditOle)
736   {
737     CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
738   }
739 
740   if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
741 #if 0
742       /* FIXME: enable it when rich-edit properly implements this method */
743       IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
744       IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
745 #endif
746       IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
747       IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
748       IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
749       IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
750       IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
751   {
752     REOBJECT            reobject;
753 
754     reobject.cbStruct = sizeof(reobject);
755     reobject.cp = REO_CP_SELECTION;
756     reobject.clsid = clsid;
757     reobject.poleobj = lpObject;
758     reobject.pstg = lpStorage;
759     reobject.polesite = lpClientSite;
760     /* convert from twips to .01 mm */
761     reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
762     reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
763     reobject.dvaspect = DVASPECT_CONTENT;
764     reobject.dwFlags = 0; /* FIXME */
765     reobject.dwUser = 0;
766 
767     /* FIXME: could be simpler */
768     ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
769   }
770 
771   if (lpObject)       IOleObject_Release(lpObject);
772   if (lpClientSite)   IOleClientSite_Release(lpClientSite);
773   if (lpStorage)      IStorage_Release(lpStorage);
774   if (lpDataObject)   IDataObject_Release(lpDataObject);
775   if (lpOleCache)     IOleCache_Release(lpOleCache);
776 
777   return ret;
778 }
779 
780 static void ME_RTFReadPictGroup(RTF_Info *info)
781 {
782   SIZEL         sz;
783   BYTE*         buffer = NULL;
784   unsigned      bufsz, bufidx;
785   BOOL          flip;
786   BYTE          val;
787   METAFILEPICT  mfp;
788   HENHMETAFILE  hemf;
789   HBITMAP       hbmp;
790   enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
791 
792   RTFGetToken (info);
793   if (info->rtfClass == rtfEOF)
794     return;
795   mfp.mm = MM_TEXT;
796   /* fetch picture type */
797   if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
798   {
799     mfp.mm = info->rtfParam;
800     gfx = gfx_metafile;
801   }
802   else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
803   {
804     if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
805     gfx = gfx_dib;
806   }
807   else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
808   {
809     gfx = gfx_enhmetafile;
810   }
811   else
812   {
813     FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
814     goto skip_group;
815   }
816   sz.cx = sz.cy = 0;
817   /* fetch picture attributes */
818   for (;;)
819   {
820     RTFGetToken (info);
821     if (info->rtfClass == rtfEOF)
822       return;
823     if (info->rtfClass == rtfText)
824       break;
825     if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
826     {
827       ERR("Expected picture attribute (%d %d)\n",
828         info->rtfClass, info->rtfMajor);
829       goto skip_group;
830     }
831     else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
832     {
833       if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
834     }
835     else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
836     {
837       if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
838     }
839     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
840       sz.cx = info->rtfParam;
841     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
842       sz.cy = info->rtfParam;
843     else
844       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
845   }
846   /* fetch picture data */
847   bufsz = 1024;
848   bufidx = 0;
849   buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
850   val = info->rtfMajor;
851   for (flip = TRUE;; flip = !flip)
852   {
853     RTFGetToken (info);
854     if (info->rtfClass == rtfEOF)
855     {
856       HeapFree(GetProcessHeap(), 0, buffer);
857       return; /* Warn ?? */
858     }
859     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
860       break;
861     if (info->rtfClass != rtfText) goto skip_group;
862     if (flip)
863     {
864       if (bufidx >= bufsz &&
865           !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
866         goto skip_group;
867       buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
868     }
869     else
870       val = info->rtfMajor;
871   }
872   if (flip) FIXME("wrong hex string\n");
873 
874   switch (gfx)
875   {
876   case gfx_enhmetafile:
877     if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
878       ME_RTFInsertOleObject(info, hemf, NULL, &sz);
879     break;
880   case gfx_metafile:
881     if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
882         ME_RTFInsertOleObject(info, hemf, NULL, &sz);
883     break;
884   case gfx_dib:
885     {
886       BITMAPINFO* bi = (BITMAPINFO*)buffer;
887       HDC         hdc = GetDC(0);
888       unsigned    nc = bi->bmiHeader.biClrUsed;
889 
890       /* not quite right, especially for bitfields type of compression */
891       if (!nc && bi->bmiHeader.biBitCount <= 8)
892         nc = 1 << bi->bmiHeader.biBitCount;
893       if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
894                                  CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
895                                  bi, DIB_RGB_COLORS)))
896           ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
897       ReleaseDC(0, hdc);
898     }
899     break;
900   default:
901     break;
902   }
903   HeapFree(GetProcessHeap(), 0, buffer);
904   RTFRouteToken (info); /* feed "}" back to router */
905   return;
906 skip_group:
907   HeapFree(GetProcessHeap(), 0, buffer);
908   RTFSkipGroup(info);
909   RTFRouteToken(info);  /* feed "}" back to router */
910 }
911 
912 /* for now, lookup the \result part and use it, whatever the object */
913 static void ME_RTFReadObjectGroup(RTF_Info *info)
914 {
915   for (;;)
916   {
917     RTFGetToken (info);
918     if (info->rtfClass == rtfEOF)
919       return;
920     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
921       break;
922     if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
923     {
924       RTFGetToken (info);
925       if (info->rtfClass == rtfEOF)
926         return;
927       if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
928       {
929         int     level = 1;
930 
931         while (RTFGetToken (info) != rtfEOF)
932         {
933           if (info->rtfClass == rtfGroup)
934           {
935             if (info->rtfMajor == rtfBeginGroup) level++;
936             else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
937           }
938           RTFRouteToken(info);
939         }
940       }
941       else RTFSkipGroup(info);
942       continue;
943     }
944     if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
945     {
946       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
947       return;
948     }
949   }
950   RTFRouteToken(info);  /* feed "}" back to router */
951 }
952 
953 static void ME_RTFReadHook(RTF_Info *info) {
954   switch(info->rtfClass)
955   {
956     case rtfGroup:
957       switch(info->rtfMajor)
958       {
959         case rtfBeginGroup:
960           if (info->stackTop < maxStack) {
961             info->stack[info->stackTop].fmt = info->style->fmt;
962             info->stack[info->stackTop].codePage = info->codePage;
963             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
964           }
965           info->stackTop++;
966           info->styleChanged = FALSE;
967           break;
968         case rtfEndGroup:
969         {
970           ME_Style *s;
971           RTFFlushOutputBuffer(info);
972           info->stackTop--;
973           if (info->stackTop<=0) {
974             info->rtfClass = rtfEOF;
975             return;
976           }
977           assert(info->stackTop >= 0);
978           if (info->styleChanged)
979           {
980             /* FIXME too slow ? how come ? */
981             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
982             ME_ReleaseStyle(info->style);
983             info->style = s;
984             info->codePage = info->stack[info->stackTop].codePage;
985             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
986           }
987           break;
988         }
989       }
990       break;
991     case rtfControl:
992       switch(info->rtfMajor)
993       {
994         case rtfCharAttr:
995           ME_RTFCharAttrHook(info);
996           break;
997         case rtfParAttr:
998           ME_RTFParAttrHook(info);
999           break;
1000         case rtfTblAttr:
1001           ME_RTFTblAttrHook(info);
1002           break;
1003         case rtfSpecialChar:
1004           if (info->rtfMinor == rtfCell)
1005           {
1006             RTFFlushOutputBuffer(info);
1007             ME_InsertTableCellFromCursor(info->editor, 0);
1008           }
1009       }
1010       break;
1011   }
1012 }
1013 
1014 void
1015 ME_StreamInFill(ME_InStream *stream)
1016 {
1017   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1018                                                                 (BYTE *)stream->buffer,
1019                                                                 sizeof(stream->buffer),
1020                                                                 (LONG *)&stream->dwSize);
1021   stream->dwUsed = 0;
1022 }
1023 
1024 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1025 {
1026   RTF_Info parser;
1027   ME_Style *style;
1028   int from, to, to2, nUndoMode;
1029   int nEventMask = editor->nEventMask;
1030   ME_InStream inStream;
1031   BOOL invalidRTF = FALSE;
1032 
1033   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1034   editor->nEventMask = 0;
1035 
1036   ME_GetSelection(editor, &from, &to);
1037   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1038     style = ME_GetSelectionInsertStyle(editor);
1039 
1040     ME_InternalDeleteText(editor, from, to-from);
1041   }
1042   else {
1043     ME_DisplayItem *para_item;
1044     style = editor->pBuffer->pDefaultStyle;
1045     ME_AddRefStyle(style);
1046     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
1047     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1048     from = to = 0;
1049     ME_ClearTempStyle(editor);
1050 
1051     para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1052     ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1053   }
1054 
1055 
1056   /* Back up undo mode to a local variable */
1057   nUndoMode = editor->nUndoMode;
1058 
1059   /* Only create an undo if SFF_SELECTION is set */
1060   if (!(format & SFF_SELECTION))
1061     editor->nUndoMode = umIgnore;
1062 
1063   inStream.editstream = stream;
1064   inStream.editstream->dwError = 0;
1065   inStream.dwSize = 0;
1066   inStream.dwUsed = 0;
1067 
1068   if (format & SF_RTF)
1069   {
1070     /* Check if it's really RTF, and if it is not, use plain text */
1071     ME_StreamInFill(&inStream);
1072     if (!inStream.editstream->dwError)
1073     {
1074       if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1075         || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1076       {
1077         invalidRTF = TRUE;
1078         inStream.editstream->dwError = -16;
1079       }
1080     }
1081   }
1082 
1083   if (!invalidRTF && !inStream.editstream->dwError)
1084   {
1085     if (format & SF_RTF) {
1086       /* setup the RTF parser */
1087       memset(&parser, 0, sizeof parser);
1088       RTFSetEditStream(&parser, &inStream);
1089       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1090       parser.hwndEdit = editor->hWnd;
1091       parser.editor = editor;
1092       parser.style = style;
1093       WriterInit(&parser);
1094       RTFInit(&parser);
1095       RTFSetReadHook(&parser, ME_RTFReadHook);
1096       RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1097       RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1098       BeginFile(&parser);
1099 
1100       /* do the parsing */
1101       RTFRead(&parser);
1102       RTFFlushOutputBuffer(&parser);
1103       RTFDestroy(&parser);
1104       if (parser.lpRichEditOle)
1105         IRichEditOle_Release(parser.lpRichEditOle);
1106 
1107       if (!inStream.editstream->dwError && parser.stackTop > 0)
1108         inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1109 
1110       /* Remove last line break, as mandated by tests. This is not affected by
1111          CR/LF counters, since RTF streaming presents only \para tokens, which
1112          are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1113        */
1114       if (stripLastCR) {
1115         int newfrom, newto;
1116         ME_GetSelection(editor, &newfrom, &newto);
1117         if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1118           WCHAR lastchar[3] = {'\0', '\0'};
1119           int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1120 
1121           ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1122           if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1123             ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize);
1124           }
1125         }
1126       }
1127 
1128       style = parser.style;
1129     }
1130     else if (format & SF_TEXT)
1131       ME_StreamInText(editor, format, &inStream, style);
1132     else
1133       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1134     ME_GetSelection(editor, &to, &to2);
1135     /* put the cursor at the top */
1136     if (!(format & SFF_SELECTION))
1137       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1138   }
1139 
1140   /* Restore saved undo mode */
1141   editor->nUndoMode = nUndoMode;
1142 
1143   /* even if we didn't add an undo, we need to commit anything on the stack */
1144   ME_CommitUndo(editor);
1145 
1146   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1147   if (!(format & SFF_SELECTION))
1148     ME_EmptyUndoStack(editor);
1149 
1150   ME_ReleaseStyle(style);
1151   editor->nEventMask = nEventMask;
1152   ME_UpdateRepaint(editor);
1153   if (!(format & SFF_SELECTION)) {
1154     ME_ClearTempStyle(editor);
1155   }
1156   HideCaret(editor->hWnd);
1157   ME_MoveCaret(editor);
1158   ShowCaret(editor->hWnd);
1159   ME_SendSelChange(editor);
1160   ME_SendRequestResize(editor, FALSE);
1161 
1162   return 0;
1163 }
1164 
1165 
1166 typedef struct tagME_RTFStringStreamStruct
1167 {
1168   char *string;
1169   int pos;
1170   int length;
1171 } ME_RTFStringStreamStruct;
1172 
1173 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1174 {
1175   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1176   int count;
1177 
1178   count = min(cb, pStruct->length - pStruct->pos);
1179   memmove(lpBuff, pStruct->string + pStruct->pos, count);
1180   pStruct->pos += count;
1181   *pcb = count;
1182   return 0;
1183 }
1184 
1185 static void
1186 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1187 {
1188   EDITSTREAM es;
1189   ME_RTFStringStreamStruct data;
1190 
1191   data.string = string;
1192   data.length = strlen(string);
1193   data.pos = 0;
1194   es.dwCookie = (DWORD)&data;
1195   es.pfnCallback = ME_ReadFromRTFString;
1196   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1197 }
1198 
1199 
1200 ME_DisplayItem *
1201 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1202 {
1203   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1204   int runLength;
1205   
1206   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1207     item = ME_FindItemFwd(item, diParagraph);
1208 
1209   if (!item)
1210     return item;
1211 
1212   nOffset -= item->member.para.nCharOfs;
1213   if (nItemType == diParagraph) {
1214     if (nItemOffset)
1215       *nItemOffset = nOffset;
1216     return item;
1217   }
1218   
1219   do {
1220     item = ME_FindItemFwd(item, diRun);
1221     runLength = ME_StrLen(item->member.run.strText);
1222     if (item->member.run.nFlags & MERF_ENDPARA)
1223       runLength = item->member.run.nCR + item->member.run.nLF;
1224   } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1225   if (item) {
1226     nOffset -= item->member.run.nCharOfs;
1227 
1228     /* Special case: nOffset may not point exactly at the division between the
1229        \r and the \n in 1.0 emulation. If such a case happens, it is sent
1230        into the next run, if one exists
1231      */
1232     if (   item->member.run.nFlags & MERF_ENDPARA
1233         && nOffset == item->member.run.nCR
1234         && item->member.run.nLF > 0) {
1235       ME_DisplayItem *nextItem;
1236       nextItem = ME_FindItemFwd(item, diRun);
1237       if (nextItem) {
1238         nOffset = 0;
1239         item = nextItem;
1240       }
1241     }
1242     if (nItemOffset)
1243       *nItemOffset = nOffset;
1244   }
1245   return item;
1246 }
1247 
1248 
1249 static int
1250 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1251 {
1252   const int nLen = lstrlenW(text);
1253   const int nTextLen = ME_GetTextLength(editor);
1254   int nStart, nEnd;
1255   int nMin, nMax;
1256   ME_DisplayItem *item;
1257   ME_DisplayItem *para;
1258   WCHAR wLastChar = ' ';
1259 
1260   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1261         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1262   
1263   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1264     FIXME("Flags 0x%08x not implemented\n",
1265         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1266 
1267   nMin = chrg->cpMin;
1268   if (chrg->cpMax == -1)
1269     nMax = nTextLen;
1270   else
1271     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1272   
1273   /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1274   if (editor->bEmulateVersion10 && nMax == nTextLen)
1275   {
1276     flags |= FR_DOWN;
1277   }
1278 
1279   /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1280   if (editor->bEmulateVersion10 && nMax < nMin)
1281   {
1282     if (chrgText)
1283     {
1284       chrgText->cpMin = -1;
1285       chrgText->cpMax = -1;
1286     }
1287     return -1;
1288   }
1289 
1290   /* when searching up, if cpMin < cpMax, then instead of searching
1291    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1292    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1293    * case, it is always bigger than cpMin.
1294    */
1295   if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1296   {
1297     int nSwap = nMax;
1298 
1299     nMax = nMin > nTextLen ? nTextLen : nMin;
1300     if (nMin < nSwap || chrg->cpMax == -1)
1301       nMin = 0;
1302     else
1303       nMin = nSwap;
1304   }
1305 
1306   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1307   {
1308     if (chrgText)
1309       chrgText->cpMin = chrgText->cpMax = -1;
1310     return -1;
1311   }
1312  
1313   if (flags & FR_DOWN) /* Forward search */
1314   {
1315     /* If possible, find the character before where the search starts */
1316     if ((flags & FR_WHOLEWORD) && nMin)
1317     {
1318       nStart = nMin - 1;
1319       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1320       if (!item)
1321       {
1322         if (chrgText)
1323           chrgText->cpMin = chrgText->cpMax = -1;
1324         return -1;
1325       }
1326       wLastChar = item->member.run.strText->szData[nStart];
1327     }
1328 
1329     nStart = nMin;
1330     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1331     if (!item)
1332     {
1333       if (chrgText)
1334         chrgText->cpMin = chrgText->cpMax = -1;
1335       return -1;
1336     }
1337 
1338     para = ME_GetParagraph(item);
1339     while (item
1340            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1341     {
1342       ME_DisplayItem *pCurItem = item;
1343       int nCurStart = nStart;
1344       int nMatched = 0;
1345     
1346       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1347       {
1348         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1349           break;
1350 
1351         nMatched++;
1352         if (nMatched == nLen)
1353         {
1354           ME_DisplayItem *pNextItem = pCurItem;
1355           int nNextStart = nCurStart;
1356           WCHAR wNextChar;
1357 
1358           /* Check to see if next character is a whitespace */
1359           if (flags & FR_WHOLEWORD)
1360           {
1361             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1362             {
1363               pNextItem = ME_FindItemFwd(pCurItem, diRun);
1364               nNextStart = -nMatched;
1365             }
1366 
1367             if (pNextItem)
1368               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1369             else
1370               wNextChar = ' ';
1371 
1372             if (isalnumW(wNextChar))
1373               break;
1374           }
1375 
1376           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1377           if (chrgText)
1378           {
1379             chrgText->cpMin = nStart;
1380             chrgText->cpMax = nStart + nLen;
1381           }
1382           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1383           return nStart;
1384         }
1385         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1386         {
1387           pCurItem = ME_FindItemFwd(pCurItem, diRun);
1388           para = ME_GetParagraph(pCurItem);
1389           nCurStart = -nMatched;
1390         }
1391       }
1392       if (pCurItem)
1393         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1394       else
1395         wLastChar = ' ';
1396 
1397       nStart++;
1398       if (nStart == ME_StrLen(item->member.run.strText))
1399       {
1400         item = ME_FindItemFwd(item, diRun);
1401         para = ME_GetParagraph(item);
1402         nStart = 0;
1403       }
1404     }
1405   }
1406   else /* Backward search */
1407   {
1408     /* If possible, find the character after where the search ends */
1409     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1410     {
1411       nEnd = nMax + 1;
1412       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1413       if (!item)
1414       {
1415         if (chrgText)
1416           chrgText->cpMin = chrgText->cpMax = -1;
1417         return -1;
1418       }
1419       wLastChar = item->member.run.strText->szData[nEnd];
1420     }
1421 
1422     nEnd = nMax;
1423     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1424     if (!item)
1425     {
1426       if (chrgText)
1427         chrgText->cpMin = chrgText->cpMax = -1;
1428       return -1;
1429     }
1430     
1431     para = ME_GetParagraph(item);
1432     
1433     while (item
1434            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1435     {
1436       ME_DisplayItem *pCurItem = item;
1437       int nCurEnd = nEnd;
1438       int nMatched = 0;
1439       
1440       if (nCurEnd - nMatched == 0)
1441       {
1442         pCurItem = ME_FindItemBack(pCurItem, diRun);
1443         para = ME_GetParagraph(pCurItem);
1444         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1445       }
1446       
1447       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1448       {
1449         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1450           break;
1451 
1452         nMatched++;
1453         if (nMatched == nLen)
1454         {
1455           ME_DisplayItem *pPrevItem = pCurItem;
1456           int nPrevEnd = nCurEnd;
1457           WCHAR wPrevChar;
1458 
1459           /* Check to see if previous character is a whitespace */
1460           if (flags & FR_WHOLEWORD)
1461           {
1462             if (nPrevEnd - nMatched == 0)
1463             {
1464               pPrevItem = ME_FindItemBack(pCurItem, diRun);
1465               if (pPrevItem)
1466                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1467             }
1468 
1469             if (pPrevItem)
1470               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1471             else
1472               wPrevChar = ' ';
1473 
1474             if (isalnumW(wPrevChar))
1475               break;
1476           }
1477 
1478           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1479           if (chrgText)
1480           {
1481             chrgText->cpMin = nStart;
1482             chrgText->cpMax = nStart + nLen;
1483           }
1484           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1485           return nStart;
1486         }
1487         if (nCurEnd - nMatched == 0)
1488         {
1489           pCurItem = ME_FindItemBack(pCurItem, diRun);
1490           /* Don't care about pCurItem becoming NULL here; it's already taken
1491            * care of in the exterior loop condition */
1492           para = ME_GetParagraph(pCurItem);
1493           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1494         }
1495       }
1496       if (pCurItem)
1497         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1498       else
1499         wLastChar = ' ';
1500 
1501       nEnd--;
1502       if (nEnd < 0)
1503       {
1504         item = ME_FindItemBack(item, diRun);
1505         para = ME_GetParagraph(item);
1506         nEnd = ME_StrLen(item->member.run.strText);
1507       }
1508     }
1509   }
1510   TRACE("not found\n");
1511   if (chrgText)
1512     chrgText->cpMin = chrgText->cpMax = -1;
1513   return -1;
1514 }
1515 
1516 /* helper to send a msg filter notification */
1517 static BOOL
1518 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1519 {
1520     MSGFILTER msgf;
1521 
1522     msgf.nmhdr.hwndFrom = editor->hWnd;
1523     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1524     msgf.nmhdr.code = EN_MSGFILTER;
1525     msgf.msg = msg;
1526 
1527     msgf.wParam = *wParam;
1528     msgf.lParam = *lParam;
1529     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1530         return FALSE;
1531     *wParam = msgf.wParam;
1532     *lParam = msgf.lParam;
1533     msgf.wParam = *wParam;
1534 
1535     return TRUE;
1536 }
1537 
1538 static BOOL
1539 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1540 {
1541   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1542   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1543 
1544   if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1545       editor->nSelectionType = stPosition;
1546 
1547   switch (nKey)
1548   {
1549     case VK_LEFT:
1550     case VK_RIGHT:
1551     case VK_HOME:
1552     case VK_END:
1553         editor->nUDArrowX = -1;
1554         /* fall through */
1555     case VK_UP:
1556     case VK_DOWN:
1557     case VK_PRIOR:
1558     case VK_NEXT:
1559       ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1560       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1561       return TRUE;
1562     case VK_BACK:
1563     case VK_DELETE:
1564       editor->nUDArrowX = -1;
1565       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1566       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1567         return FALSE;
1568       if (ME_IsSelection(editor))
1569       {
1570         ME_DeleteSelection(editor);
1571         ME_CommitUndo(editor);
1572       }
1573       else if (nKey == VK_DELETE)
1574       {
1575         /* Delete stops group typing.
1576          * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1577         ME_DeleteTextAtCursor(editor, 1, 1);
1578         ME_CommitUndo(editor);
1579       }
1580       else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1581       {
1582           /* Backspace can be grouped for a single undo */
1583           ME_ContinueCoalescingTransaction(editor);
1584           ME_DeleteTextAtCursor(editor, 1, 1);
1585           ME_CommitCoalescingUndo(editor);
1586       }
1587       else
1588         return TRUE;
1589       ME_UpdateSelectionLinkAttribute(editor);
1590       ME_UpdateRepaint(editor);
1591       ME_SendRequestResize(editor, FALSE);
1592       return TRUE;
1593 
1594     default:
1595       if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1596           editor->nUDArrowX = -1;
1597       if (ctrl_is_down)
1598       {
1599         if (nKey == 'W')
1600         {
1601           CHARFORMAT2W chf;
1602           char buf[2048];
1603           chf.cbSize = sizeof(chf);
1604           
1605           ME_GetSelectionCharFormat(editor, &chf);
1606           ME_DumpStyleToBuf(&chf, buf);
1607           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1608         }
1609         if (nKey == 'Q')
1610         {
1611           ME_CheckCharOffsets(editor);
1612         }
1613       }
1614   }
1615   return FALSE;
1616 }
1617 
1618 /* Process the message and calculate the new click count.
1619  *
1620  * returns: The click count if it is mouse down event, else returns 0. */
1621 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
1622                                   LPARAM lParam)
1623 {
1624     static int clickNum = 0;
1625     if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
1626         return 0;
1627 
1628     if ((msg == WM_LBUTTONDBLCLK) ||
1629         (msg == WM_RBUTTONDBLCLK) ||
1630         (msg == WM_MBUTTONDBLCLK) ||
1631         (msg == WM_XBUTTONDBLCLK))
1632     {
1633         msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1634     }
1635 
1636     if ((msg == WM_LBUTTONDOWN) ||
1637         (msg == WM_RBUTTONDOWN) ||
1638         (msg == WM_MBUTTONDOWN) ||
1639         (msg == WM_XBUTTONDOWN))
1640     {
1641         static MSG prevClickMsg;
1642         MSG clickMsg;
1643         clickMsg.hwnd = hWnd;
1644         clickMsg.message = msg;
1645         clickMsg.wParam = wParam;
1646         clickMsg.lParam = lParam;
1647         clickMsg.time = GetMessageTime();
1648         clickMsg.pt.x = (short)LOWORD(lParam);
1649         clickMsg.pt.y = (short)HIWORD(lParam);
1650         if ((clickNum != 0) &&
1651             (clickMsg.message == prevClickMsg.message) &&
1652             (clickMsg.hwnd == prevClickMsg.hwnd) &&
1653             (clickMsg.wParam == prevClickMsg.wParam) &&
1654             (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
1655             (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1656             (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1657         {
1658             clickNum++;
1659         } else {
1660             clickNum = 1;
1661         }
1662         prevClickMsg = clickMsg;
1663     } else {
1664         return 0;
1665     }
1666     return clickNum;
1667 }
1668 
1669 static BOOL ME_SetCursor(ME_TextEditor *editor)
1670 {
1671   POINT pt;
1672   BOOL isExact;
1673   int offset;
1674   DWORD messagePos = GetMessagePos();
1675   pt.x = (short)LOWORD(messagePos);
1676   pt.y = (short)HIWORD(messagePos);
1677   ScreenToClient(editor->hWnd, &pt);
1678   if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1679       (pt.x < editor->selofs ||
1680        (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
1681   {
1682       SetCursor(hLeft);
1683       return TRUE;
1684   }
1685   offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
1686   if (isExact)
1687   {
1688       if (editor->AutoURLDetect_bEnable)
1689       {
1690           ME_Cursor cursor;
1691           ME_Run *run;
1692           ME_CursorFromCharOfs(editor, offset, &cursor);
1693           run = &cursor.pRun->member.run;
1694           if (editor->AutoURLDetect_bEnable &&
1695               run->style->fmt.dwMask & CFM_LINK &&
1696               run->style->fmt.dwEffects & CFE_LINK)
1697           {
1698               SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
1699               return TRUE;
1700           }
1701       }
1702       if (ME_IsSelection(editor))
1703       {
1704           int selStart, selEnd;
1705           ME_GetSelection(editor, &selStart, &selEnd);
1706           if (selStart <= offset && selEnd >= offset) {
1707               SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
1708               return TRUE;
1709           }
1710       }
1711   }
1712   SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
1713   return TRUE;
1714 }
1715 
1716 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1717 {
1718   CHARRANGE selrange;
1719   HMENU menu;
1720   int seltype = 0;
1721   if(!editor->lpOleCallback)
1722     return FALSE;
1723   ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
1724   if(selrange.cpMin == selrange.cpMax)
1725     seltype |= SEL_EMPTY;
1726   else
1727   {
1728     /* FIXME: Handle objects */
1729     seltype |= SEL_TEXT;
1730     if(selrange.cpMax-selrange.cpMin > 1)
1731       seltype |= SEL_MULTICHAR;
1732   }
1733   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1734   {
1735     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1736     DestroyMenu(menu);
1737   }
1738   return TRUE;
1739 }
1740 
1741 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1742   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1743   int i;
1744   ed->hWnd = hWnd;
1745   ed->bEmulateVersion10 = FALSE;
1746   ed->pBuffer = ME_MakeText();
1747   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1748   ME_MakeFirstParagraph(ed);
1749   /* The four cursors are for:
1750    * 0 - The position where the caret is shown
1751    * 1 - The anchored end of the selection (for normal selection)
1752    * 2 & 3 - The anchored start and end respectively for word, line,
1753    * or paragraph selection.
1754    */
1755   ed->nCursors = 4;
1756   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1757   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1758   ed->pCursors[0].nOffset = 0;
1759   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1760   ed->pCursors[1].nOffset = 0;
1761   ed->pCursors[2] = ed->pCursors[0];
1762   ed->pCursors[3] = ed->pCursors[1];
1763   ed->nLastTotalLength = ed->nTotalLength = 0;
1764   ed->nHeight = 0;
1765   ed->nUDArrowX = -1;
1766   ed->nSequence = 0;
1767   ed->rgbBackColor = -1;
1768   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1769   ed->bCaretAtEnd = FALSE;
1770   ed->nEventMask = 0;
1771   ed->nModifyStep = 0;
1772   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1773   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1774   ed->nUndoStackSize = 0;
1775   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1776   ed->nUndoMode = umAddToUndo;
1777   ed->nParagraphs = 1;
1778   ed->nLastSelStart = ed->nLastSelEnd = 0;
1779   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1780   ed->bRedraw = TRUE;
1781   ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
1782   ed->bHideSelection = FALSE;
1783   ed->nInvalidOfs = -1;
1784   ed->pfnWordBreak = NULL;
1785   ed->lpOleCallback = NULL;
1786   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1787   ed->AutoURLDetect_bEnable = FALSE;
1788   ed->bHaveFocus = FALSE;
1789   for (i=0; i<HFONT_CACHE_SIZE; i++)
1790   {
1791     ed->pFontCache[i].nRefs = 0;
1792     ed->pFontCache[i].nAge = 0;
1793     ed->pFontCache[i].hFont = NULL;
1794   }
1795   
1796   ME_CheckCharOffsets(ed);
1797   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1798     ed->selofs = SELECTIONBAR_WIDTH;
1799   else
1800     ed->selofs = 0;
1801   ed->nSelectionType = stPosition;
1802 
1803   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1804     ed->cPasswordMask = '*';
1805   else
1806     ed->cPasswordMask = 0;
1807   
1808   ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
1809 
1810   /* Default vertical scrollbar information */
1811   ed->vert_si.cbSize = sizeof(SCROLLINFO);
1812   ed->vert_si.nMin = 0;
1813   ed->vert_si.nMax = 0;
1814   ed->vert_si.nPage = 0;
1815   ed->vert_si.nPos = 0;
1816 
1817   return ed;
1818 }
1819 
1820 typedef struct tagME_GlobalDestStruct
1821 {
1822   HGLOBAL hData;
1823   int nLength;
1824 } ME_GlobalDestStruct;
1825 
1826 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1827 {
1828   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1829   int i;
1830   WORD *pSrc, *pDest;
1831   
1832   cb = cb >> 1;
1833   pDest = (WORD *)lpBuff;
1834   pSrc = (WORD *)GlobalLock(pData->hData);
1835   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1836     pDest[i] = pSrc[pData->nLength+i];
1837   }    
1838   pData->nLength += i;
1839   *pcb = 2*i;
1840   GlobalUnlock(pData->hData);
1841   return 0;
1842 }
1843 
1844 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1845 {
1846   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1847   int i;
1848   BYTE *pSrc, *pDest;
1849   
1850   pDest = lpBuff;
1851   pSrc = (BYTE *)GlobalLock(pData->hData);
1852   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1853     pDest[i] = pSrc[pData->nLength+i];
1854   }    
1855   pData->nLength += i;
1856   *pcb = i;
1857   GlobalUnlock(pData->hData);
1858   return 0;
1859 }
1860 
1861 
1862 void ME_DestroyEditor(ME_TextEditor *editor)
1863 {
1864   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1865   ME_DisplayItem *p = pFirst, *pNext = NULL;
1866   int i;
1867 
1868   ME_ClearTempStyle(editor);
1869   ME_EmptyUndoStack(editor);
1870   while(p) {
1871     pNext = p->next;
1872     ME_DestroyDisplayItem(p);
1873     p = pNext;
1874   }
1875   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1876   for (i=0; i<HFONT_CACHE_SIZE; i++)
1877   {
1878     if (editor->pFontCache[i].hFont)
1879       DeleteObject(editor->pFontCache[i].hFont);
1880   }
1881   if (editor->rgbBackColor != -1)
1882     DeleteObject(editor->hbrBackground);
1883   if(editor->lpOleCallback)
1884     IUnknown_Release(editor->lpOleCallback);
1885 
1886   FREE_OBJ(editor->pBuffer);
1887   FREE_OBJ(editor->pCursors);
1888 
1889   FREE_OBJ(editor);
1890 }
1891 
1892 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1893 {
1894     TRACE("\n");
1895     switch (fdwReason)
1896     {
1897     case DLL_PROCESS_ATTACH:
1898       DisableThreadLibraryCalls(hinstDLL);
1899       me_heap = HeapCreate (0, 0x10000, 0);
1900       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1901       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1902       LookupInit();
1903       break;
1904 
1905     case DLL_PROCESS_DETACH:
1906       UnregisterClassW(RichEdit20W, 0);
1907       UnregisterClassW(RichEdit50W, 0);
1908       UnregisterClassA("RichEdit20A", 0);
1909       UnregisterClassA("RichEdit50A", 0);
1910       if (ME_ListBoxRegistered)
1911           UnregisterClassW(REListBox20W, 0);
1912       if (ME_ComboBoxRegistered)
1913           UnregisterClassW(REComboBox20W, 0);
1914       LookupCleanup();
1915       HeapDestroy (me_heap);
1916       me_heap = NULL;
1917       break;
1918     }
1919     return TRUE;
1920 }
1921 
1922 
1923 #define UNSUPPORTED_MSG(e) \
1924   case e: \
1925     FIXME(#e ": stub\n"); \
1926     return DefWindowProcW(hWnd, msg, wParam, lParam);
1927 
1928 static const char * const edit_messages[] = {
1929   "EM_GETSEL",
1930   "EM_SETSEL",
1931   "EM_GETRECT",
1932   "EM_SETRECT",
1933   "EM_SETRECTNP",
1934   "EM_SCROLL",
1935   "EM_LINESCROLL",
1936   "EM_SCROLLCARET",
1937   "EM_GETMODIFY",
1938   "EM_SETMODIFY",
1939   "EM_GETLINECOUNT",
1940   "EM_LINEINDEX",
1941   "EM_SETHANDLE",
1942   "EM_GETHANDLE",
1943   "EM_GETTHUMB",
1944   "EM_UNKNOWN_BF",
1945   "EM_UNKNOWN_C0",
1946   "EM_LINELENGTH",
1947   "EM_REPLACESEL",
1948   "EM_UNKNOWN_C3",
1949   "EM_GETLINE",
1950   "EM_LIMITTEXT",
1951   "EM_CANUNDO",
1952   "EM_UNDO",
1953   "EM_FMTLINES",
1954   "EM_LINEFROMCHAR",
1955   "EM_UNKNOWN_CA",
1956   "EM_SETTABSTOPS",
1957   "EM_SETPASSWORDCHAR",
1958   "EM_EMPTYUNDOBUFFER",
1959   "EM_GETFIRSTVISIBLELINE",
1960   "EM_SETREADONLY",
1961   "EM_SETWORDBREAKPROC",
1962   "EM_GETWORDBREAKPROC",
1963   "EM_GETPASSWORDCHAR",
1964   "EM_SETMARGINS",
1965   "EM_GETMARGINS",
1966   "EM_GETLIMITTEXT",
1967   "EM_POSFROMCHAR",
1968   "EM_CHARFROMPOS"
1969 };
1970 
1971 static const char * const richedit_messages[] = {
1972   "EM_CANPASTE",
1973   "EM_DISPLAYBAND",
1974   "EM_EXGETSEL",
1975   "EM_EXLIMITTEXT",
1976   "EM_EXLINEFROMCHAR",
1977   "EM_EXSETSEL",
1978   "EM_FINDTEXT",
1979   "EM_FORMATRANGE",
1980   "EM_GETCHARFORMAT",
1981   "EM_GETEVENTMASK",
1982   "EM_GETOLEINTERFACE",
1983   "EM_GETPARAFORMAT",
1984   "EM_GETSELTEXT",
1985   "EM_HIDESELECTION", 
1986   "EM_PASTESPECIAL",
1987   "EM_REQUESTRESIZE",
1988   "EM_SELECTIONTYPE",
1989   "EM_SETBKGNDCOLOR",
1990   "EM_SETCHARFORMAT",
1991   "EM_SETEVENTMASK",
1992   "EM_SETOLECALLBACK",
1993   "EM_SETPARAFORMAT",
1994   "EM_SETTARGETDEVICE",
1995   "EM_STREAMIN",
1996   "EM_STREAMOUT",
1997   "EM_GETTEXTRANGE",
1998   "EM_FINDWORDBREAK",
1999   "EM_SETOPTIONS",
2000   "EM_GETOPTIONS",
2001   "EM_FINDTEXTEX",
2002   "EM_GETWORDBREAKPROCEX",
2003   "EM_SETWORDBREAKPROCEX",
2004   "EM_SETUNDOLIMIT",
2005   "EM_UNKNOWN_USER_83",
2006   "EM_REDO",
2007   "EM_CANREDO",
2008   "EM_GETUNDONAME",
2009   "EM_GETREDONAME",
2010   "EM_STOPGROUPTYPING",
2011   "EM_SETTEXTMODE",
2012   "EM_GETTEXTMODE",
2013   "EM_AUTOURLDETECT",
2014   "EM_GETAUTOURLDETECT",
2015   "EM_SETPALETTE",
2016   "EM_GETTEXTEX",
2017   "EM_GETTEXTLENGTHEX",
2018   "EM_SHOWSCROLLBAR",
2019   "EM_SETTEXTEX",
2020   "EM_UNKNOWN_USER_98",
2021   "EM_UNKNOWN_USER_99",
2022   "EM_SETPUNCTUATION",
2023   "EM_GETPUNCTUATION",
2024   "EM_SETWORDWRAPMODE",
2025   "EM_GETWORDWRAPMODE",
2026   "EM_SETIMECOLOR",
2027   "EM_GETIMECOLOR",
2028   "EM_SETIMEOPTIONS",
2029   "EM_GETIMEOPTIONS",
2030   "EM_CONVPOSITION",
2031   "EM_UNKNOWN_USER_109",
2032   "EM_UNKNOWN_USER_110",
2033   "EM_UNKNOWN_USER_111",
2034   "EM_UNKNOWN_USER_112",
2035   "EM_UNKNOWN_USER_113",
2036   "EM_UNKNOWN_USER_114",
2037   "EM_UNKNOWN_USER_115",
2038   "EM_UNKNOWN_USER_116",
2039   "EM_UNKNOWN_USER_117",
2040   "EM_UNKNOWN_USER_118",
2041   "EM_UNKNOWN_USER_119",
2042   "EM_SETLANGOPTIONS",
2043   "EM_GETLANGOPTIONS",
2044   "EM_GETIMECOMPMODE",
2045   "EM_FINDTEXTW",
2046   "EM_FINDTEXTEXW",
2047   "EM_RECONVERSION",
2048   "EM_SETIMEMODEBIAS",
2049   "EM_GETIMEMODEBIAS"
2050 };
2051 
2052 static const char *
2053 get_msg_name(UINT msg)
2054 {
2055   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2056     return edit_messages[msg - EM_GETSEL];
2057   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2058     return richedit_messages[msg - EM_CANPASTE];
2059   return "";
2060 }
2061 
2062 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2063                                       LPARAM lParam, BOOL unicode)
2064 {
2065   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2066   
2067   TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2068         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2069   
2070   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2071     ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2072     return 0; 
2073   }
2074 
2075   switch(msg) {
2076   
2077   UNSUPPORTED_MSG(EM_DISPLAYBAND)
2078   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2079   UNSUPPORTED_MSG(EM_FMTLINES)
2080   UNSUPPORTED_MSG(EM_FORMATRANGE)
2081   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2082   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2083   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2084   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2085   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2086   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2087   UNSUPPORTED_MSG(EM_GETREDONAME)
2088   UNSUPPORTED_MSG(EM_GETTEXTMODE)
2089   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2090   UNSUPPORTED_MSG(EM_GETUNDONAME)
2091   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2092   UNSUPPORTED_MSG(EM_PASTESPECIAL)
2093   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2094   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2095   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2096   UNSUPPORTED_MSG(EM_SETFONTSIZE)
2097   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2098   UNSUPPORTED_MSG(EM_SETPALETTE)
2099   UNSUPPORTED_MSG(EM_SETTABSTOPS)
2100   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2101   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2102   UNSUPPORTED_MSG(WM_STYLECHANGING)
2103   UNSUPPORTED_MSG(WM_STYLECHANGED)
2104 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
2105     
2106 /* Messages specific to Richedit controls */
2107   
2108   case EM_STREAMIN:
2109    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2110   case EM_STREAMOUT:
2111    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2112   case WM_GETDLGCODE:
2113   {
2114     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2115     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2116     {
2117       int vk = (int)((LPMSG)lParam)->wParam;
2118       /* if style says we want return key */
2119       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2120       {
2121         code |= DLGC_WANTMESSAGE;
2122       }
2123       /* we always handle ctrl-tab */
2124       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2125       {
2126         code |= DLGC_WANTMESSAGE;
2127       }
2128     }
2129     return code;
2130   }
2131   case WM_NCCREATE:
2132   {
2133     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2134     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2135     editor = ME_MakeEditor(hWnd);
2136     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2137     return TRUE;
2138   }
2139   case EM_EMPTYUNDOBUFFER:
2140     ME_EmptyUndoStack(editor);
2141     return 0;
2142   case EM_GETSEL:
2143   {
2144     /* Note: wParam/lParam can be NULL */
2145     UINT from, to;
2146     PUINT pfrom = wParam ? (PUINT)wParam : &from;
2147     PUINT pto = lParam ? (PUINT)lParam : &to;
2148     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2149     if ((*pfrom|*pto) & 0xFFFF0000)
2150       return -1;
2151     return MAKELONG(*pfrom,*pto);
2152   }
2153   case EM_EXGETSEL:
2154   {
2155     CHARRANGE *pRange = (CHARRANGE *)lParam;
2156     ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2157     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2158     return 0;
2159   }
2160   case EM_SETUNDOLIMIT:
2161   {
2162     if ((int)wParam < 0)
2163       editor->nUndoLimit = STACK_SIZE_DEFAULT;
2164     else
2165       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2166     /* Setting a max stack size keeps wine from getting killed 
2167       for hogging memory. Windows allocates all this memory at once, so
2168       no program would realistically set a value above our maximum. */
2169     return editor->nUndoLimit;
2170   }
2171   case EM_CANUNDO:
2172     return editor->pUndoStack != NULL;
2173   case EM_CANREDO:
2174     return editor->pRedoStack != NULL;
2175   case WM_UNDO: /* FIXME: actually not the same */
2176   case EM_UNDO:
2177     return ME_Undo(editor);
2178   case EM_REDO:
2179     return ME_Redo(editor);
2180   case EM_GETOPTIONS:
2181   {
2182     /* these flags are equivalent to the ES_* counterparts */
2183     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2184                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2185     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2186 
2187     return settings;
2188   }
2189   case EM_SETOPTIONS:
2190   {
2191     /* these flags are equivalent to ES_* counterparts                      
2192      * ECO_READONLY is already implemented in the code, only requires 
2193      * setting the bit to work                                        
2194      */
2195     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2196                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2197     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2198     DWORD settings = mask & raw;
2199 
2200     switch(wParam)
2201     {
2202       case ECOOP_SET:
2203         settings = lParam;
2204         break;
2205       case ECOOP_OR:
2206         settings |= lParam;
2207         break;
2208       case ECOOP_AND:
2209         settings &= lParam;
2210         break;
2211       case ECOOP_XOR:
2212         settings ^= lParam;
2213     }
2214     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2215 
2216     if (settings & ECO_AUTOWORDSELECTION)
2217       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2218     if (settings & ECO_SELECTIONBAR)
2219         editor->selofs = SELECTIONBAR_WIDTH;
2220     else
2221         editor->selofs = 0;
2222     ME_WrapMarkedParagraphs(editor);
2223 
2224     if (settings & ECO_VERTICAL)
2225       FIXME("ECO_VERTICAL not implemented yet!\n");
2226     if (settings & ECO_AUTOHSCROLL)
2227       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2228     if (settings & ECO_AUTOVSCROLL)
2229       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2230     if (settings & ECO_NOHIDESEL)
2231       FIXME("ECO_NOHIDESEL not implemented yet!\n");
2232     if (settings & ECO_WANTRETURN)
2233       FIXME("ECO_WANTRETURN not implemented yet!\n");
2234 
2235     return settings;
2236   }
2237   case EM_SETSEL:
2238   {
2239     ME_InvalidateSelection(editor);
2240     ME_SetSelection(editor, wParam, lParam);
2241     ME_InvalidateSelection(editor);
2242     HideCaret(editor->hWnd);
2243     ME_ShowCaret(editor);
2244     ME_SendSelChange(editor);
2245     return 0;
2246   }
2247   case EM_SETSCROLLPOS:
2248   {
2249     POINT *point = (POINT *)lParam;
2250     ME_ScrollAbs(editor, point->y);
2251     return 0;
2252   }
2253   case EM_AUTOURLDETECT:
2254   {
2255     if (wParam==1 || wParam ==0) 
2256     {
2257         editor->AutoURLDetect_bEnable = (BOOL)wParam;
2258         return 0;
2259     }
2260     return E_INVALIDARG;
2261   }
2262   case EM_GETAUTOURLDETECT:
2263   {
2264     return editor->AutoURLDetect_bEnable;
2265   }
2266   case EM_EXSETSEL:
2267   {
2268     int end;
2269     CHARRANGE range = *(CHARRANGE *)lParam;
2270 
2271     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2272 
2273     ME_InvalidateSelection(editor);
2274     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2275     ME_InvalidateSelection(editor);
2276     HideCaret(editor->hWnd);
2277     ME_ShowCaret(editor);
2278     ME_SendSelChange(editor);
2279 
2280     return end;
2281   }
2282   case EM_SHOWSCROLLBAR:
2283   {
2284     ShowScrollBar(editor->hWnd, wParam, lParam);
2285     return 0;
2286   }
2287   case EM_SETTEXTEX:
2288   {
2289     LPWSTR wszText;
2290     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2291     size_t len;
2292     int from, to;
2293     ME_Style *style;
2294     int oldModify = editor->nModifyStep;
2295 
2296     if (!pStruct) return 0;
2297 
2298     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2299           pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2300           pStruct->flags, pStruct->codepage);
2301 
2302     /* FIXME: make use of pStruct->codepage in the to unicode translation */
2303     wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2304     len = wszText ? lstrlenW(wszText) : 0;
2305 
2306     if (pStruct->flags & ST_SELECTION) {
2307       ME_GetSelection(editor, &from, &to);
2308       style = ME_GetSelectionInsertStyle(editor);
2309       ME_InternalDeleteText(editor, from, to - from);
2310       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2311           ME_StreamInRTFString(editor, 0, (char *)lParam);
2312       else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2313       ME_ReleaseStyle(style);
2314 
2315       if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2316     }
2317     else {
2318       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2319       if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2320           ME_StreamInRTFString(editor, 0, (char *)lParam);
2321       else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2322       len = 1;
2323 
2324       if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2325     }
2326     ME_CommitUndo(editor);
2327     if (!(pStruct->flags & ST_KEEPUNDO))
2328     {
2329       editor->nModifyStep = oldModify;
2330       ME_EmptyUndoStack(editor);
2331     }
2332     ME_UpdateRepaint(editor);
2333     return len;
2334   }
2335   case EM_SETBKGNDCOLOR:
2336   {
2337     LRESULT lColor;
2338     if (editor->rgbBackColor != -1) {
2339       DeleteObject(editor->hbrBackground);
2340       lColor = editor->rgbBackColor;
2341     }
2342     else lColor = GetSysColor(COLOR_WINDOW);
2343 
2344     if (wParam)
2345     {
2346       editor->rgbBackColor = -1;
2347       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2348     }
2349     else
2350     {
2351       editor->rgbBackColor = lParam;
2352       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2353     }
2354     if (editor->bRedraw)
2355     {
2356       InvalidateRect(hWnd, NULL, TRUE);
2357       UpdateWindow(hWnd);
2358     }
2359     return lColor;
2360   }
2361   case EM_GETMODIFY:
2362     return editor->nModifyStep == 0 ? 0 : -1;
2363   case EM_SETMODIFY:
2364   {
2365     if (wParam)
2366       editor->nModifyStep = 1;
2367     else
2368       editor->nModifyStep = 0;
2369     
2370     return 0;
2371   }
2372   case EM_SETREADONLY:
2373   {
2374     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2375     if (wParam)
2376       nStyle |= ES_READONLY;
2377     else
2378       nStyle &= ~ES_READONLY;
2379     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2380     return 0;
2381   }
2382   case EM_SETEVENTMASK:
2383   {
2384     DWORD nOldMask = editor->nEventMask;
2385     
2386     editor->nEventMask = lParam;
2387     return nOldMask;
2388   }
2389   case EM_GETEVENTMASK:
2390     return editor->nEventMask;
2391   case EM_SETCHARFORMAT:
2392   {
2393     CHARFORMAT2W buf, *p;
2394     BOOL bRepaint = TRUE;
2395     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2396     if (p == NULL) return 0;
2397     if (!wParam)
2398       ME_SetDefaultCharFormat(editor, p);
2399     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2400       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2401       return 0;
2402     } else if (wParam == SCF_ALL) {
2403       if (editor->mode & TM_PLAINTEXT)
2404         ME_SetDefaultCharFormat(editor, p);
2405       else {
2406         ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2407         editor->nModifyStep = 1;
2408       }
2409     } else if (editor->mode & TM_PLAINTEXT) {
2410       return 0;
2411     } else {
2412       int from, to;
2413       ME_GetSelection(editor, &from, &to);
2414       bRepaint = (from != to);
2415       ME_SetSelectionCharFormat(editor, p);
2416       if (from != to) editor->nModifyStep = 1;
2417     }
2418     ME_CommitUndo(editor);
2419     if (bRepaint)
2420       ME_RewrapRepaint(editor);
2421     return 1;
2422   }
2423   case EM_GETCHARFORMAT:
2424   {
2425     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2426     if (dst->cbSize != sizeof(CHARFORMATA) &&
2427         dst->cbSize != sizeof(CHARFORMATW) &&
2428         dst->cbSize != sizeof(CHARFORMAT2A) &&
2429         dst->cbSize != sizeof(CHARFORMAT2W))
2430       return 0;
2431     tmp.cbSize = sizeof(tmp);
2432     if (!wParam)
2433       ME_GetDefaultCharFormat(editor, &tmp);
2434     else
2435       ME_GetSelectionCharFormat(editor, &tmp);
2436     ME_CopyToCFAny(dst, &tmp);
2437     return tmp.dwMask;
2438   }
2439   case EM_SETPARAFORMAT:
2440     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2441     ME_RewrapRepaint(editor);
2442     ME_CommitUndo(editor);
2443     return 0;
2444   case EM_GETPARAFORMAT:
2445     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2446     return 0;
2447   case EM_GETFIRSTVISIBLELINE:
2448   {
2449     ME_DisplayItem *p = editor->pBuffer->pFirst;
2450     int y = ME_GetYScrollPos(editor);
2451     int ypara = 0;
2452     int count = 0;
2453     int ystart, yend;
2454     while(p) {
2455       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2456       if (p->type == diTextEnd)
2457         break;
2458       if (p->type == diParagraph) {
2459         ypara = p->member.para.nYPos;
2460         continue;
2461       }
2462       ystart = ypara + p->member.row.nYPos;
2463       yend = ystart + p->member.row.nHeight;
2464       if (y < yend) {
2465         break;
2466       }
2467       count++;
2468     }
2469     return count;
2470   }
2471   case EM_HIDESELECTION:
2472   {
2473      editor->bHideSelection = (wParam != 0);
2474      ME_InvalidateSelection(editor);
2475      return 0;
2476   }
2477   case EM_LINESCROLL:
2478   {
2479     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2480     return TRUE; /* Should return false if a single line richedit control */
2481   }
2482   case WM_CLEAR:
2483   {
2484     int from, to;
2485     ME_GetSelection(editor, &from, &to);
2486     ME_InternalDeleteText(editor, from, to-from);
2487     ME_CommitUndo(editor);
2488     ME_UpdateRepaint(editor);
2489     return 0;
2490   }
2491   case EM_REPLACESEL:
2492   {
2493     int from, to;
2494     ME_Style *style;
2495     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2496     size_t len = wszText ? lstrlenW(wszText) : 0;
2497     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2498 
2499     ME_GetSelection(editor, &from, &to);
2500     style = ME_GetSelectionInsertStyle(editor);
2501     ME_InternalDeleteText(editor, from, to-from);
2502     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2503     ME_ReleaseStyle(style);
2504     /* drop temporary style if line end */
2505     /*
2506      * FIXME question: does abc\n mean: put abc,
2507      * clear temp style, put \n? (would require a change)
2508      */
2509     if (len>0 && wszText[len-1] == '\n')
2510       ME_ClearTempStyle(editor);
2511     ME_EndToUnicode(unicode, wszText);
2512     ME_CommitUndo(editor);
2513     if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2514     if (!wParam)
2515       ME_EmptyUndoStack(editor);
2516     ME_UpdateRepaint(editor);
2517     return len;
2518   }
2519   case EM_SCROLLCARET:
2520   {
2521     int top, bottom; /* row's edges relative to document top */
2522     int nPos;
2523     ME_DisplayItem *para, *row;
2524     
2525     nPos = ME_GetYScrollPos(editor);
2526     row = ME_RowStart(editor->pCursors[0].pRun);
2527     para = ME_GetParagraph(row);
2528     top = para->member.para.nYPos + row->member.row.nYPos;
2529     bottom = top + row->member.row.nHeight;
2530     
2531     if (top < nPos) /* caret above window */
2532       ME_ScrollAbs(editor,  top);
2533     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2534       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2535     return 0;
2536   }
2537   case WM_SETFONT:
2538   {
2539     LOGFONTW lf;
2540     CHARFORMAT2W fmt;
2541     HDC hDC;
2542     BOOL bRepaint = LOWORD(lParam);
2543     
2544     if (!wParam)
2545       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
2546     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2547     hDC = GetDC(hWnd);
2548     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
2549     ReleaseDC(hWnd, hDC);   
2550     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2551     ME_SetDefaultCharFormat(editor, &fmt);
2552 
2553     ME_CommitUndo(editor);
2554     if (bRepaint)
2555       ME_RewrapRepaint(editor);
2556     return 0;
2557   }
2558   case WM_SETTEXT:
2559   {
2560     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2561     if (lParam)
2562     {
2563       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2564       if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2565       {
2566         /* Undocumented: WM_SETTEXT supports RTF text */
2567         ME_StreamInRTFString(editor, 0, (char *)lParam);
2568       }
2569       else
2570       {
2571         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2572         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2573         if (lstrlenW(wszText) > 0)
2574         {
2575           int len = -1;
2576 
2577           /* uses default style! */
2578           if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2579           {
2580             WCHAR * p;
2581 
2582             p = wszText;
2583             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2584             len = p - wszText;
2585           }
2586           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2587         }
2588         ME_EndToUnicode(unicode, wszText);
2589       }
2590     }
2591     else
2592       TRACE("WM_SETTEXT - NULL\n");
2593     if (editor->AutoURLDetect_bEnable)
2594     {
2595       ME_UpdateLinkAttribute(editor, 0, -1);
2596     }
2597     ME_SetSelection(editor, 0, 0);
2598     editor->nModifyStep = 0;
2599     ME_CommitUndo(editor);
2600     ME_EmptyUndoStack(editor);
2601     ME_UpdateRepaint(editor);
2602     return 1;
2603   }
2604   case EM_CANPASTE:
2605   {
2606     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2607     if (IsClipboardFormatAvailable(nRTFFormat))
2608       return TRUE;
2609     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2610       return TRUE;
2611     return FALSE;
2612   }
2613   case WM_PASTE:
2614   {    
2615     DWORD dwFormat = 0;
2616     EDITSTREAM es;
2617     ME_GlobalDestStruct gds;
2618     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2619     UINT cf = 0;
2620 
2621     if (IsClipboardFormatAvailable(nRTFFormat))
2622       cf = nRTFFormat, dwFormat = SF_RTF;
2623     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2624       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2625     else
2626       return 0;
2627 
2628     if (!OpenClipboard(hWnd))
2629       return 0;
2630     gds.hData = GetClipboardData(cf);
2631     gds.nLength = 0;
2632     es.dwCookie = (DWORD)&gds;
2633     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2634     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2635 
2636     CloseClipboard();
2637     return 0;
2638   }
2639   case WM_CUT:
2640   case WM_COPY:
2641   {
2642     LPDATAOBJECT dataObj = NULL;
2643     CHARRANGE range;
2644     HRESULT hr = S_OK;
2645 
2646     if (editor->cPasswordMask)
2647       return 0; /* Copying or Cutting masked text isn't allowed */
2648 
2649     ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2650     if(editor->lpOleCallback)
2651         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2652     if(FAILED(hr) || !dataObj)
2653         hr = ME_GetDataObject(editor, &range, &dataObj);
2654     if(SUCCEEDED(hr)) {
2655         hr = OleSetClipboard(dataObj);
2656         IDataObject_Release(dataObj);
2657     }
2658     if (SUCCEEDED(hr) && msg == WM_CUT)
2659     {
2660       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2661       ME_CommitUndo(editor);
2662       ME_UpdateRepaint(editor);
2663     }
2664     return 0;
2665   }
2666   case WM_GETTEXTLENGTH:
2667   {
2668     GETTEXTLENGTHEX how;
2669 
2670     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2671     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2672     how.codepage = unicode ? 1200 : CP_ACP;
2673     return ME_GetTextLengthEx(editor, &how);
2674   }
2675   case EM_GETTEXTLENGTHEX:
2676     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2677   case WM_GETTEXT:
2678   {
2679     GETTEXTEX ex;
2680     LRESULT rc;
2681     LPSTR bufferA = NULL;
2682     LPWSTR bufferW = NULL;
2683 
2684     if (unicode)
2685         bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2686     else
2687         bufferA = heap_alloc(wParam + 2);
2688 
2689     ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2690     ex.flags = GT_USECRLF;
2691     ex.codepage = unicode ? 1200 : CP_ACP;
2692     ex.lpDefaultChar = NULL;
2693     ex.lpUsedDefChar = NULL;
2694     rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2695 
2696     if (unicode)
2697     {
2698         memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2699         if (lstrlenW(bufferW) >= wParam) rc = 0;
2700     }
2701     else
2702     {
2703         memcpy((LPSTR)lParam, bufferA, wParam);
2704         if (strlen(bufferA) >= wParam) rc = 0;
2705     }
2706     heap_free(bufferA);
2707     heap_free(bufferW);
2708     return rc;
2709   }
2710   case EM_GETTEXTEX:
2711   {
2712     GETTEXTEX *ex = (GETTEXTEX*)wParam;
2713     int nStart, nCount; /* in chars */
2714 
2715     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2716       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2717 
2718     if (ex->flags & GT_SELECTION)
2719     {
2720       ME_GetSelection(editor, &nStart, &nCount);
2721       nCount -= nStart;
2722     }
2723     else
2724     {
2725       nStart = 0;
2726       nCount = 0x7fffffff;
2727     }
2728     if (ex->codepage == 1200)
2729     {
2730       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2731       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2732     }
2733     else
2734     {
2735       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2736         we can just take a bigger buffer? :)
2737         The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2738         occurs only in richedit 2.0 mode, in which line breaks have only one CR
2739        */
2740       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2741       LPWSTR buffer;
2742       DWORD buflen = ex->cb;
2743       LRESULT rc;
2744       DWORD flags = 0;
2745 
2746       nCount = min(nCount, ex->cb - 1);
2747       buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2748 
2749       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2750       rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2751       if (rc) rc--; /* do not count 0 terminator */
2752 
2753       heap_free(buffer);
2754       return rc;
2755     }
2756   }
2757   case EM_GETSELTEXT:
2758   {
2759     int from, to;
2760     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2761     ME_GetSelection(editor, &from, &to);
2762     tr.chrg.cpMin = from;
2763     tr.chrg.cpMax = to;
2764     tr.lpstrText = (WCHAR *)lParam;
2765     return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2766   }
2767   case EM_GETSCROLLPOS:
2768   {
2769       POINT *point = (POINT *)lParam;
2770       point->x = 0; /* FIXME side scrolling not implemented */
2771       point->y = ME_GetYScrollPos(editor);
2772       return 1;
2773   }
2774   case EM_GETTEXTRANGE:
2775   {
2776     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2777     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2778       rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2779       editor->bEmulateVersion10, ME_GetTextLength(editor));
2780     if (unicode)
2781       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
2782     else
2783     {
2784       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2785       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2786       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
2787       /* FIXME this is a potential security hole (buffer overrun) 
2788          if you know more about wchar->mbyte conversion please explain
2789       */
2790       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2791       FREE_OBJ(p);
2792       return nChars;
2793     }
2794   }
2795   case EM_GETLINE:
2796   {
2797     ME_DisplayItem *run;
2798     const unsigned int nMaxChars = *(WORD *) lParam;
2799     unsigned int nCharsLeft = nMaxChars;
2800     char *dest = (char *) lParam;
2801     BOOL wroteNull = FALSE;
2802 
2803     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2804           unicode ? "Unicode" : "Ansi");
2805 
2806     run = ME_FindRowWithNumber(editor, wParam);
2807     if (run == NULL)
2808       return 0;
2809 
2810     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2811            && !(run->member.run.nFlags & MERF_ENDPARA))
2812     {
2813       unsigned int nCopy;
2814       ME_String *strText;
2815       if (run->type != diRun)
2816         break;
2817       strText = run->member.run.strText;
2818       nCopy = min(nCharsLeft, strText->nLen);
2819 
2820       if (unicode)
2821         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2822       else
2823         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2824                                     nCharsLeft, NULL, NULL);
2825       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2826       nCharsLeft -= nCopy;
2827     }
2828 
2829     /* append line termination, space allowing */
2830     if (nCharsLeft > 0)
2831     {
2832       if (run && (run->member.run.nFlags & MERF_ENDPARA))
2833       {
2834         unsigned int i;
2835         /* Write as many \r as encoded in end-of-paragraph, space allowing */
2836         for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
2837         {
2838           *((WCHAR *)dest) = '\r';
2839           dest += unicode ? sizeof(WCHAR) : 1;
2840         }
2841         /* Write as many \n as encoded in end-of-paragraph, space allowing */
2842         for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
2843         {
2844           *((WCHAR *)dest) = '\n';
2845           dest += unicode ? sizeof(WCHAR) : 1;
2846         }
2847       }
2848       if (nCharsLeft > 0)
2849       {
2850         if (unicode)
2851           *((WCHAR *)dest) = '\0';
2852         else
2853           *dest = '\0';
2854         nCharsLeft--;
2855         wroteNull = TRUE;
2856       }
2857     }
2858 
2859     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
2860     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
2861   }
2862   case EM_GETLINECOUNT:
2863   {
2864     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2865     int nRows = 0;
2866 
2867     ME_DisplayItem *prev_para = NULL, *last_para = NULL;
2868 
2869     while (item != editor->pBuffer->pLast)
2870     {
2871       assert(item->type == diParagraph);
2872       prev_para = ME_FindItemBack(item, diRun);
2873       if (prev_para) {
2874         assert(prev_para->member.run.nFlags & MERF_ENDPARA);
2875       }
2876       nRows += item->member.para.nRows;
2877       item = item->member.para.next_para;
2878     }
2879     last_para = ME_FindItemBack(item, diRun);
2880     assert(last_para);
2881     assert(last_para->member.run.nFlags & MERF_ENDPARA);
2882     if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
2883         && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
2884     {
2885       /* In 1.0 emulation, the last solitary \r at the very end of the text
2886          (if one exists) is NOT a line break.
2887          FIXME: this is an ugly hack. This should have a more regular model. */
2888       nRows--;
2889     }
2890 
2891     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2892     return max(1, nRows);
2893   }
2894   case EM_LINEFROMCHAR:
2895   {
2896     if (wParam == -1)
2897       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2898     else
2899       return ME_RowNumberFromCharOfs(editor, wParam);
2900   }
2901   case EM_EXLINEFROMCHAR:
2902   {
2903     if (lParam == -1)
2904       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2905     else    
2906       return ME_RowNumberFromCharOfs(editor, lParam);
2907   }
2908   case EM_LINEINDEX:
2909   {
2910     ME_DisplayItem *item, *para;
2911     int nCharOfs;
2912     
2913     if (wParam == -1)
2914       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2915     else
2916       item = ME_FindRowWithNumber(editor, wParam);
2917     if (!item)
2918       return -1;
2919     para = ME_GetParagraph(item);
2920     item = ME_FindItemFwd(item, diRun);
2921     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2922     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2923     return nCharOfs;
2924   }
2925   case EM_LINELENGTH:
2926   {
2927     ME_DisplayItem *item, *item_end;
2928     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2929     
2930     if (wParam > ME_GetTextLength(editor))
2931       return 0;
2932     if (wParam == -1)
2933     {
2934       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2935       return 0;
2936     }
2937     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2938     item = ME_RowStart(item);
2939     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2940     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2941     if (item_end->type == diStartRow)
2942       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2943     else
2944     {
2945       ME_DisplayItem *endPara;
2946 
2947       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
2948       endPara = ME_FindItemFwd(item, diParagraphOrEnd);
2949       endPara = ME_FindItemBack(endPara, diRun);
2950       assert(endPara);
2951       assert(endPara->type == diRun);
2952       assert(endPara->member.run.nFlags & MERF_ENDPARA);
2953       nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
2954     }
2955     nChars = nNextLineOfs - nThisLineOfs;
2956     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2957     return nChars;
2958   }
2959   case EM_EXLIMITTEXT:
2960   {
2961     if ((int)lParam < 0)
2962      return 0;
2963     if (lParam == 0)
2964       editor->nTextLimit = 65536;
2965     else
2966       editor->nTextLimit = (int) lParam;
2967     return 0;
2968   }
2969   case EM_LIMITTEXT:
2970   {
2971     if (wParam == 0)
2972       editor->nTextLimit = 65536;
2973     else
2974       editor->nTextLimit = (int) wParam;
2975     return 0;
2976   }
2977   case EM_GETLIMITTEXT:
2978   {
2979     return editor->nTextLimit;
2980   }
2981   case EM_FINDTEXT:
2982   {
2983     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2984     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2985     WCHAR *tmp;
2986     LRESULT r;
2987 
2988     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2989       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2990     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2991     FREE_OBJ( tmp );
2992     return r;
2993   }
2994   case EM_FINDTEXTEX:
2995   {
2996     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2997     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2998     WCHAR *tmp;
2999     LRESULT r;
3000 
3001     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3002       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3003     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3004     FREE_OBJ( tmp );
3005     return r;
3006   }
3007   case EM_FINDTEXTW:
3008   {
3009     FINDTEXTW *ft = (FINDTEXTW *)lParam;
3010     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3011   }
3012   case EM_FINDTEXTEXW:
3013   {
3014     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3015     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3016   }
3017   case EM_GETZOOM:
3018     if (!wParam || !lParam)
3019       return FALSE;
3020     *(int *)wParam = editor->nZoomNumerator;
3021     *(int *)lParam = editor->nZoomDenominator;
3022     return TRUE;
3023   case EM_SETZOOM:
3024     return ME_SetZoom(editor, wParam, lParam);
3025   case EM_CHARFROMPOS:
3026     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3027   case EM_POSFROMCHAR:
3028   {
3029     ME_DisplayItem *pRun;
3030     int nCharOfs, nOffset, nLength;
3031     POINTL pt = {0,0};
3032     SCROLLINFO si;
3033     
3034     nCharOfs = wParam; 
3035     /* detect which API version we're dealing with */
3036     if (wParam >= 0x40000)
3037         nCharOfs = lParam;
3038     nLength = ME_GetTextLength(editor);
3039     
3040     if (nCharOfs < nLength) { 
3041         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3042         assert(pRun->type == diRun);
3043         pt.y = pRun->member.run.pt.y;
3044         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3045         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
3046     } else {
3047         pt.x = 0;
3048         pt.y = editor->pBuffer->pLast->member.para.nYPos;
3049     }
3050     pt.x += editor->selofs;
3051 
3052     si.cbSize = sizeof(si);
3053     si.fMask = SIF_POS;
3054     if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3055     si.cbSize = sizeof(si);
3056     si.fMask = SIF_POS;
3057     if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3058 
3059     if (wParam >= 0x40000) {
3060         *(POINTL *)wParam = pt;
3061     }
3062     return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3063   }
3064   case WM_CREATE:
3065   {
3066     SCROLLINFO si;
3067 
3068     GetClientRect(hWnd, &editor->rcFormat);
3069     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3070     { /* Squelch the default horizontal scrollbar it would make */
3071       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3072     }
3073 
3074     si.cbSize = sizeof(si);
3075     si.fMask = SIF_PAGE | SIF_RANGE;
3076     if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3077       si.fMask |= SIF_DISABLENOSCROLL;
3078     si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3079     si.nMin = 0;
3080     si.nPage = 0;
3081     SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3082 
3083     ME_CommitUndo(editor);
3084     ME_WrapMarkedParagraphs(editor);
3085     ME_MoveCaret(editor);
3086     return 0;
3087   }
3088   case WM_DESTROY:
3089     ME_DestroyEditor(editor);
3090     SetWindowLongPtrW(hWnd, 0, 0);
3091     return 0;
3092   case WM_SETCURSOR:
3093   {
3094     return ME_SetCursor(editor);
3095   }
3096   case WM_LBUTTONDBLCLK:
3097   case WM_LBUTTONDOWN:
3098   {
3099     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3100     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3101         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3102       return 0;
3103     SetFocus(hWnd);
3104     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3105                    ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3106     SetCapture(hWnd);
3107     ME_LinkNotify(editor,msg,wParam,lParam);
3108     if (!ME_SetCursor(editor)) goto do_default;
3109     break;
3110   }
3111   case WM_MOUSEMOVE:
3112     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3113         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3114       return 0;
3115     if (GetCapture() == hWnd)
3116       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3117     ME_LinkNotify(editor,msg,wParam,lParam);
3118     /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3119     if (GetCapture() == hWnd)
3120         ME_SetCursor(editor);
3121     break;
3122   case WM_LBUTTONUP:
3123     if (GetCapture() == hWnd)
3124       ReleaseCapture();
3125     if (editor->nSelectionType == stDocument)
3126       editor->nSelectionType = stPosition;
3127     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3128         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3129       return 0;
3130     else
3131     {
3132       ME_SetCursor(editor);
3133       ME_LinkNotify(editor,msg,wParam,lParam);
3134     }
3135     break;
3136   case WM_RBUTTONUP:
3137   case WM_RBUTTONDOWN:
3138     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3139     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3140         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3141       return 0;
3142     goto do_default;
3143   case WM_CONTEXTMENU:
3144     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3145       goto do_default;
3146     break;
3147   case WM_PAINT:
3148     if (editor->bRedraw)
3149     {
3150       HDC hDC;
3151       PAINTSTRUCT ps;
3152 
3153       hDC = BeginPaint(hWnd, &ps);
3154       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3155       EndPaint(hWnd, &ps);
3156     }
3157     break;
3158   case WM_SETFOCUS:
3159     editor->bHaveFocus = TRUE;
3160     ME_ShowCaret(editor);
3161     ME_SendOldNotify(editor, EN_SETFOCUS);
3162     return 0;
3163   case WM_KILLFOCUS:
3164     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3165     editor->bHaveFocus = FALSE;
3166     ME_HideCaret(editor);
3167     ME_SendOldNotify(editor, EN_KILLFOCUS);
3168     return 0;
3169   case WM_ERASEBKGND:
3170   {
3171     if (editor->bRedraw)
3172     {
3173       HDC hDC = (HDC)wParam;
3174       RECT rc;
3175       if (GetUpdateRect(hWnd,&rc,TRUE))
3176       {
3177         FillRect(hDC, &rc, editor->hbrBackground);
3178       }
3179     }
3180     return 1;
3181   }
3182   case WM_COMMAND:
3183     TRACE("editor wnd command = %d\n", LOWORD(wParam));
3184     return 0;
3185   case WM_KEYUP:
3186     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3187         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3188       return 0;
3189     goto do_default;
3190   case WM_KEYDOWN:
3191     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3192         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3193       return 0;
3194     if (ME_KeyDown(editor, LOWORD(wParam)))
3195       return 0;
3196     goto do_default;
3197   case WM_CHAR: 
3198   {
3199     WCHAR wstr;
3200 
3201     if (unicode)
3202         wstr = (WCHAR)wParam;
3203     else
3204     {
3205         CHAR charA = wParam;
3206         MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3207     }
3208 
3209     switch (wstr)
3210     {
3211     case 1: /* Ctrl-A */
3212       ME_SetSelection(editor, 0, -1);
3213       return 0;
3214     case 3: /* Ctrl-C */
3215       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3216       return 0;
3217     }
3218     
3219     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3220       MessageBeep(MB_ICONERROR);
3221       return 0; /* FIXME really 0 ? */
3222     }
3223 
3224     switch (wstr)
3225     {
3226     case 22: /* Ctrl-V */
3227       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3228       return 0;
3229     case 24: /* Ctrl-X */
3230       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3231       return 0;
3232     case 25: /* Ctrl-Y */
3233       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3234       return 0;
3235     case 26: /* Ctrl-Z */
3236       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3237       return 0;
3238     }
3239     if (((unsigned)wstr)>=' '
3240         || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3241         || wstr=='\t') {
3242       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3243       /* WM_CHAR is restricted to nTextLimit */
3244       int from, to;
3245       ME_GetSelection(editor, &from, &to);
3246       if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3247       {
3248         ME_Style *style = ME_GetInsertStyle(editor, 0);
3249         ME_SaveTempStyle(editor);
3250         ME_ContinueCoalescingTransaction(editor);
3251         if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3252           ME_InsertEndRowFromCursor(editor, 0);
3253         else
3254           ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3255         ME_ReleaseStyle(style);
3256         ME_CommitCoalescingUndo(editor);
3257         SetCursor(NULL);
3258       }
3259 
3260       if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3261 
3262       ME_UpdateRepaint(editor);
3263     }
3264     return 0;
3265   }
3266   case EM_STOPGROUPTYPING:
3267     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3268     return 0;
3269   case EM_SCROLL: /* fall through */
3270   case WM_VSCROLL: 
3271   {
3272     int origNPos;
3273     int lineHeight;
3274     
3275     origNPos = ME_GetYScrollPos(editor);
3276     lineHeight = 24;
3277     
3278     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3279       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3280     if (lineHeight <= 0) lineHeight = 24;
3281     
3282     switch(LOWORD(wParam)) 
3283     {
3284       case SB_LINEUP:
3285         ME_ScrollUp(editor,lineHeight);
3286         break;
3287       case SB_LINEDOWN:
3288         ME_ScrollDown(editor,lineHeight);
3289         break;
3290       case SB_PAGEUP:
3291         ME_ScrollUp(editor,editor->sizeWindow.cy);
3292         break;
3293       case SB_PAGEDOWN:
3294         ME_ScrollDown(editor,editor->sizeWindow.cy);
3295         break;
3296       case SB_THUMBTRACK:
3297       case SB_THUMBPOSITION:
3298         ME_ScrollAbs(editor,HIWORD(wParam));