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