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