]> git.lyx.org Git - lyx.git/blob - src/text.C
compile fixes for stlport
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "buffer.h"
22 #include "bufferparams.h"
23 #include "BufferView.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.h"
40 #include "undo.h"
41 #include "vspace.h"
42 #include "WordLangTuple.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insettext.h"
48
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
51
52 using bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 BufferView * LyXText::bv()
79 {
80         BOOST_ASSERT(bv_owner != 0);
81         return bv_owner;
82 }
83
84
85 BufferView * LyXText::bv() const
86 {
87         BOOST_ASSERT(bv_owner != 0);
88         return bv_owner;
89 }
90
91
92 void LyXText::updateRowPositions()
93 {
94         ParagraphList::iterator pit = ownerParagraphs().begin();
95         ParagraphList::iterator end = ownerParagraphs().end();
96         for (height = 0; pit != end; ++pit) {
97                 pit->y = height;
98                 height += pit->height;
99         }
100 }
101
102
103 int LyXText::workWidth() const
104 {
105         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
106 }
107
108
109 int LyXText::getRealCursorX() const
110 {
111         int x = cursor.x();
112         if (the_locking_inset && (the_locking_inset->getLyXText(bv())!= this))
113                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
114         return x;
115 }
116
117
118 #warning FIXME  This function seems to belong outside of LyxText.
119 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
120                                      pos_type pos) const
121 {
122         if (!Encodings::is_arabic(c))
123                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
124                         return c + (0xb0 - '0');
125                 else
126                         return c;
127
128         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
129         unsigned char next_char = ' ';
130
131         pos_type const par_size = par.size();
132
133         for (pos_type i = pos + 1; i < par_size; ++i) {
134                 unsigned char const par_char = par.getChar(i);
135                 if (!Encodings::IsComposeChar_arabic(par_char)) {
136                         next_char = par_char;
137                         break;
138                 }
139         }
140
141         if (Encodings::is_arabic(next_char)) {
142                 if (Encodings::is_arabic(prev_char) &&
143                         !Encodings::is_arabic_special(prev_char))
144                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
145                 else
146                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
147         } else {
148                 if (Encodings::is_arabic(prev_char) &&
149                         !Encodings::is_arabic_special(prev_char))
150                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
151                 else
152                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
153         }
154 }
155
156 // This is the comments that some of the warnings below refers to.
157 // There are some issues in this file and I don't think they are
158 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
159 // this is a problem that has been here almost from day one and that a
160 // larger userbase with differenct access patters triggers the bad
161 // behaviour. (segfaults.) What I think happen is: In several places
162 // we store the paragraph in the current cursor and then moves the
163 // cursor. This movement of the cursor will delete paragraph at the
164 // old position if it is now empty. This will make the temporary
165 // pointer to the old cursor paragraph invalid and dangerous to use.
166 // And is some cases this will trigger a segfault. I have marked some
167 // of the cases where this happens with a warning, but I am sure there
168 // are others in this file and in text2.C. There is also a note in
169 // Delete() that you should read. In Delete I store the paragraph->id
170 // instead of a pointer to the paragraph. I am pretty sure this faulty
171 // use of temporary pointers to paragraphs that might have gotten
172 // invalidated (through a cursor movement) before they are used, are
173 // the cause of the strange crashes we get reported often.
174 //
175 // It is very tiresom to change this code, especially when it is as
176 // hard to read as it is. Help to fix all the cases where this is done
177 // would be greately appreciated.
178 //
179 // Lgb
180
181 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
182 {
183         if (pos >= pit->size())
184                 return 0;
185
186         char const c = pit->getChar(pos);
187         LyXFont const & font = getFont(pit, pos);
188         return singleWidth(pit, pos, c, font);
189 }
190
191
192 int LyXText::singleWidth(ParagraphList::iterator pit,
193                          pos_type pos, char c, LyXFont const & font) const
194 {
195         if (pos >= pit->size()) {
196                 lyxerr << "in singleWidth(), pos: " << pos << endl;
197                 BOOST_ASSERT(false);
198                 return 0;
199         }
200
201
202         // The most common case is handled first (Asger)
203         if (IsPrintable(c)) {
204                 if (font.language()->RightToLeft()) {
205                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
206                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
207                             && font.language()->lang() == "arabic") {
208                                 if (Encodings::IsComposeChar_arabic(c))
209                                         return 0;
210                                 else
211                                         c = transformChar(c, *pit, pos);
212                         } else if (font.language()->lang() == "hebrew" &&
213                                  Encodings::IsComposeChar_hebrew(c))
214                                 return 0;
215                 }
216                 return font_metrics::width(c, font);
217         }
218
219         if (c == Paragraph::META_INSET) {
220                 InsetOld * tmpinset = pit->getInset(pos);
221                 BOOST_ASSERT(tmpinset);
222                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
223                         // Because of the representation as vertical lines
224                         return 3;
225                 }
226                 return tmpinset->width();
227         }
228
229         if (IsSeparatorChar(c))
230                 c = ' ';
231         return font_metrics::width(c, font);
232 }
233
234
235 lyx::pos_type LyXText::log2vis(lyx::pos_type pos) const
236 {
237         if (bidi_start == -1)
238                 return pos;
239         else
240                 return log2vis_list[pos - bidi_start];
241 }
242
243
244 lyx::pos_type LyXText::vis2log(lyx::pos_type pos) const
245 {
246         if (bidi_start == -1)
247                 return pos;
248         else
249                 return vis2log_list[pos - bidi_start];
250 }
251
252
253 lyx::pos_type LyXText::bidi_level(lyx::pos_type pos) const
254 {
255         if (bidi_start == -1)
256                 return 0;
257         else
258                 return bidi_levels[pos - bidi_start];
259 }
260
261
262 bool LyXText::bidi_InRange(lyx::pos_type pos) const
263 {
264         return bidi_start == -1 ||
265                 (bidi_start <= pos && pos <= bidi_end);
266 }
267
268
269 void LyXText::computeBidiTables(Paragraph const & par,
270    Buffer const & buf, Row & row) const
271 {
272         bidi_same_direction = true;
273         if (!lyxrc.rtl_support) {
274                 bidi_start = -1;
275                 return;
276         }
277
278         InsetOld * inset = par.inInset();
279         if (inset && inset->owner() &&
280             inset->owner()->lyxCode() == InsetOld::ERT_CODE) {
281                 bidi_start = -1;
282                 return;
283         }
284
285         bidi_start = row.pos();
286         bidi_end = lastPos(par, row);
287
288         if (bidi_start > bidi_end) {
289                 bidi_start = -1;
290                 return;
291         }
292
293         if (bidi_end + 2 - bidi_start >
294             static_cast<pos_type>(log2vis_list.size())) {
295                 pos_type new_size =
296                         (bidi_end + 2 - bidi_start < 500) ?
297                         500 : 2 * (bidi_end + 2 - bidi_start);
298                 log2vis_list.resize(new_size);
299                 vis2log_list.resize(new_size);
300                 bidi_levels.resize(new_size);
301         }
302
303         vis2log_list[bidi_end + 1 - bidi_start] = -1;
304         log2vis_list[bidi_end + 1 - bidi_start] = -1;
305
306         BufferParams const & bufparams = buf.params();
307         pos_type stack[2];
308         bool const rtl_par = par.isRightToLeftPar(bufparams);
309         int level = 0;
310         bool rtl = false;
311         bool rtl0 = false;
312         pos_type const body_pos = par.beginningOfBody();
313
314         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
315                 bool is_space = par.isLineSeparator(lpos);
316                 pos_type const pos =
317                         (is_space && lpos + 1 <= bidi_end &&
318                          !par.isLineSeparator(lpos + 1) &&
319                          !par.isNewline(lpos + 1))
320                         ? lpos + 1 : lpos;
321                 LyXFont font = par.getFontSettings(bufparams, pos);
322                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
323                     font.number() == LyXFont::ON &&
324                     par.getFontSettings(bufparams, lpos - 1).number()
325                     == LyXFont::ON) {
326                         font = par.getFontSettings(bufparams, lpos);
327                         is_space = false;
328                 }
329
330
331                 bool new_rtl = font.isVisibleRightToLeft();
332                 bool new_rtl0 = font.isRightToLeft();
333                 int new_level;
334
335                 if (lpos == body_pos - 1
336                     && row.pos() < body_pos - 1
337                     && is_space) {
338                         new_level = rtl_par ? 1 : 0;
339                         new_rtl0 = rtl_par;
340                         new_rtl = rtl_par;
341                 } else if (new_rtl0)
342                         new_level = new_rtl ? 1 : 2;
343                 else
344                         new_level = rtl_par ? 2 : 0;
345
346                 if (is_space && new_level >= level) {
347                         new_level = level;
348                         new_rtl = rtl;
349                         new_rtl0 = rtl0;
350                 }
351
352                 int new_level2 = new_level;
353
354                 if (level == new_level && rtl0 != new_rtl0) {
355                         --new_level2;
356                         log2vis_list[lpos - bidi_start] = rtl ? 1 : -1;
357                 } else if (level < new_level) {
358                         log2vis_list[lpos - bidi_start] = rtl ? -1 : 1;
359                         if (new_level > rtl_par)
360                                 bidi_same_direction = false;
361                 } else
362                         log2vis_list[lpos - bidi_start] = new_rtl ? -1 : 1;
363                 rtl = new_rtl;
364                 rtl0 = new_rtl0;
365                 bidi_levels[lpos - bidi_start] = new_level;
366
367                 while (level > new_level2) {
368                         pos_type old_lpos = stack[--level];
369                         int delta = lpos - old_lpos - 1;
370                         if (level % 2)
371                                 delta = -delta;
372                         log2vis_list[lpos - bidi_start] += delta;
373                         log2vis_list[old_lpos - bidi_start] += delta;
374                 }
375                 while (level < new_level)
376                         stack[level++] = lpos;
377         }
378
379         while (level > 0) {
380                 pos_type const old_lpos = stack[--level];
381                 int delta = bidi_end - old_lpos;
382                 if (level % 2)
383                         delta = -delta;
384                 log2vis_list[old_lpos - bidi_start] += delta;
385         }
386
387         pos_type vpos = bidi_start - 1;
388         for (pos_type lpos = bidi_start;
389              lpos <= bidi_end; ++lpos) {
390                 vpos += log2vis_list[lpos - bidi_start];
391                 vis2log_list[vpos - bidi_start] = lpos;
392                 log2vis_list[lpos - bidi_start] = vpos;
393         }
394 }
395
396
397 // This method requires a previous call to ComputeBidiTables()
398 bool LyXText::isBoundary(Buffer const & buf, Paragraph const & par,
399                          pos_type pos) const
400 {
401         if (!lyxrc.rtl_support || pos == 0)
402                 return false;
403
404         if (!bidi_InRange(pos - 1)) {
405                 /// This can happen if pos is the first char of a row.
406                 /// Returning false in this case is incorrect!
407                 return false;
408         }
409
410         bool const rtl = bidi_level(pos - 1) % 2;
411         bool const rtl2 = bidi_InRange(pos)
412                 ? bidi_level(pos) % 2
413                 : par.isRightToLeftPar(buf.params());
414         return rtl != rtl2;
415 }
416
417
418 bool LyXText::isBoundary(Buffer const & buf, Paragraph const & par,
419                          pos_type pos, LyXFont const & font) const
420 {
421         if (!lyxrc.rtl_support)
422                 return false;    // This is just for speedup
423
424         bool const rtl = font.isVisibleRightToLeft();
425         bool const rtl2 = bidi_InRange(pos)
426                 ? bidi_level(pos) % 2
427                 : par.isRightToLeftPar(buf.params());
428         return rtl != rtl2;
429 }
430
431
432 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
433 {
434         LyXTextClass const & tclass =
435                 bv()->buffer()->params().getLyXTextClass();
436         LyXLayout_ptr const & layout = pit->layout();
437
438         string parindent = layout->parindent;
439
440         int x = LEFT_MARGIN;
441
442         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
443
444         // this is the way, LyX handles the LaTeX-Environments.
445         // I have had this idea very late, so it seems to be a
446         // later added hack and this is true
447         if (!pit->getDepth()) {
448                 if (pit->layout() == tclass.defaultLayout()) {
449                         // find the previous same level paragraph
450                         if (pit != ownerParagraphs().begin()) {
451                                 ParagraphList::iterator newpit =
452                                         depthHook(pit, ownerParagraphs(),
453                                                   pit->getDepth());
454                                 if (newpit == pit &&
455                                     newpit->layout()->nextnoindent)
456                                         parindent.erase();
457                         }
458                 }
459         } else {
460                 // find the next level paragraph
461
462                 ParagraphList::iterator newpar = outerHook(pit,
463                                                            ownerParagraphs());
464
465                 // make a corresponding row. Needed to call leftMargin()
466
467                 // check wether it is a sufficent paragraph
468                 if (newpar != ownerParagraphs().end() &&
469                     newpar->layout()->isEnvironment()) {
470                         x = leftMargin(newpar, Row(newpar->size()));
471                 }
472
473                 if (newpar != ownerParagraphs().end() &&
474                     pit->layout() == tclass.defaultLayout()) {
475                         if (newpar->params().noindent())
476                                 parindent.erase();
477                         else {
478                                 parindent = newpar->layout()->parindent;
479                         }
480
481                 }
482         }
483
484         LyXFont const labelfont = getLabelFont(pit);
485         switch (layout->margintype) {
486         case MARGIN_DYNAMIC:
487                 if (!layout->leftmargin.empty()) {
488                         x += font_metrics::signedWidth(layout->leftmargin,
489                                                   tclass.defaultfont());
490                 }
491                 if (!pit->getLabelstring().empty()) {
492                         x += font_metrics::signedWidth(layout->labelindent,
493                                                   labelfont);
494                         x += font_metrics::width(pit->getLabelstring(),
495                                             labelfont);
496                         x += font_metrics::width(layout->labelsep, labelfont);
497                 }
498                 break;
499         case MARGIN_MANUAL:
500                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
501                 // The width of an empty par, even with manual label, should be 0
502                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
503                         if (!pit->getLabelWidthString().empty()) {
504                                 x += font_metrics::width(pit->getLabelWidthString(),
505                                                labelfont);
506                                 x += font_metrics::width(layout->labelsep, labelfont);
507                         }
508                 }
509                 break;
510         case MARGIN_STATIC:
511                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
512                         / (pit->getDepth() + 4);
513                 break;
514         case MARGIN_FIRST_DYNAMIC:
515                 if (layout->labeltype == LABEL_MANUAL) {
516                         if (row.pos() >= pit->beginningOfBody()) {
517                                 x += font_metrics::signedWidth(layout->leftmargin,
518                                                           labelfont);
519                         } else {
520                                 x += font_metrics::signedWidth(layout->labelindent,
521                                                           labelfont);
522                         }
523                 } else if (row.pos()
524                            // Special case to fix problems with
525                            // theorems (JMarc)
526                            || (layout->labeltype == LABEL_STATIC
527                                && layout->latextype == LATEX_ENVIRONMENT
528                                && !isFirstInSequence(pit, ownerParagraphs()))) {
529                         x += font_metrics::signedWidth(layout->leftmargin,
530                                                   labelfont);
531                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
532                            && layout->labeltype != LABEL_BIBLIO
533                            && layout->labeltype !=
534                            LABEL_CENTERED_TOP_ENVIRONMENT) {
535                         x += font_metrics::signedWidth(layout->labelindent,
536                                                   labelfont);
537                         x += font_metrics::width(layout->labelsep, labelfont);
538                         x += font_metrics::width(pit->getLabelstring(),
539                                             labelfont);
540                 }
541                 break;
542
543         case MARGIN_RIGHT_ADDRESS_BOX:
544         {
545                 // ok, a terrible hack. The left margin depends on the widest
546                 // row in this paragraph.
547                 RowList::iterator rit = pit->rows.begin();
548                 RowList::iterator end = pit->rows.end();
549                 int minfill = rit->fill();
550                 for ( ; rit != end; ++rit)
551                         if (rit->fill() < minfill)
552                                 minfill = rit->fill();
553
554                 x += font_metrics::signedWidth(layout->leftmargin,
555                         tclass.defaultfont());
556                 x += minfill;
557         }
558         break;
559         }
560
561         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
562                 LyXLength const len = pit->params().leftIndent();
563                 int const tw = inset_owner ?
564                         inset_owner->latexTextWidth(bv()) : workWidth();
565                 x += len.inPixels(tw);
566         }
567
568         LyXAlignment align;
569
570         if (pit->params().align() == LYX_ALIGN_LAYOUT)
571                 align = layout->align;
572         else
573                 align = pit->params().align();
574
575         // set the correct parindent
576         if (row.pos() == 0) {
577                 if ((layout->labeltype == LABEL_NO_LABEL
578                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
579                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
580                      || (layout->labeltype == LABEL_STATIC
581                          && layout->latextype == LATEX_ENVIRONMENT
582                          && !isFirstInSequence(pit, ownerParagraphs())))
583                     && align == LYX_ALIGN_BLOCK
584                     && !pit->params().noindent()
585                         // in tabulars and ert paragraphs are never indented!
586                         && (!pit->inInset() || !pit->inInset()->owner() ||
587                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
588                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
589                     && (pit->layout() != tclass.defaultLayout() ||
590                         bv()->buffer()->params().paragraph_separation ==
591                         BufferParams::PARSEP_INDENT)) {
592                         x += font_metrics::signedWidth(parindent,
593                                                   tclass.defaultfont());
594                 } else if (layout->labeltype == LABEL_BIBLIO) {
595                         // ale970405 Right width for bibitems
596                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
597                 }
598         }
599
600         return x;
601 }
602
603
604 int LyXText::rightMargin(Paragraph const & par,
605         Buffer const & buf, Row const &) const
606 {
607         LyXTextClass const & tclass = buf.params().getLyXTextClass();
608         LyXLayout_ptr const & layout = par.layout();
609
610         return PAPER_MARGIN
611                 + font_metrics::signedWidth(tclass.rightmargin(),
612                                        tclass.defaultfont());
613                 + font_metrics::signedWidth(layout->rightmargin,
614                                        tclass.defaultfont())
615                 * 4 / (par.getDepth() + 4);
616 }
617
618
619 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
620 {
621         if (pit->layout()->margintype == MARGIN_MANUAL) {
622                 Row tmprow = row;
623                 tmprow.pos(pit->size());
624                 // return the beginning of the body
625                 return leftMargin(pit, tmprow);
626         }
627
628         // LabelEnd is only needed if the layout
629         // fills a flushleft label.
630         return 0;
631 }
632
633
634 namespace {
635
636 // this needs special handling - only newlines count as a break point
637 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
638 {
639         for (; i < par.size(); ++i)
640                 if (par.isNewline(i))
641                         return i;
642
643         return par.size();
644 }
645
646 };
647
648
649 pos_type LyXText::rowBreakPoint(ParagraphList::iterator pit,
650         Row const & row) const
651 {
652         // maximum pixel width of a row.
653         int width = workWidth() - rightMargin(*pit, *bv()->buffer(), row);
654
655         // inset->textWidth() returns -1 via workWidth(),
656         // but why ?
657         if (width < 0)
658                 return pit->size();
659
660         LyXLayout_ptr const & layout = pit->layout();
661
662         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
663                 return addressBreakPoint(row.pos(), *pit);
664
665         pos_type const pos = row.pos();
666         pos_type const body_pos = pit->beginningOfBody();
667         pos_type const last = pit->size();
668         pos_type point = last;
669
670         if (pos == last)
671                 return last;
672
673         // Now we iterate through until we reach the right margin
674         // or the end of the par, then choose the possible break
675         // nearest that.
676
677         int const left = leftMargin(pit, row);
678         int x = left;
679
680         // pixel width since last breakpoint
681         int chunkwidth = 0;
682
683         pos_type i = pos;
684
685         // We re-use the font resolution for the entire font span when possible
686         LyXFont font = getFont(pit, i);
687         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
688
689         for (; i < last; ++i) {
690                 if (pit->isNewline(i)) {
691                         point = i;
692                         break;
693                 }
694
695                 char const c = pit->getChar(i);
696                 if (i > endPosOfFontSpan) {
697                         font = getFont(pit, i);
698                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
699                 }
700
701                 int thiswidth;
702
703                 // add the auto-hfill from label end to the body
704                 if (body_pos && i == body_pos) {
705                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
706                         if (pit->isLineSeparator(i - 1))
707                                 thiswidth -= singleWidth(pit, i - 1);
708                         int left_margin = labelEnd(pit, row);
709                         if (thiswidth + x < left_margin)
710                                 thiswidth = left_margin - x;
711                         thiswidth += singleWidth(pit, i, c, font);
712                 } else {
713                         thiswidth = singleWidth(pit, i, c, font);
714                 }
715
716                 x += thiswidth;
717                 chunkwidth += thiswidth;
718
719                 InsetOld * in = pit->isInset(i) ? pit->getInset(i) : 0;
720
721                 // break before a character that will fall off
722                 // the right of the row
723                 if (x >= width) {
724                         // if no break before, break here
725                         if (point == last || chunkwidth >= width - left)
726                                 point = (pos < i) ? i - 1 : i;
727                         break;
728                 }
729
730                 if (!in || in->isChar()) {
731                         // some insets are line separators too
732                         if (pit->isLineSeparator(i)) {
733                                 point = i;
734                                 chunkwidth = 0;
735                         }
736                 }
737         }
738
739         if (point == last && x >= width) {
740                 // didn't find one, break at the point we reached the edge
741                 point = i;
742         } else if (i == last && x < width) {
743                 // found one, but we fell off the end of the par, so prefer
744                 // that.
745                 point = last;
746         }
747
748         // manual labels cannot be broken in LaTeX. But we
749         // want to make our on-screen rendering of footnotes
750         // etc. still break
751         if (body_pos && point < body_pos)
752                 point = body_pos - 1;
753
754         return point;
755 }
756
757
758 // returns the minimum space a row needs on the screen in pixel
759 int LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
760 {
761         if (paper_width < 0)
762                 return 0;
763
764         int w;
765         // get the pure distance
766         pos_type const last = lastPos(*pit, row);
767
768         LyXLayout_ptr const & layout = pit->layout();
769
770         // special handling of the right address boxes
771         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
772                 int const tmpfill = row.fill();
773                 row.fill(0); // the minfill in MarginLeft()
774                 w = leftMargin(pit, row);
775                 row.fill(tmpfill);
776         } else
777                 w = leftMargin(pit, row);
778
779         pos_type const body_pos = pit->beginningOfBody();
780         pos_type i = row.pos();
781
782         if (! pit->empty() && i <= last) {
783                 // We re-use the font resolution for the entire span when possible
784                 LyXFont font = getFont(pit, i);
785                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
786                 while (i <= last) {
787                         if (body_pos > 0 && i == body_pos) {
788                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
789                                 if (pit->isLineSeparator(i - 1))
790                                         w -= singleWidth(pit, i - 1);
791                                 int left_margin = labelEnd(pit, row);
792                                 if (w < left_margin)
793                                         w = left_margin;
794                         }
795                         char const c = pit->getChar(i);
796                         if (IsPrintable(c) && i > endPosOfFontSpan) {
797                                 // We need to get the next font
798                                 font = getFont(pit, i);
799                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
800                         }
801                         w += singleWidth(pit, i, c, font);
802                         ++i;
803                 }
804         }
805         if (body_pos > 0 && body_pos > last) {
806                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
807                 if (last >= 0 && pit->isLineSeparator(last))
808                         w -= singleWidth(pit, last);
809                 int const left_margin = labelEnd(pit, row);
810                 if (w < left_margin)
811                         w = left_margin;
812         }
813
814         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
815
816         // If this case happens, it means that our calculation
817         // of the widths of the chars when we do rowBreakPoint()
818         // went wrong for some reason. Typically in list bodies.
819         // Things just about hobble on anyway, though you'll end
820         // up with a "fill_separator" less than zero, which corresponds
821         // to inter-word spacing being too small. Hopefully this problem
822         // will die when the label hacks die.
823         if (lyxerr.debugging() && fill < 0) {
824                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
825                         << " w " << w << " paper_width " << paper_width
826                         << " right margin " << rightMargin(*pit, *bv()->buffer(), row) << endl;
827         }
828         return fill;
829 }
830
831
832 // returns the minimum space a manual label needs on the screen in pixel
833 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
834 {
835         pos_type last = pit->beginningOfBody();
836
837         BOOST_ASSERT(last > 0);
838
839         // -1 because a label ends either with a space that is in the label,
840         // or with the beginning of a footnote that is outside the label.
841         --last;
842
843         // a separator at this end does not count
844         if (pit->isLineSeparator(last))
845                 --last;
846
847         int w = 0;
848         pos_type i = row.pos();
849         while (i <= last) {
850                 w += singleWidth(pit, i);
851                 ++i;
852         }
853
854         int fill = 0;
855         string const & labwidstr = pit->params().labelWidthString();
856         if (!labwidstr.empty()) {
857                 LyXFont const labfont = getLabelFont(pit);
858                 int const labwidth = font_metrics::width(labwidstr, labfont);
859                 fill = max(labwidth - w, 0);
860         }
861
862         return fill;
863 }
864
865
866 LColor_color LyXText::backgroundColor() const
867 {
868         if (inset_owner)
869                 return inset_owner->backgroundColor();
870         else
871                 return LColor::background;
872 }
873
874
875 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
876 {
877         // get the maximum ascent and the maximum descent
878         double layoutasc = 0;
879         double layoutdesc = 0;
880         double tmptop = 0;
881
882         // ok, let us initialize the maxasc and maxdesc value.
883         // Only the fontsize count. The other properties
884         // are taken from the layoutfont. Nicer on the screen :)
885         LyXLayout_ptr const & layout = pit->layout();
886
887         // as max get the first character of this row then it can increase but not
888         // decrease the height. Just some point to start with so we don't have to
889         // do the assignment below too often.
890         LyXFont font = getFont(pit, row.pos());
891         LyXFont::FONT_SIZE const tmpsize = font.size();
892         font = getLayoutFont(pit);
893         LyXFont::FONT_SIZE const size = font.size();
894         font.setSize(tmpsize);
895
896         LyXFont labelfont = getLabelFont(pit);
897
898         double spacing_val = 1.0;
899         if (!pit->params().spacing().isDefault())
900                 spacing_val = pit->params().spacing().getValue();
901         else
902                 spacing_val = bv()->buffer()->params().spacing().getValue();
903         //lyxerr << "spacing_val = " << spacing_val << endl;
904
905         int maxasc  = int(font_metrics::maxAscent(font) *
906                           layout->spacing.getValue() * spacing_val);
907         int maxdesc = int(font_metrics::maxDescent(font) *
908                           layout->spacing.getValue() * spacing_val);
909
910         pos_type const pos_end = lastPos(*pit, row);
911         int labeladdon = 0;
912         int maxwidth = 0;
913
914         if (!pit->empty()) {
915                 // We re-use the font resolution for the entire font span when possible
916                 LyXFont font = getFont(pit, row.pos());
917                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(row.pos());
918
919                 // Optimisation
920                 Paragraph const & par = *pit;
921
922                 // Check if any insets are larger
923                 for (pos_type pos = row.pos(); pos <= pos_end; ++pos) {
924                         // Manual inlined optimised version of common case of
925                         // "maxwidth += singleWidth(pit, pos);"
926                         char const c = par.getChar(pos);
927
928                         if (IsPrintable(c)) {
929                                 if (pos > endPosOfFontSpan) {
930                                         // We need to get the next font
931                                         font = getFont(pit, pos);
932                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
933                                 }
934                                 if (! font.language()->RightToLeft()) {
935                                         maxwidth += font_metrics::width(c, font);
936                                 } else {
937                                         // Fall-back to normal case
938                                         maxwidth += singleWidth(pit, pos, c, font);
939                                         // And flush font cache
940                                         endPosOfFontSpan = 0;
941                                 }
942                         } else {
943                                 // Special handling of insets - are any larger?
944                                 if (par.isInset(pos)) {
945                                         InsetOld const * tmpinset = par.getInset(pos);
946                                         if (tmpinset) {
947                                                 maxwidth += tmpinset->width();
948                                                 maxasc = max(maxasc, tmpinset->ascent());
949                                                 maxdesc = max(maxdesc, tmpinset->descent());
950                                         }
951                                 } else {
952                                         // Fall-back to normal case
953                                         maxwidth += singleWidth(pit, pos, c, font);
954                                         // And flush font cache
955                                         endPosOfFontSpan = 0;
956                                 }
957                         }
958                 }
959         }
960
961         // Check if any custom fonts are larger (Asger)
962         // This is not completely correct, but we can live with the small,
963         // cosmetic error for now.
964         LyXFont::FONT_SIZE maxsize =
965                 pit->highestFontInRange(row.pos(), pos_end, size);
966         if (maxsize > font.size()) {
967                 font.setSize(maxsize);
968                 maxasc = max(maxasc, font_metrics::maxAscent(font));
969                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
970         }
971
972         // This is nicer with box insets:
973         ++maxasc;
974         ++maxdesc;
975
976         row.ascent_of_text(maxasc);
977
978         // is it a top line?
979         if (!row.pos()) {
980                 BufferParams const & bufparams = bv()->buffer()->params();
981                 // some parksips VERY EASY IMPLEMENTATION
982                 if (bv()->buffer()->params().paragraph_separation ==
983                         BufferParams::PARSEP_SKIP)
984                 {
985                         if (layout->isParagraph()
986                                 && pit->getDepth() == 0
987                                 && pit != ownerParagraphs().begin())
988                         {
989                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
990                         } else if (pit != ownerParagraphs().begin() &&
991                                    boost::prior(pit)->layout()->isParagraph() &&
992                                    boost::prior(pit)->getDepth() == 0)
993                         {
994                                 // is it right to use defskip here too? (AS)
995                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
996                         }
997                 }
998
999                 // the top margin
1000                 if (pit == ownerParagraphs().begin() && !isInInset())
1001                         maxasc += PAPER_MARGIN;
1002
1003                 // add the vertical spaces, that the user added
1004                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1005
1006                 // do not forget the DTP-lines!
1007                 // there height depends on the font of the nearest character
1008                 if (pit->params().lineTop())
1009
1010                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1011                 // and now the pagebreaks
1012                 if (pit->params().pagebreakTop())
1013                         maxasc += 3 * defaultRowHeight();
1014
1015                 if (pit->params().startOfAppendix())
1016                         maxasc += 3 * defaultRowHeight();
1017
1018                 // This is special code for the chapter, since the label of this
1019                 // layout is printed in an extra row
1020                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
1021                         float spacing_val = 1.0;
1022                         if (!pit->params().spacing().isDefault()) {
1023                                 spacing_val = pit->params().spacing().getValue();
1024                         } else {
1025                                 spacing_val = bufparams.spacing().getValue();
1026                         }
1027
1028                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1029                                          layout->spacing.getValue() *
1030                                          spacing_val)
1031                                 + int(font_metrics::maxAscent(labelfont) *
1032                                       layout->spacing.getValue() *
1033                                       spacing_val);
1034                 }
1035
1036                 // special code for the top label
1037                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1038                      || layout->labeltype == LABEL_BIBLIO
1039                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1040                     && isFirstInSequence(pit, ownerParagraphs())
1041                     && !pit->getLabelstring().empty())
1042                 {
1043                         float spacing_val = 1.0;
1044                         if (!pit->params().spacing().isDefault()) {
1045                                 spacing_val = pit->params().spacing().getValue();
1046                         } else {
1047                                 spacing_val = bufparams.spacing().getValue();
1048                         }
1049
1050                         labeladdon = int(
1051                                 (font_metrics::maxAscent(labelfont) +
1052                                  font_metrics::maxDescent(labelfont)) *
1053                                   layout->spacing.getValue() *
1054                                   spacing_val
1055                                 + layout->topsep * defaultRowHeight()
1056                                 + layout->labelbottomsep * defaultRowHeight());
1057                 }
1058
1059                 // And now the layout spaces, for example before and after
1060                 // a section, or between the items of a itemize or enumerate
1061                 // environment.
1062
1063                 if (!pit->params().pagebreakTop()) {
1064                         ParagraphList::iterator prev =
1065                                 depthHook(pit, ownerParagraphs(),
1066                                           pit->getDepth());
1067                         if (prev != pit && prev->layout() == layout &&
1068                                 prev->getDepth() == pit->getDepth() &&
1069                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1070                         {
1071                                 layoutasc = (layout->itemsep * defaultRowHeight());
1072 //                      } else if (rit != firstRow()) {
1073                         } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
1074                                 tmptop = layout->topsep;
1075
1076                                 if (tmptop > 0)
1077                                         layoutasc = (tmptop * defaultRowHeight());
1078                         } else if (pit->params().lineTop()) {
1079                                 tmptop = layout->topsep;
1080
1081                                 if (tmptop > 0)
1082                                         layoutasc = (tmptop * defaultRowHeight());
1083                         }
1084
1085                         prev = outerHook(pit, ownerParagraphs());
1086                         if (prev != ownerParagraphs().end())  {
1087                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1088                         } else if (pit != ownerParagraphs().begin()) {
1089                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1090                                 if (prior_pit->getDepth() != 0 ||
1091                                     prior_pit->layout() == layout) {
1092                                         maxasc += int(layout->parsep * defaultRowHeight());
1093                                 }
1094                         }
1095                 }
1096         }
1097
1098         // is it a bottom line?
1099         if (row.end() == pit->size()) {
1100                 // the bottom margin
1101                 ParagraphList::iterator nextpit = boost::next(pit);
1102                 if (nextpit == ownerParagraphs().end() && !isInInset())
1103                         maxdesc += PAPER_MARGIN;
1104
1105                 // add the vertical spaces, that the user added
1106                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1107
1108                 // do not forget the DTP-lines!
1109                 // there height depends on the font of the nearest character
1110                 if (pit->params().lineBottom())
1111                         maxdesc += 2 * font_metrics::ascent('x',
1112                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1113
1114                 // and now the pagebreaks
1115                 if (pit->params().pagebreakBottom())
1116                         maxdesc += 3 * defaultRowHeight();
1117
1118                 // and now the layout spaces, for example before and after
1119                 // a section, or between the items of a itemize or enumerate
1120                 // environment
1121                 if (!pit->params().pagebreakBottom()
1122                     && nextpit != ownerParagraphs().end()) {
1123                         ParagraphList::iterator comparepit = pit;
1124                         float usual = 0;
1125                         float unusual = 0;
1126
1127                         if (comparepit->getDepth() > nextpit->getDepth()) {
1128                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1129                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1130                                 if (comparepit->layout()!= nextpit->layout()
1131                                         || nextpit->getLabelWidthString() !=
1132                                         comparepit->getLabelWidthString())
1133                                 {
1134                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1135                                 }
1136                                 if (unusual > usual)
1137                                         layoutdesc = unusual;
1138                                 else
1139                                         layoutdesc = usual;
1140                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1141
1142                                 if (comparepit->layout() != nextpit->layout()
1143                                         || nextpit->getLabelWidthString() !=
1144                                         comparepit->getLabelWidthString())
1145                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1146                         }
1147                 }
1148         }
1149
1150         // incalculate the layout spaces
1151         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1152         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1153
1154         row.height(maxasc + maxdesc + labeladdon);
1155         row.baseline(maxasc + labeladdon);
1156         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
1157
1158         row.width(maxwidth);
1159         if (inset_owner) {
1160                 width = max(0, workWidth());
1161                 RowList::iterator rit = firstRow();
1162                 RowList::iterator end = endRow();
1163                 ParagraphList::iterator it = ownerParagraphs().begin();
1164                 while (rit != end) {
1165                         if (rit->width() > width)
1166                                 width = rit->width();
1167                         nextRow(it, rit);
1168                 }
1169         }
1170 }
1171
1172
1173 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1174 {
1175         // allow only if at start or end, or all previous is new text
1176         if (cursor.pos() && cursor.pos() != cursorPar()->size()
1177                 && cursorPar()->isChangeEdited(0, cursor.pos()))
1178                 return;
1179
1180         LyXTextClass const & tclass =
1181                 bv()->buffer()->params().getLyXTextClass();
1182         LyXLayout_ptr const & layout = cursorPar()->layout();
1183
1184         // this is only allowed, if the current paragraph is not empty or caption
1185         // and if it has not the keepempty flag active
1186         if (cursorPar()->empty() && !cursorPar()->allowEmpty()
1187            && layout->labeltype != LABEL_SENSITIVE)
1188                 return;
1189
1190         recUndo(cursor.par());
1191
1192         // Always break behind a space
1193         //
1194         // It is better to erase the space (Dekel)
1195         if (cursor.pos() < cursorPar()->size()
1196              && cursorPar()->isLineSeparator(cursor.pos()))
1197            cursorPar()->erase(cursor.pos());
1198
1199         // break the paragraph
1200         if (keep_layout)
1201                 keep_layout = 2;
1202         else
1203                 keep_layout = layout->isEnvironment();
1204
1205         // we need to set this before we insert the paragraph. IMO the
1206         // breakParagraph call should return a bool if it inserts the
1207         // paragraph before or behind and we should react on that one
1208         // but we can fix this in 1.3.0 (Jug 20020509)
1209         bool const isempty = (cursorPar()->allowEmpty() && cursorPar()->empty());
1210         ::breakParagraph(bv()->buffer()->params(), paragraphs, cursorPar(),
1211                          cursor.pos(), keep_layout);
1212
1213 #warning Trouble Point! (Lgb)
1214         // When ::breakParagraph is called from within an inset we must
1215         // ensure that the correct ParagraphList is used. Today that is not
1216         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1217         ParagraphList::iterator next_par = boost::next(cursorPar());
1218
1219         // well this is the caption hack since one caption is really enough
1220         if (layout->labeltype == LABEL_SENSITIVE) {
1221                 if (!cursor.pos())
1222                         // set to standard-layout
1223                         cursorPar()->applyLayout(tclass.defaultLayout());
1224                 else
1225                         // set to standard-layout
1226                         next_par->applyLayout(tclass.defaultLayout());
1227         }
1228
1229         // if the cursor is at the beginning of a row without prior newline,
1230         // move one row up!
1231         // This touches only the screen-update. Otherwise we would may have
1232         // an empty row on the screen
1233         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1234             && !cursorPar()->isNewline(cursor.pos() - 1))
1235         {
1236                 cursorLeft(bv());
1237         }
1238
1239         while (!next_par->empty() && next_par->isNewline(0))
1240                 next_par->erase(0);
1241
1242         updateCounters();
1243         redoParagraph(cursorPar());
1244         redoParagraph(next_par);
1245
1246         // This check is necessary. Otherwise the new empty paragraph will
1247         // be deleted automatically. And it is more friendly for the user!
1248         if (cursor.pos() || isempty)
1249                 setCursor(next_par, 0);
1250         else
1251                 setCursor(cursorPar(), 0);
1252 }
1253
1254
1255 // convenience function
1256 void LyXText::redoParagraph()
1257 {
1258         clearSelection();
1259         redoParagraph(cursorPar());
1260         setCursorIntern(cursor.par(), cursor.pos());
1261 }
1262
1263
1264 // insert a character, moves all the following breaks in the
1265 // same Paragraph one to the right and make a rebreak
1266 void LyXText::insertChar(char c)
1267 {
1268         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
1269
1270         // When the free-spacing option is set for the current layout,
1271         // disable the double-space checking
1272
1273         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
1274                 cursorPar()->isFreeSpacing();
1275
1276         if (lyxrc.auto_number) {
1277                 static string const number_operators = "+-/*";
1278                 static string const number_unary_operators = "+-";
1279                 static string const number_seperators = ".,:";
1280
1281                 if (current_font.number() == LyXFont::ON) {
1282                         if (!IsDigit(c) && !contains(number_operators, c) &&
1283                             !(contains(number_seperators, c) &&
1284                               cursor.pos() >= 1 &&
1285                               cursor.pos() < cursorPar()->size() &&
1286                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1287                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1288                            )
1289                                 number(bv()); // Set current_font.number to OFF
1290                 } else if (IsDigit(c) &&
1291                            real_current_font.isVisibleRightToLeft()) {
1292                         number(bv()); // Set current_font.number to ON
1293
1294                         if (cursor.pos() > 0) {
1295                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1296                                 if (contains(number_unary_operators, c) &&
1297                                     (cursor.pos() == 1 ||
1298                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1299                                      cursorPar()->isNewline(cursor.pos() - 2))
1300                                   ) {
1301                                         setCharFont(
1302                                                     cursorPar(),
1303                                                     cursor.pos() - 1,
1304                                                     current_font);
1305                                 } else if (contains(number_seperators, c) &&
1306                                            cursor.pos() >= 2 &&
1307                                            getFont(
1308                                                    cursorPar(),
1309                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1310                                         setCharFont(
1311                                                     cursorPar(),
1312                                                     cursor.pos() - 1,
1313                                                     current_font);
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319
1320         // First check, if there will be two blanks together or a blank at
1321         // the beginning of a paragraph.
1322         // I decided to handle blanks like normal characters, the main
1323         // difference are the special checks when calculating the row.fill
1324         // (blank does not count at the end of a row) and the check here
1325
1326         // The bug is triggered when we type in a description environment:
1327         // The current_font is not changed when we go from label to main text
1328         // and it should (along with realtmpfont) when we type the space.
1329         // CHECK There is a bug here! (Asger)
1330
1331         // store the current font.  This is because of the use of cursor
1332         // movements. The moving cursor would refresh the current font
1333         LyXFont realtmpfont = real_current_font;
1334         LyXFont rawtmpfont = current_font;
1335
1336         if (!freeSpacing && IsLineSeparatorChar(c)) {
1337                 if ((cursor.pos() > 0
1338                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1339                     || (cursor.pos() > 0
1340                         && cursorPar()->isNewline(cursor.pos() - 1))
1341                     || (cursor.pos() == 0)) {
1342                         static bool sent_space_message = false;
1343                         if (!sent_space_message) {
1344                                 if (cursor.pos() == 0)
1345                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1346                                 else
1347                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1348                                 sent_space_message = true;
1349                         }
1350                         charInserted();
1351                         return;
1352                 }
1353         }
1354
1355         // Here case LyXText::InsertInset already inserted the character
1356         if (c != Paragraph::META_INSET)
1357                 cursorPar()->insertChar(cursor.pos(), c);
1358
1359         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1360
1361         current_font = rawtmpfont;
1362         real_current_font = realtmpfont;
1363         redoParagraph(cursorPar());
1364         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1365
1366         charInserted();
1367 }
1368
1369
1370 void LyXText::charInserted()
1371 {
1372         // Here we could call finishUndo for every 20 characters inserted.
1373         // This is from my experience how emacs does it. (Lgb)
1374         static unsigned int counter;
1375         if (counter < 20) {
1376                 ++counter;
1377         } else {
1378                 finishUndo();
1379                 counter = 0;
1380         }
1381 }
1382
1383
1384 void LyXText::prepareToPrint(ParagraphList::iterator pit,
1385            RowList::iterator const rit) const
1386 {
1387         double w = rit->fill();
1388         double fill_hfill = 0;
1389         double fill_label_hfill = 0;
1390         double fill_separator = 0;
1391         double x = 0;
1392
1393         bool const is_rtl =
1394                 pit->isRightToLeftPar(bv()->buffer()->params());
1395         if (is_rtl)
1396                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), *rit) : 0;
1397         else
1398                 x = workWidth() > 0 ? leftMargin(pit, *rit) : 0;
1399
1400         // is there a manual margin with a manual label
1401         LyXLayout_ptr const & layout = pit->layout();
1402
1403         if (layout->margintype == MARGIN_MANUAL
1404             && layout->labeltype == LABEL_MANUAL) {
1405                 /// We might have real hfills in the label part
1406                 int nlh = numberOfLabelHfills(*pit, *rit);
1407
1408                 // A manual label par (e.g. List) has an auto-hfill
1409                 // between the label text and the body of the
1410                 // paragraph too.
1411                 // But we don't want to do this auto hfill if the par
1412                 // is empty.
1413                 if (!pit->empty())
1414                         ++nlh;
1415
1416                 if (nlh && !pit->getLabelWidthString().empty()) {
1417                         fill_label_hfill = labelFill(pit, *rit) / double(nlh);
1418                 }
1419         }
1420
1421         // are there any hfills in the row?
1422         int const nh = numberOfHfills(*pit, *rit);
1423
1424         if (nh) {
1425                 if (w > 0)
1426                         fill_hfill = w / nh;
1427         // we don't have to look at the alignment if it is ALIGN_LEFT and
1428         // if the row is already larger then the permitted width as then
1429         // we force the LEFT_ALIGN'edness!
1430         } else if (int(rit->width()) < workWidth()) {
1431                 // is it block, flushleft or flushright?
1432                 // set x how you need it
1433                 int align;
1434                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1435                         align = layout->align;
1436                 } else {
1437                         align = pit->params().align();
1438                 }
1439                 InsetOld * inset = 0;
1440                 // ERT insets should always be LEFT ALIGNED on screen
1441                 inset = pit->inInset();
1442                 if (inset && inset->owner() &&
1443                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1444                 {
1445                         align = LYX_ALIGN_LEFT;
1446                 }
1447
1448                 switch (align) {
1449             case LYX_ALIGN_BLOCK:
1450                 {
1451                         int const ns = numberOfSeparators(*pit, *rit);
1452                         RowList::iterator next_row = boost::next(rit);
1453                         if (ns
1454                                 && next_row != pit->rows.end()
1455                                 && !pit->isNewline(next_row->pos() - 1)
1456                                 ) {
1457                                         fill_separator = w / ns;
1458                         } else if (is_rtl) {
1459                                 x += w;
1460                         }
1461                         break;
1462             }
1463             case LYX_ALIGN_RIGHT:
1464                         x += w;
1465                         break;
1466             case LYX_ALIGN_CENTER:
1467                         x += w / 2;
1468                         break;
1469                 }
1470         }
1471
1472         computeBidiTables(*pit, *bv()->buffer(), *rit);
1473         if (is_rtl) {
1474                 pos_type body_pos = pit->beginningOfBody();
1475                 pos_type last = lastPos(*pit, *rit);
1476
1477                 if (body_pos > 0 &&
1478                                 (body_pos - 1 > last ||
1479                                  !pit->isLineSeparator(body_pos - 1))) {
1480                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1481                         if (body_pos - 1 <= last)
1482                                 x += fill_label_hfill;
1483                 }
1484         }
1485
1486         rit->fill_hfill(fill_hfill);
1487         rit->fill_label_hfill(fill_label_hfill);
1488         rit->fill_separator(fill_separator);
1489         rit->x(x);
1490 }
1491
1492
1493 // important for the screen
1494
1495
1496 // the cursor set functions have a special mechanism. When they
1497 // realize, that you left an empty paragraph, they will delete it.
1498 // They also delete the corresponding row
1499
1500 void LyXText::cursorRightOneWord()
1501 {
1502         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1503         setCursor(cursorPar(), cursor.pos());
1504 }
1505
1506
1507 // Skip initial whitespace at end of word and move cursor to *start*
1508 // of prior word, not to end of next prior word.
1509 void LyXText::cursorLeftOneWord()
1510 {
1511         LyXCursor tmpcursor = cursor;
1512         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1513         setCursor(getPar(tmpcursor), tmpcursor.pos());
1514 }
1515
1516
1517 void LyXText::selectWord(word_location loc)
1518 {
1519         LyXCursor from = cursor;
1520         LyXCursor to = cursor;
1521         ::getWord(*this, from, to, loc, ownerParagraphs());
1522         if (cursor != from)
1523                 setCursor(from.par(), from.pos());
1524         if (to == from)
1525                 return;
1526         selection.cursor = cursor;
1527         setCursor(to.par(), to.pos());
1528         setSelection();
1529 }
1530
1531
1532 // Select the word currently under the cursor when no
1533 // selection is currently set
1534 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1535 {
1536         if (!selection.set()) {
1537                 selectWord(loc);
1538                 return selection.set();
1539         }
1540         return false;
1541 }
1542
1543
1544 void LyXText::acceptChange()
1545 {
1546         if (!selection.set() && cursorPar()->size())
1547                 return;
1548
1549         if (selection.start.par() == selection.end.par()) {
1550                 LyXCursor & startc = selection.start;
1551                 LyXCursor & endc = selection.end;
1552                 recordUndo(Undo::INSERT, this, startc.par());
1553                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1554                 finishUndo();
1555                 clearSelection();
1556                 redoParagraph(getPar(startc));
1557                 setCursorIntern(startc.par(), 0);
1558         }
1559 #warning handle multi par selection
1560 }
1561
1562
1563 void LyXText::rejectChange()
1564 {
1565         if (!selection.set() && cursorPar()->size())
1566                 return;
1567
1568         if (selection.start.par() == selection.end.par()) {
1569                 LyXCursor & startc = selection.start;
1570                 LyXCursor & endc = selection.end;
1571                 recordUndo(Undo::INSERT, this, startc.par());
1572                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1573                 finishUndo();
1574                 clearSelection();
1575                 redoParagraph(getPar(startc));
1576                 setCursorIntern(startc.par(), 0);
1577         }
1578 #warning handle multi par selection
1579 }
1580
1581
1582 // This function is only used by the spellchecker for NextWord().
1583 // It doesn't handle LYX_ACCENTs and probably never will.
1584 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1585 {
1586         if (the_locking_inset) {
1587                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1588                 if (!word.word().empty()) {
1589                         value += float(cursor.y());
1590                         value /= float(height);
1591                         return word;
1592                 }
1593                 // we have to go on checking so move cursor to the next char
1594                 if (cursor.pos() == cursorPar()->size()) {
1595                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1596                                 return word;
1597                         cursor.par(cursor.par() + 1);
1598                         cursor.pos(0);
1599                 } else
1600                                 cursor.pos(cursor.pos() + 1);
1601         }
1602         int const tmppar = cursor.par();
1603
1604         // If this is not the very first word, skip rest of
1605         // current word because we are probably in the middle
1606         // of a word if there is text here.
1607         if (cursor.pos() || cursor.par() != 0) {
1608                 while (cursor.pos() < cursorPar()->size()
1609                        && cursorPar()->isLetter(cursor.pos()))
1610                         cursor.pos(cursor.pos() + 1);
1611         }
1612
1613         // Now, skip until we have real text (will jump paragraphs)
1614         while (true) {
1615                 ParagraphList::iterator cpit = cursorPar();
1616                 pos_type const cpos = cursor.pos();
1617
1618                 if (cpos == cpit->size()) {
1619                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1620                                 cursor.par(cursor.par() + 1);
1621                                 cursor.pos(0);
1622                                 continue;
1623                         }
1624                         break;
1625                 }
1626
1627                 bool const is_good_inset = cpit->isInset(cpos)
1628                         && cpit->getInset(cpos)->allowSpellcheck();
1629
1630                 if (!isDeletedText(*cpit, cpos)
1631                     && (is_good_inset || cpit->isLetter(cpos)))
1632                         break;
1633
1634                 cursor.pos(cpos + 1);
1635         }
1636
1637         // now check if we hit an inset so it has to be a inset containing text!
1638         if (cursor.pos() < cursorPar()->size() &&
1639             cursorPar()->isInset(cursor.pos())) {
1640                 // lock the inset!
1641                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1642                 cursorPar()->getInset(cursor.pos())->localDispatch(cmd);
1643                 // now call us again to do the above trick
1644                 // but obviously we have to start from down below ;)
1645                 return bv()->text->selectNextWordToSpellcheck(value);
1646         }
1647
1648         // Update the value if we changed paragraphs
1649         if (cursor.par() != tmppar) {
1650                 setCursor(cursor.par(), cursor.pos());
1651                 value = float(cursor.y())/float(height);
1652         }
1653
1654         // Start the selection from here
1655         selection.cursor = cursor;
1656
1657         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1658         // and find the end of the word (insets like optional hyphens
1659         // and ligature break are part of a word)
1660         while (cursor.pos() < cursorPar()->size()
1661                && cursorPar()->isLetter(cursor.pos())
1662                && !isDeletedText(*cursorPar(), cursor.pos()))
1663                 cursor.pos(cursor.pos() + 1);
1664
1665         // Finally, we copy the word to a string and return it
1666         string str;
1667         if (selection.cursor.pos() < cursor.pos()) {
1668                 pos_type i;
1669                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1670                         if (!cursorPar()->isInset(i))
1671                                 str += cursorPar()->getChar(i);
1672                 }
1673         }
1674         return WordLangTuple(str, lang_code);
1675 }
1676
1677
1678 // This one is also only for the spellchecker
1679 void LyXText::selectSelectedWord()
1680 {
1681         if (the_locking_inset) {
1682                 the_locking_inset->selectSelectedWord(bv());
1683                 return;
1684         }
1685         // move cursor to the beginning
1686         setCursor(selection.cursor.par(), selection.cursor.pos());
1687
1688         // set the sel cursor
1689         selection.cursor = cursor;
1690
1691         // now find the end of the word
1692         while (cursor.pos() < cursorPar()->size()
1693                && cursorPar()->isLetter(cursor.pos()))
1694                 cursor.pos(cursor.pos() + 1);
1695
1696         setCursor(cursorPar(), cursor.pos());
1697
1698         // finally set the selection
1699         setSelection();
1700 }
1701
1702
1703 // Delete from cursor up to the end of the current or next word.
1704 void LyXText::deleteWordForward()
1705 {
1706         if (cursorPar()->empty())
1707                 cursorRight(bv());
1708         else {
1709                 LyXCursor tmpcursor = cursor;
1710                 selection.set(true); // to avoid deletion
1711                 cursorRightOneWord();
1712                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1713                 selection.cursor = cursor;
1714                 cursor = tmpcursor;
1715                 setSelection();
1716
1717                 // Great, CutSelection() gets rid of multiple spaces.
1718                 cutSelection(true, false);
1719         }
1720 }
1721
1722
1723 // Delete from cursor to start of current or prior word.
1724 void LyXText::deleteWordBackward()
1725 {
1726         if (cursorPar()->empty())
1727                 cursorLeft(bv());
1728         else {
1729                 LyXCursor tmpcursor = cursor;
1730                 selection.set(true); // to avoid deletion
1731                 cursorLeftOneWord();
1732                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1733                 selection.cursor = cursor;
1734                 cursor = tmpcursor;
1735                 setSelection();
1736                 cutSelection(true, false);
1737         }
1738 }
1739
1740
1741 // Kill to end of line.
1742 void LyXText::deleteLineForward()
1743 {
1744         if (cursorPar()->empty())
1745                 // Paragraph is empty, so we just go to the right
1746                 cursorRight(bv());
1747         else {
1748                 LyXCursor tmpcursor = cursor;
1749                 // We can't store the row over a regular setCursor
1750                 // so we set it to 0 and reset it afterwards.
1751                 selection.set(true); // to avoid deletion
1752                 cursorEnd();
1753                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1754                 selection.cursor = cursor;
1755                 cursor = tmpcursor;
1756                 setSelection();
1757                 // What is this test for ??? (JMarc)
1758                 if (!selection.set()) {
1759                         deleteWordForward();
1760                 } else {
1761                         cutSelection(true, false);
1762                 }
1763         }
1764 }
1765
1766
1767 void LyXText::changeCase(LyXText::TextCase action)
1768 {
1769         LyXCursor from;
1770         LyXCursor to;
1771
1772         if (selection.set()) {
1773                 from = selection.start;
1774                 to = selection.end;
1775         } else {
1776                 from = cursor;
1777                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1778                 setCursor(to.par(), to.pos() + 1);
1779         }
1780
1781         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1782
1783         pos_type pos = from.pos();
1784         int par = from.par();
1785
1786         while (par != int(ownerParagraphs().size()) &&
1787                (pos != to.pos() || par != to.par())) {
1788                 ParagraphList::iterator pit = getPar(par);
1789                 if (pos == pit->size()) {
1790                         ++par;
1791                         pos = 0;
1792                         continue;
1793                 }
1794                 unsigned char c = pit->getChar(pos);
1795                 if (c != Paragraph::META_INSET) {
1796                         switch (action) {
1797                         case text_lowercase:
1798                                 c = lowercase(c);
1799                                 break;
1800                         case text_capitalization:
1801                                 c = uppercase(c);
1802                                 action = text_lowercase;
1803                                 break;
1804                         case text_uppercase:
1805                                 c = uppercase(c);
1806                                 break;
1807                         }
1808                 }
1809 #warning changes
1810                 pit->setChar(pos, c);
1811                 ++pos;
1812         }
1813 }
1814
1815
1816 void LyXText::Delete()
1817 {
1818         // this is a very easy implementation
1819
1820         LyXCursor old_cursor = cursor;
1821         int const old_cur_par_id = cursorPar()->id();
1822         int const old_cur_par_prev_id =
1823                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1824
1825         // just move to the right
1826         cursorRight(bv());
1827
1828         // CHECK Look at the comment here.
1829         // This check is not very good...
1830         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1831         // and that can very well delete the par or par->previous in
1832         // old_cursor. Will a solution where we compare paragraph id's
1833         //work better?
1834         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1835         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1836                 // delete-empty-paragraph-mechanism has done it
1837                 return;
1838         }
1839
1840         // if you had success make a backspace
1841         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1842                 recordUndo(Undo::DELETE, this, old_cursor.par());
1843                 backspace();
1844         }
1845 }
1846
1847
1848 void LyXText::backspace()
1849 {
1850         // Get the font that is used to calculate the baselineskip
1851         ParagraphList::iterator pit = cursorPar();
1852         pos_type lastpos = pit->size();
1853
1854         if (cursor.pos() == 0) {
1855                 // The cursor is at the beginning of a paragraph,
1856                 // so the the backspace will collapse two paragraphs into one.
1857
1858                 // but it's not allowed unless it's new
1859                 if (pit->isChangeEdited(0, pit->size()))
1860                         return;
1861
1862                 // we may paste some paragraphs
1863
1864                 // is it an empty paragraph?
1865
1866                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1867                         // This is an empty paragraph and we delete it just
1868                         // by moving the cursor one step
1869                         // left and let the DeleteEmptyParagraphMechanism
1870                         // handle the actual deletion of the paragraph.
1871
1872                         if (cursor.par()) {
1873                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1874                                 if (cursorPar()->layout() == tmppit->layout()
1875                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1876                                         // Inherit bottom DTD from the paragraph below.
1877                                         // (the one we are deleting)
1878                                         tmppit->params().lineBottom(cursorPar()->params().lineBottom());
1879                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1880                                         tmppit->params().pagebreakBottom(cursorPar()->params().pagebreakBottom());
1881                                 }
1882
1883                                 cursorLeft(bv());
1884
1885                                 // the layout things can change the height of a row !
1886                                 redoParagraph();
1887                                 return;
1888                         }
1889                 }
1890
1891                 if (cursor.par() != 0)
1892                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1893
1894                 ParagraphList::iterator tmppit = cursorPar();
1895                 // We used to do cursorLeftIntern() here, but it is
1896                 // not a good idea since it triggers the auto-delete
1897                 // mechanism. So we do a cursorLeftIntern()-lite,
1898                 // without the dreaded mechanism. (JMarc)
1899                 if (cursor.par() != 0) {
1900                         // steps into the above paragraph.
1901                         setCursorIntern(cursor.par() - 1,
1902                                         getPar(cursor.par() - 1)->size(),
1903                                         false);
1904                 }
1905
1906                 // Pasting is not allowed, if the paragraphs have different
1907                 // layout. I think it is a real bug of all other
1908                 // word processors to allow it. It confuses the user.
1909                 // Correction: Pasting is always allowed with standard-layout
1910                 Buffer & buf = *bv()->buffer();
1911                 BufferParams const & bufparams = buf.params();
1912                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1913
1914                 if (cursorPar() != tmppit
1915                     && (cursorPar()->layout() == tmppit->layout()
1916                         || tmppit->layout() == tclass.defaultLayout())
1917                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1918                         mergeParagraph(bufparams,
1919                                        buf.paragraphs(), cursorPar());
1920
1921                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1922                                 cursor.pos(cursor.pos() - 1);
1923
1924                         // the row may have changed, block, hfills etc.
1925                         updateCounters();
1926                         setCursor(cursor.par(), cursor.pos(), false);
1927                 }
1928         } else {
1929                 // this is the code for a normal backspace, not pasting
1930                 // any paragraphs
1931                 recordUndo(Undo::DELETE, this, cursor.par());
1932                 // We used to do cursorLeftIntern() here, but it is
1933                 // not a good idea since it triggers the auto-delete
1934                 // mechanism. So we do a cursorLeftIntern()-lite,
1935                 // without the dreaded mechanism. (JMarc)
1936                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1937                                 false, cursor.boundary());
1938                 cursorPar()->erase(cursor.pos());
1939         }
1940
1941         lastpos = cursorPar()->size();
1942         if (cursor.pos() == lastpos)
1943                 setCurrentFont();
1944
1945         redoParagraph();
1946         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1947 }
1948
1949
1950 ParagraphList::iterator LyXText::cursorPar() const
1951 {
1952         return getPar(cursor.par());
1953 }
1954
1955
1956 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1957 {
1958         return getPar(cur.par());
1959 }
1960
1961
1962 ParagraphList::iterator LyXText::getPar(int par) const
1963 {
1964         BOOST_ASSERT(par >= 0);
1965         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1966         ParagraphList::iterator pit = ownerParagraphs().begin();
1967         std::advance(pit, par);
1968         return pit;
1969 }
1970
1971
1972
1973 RowList::iterator LyXText::cursorRow() const
1974 {
1975         return getRow(*cursorPar(), cursor.pos());
1976 }
1977
1978
1979 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
1980 {
1981         return getRow(*getPar(cur), cur.pos());
1982 }
1983
1984
1985 RowList::iterator LyXText::getRow(Paragraph & par, pos_type pos) const
1986 {
1987         RowList::iterator rit = boost::prior(par.rows.end());
1988         RowList::iterator const begin = par.rows.begin();
1989
1990         while (rit != begin && rit->pos() > pos)
1991                 --rit;
1992
1993         return rit;
1994 }
1995
1996
1997 RowList::iterator
1998 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1999 {
2000         //lyxerr << "getRowNearY: y " << y << endl;
2001
2002         pit = boost::prior(ownerParagraphs().end());
2003
2004         RowList::iterator rit = lastRow();
2005         RowList::iterator rbegin = firstRow();
2006
2007         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
2008                 previousRow(pit, rit);
2009
2010         return rit;
2011 }
2012
2013
2014 int LyXText::getDepth() const
2015 {
2016         return cursorPar()->getDepth();
2017 }
2018
2019
2020 RowList::iterator LyXText::firstRow() const
2021 {
2022         return ownerParagraphs().front().rows.begin();
2023 }
2024
2025
2026 RowList::iterator LyXText::lastRow() const
2027 {
2028         return boost::prior(endRow());
2029 }
2030
2031
2032 RowList::iterator LyXText::endRow() const
2033 {
2034         return ownerParagraphs().back().rows.end();
2035 }
2036
2037
2038 void LyXText::nextRow(ParagraphList::iterator & pit,
2039         RowList::iterator & rit) const
2040 {
2041         ++rit;
2042         if (rit == pit->rows.end()) {
2043                 ++pit;
2044                 if (pit == ownerParagraphs().end())
2045                         --pit;
2046                 else
2047                         rit = pit->rows.begin();
2048         }
2049 }
2050
2051
2052 void LyXText::previousRow(ParagraphList::iterator & pit,
2053         RowList::iterator & rit) const
2054 {
2055         if (rit != pit->rows.begin())
2056                 --rit;
2057         else {
2058                 BOOST_ASSERT(pit != ownerParagraphs().begin());
2059                 --pit;
2060                 rit = boost::prior(pit->rows.end());
2061         }
2062 }
2063
2064
2065 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
2066 {
2067         if (!selection.set())
2068                 return string();
2069
2070         // should be const ...
2071         ParagraphList::iterator startpit = getPar(selection.start);
2072         ParagraphList::iterator endpit = getPar(selection.end);
2073         size_t const startpos = selection.start.pos();
2074         size_t const endpos = selection.end.pos();
2075
2076         if (startpit == endpit)
2077                 return startpit->asString(buffer, startpos, endpos, label);
2078
2079         // First paragraph in selection
2080         string result =
2081                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
2082
2083         // The paragraphs in between (if any)
2084         ParagraphList::iterator pit = startpit;
2085         for (++pit; pit != endpit; ++pit)
2086                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
2087
2088         // Last paragraph in selection
2089         result += endpit->asString(buffer, 0, endpos, label);
2090
2091         return result;
2092 }
2093
2094
2095 int LyXText::parOffset(ParagraphList::iterator pit) const
2096 {
2097         return std::distance(ownerParagraphs().begin(), pit);
2098 }
2099
2100
2101 int LyXText::redoParagraphInternal(ParagraphList::iterator pit)
2102 {
2103         // remove rows of paragraph, keep track of height changes
2104         height -= pit->height;
2105         pit->rows.clear();
2106
2107         // redo insets
2108         InsetList::iterator ii = pit->insetlist.begin();
2109         InsetList::iterator iend = pit->insetlist.end();
2110         for (; ii != iend; ++ii) {
2111                 Dimension dim;
2112                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
2113                 ii->inset->metrics(mi, dim);
2114         }
2115
2116         // rebreak the paragraph
2117         int par_width = 0;
2118         int const ww = workWidth();
2119         pit->height = 0;
2120
2121         for (pos_type z = 0; z < pit->size() + 1; ) {
2122                 Row row(z);
2123                 z = rowBreakPoint(pit, row) + 1;
2124                 row.end(z);
2125                 pit->rows.push_back(row);
2126         }
2127
2128         RowList::iterator rit = pit->rows.begin();
2129         RowList::iterator end = pit->rows.end();
2130         for (rit = pit->rows.begin(); rit != end; ++rit) {
2131                 int const f = fill(pit, *rit, ww);
2132                 int const w = ww - f;
2133                 par_width = std::max(par_width, w);
2134                 rit->fill(f);
2135                 rit->width(w);
2136                 prepareToPrint(pit, rit);
2137                 setHeightOfRow(pit, *rit);
2138                 rit->y_offset(pit->height);
2139                 pit->height += rit->height();
2140         }
2141         height += pit->height;
2142
2143         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
2144         return par_width;
2145 }
2146
2147
2148 int LyXText::redoParagraphs(ParagraphList::iterator start,
2149   ParagraphList::iterator end)
2150 {
2151         int pars_width = 0;
2152         for ( ; start != end; ++start) {
2153                 int par_width = redoParagraphInternal(start);
2154                 pars_width = std::max(par_width, pars_width);
2155         }
2156         updateRowPositions();
2157         return pars_width;
2158 }
2159
2160
2161 void LyXText::redoParagraph(ParagraphList::iterator pit)
2162 {
2163         redoParagraphInternal(pit);
2164         updateRowPositions();
2165 }
2166
2167
2168 void LyXText::fullRebreak()
2169 {
2170         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2171         redoCursor();
2172         selection.cursor = cursor;
2173 }
2174
2175
2176 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
2177 {
2178         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
2179         //      << " workWidth: " << workWidth() << endl;
2180         //BOOST_ASSERT(mi.base.textwidth);
2181
2182         // rebuild row cache
2183         width  = 0;
2184         ///height = 0;
2185
2186         //anchor_y_ = 0;
2187         width = redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2188
2189         // final dimension
2190         dim.asc = firstRow()->ascent_of_text();
2191         dim.des = height - dim.asc;
2192         dim.wid = std::max(mi.base.textwidth, int(width));
2193 }
2194