]> git.lyx.org Git - lyx.git/blob - src/text.C
9760a8a60aa6ba0d2748932137c4ebf3594fa780
[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 different 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                 // Break before...      
695                 if (i + 1 < last) {
696                         InsetOld * in = pit->getInset(i + 1);
697                         if (in && in->display()) {
698                                 point = i;
699                                 break;
700                         }
701                         // ...and after.
702                         in = pit->getInset(i);
703                         if (in && in->display()) {
704                                 point = i;
705                                 break;
706                         }
707                 }
708
709                 char const c = pit->getChar(i);
710                 if (i > endPosOfFontSpan) {
711                         font = getFont(pit, i);
712                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
713                 }
714
715                 int thiswidth;
716
717                 // add the auto-hfill from label end to the body
718                 if (body_pos && i == body_pos) {
719                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
720                         if (pit->isLineSeparator(i - 1))
721                                 thiswidth -= singleWidth(pit, i - 1);
722                         int left_margin = labelEnd(pit, row);
723                         if (thiswidth + x < left_margin)
724                                 thiswidth = left_margin - x;
725                         thiswidth += singleWidth(pit, i, c, font);
726                 } else {
727                         thiswidth = singleWidth(pit, i, c, font);
728                 }
729
730                 x += thiswidth;
731                 chunkwidth += thiswidth;
732
733                 InsetOld * in = pit->getInset(i);
734
735                 // break before a character that will fall off
736                 // the right of the row
737                 if (x >= width) {
738                         // if no break before, break here
739                         if (point == last || chunkwidth >= width - left) {
740                                 if (pos < i) {
741                                         point = i - 1;
742                                         break;
743                                 }
744                         }
745                 }
746
747                 if (!in || in->isChar()) {
748                         // some insets are line separators too
749                         if (pit->isLineSeparator(i)) {
750                                 point = i;
751                                 chunkwidth = 0;
752                         }
753                 }
754         }
755
756         if (point == last && x >= width) {
757                 // didn't find one, break at the point we reached the edge
758                 point = i;
759         } else if (i == last && x < width) {
760                 // found one, but we fell off the end of the par, so prefer
761                 // that.
762                 point = last;
763         }
764
765         // manual labels cannot be broken in LaTeX. But we
766         // want to make our on-screen rendering of footnotes
767         // etc. still break
768         if (body_pos && point < body_pos)
769                 point = body_pos - 1;
770
771         return point;
772 }
773
774
775 // returns the minimum space a row needs on the screen in pixel
776 int LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
777 {
778         if (paper_width < 0)
779                 return 0;
780
781         int w;
782         // get the pure distance
783         pos_type const last = lastPos(*pit, row);
784
785         LyXLayout_ptr const & layout = pit->layout();
786
787         // special handling of the right address boxes
788         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
789                 int const tmpfill = row.fill();
790                 row.fill(0); // the minfill in MarginLeft()
791                 w = leftMargin(pit, row);
792                 row.fill(tmpfill);
793         } else
794                 w = leftMargin(pit, row);
795
796         pos_type const body_pos = pit->beginningOfBody();
797         pos_type i = row.pos();
798
799         if (! pit->empty() && i <= last) {
800                 // We re-use the font resolution for the entire span when possible
801                 LyXFont font = getFont(pit, i);
802                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
803                 while (i <= last) {
804                         if (body_pos > 0 && i == body_pos) {
805                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
806                                 if (pit->isLineSeparator(i - 1))
807                                         w -= singleWidth(pit, i - 1);
808                                 int left_margin = labelEnd(pit, row);
809                                 if (w < left_margin)
810                                         w = left_margin;
811                         }
812                         char const c = pit->getChar(i);
813                         if (IsPrintable(c) && i > endPosOfFontSpan) {
814                                 // We need to get the next font
815                                 font = getFont(pit, i);
816                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
817                         }
818                         w += singleWidth(pit, i, c, font);
819                         ++i;
820                 }
821         }
822         if (body_pos > 0 && body_pos > last) {
823                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
824                 if (last >= 0 && pit->isLineSeparator(last))
825                         w -= singleWidth(pit, last);
826                 int const left_margin = labelEnd(pit, row);
827                 if (w < left_margin)
828                         w = left_margin;
829         }
830
831         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
832
833         // If this case happens, it means that our calculation
834         // of the widths of the chars when we do rowBreakPoint()
835         // went wrong for some reason. Typically in list bodies.
836         // Things just about hobble on anyway, though you'll end
837         // up with a "fill_separator" less than zero, which corresponds
838         // to inter-word spacing being too small. Hopefully this problem
839         // will die when the label hacks die.
840         if (lyxerr.debugging() && fill < 0) {
841                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
842                         << " w " << w << " paper_width " << paper_width
843                         << " right margin " << rightMargin(*pit, *bv()->buffer(), row) << endl;
844         }
845         return fill;
846 }
847
848
849 // returns the minimum space a manual label needs on the screen in pixel
850 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
851 {
852         pos_type last = pit->beginningOfBody();
853
854         BOOST_ASSERT(last > 0);
855
856         // -1 because a label ends either with a space that is in the label,
857         // or with the beginning of a footnote that is outside the label.
858         --last;
859
860         // a separator at this end does not count
861         if (pit->isLineSeparator(last))
862                 --last;
863
864         int w = 0;
865         pos_type i = row.pos();
866         while (i <= last) {
867                 w += singleWidth(pit, i);
868                 ++i;
869         }
870
871         int fill = 0;
872         string const & labwidstr = pit->params().labelWidthString();
873         if (!labwidstr.empty()) {
874                 LyXFont const labfont = getLabelFont(pit);
875                 int const labwidth = font_metrics::width(labwidstr, labfont);
876                 fill = max(labwidth - w, 0);
877         }
878
879         return fill;
880 }
881
882
883 LColor_color LyXText::backgroundColor() const
884 {
885         if (inset_owner)
886                 return inset_owner->backgroundColor();
887         else
888                 return LColor::background;
889 }
890
891
892 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
893 {
894         // get the maximum ascent and the maximum descent
895         double layoutasc = 0;
896         double layoutdesc = 0;
897         double tmptop = 0;
898
899         // ok, let us initialize the maxasc and maxdesc value.
900         // Only the fontsize count. The other properties
901         // are taken from the layoutfont. Nicer on the screen :)
902         LyXLayout_ptr const & layout = pit->layout();
903
904         // as max get the first character of this row then it can increase but not
905         // decrease the height. Just some point to start with so we don't have to
906         // do the assignment below too often.
907         LyXFont font = getFont(pit, row.pos());
908         LyXFont::FONT_SIZE const tmpsize = font.size();
909         font = getLayoutFont(pit);
910         LyXFont::FONT_SIZE const size = font.size();
911         font.setSize(tmpsize);
912
913         LyXFont labelfont = getLabelFont(pit);
914
915         double spacing_val = 1.0;
916         if (!pit->params().spacing().isDefault())
917                 spacing_val = pit->params().spacing().getValue();
918         else
919                 spacing_val = bv()->buffer()->params().spacing().getValue();
920         //lyxerr << "spacing_val = " << spacing_val << endl;
921
922         int maxasc  = int(font_metrics::maxAscent(font) *
923                           layout->spacing.getValue() * spacing_val);
924         int maxdesc = int(font_metrics::maxDescent(font) *
925                           layout->spacing.getValue() * spacing_val);
926
927         pos_type const pos_end = lastPos(*pit, row);
928         int labeladdon = 0;
929         int maxwidth = 0;
930
931         if (!pit->empty()) {
932                 // We re-use the font resolution for the entire font span when possible
933                 LyXFont font = getFont(pit, row.pos());
934                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(row.pos());
935
936                 // Optimisation
937                 Paragraph const & par = *pit;
938
939                 // Check if any insets are larger
940                 for (pos_type pos = row.pos(); pos <= pos_end; ++pos) {
941                         // Manual inlined optimised version of common case of
942                         // "maxwidth += singleWidth(pit, pos);"
943                         char const c = par.getChar(pos);
944
945                         if (IsPrintable(c)) {
946                                 if (pos > endPosOfFontSpan) {
947                                         // We need to get the next font
948                                         font = getFont(pit, pos);
949                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
950                                 }
951                                 if (! font.language()->RightToLeft()) {
952                                         maxwidth += font_metrics::width(c, font);
953                                 } else {
954                                         // Fall-back to normal case
955                                         maxwidth += singleWidth(pit, pos, c, font);
956                                         // And flush font cache
957                                         endPosOfFontSpan = 0;
958                                 }
959                         } else {
960                                 // Special handling of insets - are any larger?
961                                 if (par.isInset(pos)) {
962                                         InsetOld const * tmpinset = par.getInset(pos);
963                                         if (tmpinset) {
964                                                 maxwidth += tmpinset->width();
965                                                 maxasc = max(maxasc, tmpinset->ascent());
966                                                 maxdesc = max(maxdesc, tmpinset->descent());
967                                         }
968                                 } else {
969                                         // Fall-back to normal case
970                                         maxwidth += singleWidth(pit, pos, c, font);
971                                         // And flush font cache
972                                         endPosOfFontSpan = 0;
973                                 }
974                         }
975                 }
976         }
977
978         // Check if any custom fonts are larger (Asger)
979         // This is not completely correct, but we can live with the small,
980         // cosmetic error for now.
981         LyXFont::FONT_SIZE maxsize =
982                 pit->highestFontInRange(row.pos(), pos_end, size);
983         if (maxsize > font.size()) {
984                 font.setSize(maxsize);
985                 maxasc = max(maxasc, font_metrics::maxAscent(font));
986                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
987         }
988
989         // This is nicer with box insets:
990         ++maxasc;
991         ++maxdesc;
992
993         row.ascent_of_text(maxasc);
994
995         // is it a top line?
996         if (!row.pos()) {
997                 BufferParams const & bufparams = bv()->buffer()->params();
998                 // some parksips VERY EASY IMPLEMENTATION
999                 if (bv()->buffer()->params().paragraph_separation ==
1000                         BufferParams::PARSEP_SKIP)
1001                 {
1002                         if (layout->isParagraph()
1003                                 && pit->getDepth() == 0
1004                                 && pit != ownerParagraphs().begin())
1005                         {
1006                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
1007                         } else if (pit != ownerParagraphs().begin() &&
1008                                    boost::prior(pit)->layout()->isParagraph() &&
1009                                    boost::prior(pit)->getDepth() == 0)
1010                         {
1011                                 // is it right to use defskip here too? (AS)
1012                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
1013                         }
1014                 }
1015
1016                 // the top margin
1017                 if (pit == ownerParagraphs().begin() && !isInInset())
1018                         maxasc += PAPER_MARGIN;
1019
1020                 // add the vertical spaces, that the user added
1021                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1022
1023                 // do not forget the DTP-lines!
1024                 // there height depends on the font of the nearest character
1025                 if (pit->params().lineTop())
1026
1027                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1028                 // and now the pagebreaks
1029                 if (pit->params().pagebreakTop())
1030                         maxasc += 3 * defaultRowHeight();
1031
1032                 if (pit->params().startOfAppendix())
1033                         maxasc += 3 * defaultRowHeight();
1034
1035                 // This is special code for the chapter, since the label of this
1036                 // layout is printed in an extra row
1037                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
1038                         float spacing_val = 1.0;
1039                         if (!pit->params().spacing().isDefault()) {
1040                                 spacing_val = pit->params().spacing().getValue();
1041                         } else {
1042                                 spacing_val = bufparams.spacing().getValue();
1043                         }
1044
1045                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1046                                          layout->spacing.getValue() *
1047                                          spacing_val)
1048                                 + int(font_metrics::maxAscent(labelfont) *
1049                                       layout->spacing.getValue() *
1050                                       spacing_val);
1051                 }
1052
1053                 // special code for the top label
1054                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1055                      || layout->labeltype == LABEL_BIBLIO
1056                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1057                     && isFirstInSequence(pit, ownerParagraphs())
1058                     && !pit->getLabelstring().empty())
1059                 {
1060                         float spacing_val = 1.0;
1061                         if (!pit->params().spacing().isDefault()) {
1062                                 spacing_val = pit->params().spacing().getValue();
1063                         } else {
1064                                 spacing_val = bufparams.spacing().getValue();
1065                         }
1066
1067                         labeladdon = int(
1068                                 (font_metrics::maxAscent(labelfont) +
1069                                  font_metrics::maxDescent(labelfont)) *
1070                                   layout->spacing.getValue() *
1071                                   spacing_val
1072                                 + layout->topsep * defaultRowHeight()
1073                                 + layout->labelbottomsep * defaultRowHeight());
1074                 }
1075
1076                 // And now the layout spaces, for example before and after
1077                 // a section, or between the items of a itemize or enumerate
1078                 // environment.
1079
1080                 if (!pit->params().pagebreakTop()) {
1081                         ParagraphList::iterator prev =
1082                                 depthHook(pit, ownerParagraphs(),
1083                                           pit->getDepth());
1084                         if (prev != pit && prev->layout() == layout &&
1085                                 prev->getDepth() == pit->getDepth() &&
1086                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1087                         {
1088                                 layoutasc = (layout->itemsep * defaultRowHeight());
1089 //                      } else if (rit != firstRow()) {
1090                         } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
1091                                 tmptop = layout->topsep;
1092
1093                                 if (tmptop > 0)
1094                                         layoutasc = (tmptop * defaultRowHeight());
1095                         } else if (pit->params().lineTop()) {
1096                                 tmptop = layout->topsep;
1097
1098                                 if (tmptop > 0)
1099                                         layoutasc = (tmptop * defaultRowHeight());
1100                         }
1101
1102                         prev = outerHook(pit, ownerParagraphs());
1103                         if (prev != ownerParagraphs().end())  {
1104                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1105                         } else if (pit != ownerParagraphs().begin()) {
1106                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1107                                 if (prior_pit->getDepth() != 0 ||
1108                                     prior_pit->layout() == layout) {
1109                                         maxasc += int(layout->parsep * defaultRowHeight());
1110                                 }
1111                         }
1112                 }
1113         }
1114
1115         // is it a bottom line?
1116         if (row.end() == pit->size()) {
1117                 // the bottom margin
1118                 ParagraphList::iterator nextpit = boost::next(pit);
1119                 if (nextpit == ownerParagraphs().end() && !isInInset())
1120                         maxdesc += PAPER_MARGIN;
1121
1122                 // add the vertical spaces, that the user added
1123                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1124
1125                 // do not forget the DTP-lines!
1126                 // there height depends on the font of the nearest character
1127                 if (pit->params().lineBottom())
1128                         maxdesc += 2 * font_metrics::ascent('x',
1129                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1130
1131                 // and now the pagebreaks
1132                 if (pit->params().pagebreakBottom())
1133                         maxdesc += 3 * defaultRowHeight();
1134
1135                 // and now the layout spaces, for example before and after
1136                 // a section, or between the items of a itemize or enumerate
1137                 // environment
1138                 if (!pit->params().pagebreakBottom()
1139                     && nextpit != ownerParagraphs().end()) {
1140                         ParagraphList::iterator comparepit = pit;
1141                         float usual = 0;
1142                         float unusual = 0;
1143
1144                         if (comparepit->getDepth() > nextpit->getDepth()) {
1145                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1146                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1147                                 if (comparepit->layout()!= nextpit->layout()
1148                                         || nextpit->getLabelWidthString() !=
1149                                         comparepit->getLabelWidthString())
1150                                 {
1151                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1152                                 }
1153                                 if (unusual > usual)
1154                                         layoutdesc = unusual;
1155                                 else
1156                                         layoutdesc = usual;
1157                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1158
1159                                 if (comparepit->layout() != nextpit->layout()
1160                                         || nextpit->getLabelWidthString() !=
1161                                         comparepit->getLabelWidthString())
1162                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1163                         }
1164                 }
1165         }
1166
1167         // incalculate the layout spaces
1168         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1169         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1170
1171         row.height(maxasc + maxdesc + labeladdon);
1172         row.baseline(maxasc + labeladdon);
1173         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
1174
1175         row.width(maxwidth);
1176         if (inset_owner) {
1177                 width = max(0, workWidth());
1178                 RowList::iterator rit = firstRow();
1179                 RowList::iterator end = endRow();
1180                 ParagraphList::iterator it = ownerParagraphs().begin();
1181                 while (rit != end) {
1182                         if (rit->width() > width)
1183                                 width = rit->width();
1184                         nextRow(it, rit);
1185                 }
1186         }
1187 }
1188
1189
1190 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1191 {
1192         // allow only if at start or end, or all previous is new text
1193         if (cursor.pos() && cursor.pos() != cursorPar()->size()
1194                 && cursorPar()->isChangeEdited(0, cursor.pos()))
1195                 return;
1196
1197         LyXTextClass const & tclass =
1198                 bv()->buffer()->params().getLyXTextClass();
1199         LyXLayout_ptr const & layout = cursorPar()->layout();
1200
1201         // this is only allowed, if the current paragraph is not empty or caption
1202         // and if it has not the keepempty flag active
1203         if (cursorPar()->empty() && !cursorPar()->allowEmpty()
1204            && layout->labeltype != LABEL_SENSITIVE)
1205                 return;
1206
1207         recUndo(cursor.par());
1208
1209         // Always break behind a space
1210         //
1211         // It is better to erase the space (Dekel)
1212         if (cursor.pos() < cursorPar()->size()
1213              && cursorPar()->isLineSeparator(cursor.pos()))
1214            cursorPar()->erase(cursor.pos());
1215
1216         // break the paragraph
1217         if (keep_layout)
1218                 keep_layout = 2;
1219         else
1220                 keep_layout = layout->isEnvironment();
1221
1222         // we need to set this before we insert the paragraph. IMO the
1223         // breakParagraph call should return a bool if it inserts the
1224         // paragraph before or behind and we should react on that one
1225         // but we can fix this in 1.3.0 (Jug 20020509)
1226         bool const isempty = (cursorPar()->allowEmpty() && cursorPar()->empty());
1227         ::breakParagraph(bv()->buffer()->params(), paragraphs, cursorPar(),
1228                          cursor.pos(), keep_layout);
1229
1230 #warning Trouble Point! (Lgb)
1231         // When ::breakParagraph is called from within an inset we must
1232         // ensure that the correct ParagraphList is used. Today that is not
1233         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1234         ParagraphList::iterator next_par = boost::next(cursorPar());
1235
1236         // well this is the caption hack since one caption is really enough
1237         if (layout->labeltype == LABEL_SENSITIVE) {
1238                 if (!cursor.pos())
1239                         // set to standard-layout
1240                         cursorPar()->applyLayout(tclass.defaultLayout());
1241                 else
1242                         // set to standard-layout
1243                         next_par->applyLayout(tclass.defaultLayout());
1244         }
1245
1246         // if the cursor is at the beginning of a row without prior newline,
1247         // move one row up!
1248         // This touches only the screen-update. Otherwise we would may have
1249         // an empty row on the screen
1250         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1251             && !cursorPar()->isNewline(cursor.pos() - 1))
1252         {
1253                 cursorLeft(bv());
1254         }
1255
1256         while (!next_par->empty() && next_par->isNewline(0))
1257                 next_par->erase(0);
1258
1259         updateCounters();
1260         redoParagraph(cursorPar());
1261         redoParagraph(next_par);
1262
1263         // This check is necessary. Otherwise the new empty paragraph will
1264         // be deleted automatically. And it is more friendly for the user!
1265         if (cursor.pos() || isempty)
1266                 setCursor(next_par, 0);
1267         else
1268                 setCursor(cursorPar(), 0);
1269 }
1270
1271
1272 // convenience function
1273 void LyXText::redoParagraph()
1274 {
1275         clearSelection();
1276         redoParagraph(cursorPar());
1277         setCursorIntern(cursor.par(), cursor.pos());
1278 }
1279
1280
1281 // insert a character, moves all the following breaks in the
1282 // same Paragraph one to the right and make a rebreak
1283 void LyXText::insertChar(char c)
1284 {
1285         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
1286
1287         // When the free-spacing option is set for the current layout,
1288         // disable the double-space checking
1289
1290         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
1291                 cursorPar()->isFreeSpacing();
1292
1293         if (lyxrc.auto_number) {
1294                 static string const number_operators = "+-/*";
1295                 static string const number_unary_operators = "+-";
1296                 static string const number_seperators = ".,:";
1297
1298                 if (current_font.number() == LyXFont::ON) {
1299                         if (!IsDigit(c) && !contains(number_operators, c) &&
1300                             !(contains(number_seperators, c) &&
1301                               cursor.pos() >= 1 &&
1302                               cursor.pos() < cursorPar()->size() &&
1303                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1304                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1305                            )
1306                                 number(bv()); // Set current_font.number to OFF
1307                 } else if (IsDigit(c) &&
1308                            real_current_font.isVisibleRightToLeft()) {
1309                         number(bv()); // Set current_font.number to ON
1310
1311                         if (cursor.pos() > 0) {
1312                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1313                                 if (contains(number_unary_operators, c) &&
1314                                     (cursor.pos() == 1 ||
1315                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1316                                      cursorPar()->isNewline(cursor.pos() - 2))
1317                                   ) {
1318                                         setCharFont(
1319                                                     cursorPar(),
1320                                                     cursor.pos() - 1,
1321                                                     current_font);
1322                                 } else if (contains(number_seperators, c) &&
1323                                            cursor.pos() >= 2 &&
1324                                            getFont(
1325                                                    cursorPar(),
1326                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1327                                         setCharFont(
1328                                                     cursorPar(),
1329                                                     cursor.pos() - 1,
1330                                                     current_font);
1331                                 }
1332                         }
1333                 }
1334         }
1335
1336
1337         // First check, if there will be two blanks together or a blank at
1338         // the beginning of a paragraph.
1339         // I decided to handle blanks like normal characters, the main
1340         // difference are the special checks when calculating the row.fill
1341         // (blank does not count at the end of a row) and the check here
1342
1343         // The bug is triggered when we type in a description environment:
1344         // The current_font is not changed when we go from label to main text
1345         // and it should (along with realtmpfont) when we type the space.
1346         // CHECK There is a bug here! (Asger)
1347
1348         // store the current font.  This is because of the use of cursor
1349         // movements. The moving cursor would refresh the current font
1350         LyXFont realtmpfont = real_current_font;
1351         LyXFont rawtmpfont = current_font;
1352
1353         if (!freeSpacing && IsLineSeparatorChar(c)) {
1354                 if ((cursor.pos() > 0
1355                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1356                     || (cursor.pos() > 0
1357                         && cursorPar()->isNewline(cursor.pos() - 1))
1358                     || (cursor.pos() == 0)) {
1359                         static bool sent_space_message = false;
1360                         if (!sent_space_message) {
1361                                 if (cursor.pos() == 0)
1362                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1363                                 else
1364                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1365                                 sent_space_message = true;
1366                         }
1367                         charInserted();
1368                         return;
1369                 }
1370         }
1371
1372         // Here case LyXText::InsertInset already inserted the character
1373         if (c != Paragraph::META_INSET)
1374                 cursorPar()->insertChar(cursor.pos(), c);
1375
1376         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1377
1378         current_font = rawtmpfont;
1379         real_current_font = realtmpfont;
1380         redoParagraph(cursorPar());
1381         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1382
1383         charInserted();
1384 }
1385
1386
1387 void LyXText::charInserted()
1388 {
1389         // Here we could call finishUndo for every 20 characters inserted.
1390         // This is from my experience how emacs does it. (Lgb)
1391         static unsigned int counter;
1392         if (counter < 20) {
1393                 ++counter;
1394         } else {
1395                 finishUndo();
1396                 counter = 0;
1397         }
1398 }
1399
1400
1401 void LyXText::prepareToPrint(ParagraphList::iterator pit,
1402            RowList::iterator const rit) const
1403 {
1404         double w = rit->fill();
1405         double fill_hfill = 0;
1406         double fill_label_hfill = 0;
1407         double fill_separator = 0;
1408         double x = 0;
1409
1410         bool const is_rtl =
1411                 pit->isRightToLeftPar(bv()->buffer()->params());
1412         if (is_rtl)
1413                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), *rit) : 0;
1414         else
1415                 x = workWidth() > 0 ? leftMargin(pit, *rit) : 0;
1416
1417         // is there a manual margin with a manual label
1418         LyXLayout_ptr const & layout = pit->layout();
1419
1420         if (layout->margintype == MARGIN_MANUAL
1421             && layout->labeltype == LABEL_MANUAL) {
1422                 /// We might have real hfills in the label part
1423                 int nlh = numberOfLabelHfills(*pit, *rit);
1424
1425                 // A manual label par (e.g. List) has an auto-hfill
1426                 // between the label text and the body of the
1427                 // paragraph too.
1428                 // But we don't want to do this auto hfill if the par
1429                 // is empty.
1430                 if (!pit->empty())
1431                         ++nlh;
1432
1433                 if (nlh && !pit->getLabelWidthString().empty()) {
1434                         fill_label_hfill = labelFill(pit, *rit) / double(nlh);
1435                 }
1436         }
1437
1438         // are there any hfills in the row?
1439         int const nh = numberOfHfills(*pit, *rit);
1440
1441         if (nh) {
1442                 if (w > 0)
1443                         fill_hfill = w / nh;
1444         // we don't have to look at the alignment if it is ALIGN_LEFT and
1445         // if the row is already larger then the permitted width as then
1446         // we force the LEFT_ALIGN'edness!
1447         } else if (int(rit->width()) < workWidth()) {
1448                 // is it block, flushleft or flushright?
1449                 // set x how you need it
1450                 int align;
1451                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1452                         align = layout->align;
1453                 } else {
1454                         align = pit->params().align();
1455                 }
1456                 InsetOld * inset = 0;
1457                 // ERT insets should always be LEFT ALIGNED on screen
1458                 inset = pit->inInset();
1459                 if (inset && inset->owner() &&
1460                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1461                 {
1462                         align = LYX_ALIGN_LEFT;
1463                 }
1464
1465                 // Display-style insets should always be on a centred row
1466                 // The test on pit->size() is to catch zero-size pars, which
1467                 // would trigger the assert in Paragraph::getInset().
1468                 inset = pit->size() ? pit->getInset(rit->pos()) : 0;
1469                 if (inset && inset->display()) {
1470                         align = LYX_ALIGN_CENTER;
1471                 }
1472                 
1473                 switch (align) {
1474             case LYX_ALIGN_BLOCK:
1475                 {
1476                         int const ns = numberOfSeparators(*pit, *rit);
1477                         RowList::iterator next_row = boost::next(rit);
1478                         bool disp_inset = false;
1479                         if (next_row != pit->rows.end()) {
1480                                 InsetOld * in = pit->getInset(next_row->pos());
1481                                 if (in)
1482                                         disp_inset = in->display();
1483                         }
1484                         // If we have separators, this is not the last row of a
1485                         // par, does not end in newline, and is not row above a
1486                         // display inset... then stretch it
1487                         if (ns
1488                                 && next_row != pit->rows.end()
1489                                 && !pit->isNewline(next_row->pos() - 1)
1490                                 && !disp_inset
1491                                 ) {
1492                                         fill_separator = w / ns;
1493                         } else if (is_rtl) {
1494                                 x += w;
1495                         }
1496                         break;
1497             }
1498             case LYX_ALIGN_RIGHT:
1499                         x += w;
1500                         break;
1501             case LYX_ALIGN_CENTER:
1502                         x += w / 2;
1503                         break;
1504                 }
1505         }
1506
1507         computeBidiTables(*pit, *bv()->buffer(), *rit);
1508         if (is_rtl) {
1509                 pos_type body_pos = pit->beginningOfBody();
1510                 pos_type last = lastPos(*pit, *rit);
1511
1512                 if (body_pos > 0 &&
1513                                 (body_pos - 1 > last ||
1514                                  !pit->isLineSeparator(body_pos - 1))) {
1515                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1516                         if (body_pos - 1 <= last)
1517                                 x += fill_label_hfill;
1518                 }
1519         }
1520
1521         rit->fill_hfill(fill_hfill);
1522         rit->fill_label_hfill(fill_label_hfill);
1523         rit->fill_separator(fill_separator);
1524         rit->x(x);
1525 }
1526
1527
1528 // important for the screen
1529
1530
1531 // the cursor set functions have a special mechanism. When they
1532 // realize, that you left an empty paragraph, they will delete it.
1533 // They also delete the corresponding row
1534
1535 void LyXText::cursorRightOneWord()
1536 {
1537         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1538         setCursor(cursorPar(), cursor.pos());
1539 }
1540
1541
1542 // Skip initial whitespace at end of word and move cursor to *start*
1543 // of prior word, not to end of next prior word.
1544 void LyXText::cursorLeftOneWord()
1545 {
1546         LyXCursor tmpcursor = cursor;
1547         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1548         setCursor(getPar(tmpcursor), tmpcursor.pos());
1549 }
1550
1551
1552 void LyXText::selectWord(word_location loc)
1553 {
1554         LyXCursor from = cursor;
1555         LyXCursor to = cursor;
1556         ::getWord(*this, from, to, loc, ownerParagraphs());
1557         if (cursor != from)
1558                 setCursor(from.par(), from.pos());
1559         if (to == from)
1560                 return;
1561         selection.cursor = cursor;
1562         setCursor(to.par(), to.pos());
1563         setSelection();
1564 }
1565
1566
1567 // Select the word currently under the cursor when no
1568 // selection is currently set
1569 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1570 {
1571         if (!selection.set()) {
1572                 selectWord(loc);
1573                 return selection.set();
1574         }
1575         return false;
1576 }
1577
1578
1579 void LyXText::acceptChange()
1580 {
1581         if (!selection.set() && cursorPar()->size())
1582                 return;
1583
1584         if (selection.start.par() == selection.end.par()) {
1585                 LyXCursor & startc = selection.start;
1586                 LyXCursor & endc = selection.end;
1587                 recordUndo(Undo::INSERT, this, startc.par());
1588                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1589                 finishUndo();
1590                 clearSelection();
1591                 redoParagraph(getPar(startc));
1592                 setCursorIntern(startc.par(), 0);
1593         }
1594 #warning handle multi par selection
1595 }
1596
1597
1598 void LyXText::rejectChange()
1599 {
1600         if (!selection.set() && cursorPar()->size())
1601                 return;
1602
1603         if (selection.start.par() == selection.end.par()) {
1604                 LyXCursor & startc = selection.start;
1605                 LyXCursor & endc = selection.end;
1606                 recordUndo(Undo::INSERT, this, startc.par());
1607                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1608                 finishUndo();
1609                 clearSelection();
1610                 redoParagraph(getPar(startc));
1611                 setCursorIntern(startc.par(), 0);
1612         }
1613 #warning handle multi par selection
1614 }
1615
1616
1617 // This function is only used by the spellchecker for NextWord().
1618 // It doesn't handle LYX_ACCENTs and probably never will.
1619 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1620 {
1621         if (the_locking_inset) {
1622                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1623                 if (!word.word().empty()) {
1624                         value += float(cursor.y());
1625                         value /= float(height);
1626                         return word;
1627                 }
1628                 // we have to go on checking so move cursor to the next char
1629                 if (cursor.pos() == cursorPar()->size()) {
1630                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1631                                 return word;
1632                         cursor.par(cursor.par() + 1);
1633                         cursor.pos(0);
1634                 } else
1635                                 cursor.pos(cursor.pos() + 1);
1636         }
1637         int const tmppar = cursor.par();
1638
1639         // If this is not the very first word, skip rest of
1640         // current word because we are probably in the middle
1641         // of a word if there is text here.
1642         if (cursor.pos() || cursor.par() != 0) {
1643                 while (cursor.pos() < cursorPar()->size()
1644                        && cursorPar()->isLetter(cursor.pos()))
1645                         cursor.pos(cursor.pos() + 1);
1646         }
1647
1648         // Now, skip until we have real text (will jump paragraphs)
1649         while (true) {
1650                 ParagraphList::iterator cpit = cursorPar();
1651                 pos_type const cpos = cursor.pos();
1652
1653                 if (cpos == cpit->size()) {
1654                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1655                                 cursor.par(cursor.par() + 1);
1656                                 cursor.pos(0);
1657                                 continue;
1658                         }
1659                         break;
1660                 }
1661
1662                 bool const is_good_inset = cpit->isInset(cpos)
1663                         && cpit->getInset(cpos)->allowSpellcheck();
1664
1665                 if (!isDeletedText(*cpit, cpos)
1666                     && (is_good_inset || cpit->isLetter(cpos)))
1667                         break;
1668
1669                 cursor.pos(cpos + 1);
1670         }
1671
1672         // now check if we hit an inset so it has to be a inset containing text!
1673         if (cursor.pos() < cursorPar()->size() &&
1674             cursorPar()->isInset(cursor.pos())) {
1675                 // lock the inset!
1676                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1677                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1678                 // now call us again to do the above trick
1679                 // but obviously we have to start from down below ;)
1680                 return bv()->text->selectNextWordToSpellcheck(value);
1681         }
1682
1683         // Update the value if we changed paragraphs
1684         if (cursor.par() != tmppar) {
1685                 setCursor(cursor.par(), cursor.pos());
1686                 value = float(cursor.y())/float(height);
1687         }
1688
1689         // Start the selection from here
1690         selection.cursor = cursor;
1691
1692         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1693         // and find the end of the word (insets like optional hyphens
1694         // and ligature break are part of a word)
1695         while (cursor.pos() < cursorPar()->size()
1696                && cursorPar()->isLetter(cursor.pos())
1697                && !isDeletedText(*cursorPar(), cursor.pos()))
1698                 cursor.pos(cursor.pos() + 1);
1699
1700         // Finally, we copy the word to a string and return it
1701         string str;
1702         if (selection.cursor.pos() < cursor.pos()) {
1703                 pos_type i;
1704                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1705                         if (!cursorPar()->isInset(i))
1706                                 str += cursorPar()->getChar(i);
1707                 }
1708         }
1709         return WordLangTuple(str, lang_code);
1710 }
1711
1712
1713 // This one is also only for the spellchecker
1714 void LyXText::selectSelectedWord()
1715 {
1716         if (the_locking_inset) {
1717                 the_locking_inset->selectSelectedWord(bv());
1718                 return;
1719         }
1720         // move cursor to the beginning
1721         setCursor(selection.cursor.par(), selection.cursor.pos());
1722
1723         // set the sel cursor
1724         selection.cursor = cursor;
1725
1726         // now find the end of the word
1727         while (cursor.pos() < cursorPar()->size()
1728                && cursorPar()->isLetter(cursor.pos()))
1729                 cursor.pos(cursor.pos() + 1);
1730
1731         setCursor(cursorPar(), cursor.pos());
1732
1733         // finally set the selection
1734         setSelection();
1735 }
1736
1737
1738 // Delete from cursor up to the end of the current or next word.
1739 void LyXText::deleteWordForward()
1740 {
1741         if (cursorPar()->empty())
1742                 cursorRight(bv());
1743         else {
1744                 LyXCursor tmpcursor = cursor;
1745                 selection.set(true); // to avoid deletion
1746                 cursorRightOneWord();
1747                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1748                 selection.cursor = cursor;
1749                 cursor = tmpcursor;
1750                 setSelection();
1751
1752                 // Great, CutSelection() gets rid of multiple spaces.
1753                 cutSelection(true, false);
1754         }
1755 }
1756
1757
1758 // Delete from cursor to start of current or prior word.
1759 void LyXText::deleteWordBackward()
1760 {
1761         if (cursorPar()->empty())
1762                 cursorLeft(bv());
1763         else {
1764                 LyXCursor tmpcursor = cursor;
1765                 selection.set(true); // to avoid deletion
1766                 cursorLeftOneWord();
1767                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1768                 selection.cursor = cursor;
1769                 cursor = tmpcursor;
1770                 setSelection();
1771                 cutSelection(true, false);
1772         }
1773 }
1774
1775
1776 // Kill to end of line.
1777 void LyXText::deleteLineForward()
1778 {
1779         if (cursorPar()->empty())
1780                 // Paragraph is empty, so we just go to the right
1781                 cursorRight(bv());
1782         else {
1783                 LyXCursor tmpcursor = cursor;
1784                 // We can't store the row over a regular setCursor
1785                 // so we set it to 0 and reset it afterwards.
1786                 selection.set(true); // to avoid deletion
1787                 cursorEnd();
1788                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1789                 selection.cursor = cursor;
1790                 cursor = tmpcursor;
1791                 setSelection();
1792                 // What is this test for ??? (JMarc)
1793                 if (!selection.set()) {
1794                         deleteWordForward();
1795                 } else {
1796                         cutSelection(true, false);
1797                 }
1798         }
1799 }
1800
1801
1802 void LyXText::changeCase(LyXText::TextCase action)
1803 {
1804         LyXCursor from;
1805         LyXCursor to;
1806
1807         if (selection.set()) {
1808                 from = selection.start;
1809                 to = selection.end;
1810         } else {
1811                 from = cursor;
1812                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1813                 setCursor(to.par(), to.pos() + 1);
1814         }
1815
1816         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1817
1818         pos_type pos = from.pos();
1819         int par = from.par();
1820
1821         while (par != int(ownerParagraphs().size()) &&
1822                (pos != to.pos() || par != to.par())) {
1823                 ParagraphList::iterator pit = getPar(par);
1824                 if (pos == pit->size()) {
1825                         ++par;
1826                         pos = 0;
1827                         continue;
1828                 }
1829                 unsigned char c = pit->getChar(pos);
1830                 if (c != Paragraph::META_INSET) {
1831                         switch (action) {
1832                         case text_lowercase:
1833                                 c = lowercase(c);
1834                                 break;
1835                         case text_capitalization:
1836                                 c = uppercase(c);
1837                                 action = text_lowercase;
1838                                 break;
1839                         case text_uppercase:
1840                                 c = uppercase(c);
1841                                 break;
1842                         }
1843                 }
1844 #warning changes
1845                 pit->setChar(pos, c);
1846                 ++pos;
1847         }
1848 }
1849
1850
1851 void LyXText::Delete()
1852 {
1853         // this is a very easy implementation
1854
1855         LyXCursor old_cursor = cursor;
1856         int const old_cur_par_id = cursorPar()->id();
1857         int const old_cur_par_prev_id =
1858                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1859
1860         // just move to the right
1861         cursorRight(bv());
1862
1863         // CHECK Look at the comment here.
1864         // This check is not very good...
1865         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1866         // and that can very well delete the par or par->previous in
1867         // old_cursor. Will a solution where we compare paragraph id's
1868         //work better?
1869         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1870         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1871                 // delete-empty-paragraph-mechanism has done it
1872                 return;
1873         }
1874
1875         // if you had success make a backspace
1876         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1877                 recordUndo(Undo::DELETE, this, old_cursor.par());
1878                 backspace();
1879         }
1880 }
1881
1882
1883 void LyXText::backspace()
1884 {
1885         // Get the font that is used to calculate the baselineskip
1886         ParagraphList::iterator pit = cursorPar();
1887         pos_type lastpos = pit->size();
1888
1889         if (cursor.pos() == 0) {
1890                 // The cursor is at the beginning of a paragraph,
1891                 // so the the backspace will collapse two paragraphs into one.
1892
1893                 // but it's not allowed unless it's new
1894                 if (pit->isChangeEdited(0, pit->size()))
1895                         return;
1896
1897                 // we may paste some paragraphs
1898
1899                 // is it an empty paragraph?
1900
1901                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1902                         // This is an empty paragraph and we delete it just
1903                         // by moving the cursor one step
1904                         // left and let the DeleteEmptyParagraphMechanism
1905                         // handle the actual deletion of the paragraph.
1906
1907                         if (cursor.par()) {
1908                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1909                                 if (cursorPar()->layout() == tmppit->layout()
1910                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1911                                         // Inherit bottom DTD from the paragraph below.
1912                                         // (the one we are deleting)
1913                                         tmppit->params().lineBottom(cursorPar()->params().lineBottom());
1914                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1915                                         tmppit->params().pagebreakBottom(cursorPar()->params().pagebreakBottom());
1916                                 }
1917
1918                                 cursorLeft(bv());
1919
1920                                 // the layout things can change the height of a row !
1921                                 redoParagraph();
1922                                 return;
1923                         }
1924                 }
1925
1926                 if (cursor.par() != 0)
1927                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1928
1929                 ParagraphList::iterator tmppit = cursorPar();
1930                 // We used to do cursorLeftIntern() here, but it is
1931                 // not a good idea since it triggers the auto-delete
1932                 // mechanism. So we do a cursorLeftIntern()-lite,
1933                 // without the dreaded mechanism. (JMarc)
1934                 if (cursor.par() != 0) {
1935                         // steps into the above paragraph.
1936                         setCursorIntern(cursor.par() - 1,
1937                                         getPar(cursor.par() - 1)->size(),
1938                                         false);
1939                 }
1940
1941                 // Pasting is not allowed, if the paragraphs have different
1942                 // layout. I think it is a real bug of all other
1943                 // word processors to allow it. It confuses the user.
1944                 // Correction: Pasting is always allowed with standard-layout
1945                 Buffer & buf = *bv()->buffer();
1946                 BufferParams const & bufparams = buf.params();
1947                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1948
1949                 if (cursorPar() != tmppit
1950                     && (cursorPar()->layout() == tmppit->layout()
1951                         || tmppit->layout() == tclass.defaultLayout())
1952                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1953                         mergeParagraph(bufparams,
1954                                        buf.paragraphs(), cursorPar());
1955
1956                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1957                                 cursor.pos(cursor.pos() - 1);
1958
1959                         // the row may have changed, block, hfills etc.
1960                         updateCounters();
1961                         setCursor(cursor.par(), cursor.pos(), false);
1962                 }
1963         } else {
1964                 // this is the code for a normal backspace, not pasting
1965                 // any paragraphs
1966                 recordUndo(Undo::DELETE, this, cursor.par());
1967                 // We used to do cursorLeftIntern() here, but it is
1968                 // not a good idea since it triggers the auto-delete
1969                 // mechanism. So we do a cursorLeftIntern()-lite,
1970                 // without the dreaded mechanism. (JMarc)
1971                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1972                                 false, cursor.boundary());
1973                 cursorPar()->erase(cursor.pos());
1974         }
1975
1976         lastpos = cursorPar()->size();
1977         if (cursor.pos() == lastpos)
1978                 setCurrentFont();
1979
1980         redoParagraph();
1981         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1982 }
1983
1984
1985 ParagraphList::iterator LyXText::cursorPar() const
1986 {
1987         return getPar(cursor.par());
1988 }
1989
1990
1991 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1992 {
1993         return getPar(cur.par());
1994 }
1995
1996
1997 ParagraphList::iterator LyXText::getPar(int par) const
1998 {
1999         BOOST_ASSERT(par >= 0);
2000         BOOST_ASSERT(par < int(ownerParagraphs().size()));
2001         ParagraphList::iterator pit = ownerParagraphs().begin();
2002         std::advance(pit, par);
2003         return pit;
2004 }
2005
2006
2007
2008 RowList::iterator LyXText::cursorRow() const
2009 {
2010         return getRow(*cursorPar(), cursor.pos());
2011 }
2012
2013
2014 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2015 {
2016         return getRow(*getPar(cur), cur.pos());
2017 }
2018
2019
2020 RowList::iterator LyXText::getRow(Paragraph & par, pos_type pos) const
2021 {
2022         RowList::iterator rit = boost::prior(par.rows.end());
2023         RowList::iterator const begin = par.rows.begin();
2024
2025         while (rit != begin && rit->pos() > pos)
2026                 --rit;
2027
2028         return rit;
2029 }
2030
2031
2032 RowList::iterator
2033 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
2034 {
2035         //lyxerr << "getRowNearY: y " << y << endl;
2036
2037         pit = boost::prior(ownerParagraphs().end());
2038
2039         RowList::iterator rit = lastRow();
2040         RowList::iterator rbegin = firstRow();
2041
2042         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
2043                 previousRow(pit, rit);
2044
2045         return rit;
2046 }
2047
2048
2049 int LyXText::getDepth() const
2050 {
2051         return cursorPar()->getDepth();
2052 }
2053
2054
2055 RowList::iterator LyXText::firstRow() const
2056 {
2057         return ownerParagraphs().front().rows.begin();
2058 }
2059
2060
2061 RowList::iterator LyXText::lastRow() const
2062 {
2063         return boost::prior(endRow());
2064 }
2065
2066
2067 RowList::iterator LyXText::endRow() const
2068 {
2069         return ownerParagraphs().back().rows.end();
2070 }
2071
2072
2073 void LyXText::nextRow(ParagraphList::iterator & pit,
2074         RowList::iterator & rit) const
2075 {
2076         ++rit;
2077         if (rit == pit->rows.end()) {
2078                 ++pit;
2079                 if (pit == ownerParagraphs().end())
2080                         --pit;
2081                 else
2082                         rit = pit->rows.begin();
2083         }
2084 }
2085
2086
2087 void LyXText::previousRow(ParagraphList::iterator & pit,
2088         RowList::iterator & rit) const
2089 {
2090         if (rit != pit->rows.begin())
2091                 --rit;
2092         else {
2093                 BOOST_ASSERT(pit != ownerParagraphs().begin());
2094                 --pit;
2095                 rit = boost::prior(pit->rows.end());
2096         }
2097 }
2098
2099
2100 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
2101 {
2102         if (!selection.set())
2103                 return string();
2104
2105         // should be const ...
2106         ParagraphList::iterator startpit = getPar(selection.start);
2107         ParagraphList::iterator endpit = getPar(selection.end);
2108         size_t const startpos = selection.start.pos();
2109         size_t const endpos = selection.end.pos();
2110
2111         if (startpit == endpit)
2112                 return startpit->asString(buffer, startpos, endpos, label);
2113
2114         // First paragraph in selection
2115         string result =
2116                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
2117
2118         // The paragraphs in between (if any)
2119         ParagraphList::iterator pit = startpit;
2120         for (++pit; pit != endpit; ++pit)
2121                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
2122
2123         // Last paragraph in selection
2124         result += endpit->asString(buffer, 0, endpos, label);
2125
2126         return result;
2127 }
2128
2129
2130 int LyXText::parOffset(ParagraphList::iterator pit) const
2131 {
2132         return std::distance(ownerParagraphs().begin(), pit);
2133 }
2134
2135
2136 int LyXText::redoParagraphInternal(ParagraphList::iterator pit)
2137 {
2138         // remove rows of paragraph, keep track of height changes
2139         height -= pit->height;
2140         pit->rows.clear();
2141
2142         // redo insets
2143         InsetList::iterator ii = pit->insetlist.begin();
2144         InsetList::iterator iend = pit->insetlist.end();
2145         for (; ii != iend; ++ii) {
2146                 Dimension dim;
2147                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
2148                 ii->inset->metrics(mi, dim);
2149         }
2150
2151         // rebreak the paragraph
2152         int par_width = 0;
2153         int const ww = workWidth();
2154         pit->height = 0;
2155
2156         for (pos_type z = 0; z < pit->size() + 1; ) {
2157                 Row row(z);
2158                 z = rowBreakPoint(pit, row) + 1;
2159                 row.end(z);
2160                 pit->rows.push_back(row);
2161         }
2162
2163         RowList::iterator rit = pit->rows.begin();
2164         RowList::iterator end = pit->rows.end();
2165         for (rit = pit->rows.begin(); rit != end; ++rit) {
2166                 int const f = fill(pit, *rit, ww);
2167                 int const w = ww - f;
2168                 par_width = std::max(par_width, w);
2169                 rit->fill(f);
2170                 rit->width(w);
2171                 prepareToPrint(pit, rit);
2172                 setHeightOfRow(pit, *rit);
2173                 rit->y_offset(pit->height);
2174                 pit->height += rit->height();
2175         }
2176         height += pit->height;
2177
2178         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
2179         return par_width;
2180 }
2181
2182
2183 int LyXText::redoParagraphs(ParagraphList::iterator start,
2184   ParagraphList::iterator end)
2185 {
2186         int pars_width = 0;
2187         for ( ; start != end; ++start) {
2188                 int par_width = redoParagraphInternal(start);
2189                 pars_width = std::max(par_width, pars_width);
2190         }
2191         updateRowPositions();
2192         return pars_width;
2193 }
2194
2195
2196 void LyXText::redoParagraph(ParagraphList::iterator pit)
2197 {
2198         redoParagraphInternal(pit);
2199         updateRowPositions();
2200 }
2201
2202
2203 void LyXText::fullRebreak()
2204 {
2205         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2206         redoCursor();
2207         selection.cursor = cursor;
2208 }
2209
2210
2211 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
2212 {
2213         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
2214         //      << " workWidth: " << workWidth() << endl;
2215         //BOOST_ASSERT(mi.base.textwidth);
2216
2217         // rebuild row cache
2218         width  = 0;
2219         ///height = 0;
2220
2221         //anchor_y_ = 0;
2222         width = redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2223
2224         // final dimension
2225         dim.asc = firstRow()->ascent_of_text();
2226         dim.des = height - dim.asc;
2227         dim.wid = std::max(mi.base.textwidth, int(width));
2228 }