jscript: Rename jsheap_t to heap_pool_t.
[wine] / dlls / riched20 / run.c
1 /*
2  * RichEdit - operations on runs (diRun, rectangular pieces of paragraphs).
3  * Splitting/joining runs. Adjusting offsets after deleting/adding content.
4  * Character/pixel conversions.
5  *
6  * Copyright 2004 by Krzysztof Foltman
7  * Copyright 2006 by Phil Krylov
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 #include "editor.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
27 WINE_DECLARE_DEBUG_CHANNEL(richedit_check);
28 WINE_DECLARE_DEBUG_CHANNEL(richedit_lists);
29
30 /******************************************************************************
31  * ME_CanJoinRuns
32  *
33  * Returns 1 if two runs can be safely merged into one, 0 otherwise.
34  */ 
35 int ME_CanJoinRuns(const ME_Run *run1, const ME_Run *run2)
36 {
37   if ((run1->nFlags | run2->nFlags) & MERF_NOJOIN)
38     return 0;
39   if (run1->style != run2->style)
40     return 0;
41   if ((run1->nFlags & MERF_STYLEFLAGS) != (run2->nFlags & MERF_STYLEFLAGS))
42     return 0;
43   return 1;
44 }
45
46 void ME_SkipAndPropagateCharOffset(ME_DisplayItem *p, int shift)
47 {
48   p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
49   assert(p);
50   ME_PropagateCharOffset(p, shift);
51 }
52
53 /******************************************************************************
54  * ME_PropagateCharOffsets
55  *
56  * Shifts (increases or decreases) character offset (relative to beginning of 
57  * the document) of the part of the text starting from given place.  
58  */ 
59 void ME_PropagateCharOffset(ME_DisplayItem *p, int shift)
60 {
61         /* Runs in one paragraph contain character offset relative to their owning
62          * paragraph. If we start the shifting from the run, we need to shift
63          * all the relative offsets until the end of the paragraph
64          */                 
65   if (p->type == diRun) /* propagate in all runs in this para */
66   {
67     TRACE("PropagateCharOffset(%s, %d)\n", debugstr_run( &p->member.run ), shift);
68     do {
69       p->member.run.nCharOfs += shift;
70       assert(p->member.run.nCharOfs >= 0);
71       p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
72     } while(p->type == diRun);
73   }
74         /* Runs in next paragraphs don't need their offsets updated, because they, 
75          * again, those offsets are relative to their respective paragraphs.
76          * Instead of that, we're updating paragraphs' character offsets.         
77          */                 
78   if (p->type == diParagraph) /* propagate in all next paras */
79   {
80     do {
81       p->member.para.nCharOfs += shift;
82       assert(p->member.para.nCharOfs >= 0);
83       p = p->member.para.next_para;
84     } while(p->type == diParagraph);
85   }
86   /* diTextEnd also has character offset in it, which makes finding text length
87    * easier. But it needs to be up to date first.
88    */
89   if (p->type == diTextEnd)
90   {
91     p->member.para.nCharOfs += shift;
92     assert(p->member.para.nCharOfs >= 0);
93   }
94 }
95
96 /******************************************************************************
97  * ME_CheckCharOffsets
98  * 
99  * Checks if editor lists' validity and optionally dumps the document structure
100  */      
101 void ME_CheckCharOffsets(ME_TextEditor *editor)
102 {
103   ME_DisplayItem *p = editor->pBuffer->pFirst;
104   int ofs = 0, ofsp = 0;
105   if(TRACE_ON(richedit_lists))
106   {
107     TRACE_(richedit_lists)("---\n");
108     ME_DumpDocument(editor->pBuffer);
109   }
110   do {
111     p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
112     switch(p->type) {
113       case diTextEnd:
114         TRACE_(richedit_check)("tend, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
115         assert(ofsp+ofs == p->member.para.nCharOfs);
116         return;
117       case diParagraph:
118         TRACE_(richedit_check)("para, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
119         assert(ofsp+ofs == p->member.para.nCharOfs);
120         ofsp = p->member.para.nCharOfs;
121         ofs = 0;
122         break;
123       case diRun:
124         TRACE_(richedit_check)("run, real ofs = %d (+ofsp = %d), counted = %d, len = %d, txt = %s, flags=%08x, fx&mask = %08x\n",
125           p->member.run.nCharOfs, p->member.run.nCharOfs+ofsp, ofsp+ofs,
126           p->member.run.len, debugstr_run( &p->member.run ),
127           p->member.run.nFlags,
128           p->member.run.style->fmt.dwMask & p->member.run.style->fmt.dwEffects);
129         assert(ofs == p->member.run.nCharOfs);
130         assert(p->member.run.len);
131         ofs += p->member.run.len;
132         break;
133       case diCell:
134         TRACE_(richedit_check)("cell\n");
135         break;
136       default:
137         assert(0);
138     }
139   } while(1);
140 }
141
142 /******************************************************************************
143  * ME_CharOfsFromRunOfs
144  *
145  * Converts a character position relative to the start of the run, to a
146  * character position relative to the start of the document.
147  * Kind of a "local to global" offset conversion.
148  */
149 int ME_CharOfsFromRunOfs(ME_TextEditor *editor, const ME_DisplayItem *pPara,
150                          const ME_DisplayItem *pRun, int nOfs)
151 {
152   assert(pRun && pRun->type == diRun);
153   assert(pPara && pPara->type == diParagraph);
154   return pPara->member.para.nCharOfs + pRun->member.run.nCharOfs + nOfs;
155 }
156
157 /******************************************************************************
158  * ME_CursorFromCharOfs
159  *
160  * Converts a character offset (relative to the start of the document) to
161  * a cursor structure (which contains a run and a position relative to that
162  * run).
163  */
164 void ME_CursorFromCharOfs(ME_TextEditor *editor, int nCharOfs, ME_Cursor *pCursor)
165 {
166   ME_RunOfsFromCharOfs(editor, nCharOfs, &pCursor->pPara,
167                        &pCursor->pRun, &pCursor->nOffset);
168 }
169
170 /******************************************************************************
171  * ME_RunOfsFromCharOfs
172  *
173  * Find a run and relative character offset given an absolute character offset
174  * (absolute offset being an offset relative to the start of the document).
175  * Kind of a "global to local" offset conversion.
176  */
177 void ME_RunOfsFromCharOfs(ME_TextEditor *editor,
178                           int nCharOfs,
179                           ME_DisplayItem **ppPara,
180                           ME_DisplayItem **ppRun,
181                           int *pOfs)
182 {
183   ME_DisplayItem *item, *next_item;
184
185   nCharOfs = max(nCharOfs, 0);
186   nCharOfs = min(nCharOfs, ME_GetTextLength(editor));
187
188   /* Find the paragraph at the offset. */
189   next_item = editor->pBuffer->pFirst->member.para.next_para;
190   do {
191     item = next_item;
192     next_item = item->member.para.next_para;
193   } while (next_item->member.para.nCharOfs <= nCharOfs);
194   assert(item->type == diParagraph);
195   nCharOfs -= item->member.para.nCharOfs;
196   if (ppPara) *ppPara = item;
197
198   /* Find the run at the offset. */
199   next_item = ME_FindItemFwd(item, diRun);
200   do {
201     item = next_item;
202     next_item = ME_FindItemFwd(item, diRunOrParagraphOrEnd);
203   } while (next_item->type == diRun &&
204            next_item->member.run.nCharOfs <= nCharOfs);
205   assert(item->type == diRun);
206   nCharOfs -= item->member.run.nCharOfs;
207
208   if (ppRun) *ppRun = item;
209   if (pOfs) *pOfs = nCharOfs;
210 }
211
212 /******************************************************************************
213  * ME_JoinRuns
214  * 
215  * Merges two adjacent runs, the one given as a parameter and the next one.
216  */    
217 void ME_JoinRuns(ME_TextEditor *editor, ME_DisplayItem *p)
218 {
219   ME_DisplayItem *pNext = p->next;
220   int i;
221   assert(p->type == diRun && pNext->type == diRun);
222   assert(p->member.run.nCharOfs != -1);
223   ME_GetParagraph(p)->member.para.nFlags |= MEPF_REWRAP;
224
225   /* Update all cursors so that they don't contain the soon deleted run */
226   for (i=0; i<editor->nCursors; i++) {
227     if (editor->pCursors[i].pRun == pNext) {
228       editor->pCursors[i].pRun = p;
229       editor->pCursors[i].nOffset += p->member.run.len;
230     }
231   }
232
233   p->member.run.len += pNext->member.run.len;
234   ME_Remove(pNext);
235   ME_DestroyDisplayItem(pNext);
236   ME_UpdateRunFlags(editor, &p->member.run);
237   if(TRACE_ON(richedit))
238   {
239     TRACE("Before check after join\n");
240     ME_CheckCharOffsets(editor);
241     TRACE("After check after join\n");
242   }
243 }
244
245 /******************************************************************************
246  * ME_SplitRunSimple
247  *
248  * Does the most basic job of splitting a run into two - it does not
249  * update the positions and extents.
250  */
251 ME_DisplayItem *ME_SplitRunSimple(ME_TextEditor *editor, ME_Cursor *cursor)
252 {
253   ME_DisplayItem *run = cursor->pRun;
254   ME_DisplayItem *new_run;
255   int i;
256   int nOffset = cursor->nOffset;
257
258   assert(!(run->member.run.nFlags & MERF_NONTEXT));
259
260   new_run = ME_MakeRun(run->member.run.style,
261                        run->member.run.nFlags & MERF_SPLITMASK);
262   new_run->member.run.nCharOfs = run->member.run.nCharOfs + nOffset;
263   new_run->member.run.len = run->member.run.len - nOffset;
264   new_run->member.run.para = run->member.run.para;
265   run->member.run.len = nOffset;
266   cursor->pRun = new_run;
267   cursor->nOffset = 0;
268
269   ME_InsertBefore(run->next, new_run);
270
271   ME_UpdateRunFlags(editor, &run->member.run);
272   ME_UpdateRunFlags(editor, &new_run->member.run);
273   for (i = 0; i < editor->nCursors; i++) {
274     if (editor->pCursors[i].pRun == run &&
275         editor->pCursors[i].nOffset >= nOffset) {
276       editor->pCursors[i].pRun = new_run;
277       editor->pCursors[i].nOffset -= nOffset;
278     }
279   }
280   cursor->pPara->member.para.nFlags |= MEPF_REWRAP;
281   return run;
282 }
283
284 /******************************************************************************
285  * ME_MakeRun
286  * 
287  * A helper function to create run structures quickly.
288  */   
289 ME_DisplayItem *ME_MakeRun(ME_Style *s, int nFlags)
290 {
291   ME_DisplayItem *item = ME_MakeDI(diRun);
292   item->member.run.style = s;
293   item->member.run.ole_obj = NULL;
294   item->member.run.nFlags = nFlags;
295   item->member.run.nCharOfs = -1;
296   item->member.run.len = 0;
297   item->member.run.para = NULL;
298   ME_AddRefStyle(s);
299   return item;
300 }
301
302 /******************************************************************************
303  * ME_InsertRunAtCursor
304  *
305  * Inserts a new run with given style, flags and content at a given position,
306  * which is passed as a cursor structure (which consists of a run and 
307  * a run-relative character offset).
308  */
309 ME_DisplayItem *
310 ME_InsertRunAtCursor(ME_TextEditor *editor, ME_Cursor *cursor, ME_Style *style,
311                      const WCHAR *str, int len, int flags)
312 {
313   ME_DisplayItem *pDI;
314
315   if (cursor->nOffset)
316     ME_SplitRunSimple(editor, cursor);
317
318   add_undo_delete_run( editor, cursor->pPara->member.para.nCharOfs +
319                        cursor->pRun->member.run.nCharOfs, len );
320
321   pDI = ME_MakeRun(style, flags);
322   pDI->member.run.nCharOfs = cursor->pRun->member.run.nCharOfs;
323   pDI->member.run.len = len;
324   pDI->member.run.para = cursor->pRun->member.run.para;
325   ME_InsertString( pDI->member.run.para->text, pDI->member.run.nCharOfs, str, len );
326   ME_InsertBefore(cursor->pRun, pDI);
327   TRACE("Shift length:%d\n", len);
328   ME_PropagateCharOffset(cursor->pRun, len);
329   cursor->pPara->member.para.nFlags |= MEPF_REWRAP;
330   return pDI;
331 }
332
333 static BOOL run_is_splittable( const ME_Run *run )
334 {
335     WCHAR *str = get_text( run, 0 ), *p;
336     int i;
337     BOOL found_ink = FALSE;
338
339     for (i = 0, p = str; i < run->len; i++, p++)
340     {
341         if (ME_IsWSpace( *p ))
342         {
343             if (found_ink) return TRUE;
344         }
345         else
346             found_ink = TRUE;
347     }
348     return FALSE;
349 }
350
351 static BOOL run_is_entirely_ws( const ME_Run *run )
352 {
353     WCHAR *str = get_text( run, 0 ), *p;
354     int i;
355
356     for (i = 0, p = str; i < run->len; i++, p++)
357         if (!ME_IsWSpace( *p )) return FALSE;
358
359     return TRUE;
360 }
361
362 /******************************************************************************
363  * ME_UpdateRunFlags
364  *
365  * Determine some of run attributes given its content (style, text content).
366  * Some flags cannot be determined by this function (MERF_GRAPHICS,
367  * MERF_ENDPARA)
368  */
369 void ME_UpdateRunFlags(ME_TextEditor *editor, ME_Run *run)
370 {
371   assert(run->nCharOfs >= 0);
372
373   if (RUN_IS_HIDDEN(run) || run->nFlags & MERF_TABLESTART)
374     run->nFlags |= MERF_HIDDEN;
375   else
376     run->nFlags &= ~MERF_HIDDEN;
377
378   if (run_is_splittable( run ))
379     run->nFlags |= MERF_SPLITTABLE;
380   else
381     run->nFlags &= ~MERF_SPLITTABLE;
382
383   if (!(run->nFlags & MERF_NOTEXT))
384   {
385     if (run_is_entirely_ws( run ))
386       run->nFlags |= MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE;
387     else
388     {
389       run->nFlags &= ~MERF_WHITESPACE;
390
391       if (ME_IsWSpace( *get_text( run, 0 ) ))
392         run->nFlags |= MERF_STARTWHITE;
393       else
394         run->nFlags &= ~MERF_STARTWHITE;
395
396       if (ME_IsWSpace( *get_text( run, run->len - 1 ) ))
397         run->nFlags |= MERF_ENDWHITE;
398       else
399         run->nFlags &= ~MERF_ENDWHITE;
400     }
401   }
402   else
403     run->nFlags &= ~(MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE);
404 }
405
406 /******************************************************************************
407  * ME_CharFromPointCursor
408  *
409  * Returns a character position inside the run given a run-relative
410  * pixel horizontal position. This version rounds to the nearest character edge
411  * (ie. if the second character is at pixel position 8, then for cx=0..3
412  * it returns 0, and for cx=4..7 it returns 1).
413  *
414  * It is used for mouse click handling, for better usability (and compatibility
415  * with the native control).
416  */
417 int ME_CharFromPointCursor(ME_TextEditor *editor, int cx, ME_Run *run)
418 {
419   ME_String *mask_text = NULL;
420   WCHAR *str;
421   int fit = 0;
422   ME_Context c;
423   HGDIOBJ hOldFont;
424   SIZE sz, sz2, sz3;
425   if (!run->len || cx <= 0)
426     return 0;
427
428   if (run->nFlags & (MERF_TAB | MERF_ENDCELL))
429   {
430     if (cx < run->nWidth/2)
431       return 0;
432     return 1;
433   }
434   ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
435   if (run->nFlags & MERF_GRAPHICS)
436   {
437     SIZE sz;
438     ME_GetOLEObjectSize(&c, run, &sz);
439     ME_DestroyContext(&c);
440     if (cx < sz.cx/2)
441       return 0;
442     return 1;
443   }
444
445   if (editor->cPasswordMask)
446   {
447     mask_text = ME_MakeStringR( editor->cPasswordMask, run->len );
448     str = mask_text->szData;
449   }
450   else
451     str = get_text( run, 0 );
452
453   hOldFont = ME_SelectStyleFont(&c, run->style);
454   GetTextExtentExPointW(c.hDC, str, run->len,
455                         cx, &fit, NULL, &sz);
456   if (fit != run->len)
457   {
458     GetTextExtentPoint32W(c.hDC, str, fit, &sz2);
459     GetTextExtentPoint32W(c.hDC, str, fit + 1, &sz3);
460     if (cx >= (sz2.cx+sz3.cx)/2)
461       fit = fit + 1;
462   }
463
464   ME_DestroyString( mask_text );
465
466   ME_UnselectStyleFont(&c, run->style, hOldFont);
467   ME_DestroyContext(&c);
468   return fit;
469 }
470
471 /******************************************************************************
472  * ME_GetTextExtent
473  *
474  * Finds a width and a height of the text using a specified style
475  */
476 static void ME_GetTextExtent(ME_Context *c, LPCWSTR szText, int nChars, ME_Style *s, SIZE *size)
477 {
478   HGDIOBJ hOldFont;
479   if (c->hDC) {
480     hOldFont = ME_SelectStyleFont(c, s);
481     GetTextExtentPoint32W(c->hDC, szText, nChars, size);
482     ME_UnselectStyleFont(c, s, hOldFont);
483   } else {
484     size->cx = 0;
485     size->cy = 0;
486   }
487 }
488
489 /******************************************************************************
490  * ME_PointFromCharContext
491  *
492  * Returns a run-relative pixel position given a run-relative character
493  * position (character offset)
494  */
495 int ME_PointFromCharContext(ME_Context *c, ME_Run *pRun, int nOffset)
496 {
497   SIZE size;
498   ME_String *mask_text = NULL;
499   WCHAR *str;
500
501   if (pRun->nFlags & MERF_GRAPHICS)
502   {
503     if (nOffset)
504       ME_GetOLEObjectSize(c, pRun, &size);
505     return nOffset != 0;
506   } else if (pRun->nFlags & MERF_ENDPARA) {
507     nOffset = 0;
508   }
509
510   if (c->editor->cPasswordMask)
511   {
512     mask_text = ME_MakeStringR(c->editor->cPasswordMask, pRun->len);
513     str = mask_text->szData;
514   }
515   else
516       str = get_text( pRun, 0 );
517
518   ME_GetTextExtent(c, str, nOffset, pRun->style, &size);
519   ME_DestroyString( mask_text );
520   return size.cx;
521 }
522
523 /******************************************************************************
524  * ME_PointFromChar
525  *
526  * Calls ME_PointFromCharContext after first creating a context.
527  */
528 int ME_PointFromChar(ME_TextEditor *editor, ME_Run *pRun, int nOffset)
529 {
530     ME_Context c;
531     int ret;
532
533     ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
534     ret = ME_PointFromCharContext( &c, pRun, nOffset );
535     ME_DestroyContext(&c);
536
537     return ret;
538 }
539
540 /******************************************************************************
541  * ME_GetRunSizeCommon
542  * 
543  * Finds width, height, ascent and descent of a run, up to given character
544  * (nLen).
545  */
546 SIZE ME_GetRunSizeCommon(ME_Context *c, const ME_Paragraph *para, ME_Run *run, int nLen,
547                          int startx, int *pAscent, int *pDescent)
548 {
549   SIZE size;
550   int nMaxLen = run->len;
551
552   if (nLen>nMaxLen)
553     nLen = nMaxLen;
554
555   /* FIXME the following call also ensures that TEXTMETRIC structure is filled
556    * this is wasteful for MERF_NONTEXT runs, but that shouldn't matter
557    * in practice
558    */
559   
560   if (c->editor->cPasswordMask)
561   {
562     ME_String *szMasked = ME_MakeStringR(c->editor->cPasswordMask,nLen);
563     ME_GetTextExtent(c, szMasked->szData, nLen,run->style, &size); 
564     ME_DestroyString(szMasked);
565   }
566   else
567   {
568     ME_GetTextExtent(c, get_text( run, 0 ), nLen, run->style, &size);
569   }
570   *pAscent = run->style->tm.tmAscent;
571   *pDescent = run->style->tm.tmDescent;
572   size.cy = *pAscent + *pDescent;
573
574   if (run->nFlags & MERF_TAB)
575   {
576     int pos = 0, i = 0, ppos, shift = 0;
577     PARAFORMAT2 *pFmt = para->pFmt;
578
579     if (c->editor->bEmulateVersion10 && /* v1.0 - 3.0 */
580         pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
581       /* The horizontal gap shifts the tab positions to leave the gap. */
582       shift = pFmt->dxOffset * 2;
583     do {
584       if (i < pFmt->cTabCount)
585       {
586         /* Only one side of the horizontal gap is needed at the end of
587          * the table row. */
588         if (i == pFmt->cTabCount -1)
589           shift = shift >> 1;
590         pos = shift + (pFmt->rgxTabs[i]&0x00FFFFFF);
591         i++;
592       }
593       else
594       {
595         pos += lDefaultTab - (pos % lDefaultTab);
596       }
597       ppos = ME_twips2pointsX(c, pos);
598       if (ppos > startx + run->pt.x) {
599         size.cx = ppos - startx - run->pt.x;
600         break;
601       }
602     } while(1);
603     size.cy = *pAscent + *pDescent;
604     return size;
605   }
606   if (run->nFlags & MERF_GRAPHICS)
607   {
608     ME_GetOLEObjectSize(c, run, &size);
609     if (size.cy > *pAscent)
610       *pAscent = size.cy;
611     /* descent is unchanged */
612     return size;
613   }
614   return size;
615 }
616
617 /******************************************************************************
618  * ME_GetRunSize
619  * 
620  * Finds width and height (but not ascent and descent) of a part of the run
621  * up to given character.    
622  */     
623 SIZE ME_GetRunSize(ME_Context *c, const ME_Paragraph *para,
624                    ME_Run *run, int nLen, int startx)
625 {
626   int asc, desc;
627   return ME_GetRunSizeCommon(c, para, run, nLen, startx, &asc, &desc);
628 }
629
630 /******************************************************************************
631  * ME_SetSelectionCharFormat
632  *
633  * Applies a style change, either to a current selection, or to insert cursor
634  * (ie. the style next typed characters will use).
635  */
636 void ME_SetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
637 {
638   if (!ME_IsSelection(editor))
639   {
640     ME_Style *s;
641     if (!editor->pBuffer->pCharStyle)
642       editor->pBuffer->pCharStyle = ME_GetInsertStyle(editor, 0);
643     s = ME_ApplyStyle(editor->pBuffer->pCharStyle, pFmt);
644     ME_ReleaseStyle(editor->pBuffer->pCharStyle);
645     editor->pBuffer->pCharStyle = s;
646   } else {
647     ME_Cursor *from, *to;
648     ME_GetSelection(editor, &from, &to);
649     ME_SetCharFormat(editor, from, to, pFmt);
650   }
651 }
652
653 /******************************************************************************
654  * ME_SetCharFormat
655  *
656  * Applies a style change to the specified part of the text
657  *
658  * The start and end cursors specify the part of the text.  These cursors will
659  * be updated to stay valid, but this function may invalidate other
660  * non-selection cursors. The end cursor may be NULL to specify all the text
661  * following the start cursor.
662  *
663  * If no text is selected, then nothing is done.
664  */
665 void ME_SetCharFormat(ME_TextEditor *editor, ME_Cursor *start, ME_Cursor *end, CHARFORMAT2W *pFmt)
666 {
667   ME_DisplayItem *para;
668   ME_DisplayItem *run;
669   ME_DisplayItem *end_run = NULL;
670
671   if (end && start->pRun == end->pRun && start->nOffset == end->nOffset)
672     return;
673
674   if (start->nOffset)
675   {
676     /* SplitRunSimple may or may not update the cursors, depending on whether they
677      * are selection cursors, but we need to make sure they are valid. */
678     int split_offset = start->nOffset;
679     ME_DisplayItem *split_run = ME_SplitRunSimple(editor, start);
680     if (end && end->pRun == split_run)
681     {
682       end->pRun = start->pRun;
683       end->nOffset -= split_offset;
684     }
685   }
686
687   if (end && end->nOffset)
688     ME_SplitRunSimple(editor, end);
689   end_run = end ? end->pRun : NULL;
690
691   run = start->pRun;
692   para = start->pPara;
693   para->member.para.nFlags |= MEPF_REWRAP;
694
695   while(run != end_run)
696   {
697     ME_Style *new_style = ME_ApplyStyle(run->member.run.style, pFmt);
698     /* ME_DumpStyle(new_style); */
699
700     add_undo_set_char_fmt( editor, para->member.para.nCharOfs + run->member.run.nCharOfs,
701                            run->member.run.len, &run->member.run.style->fmt );
702     ME_ReleaseStyle(run->member.run.style);
703     run->member.run.style = new_style;
704     run = ME_FindItemFwd(run, diRunOrParagraph);
705     if (run && run->type == diParagraph)
706     {
707       para = run;
708       run = ME_FindItemFwd(run, diRun);
709       if (run != end_run)
710         para->member.para.nFlags |= MEPF_REWRAP;
711     }
712   }
713 }
714
715 /******************************************************************************
716  * ME_SetDefaultCharFormat
717  * 
718  * Applies a style change to the default character style.
719  */     
720 void ME_SetDefaultCharFormat(ME_TextEditor *editor, CHARFORMAT2W *mod)
721 {
722   ME_Style *style;
723
724   assert(mod->cbSize == sizeof(CHARFORMAT2W));
725   style = ME_ApplyStyle(editor->pBuffer->pDefaultStyle, mod);
726   editor->pBuffer->pDefaultStyle->fmt = style->fmt;
727   editor->pBuffer->pDefaultStyle->tm = style->tm;
728   ME_ReleaseStyle(style);
729   ME_MarkAllForWrapping(editor);
730   /*  pcf = editor->pBuffer->pDefaultStyle->fmt; */
731 }
732
733 static void ME_GetRunCharFormat(ME_TextEditor *editor, ME_DisplayItem *run, CHARFORMAT2W *pFmt)
734 {
735   ME_CopyCharFormat(pFmt, &run->member.run.style->fmt);
736   if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_CF1UNDERLINE))
737   {
738     pFmt->dwMask |= CFM_UNDERLINE;
739     pFmt->dwEffects |= CFE_UNDERLINE;
740   }
741   if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_UNDERLINENONE))
742   {
743     pFmt->dwMask |= CFM_UNDERLINE;
744     pFmt->dwEffects &= ~CFE_UNDERLINE;
745   }
746 }
747
748 /******************************************************************************
749  * ME_GetDefaultCharFormat
750  * 
751  * Retrieves the current default character style (the one applied where no
752  * other style was applied) .
753  */     
754 void ME_GetDefaultCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
755 {
756   ME_CopyCharFormat(pFmt, &editor->pBuffer->pDefaultStyle->fmt);
757 }
758
759 /******************************************************************************
760  * ME_GetSelectionCharFormat
761  *
762  * If selection exists, it returns all style elements that are set consistently
763  * in the whole selection. If not, it just returns the current style.
764  */
765 void ME_GetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
766 {
767   ME_Cursor *from, *to;
768   if (!ME_IsSelection(editor) && editor->pBuffer->pCharStyle)
769   {
770     ME_CopyCharFormat(pFmt, &editor->pBuffer->pCharStyle->fmt);
771     return;
772   }
773   ME_GetSelection(editor, &from, &to);
774   ME_GetCharFormat(editor, from, to, pFmt);
775 }
776
777 /******************************************************************************
778  * ME_GetCharFormat
779  *
780  * Returns the style consisting of those attributes which are consistently set
781  * in the whole character range.
782  */
783 void ME_GetCharFormat(ME_TextEditor *editor, const ME_Cursor *from,
784                       const ME_Cursor *to, CHARFORMAT2W *pFmt)
785 {
786   ME_DisplayItem *run, *run_end;
787   CHARFORMAT2W tmp;
788
789   run = from->pRun;
790   /* special case - if selection is empty, take previous char's formatting */
791   if (from->pRun == to->pRun && from->nOffset == to->nOffset)
792   {
793     if (!from->nOffset)
794     {
795       ME_DisplayItem *tmp_run = ME_FindItemBack(run, diRunOrParagraph);
796       if (tmp_run->type == diRun) {
797         ME_GetRunCharFormat(editor, tmp_run, pFmt);
798         return;
799       }
800     }
801     ME_GetRunCharFormat(editor, run, pFmt);
802     return;
803   }
804
805   run_end = to->pRun;
806   if (!to->nOffset)
807     run_end = ME_FindItemBack(run_end, diRun);
808
809   ME_GetRunCharFormat(editor, run, pFmt);
810
811   if (run == run_end) return;
812
813   do {
814     /* FIXME add more style feature comparisons */
815     DWORD dwAttribs = CFM_SIZE | CFM_FACE | CFM_COLOR | CFM_UNDERLINETYPE;
816     DWORD dwEffects = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_PROTECTED | CFM_LINK | CFM_SUPERSCRIPT;
817
818     run = ME_FindItemFwd(run, diRun);
819
820     ZeroMemory(&tmp, sizeof(tmp));
821     tmp.cbSize = sizeof(tmp);
822     ME_GetRunCharFormat(editor, run, &tmp);
823
824     assert((tmp.dwMask & dwAttribs) == dwAttribs);
825     /* reset flags that differ */
826
827     if (pFmt->yHeight != tmp.yHeight)
828       pFmt->dwMask &= ~CFM_SIZE;
829     if (pFmt->dwMask & CFM_FACE)
830     {
831       if (!(tmp.dwMask & CFM_FACE))
832         pFmt->dwMask &= ~CFM_FACE;
833       else if (lstrcmpW(pFmt->szFaceName, tmp.szFaceName) ||
834           pFmt->bPitchAndFamily != tmp.bPitchAndFamily)
835         pFmt->dwMask &= ~CFM_FACE;
836     }
837     if (pFmt->yHeight != tmp.yHeight)
838       pFmt->dwMask &= ~CFM_SIZE;
839     if (pFmt->bUnderlineType != tmp.bUnderlineType)
840       pFmt->dwMask &= ~CFM_UNDERLINETYPE;
841     if (pFmt->dwMask & CFM_COLOR)
842     {
843       if (!((pFmt->dwEffects&CFE_AUTOCOLOR) & (tmp.dwEffects&CFE_AUTOCOLOR)))
844       {
845         if (pFmt->crTextColor != tmp.crTextColor)
846           pFmt->dwMask &= ~CFM_COLOR;
847       }
848     }
849
850     pFmt->dwMask &= ~((pFmt->dwEffects ^ tmp.dwEffects) & dwEffects);
851     pFmt->dwEffects = tmp.dwEffects;
852
853   } while(run != run_end);
854 }