]> git.lyx.org Git - lyx.git/blob - src/text.C
When calculating fill, exploit data structure to avoid superfluous calls to getFont.
[lyx.git] / src / text.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "paragraph.h"
16 #include "gettext.h"
17 #include "bufferparams.h"
18 #include "buffer.h"
19 #include "debug.h"
20 #include "intl.h"
21 #include "lyxrc.h"
22 #include "encoding.h"
23 #include "frontends/LyXView.h"
24 #include "frontends/Painter.h"
25 #include "frontends/font_metrics.h"
26 #include "frontends/screen.h"
27 #include "frontends/WorkArea.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "text_funcs.h"
34 #include "WordLangTuple.h"
35 #include "paragraph_funcs.h"
36 #include "rowpainter.h"
37 #include "lyxrow_funcs.h"
38 #include "metricsinfo.h"
39
40 #include "insets/insettext.h"
41
42 #include "support/textutils.h"
43 #include "support/LAssert.h"
44 #include "support/lstrings.h"
45
46 #include <algorithm>
47
48 using namespace lyx::support;
49
50 using std::max;
51 using std::min;
52 using std::endl;
53 using std::pair;
54
55 using lyx::pos_type;
56 using lyx::word_location;
57
58 using namespace bv_funcs;
59
60 /// top, right, bottom pixel margin
61 extern int const PAPER_MARGIN = 20;
62 /// margin for changebar
63 extern int const CHANGEBAR_MARGIN = 10;
64 /// left margin
65 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
66
67 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
68
69
70 BufferView * LyXText::bv()
71 {
72         Assert(bv_owner != 0);
73         return bv_owner;
74 }
75
76
77 BufferView * LyXText::bv() const
78 {
79         Assert(bv_owner != 0);
80         return bv_owner;
81 }
82
83
84 void LyXText::updateRowPositions()
85 {
86         RowList::iterator rit = rows().begin();
87         RowList::iterator rend = rows().end();
88         for (int y = 0; rit != rend ; ++rit) {
89                 rit->y(y);
90                 y += rit->height();
91         }
92 }
93
94
95 int LyXText::top_y() const
96 {
97         if (anchor_row_ == rowlist_.end())
98                 return 0;
99
100         return anchor_row_->y() + anchor_row_offset_;
101 }
102
103
104 void LyXText::top_y(int newy)
105 {
106         if (rows().empty())
107                 return;
108
109         if (isInInset()) {
110                 anchor_row_ = rows().begin();
111                 anchor_row_offset_ = newy;
112                 return;
113         }
114
115         lyxerr[Debug::GUI] << "setting top y = " << newy << endl;
116
117         int y = newy;
118         RowList::iterator rit = getRowNearY(y);
119
120         if (rit == anchor_row_ && anchor_row_offset_ == newy - y) {
121                 lyxerr[Debug::GUI] << "top_y to same value, skipping update" << endl;
122                 return;
123         }
124
125         anchor_row_ = rit;
126         anchor_row_offset_ = newy - y;
127         lyxerr[Debug::GUI] << "changing reference to row: " << &*anchor_row_
128                << " offset: " << anchor_row_offset_ << endl;
129         postPaint();
130 }
131
132
133 void LyXText::anchor_row(RowList::iterator rit)
134 {
135         int old_y = top_y();
136         anchor_row_offset_ = 0;
137         anchor_row_ = rit;
138         anchor_row_offset_ = old_y - top_y();
139         lyxerr[Debug::GUI] << "anchor_row(): changing reference to row: "
140                            << &*anchor_row_ << " offset: "
141                            << anchor_row_offset_ << endl;
142 }
143
144
145 int LyXText::workWidth() const
146 {
147         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
148 }
149
150
151 int LyXText::workWidth(InsetOld const * inset) const
152 {
153         ParagraphList::iterator par = std::find(ownerParagraphs().begin(),
154                                                 ownerParagraphs().end(),
155                                                 *inset->parOwner());
156         if (par == ownerParagraphs().end()) {
157                 lyxerr[Debug::GUI] << "LyXText::workWidth: unexpected\n";
158                 return -1;
159         }
160
161         pos_type pos = par->getPositionOfInset(inset);
162         Assert(pos != -1);
163
164         LyXLayout_ptr const & layout = par->layout();
165
166         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
167                 // Optimization here: in most cases, the real row is
168                 // not needed, but only the par/pos values. So we just
169                 // construct a dummy row for leftMargin. (JMarc)
170                 Row dummyrow;
171                 dummyrow.par(par);
172                 dummyrow.pos(pos);
173                 return workWidth() - leftMargin(dummyrow);
174         } else {
175                 int dummy_y;
176                 RowList::iterator row = getRow(par, pos, dummy_y);
177                 RowList::iterator frow = row;
178                 RowList::iterator beg = rowlist_.begin();
179
180                 while (frow != beg && frow->par() == boost::prior(frow)->par())
181                         --frow;
182
183                 // FIXME: I don't understand this code - jbl
184
185                 unsigned int maxw = 0;
186                 while (!isParEnd(*this, frow)) {
187                         if ((frow != row) && (maxw < frow->width()))
188                                 maxw = frow->width();
189                         ++frow;
190                 }
191                 if (maxw)
192                         return maxw;
193
194         }
195         return workWidth();
196 }
197
198
199 int LyXText::getRealCursorX() const
200 {
201         int x = cursor.x();
202         if (the_locking_inset && (the_locking_inset->getLyXText(bv())!= this))
203                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
204         return x;
205 }
206
207
208 #warning FIXME  This function seems to belong outside of LyxText.
209 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
210                                      pos_type pos) const
211 {
212         if (!Encodings::is_arabic(c))
213                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
214                         return c + (0xb0 - '0');
215                 else
216                         return c;
217
218         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
219         unsigned char next_char = ' ';
220
221         pos_type const par_size = par.size();
222
223         for (pos_type i = pos + 1; i < par_size; ++i) {
224                 unsigned char const par_char = par.getChar(i);
225                 if (!Encodings::IsComposeChar_arabic(par_char)) {
226                         next_char = par_char;
227                         break;
228                 }
229         }
230
231         if (Encodings::is_arabic(next_char)) {
232                 if (Encodings::is_arabic(prev_char) &&
233                         !Encodings::is_arabic_special(prev_char))
234                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
235                 else
236                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
237         } else {
238                 if (Encodings::is_arabic(prev_char) &&
239                         !Encodings::is_arabic_special(prev_char))
240                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
241                 else
242                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
243         }
244 }
245
246 // This is the comments that some of the warnings below refers to.
247 // There are some issues in this file and I don't think they are
248 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
249 // this is a problem that has been here almost from day one and that a
250 // larger userbase with differenct access patters triggers the bad
251 // behaviour. (segfaults.) What I think happen is: In several places
252 // we store the paragraph in the current cursor and then moves the
253 // cursor. This movement of the cursor will delete paragraph at the
254 // old position if it is now empty. This will make the temporary
255 // pointer to the old cursor paragraph invalid and dangerous to use.
256 // And is some cases this will trigger a segfault. I have marked some
257 // of the cases where this happens with a warning, but I am sure there
258 // are others in this file and in text2.C. There is also a note in
259 // Delete() that you should read. In Delete I store the paragraph->id
260 // instead of a pointer to the paragraph. I am pretty sure this faulty
261 // use of temporary pointers to paragraphs that might have gotten
262 // invalidated (through a cursor movement) before they are used, are
263 // the cause of the strange crashes we get reported often.
264 //
265 // It is very tiresom to change this code, especially when it is as
266 // hard to read as it is. Help to fix all the cases where this is done
267 // would be greately appreciated.
268 //
269 // Lgb
270
271 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
272 {
273         if (pos >= pit->size())
274                 return 0;
275
276         char const c = pit->getChar(pos);
277         return singleWidth(pit, pos, c);
278 }
279
280
281 int LyXText::singleWidth(ParagraphList::iterator pit,
282                          pos_type pos, char c) const
283 {
284         if (pos >= pit->size())
285                 return 0;
286
287         LyXFont const & font = getFont(bv()->buffer(), pit, pos);
288
289         // The most common case is handled first (Asger)
290         if (IsPrintable(c)) {
291                 if (font.language()->RightToLeft()) {
292                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
293                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
294                             && font.language()->lang() == "arabic") {
295                                 if (Encodings::IsComposeChar_arabic(c))
296                                         return 0;
297                                 else
298                                         c = transformChar(c, *pit, pos);
299                         } else if (font.language()->lang() == "hebrew" &&
300                                  Encodings::IsComposeChar_hebrew(c))
301                                 return 0;
302                 }
303                 return font_metrics::width(c, font);
304         }
305
306         if (c == Paragraph::META_INSET) {
307                 InsetOld * tmpinset = pit->getInset(pos);
308                 if (tmpinset) {
309                         if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
310                                 // Because of the representation as vertical lines
311                                 return 3;
312                         }
313 #if 0
314 #warning inset->update FIXME
315                         // this IS needed otherwise on initialitation we don't get the fill
316                         // of the row right (ONLY on initialization if we read a file!)
317                         // should be changed! (Jug 20011204)
318                         //tmpinset->update(bv());
319                         Dimension dim;
320                         MetricsInfo mi(bv(), font, workWidth());
321                         tmpinset->metrics(mi, dim);
322                         return dim.wid;
323 #else
324                         return tmpinset->width();
325 #endif
326                 }
327                 return 0;
328         }
329
330         if (IsSeparatorChar(c))
331                 c = ' ';
332         return font_metrics::width(c, font);
333 }
334
335
336 lyx::pos_type LyXText::log2vis(lyx::pos_type pos) const
337 {
338         if (bidi_start == -1)
339                 return pos;
340         else
341                 return log2vis_list[pos - bidi_start];
342 }
343
344
345 lyx::pos_type LyXText::vis2log(lyx::pos_type pos) const
346 {
347         if (bidi_start == -1)
348                 return pos;
349         else
350                 return vis2log_list[pos - bidi_start];
351 }
352
353
354 lyx::pos_type LyXText::bidi_level(lyx::pos_type pos) const
355 {
356         if (bidi_start == -1)
357                 return 0;
358         else
359                 return bidi_levels[pos - bidi_start];
360 }
361
362
363 bool LyXText::bidi_InRange(lyx::pos_type pos) const
364 {
365         return bidi_start == -1 ||
366                 (bidi_start <= pos && pos <= bidi_end);
367 }
368
369
370 void LyXText::computeBidiTables(Buffer const * buf,
371                                 RowList::iterator row) const
372 {
373         bidi_same_direction = true;
374         if (!lyxrc.rtl_support) {
375                 bidi_start = -1;
376                 return;
377         }
378
379         ParagraphList::iterator row_par = row->par();
380
381         InsetOld * inset = row_par->inInset();
382         if (inset && inset->owner() &&
383             inset->owner()->lyxCode() == InsetOld::ERT_CODE) {
384                 bidi_start = -1;
385                 return;
386         }
387
388         bidi_start = row->pos();
389         bidi_end = lastPrintablePos(*this, row);
390
391         if (bidi_start > bidi_end) {
392                 bidi_start = -1;
393                 return;
394         }
395
396         if (bidi_end + 2 - bidi_start >
397             static_cast<pos_type>(log2vis_list.size())) {
398                 pos_type new_size =
399                         (bidi_end + 2 - bidi_start < 500) ?
400                         500 : 2 * (bidi_end + 2 - bidi_start);
401                 log2vis_list.resize(new_size);
402                 vis2log_list.resize(new_size);
403                 bidi_levels.resize(new_size);
404         }
405
406         vis2log_list[bidi_end + 1 - bidi_start] = -1;
407         log2vis_list[bidi_end + 1 - bidi_start] = -1;
408
409         pos_type stack[2];
410         bool const rtl_par =
411                 row_par->isRightToLeftPar(buf->params);
412         int level = 0;
413         bool rtl = false;
414         bool rtl0 = false;
415         pos_type const body_pos = row_par->beginningOfBody();
416
417         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
418                 bool is_space = row_par->isLineSeparator(lpos);
419                 pos_type const pos =
420                         (is_space && lpos + 1 <= bidi_end &&
421                          !row_par->isLineSeparator(lpos + 1) &&
422                          !row_par->isNewline(lpos + 1))
423                         ? lpos + 1 : lpos;
424                 LyXFont font = row_par->getFontSettings(buf->params, pos);
425                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
426                     font.number() == LyXFont::ON &&
427                     row_par->getFontSettings(buf->params, lpos - 1).number()
428                     == LyXFont::ON) {
429                         font = row_par->getFontSettings(buf->params, lpos);
430                         is_space = false;
431                 }
432
433
434                 bool new_rtl = font.isVisibleRightToLeft();
435                 bool new_rtl0 = font.isRightToLeft();
436                 int new_level;
437
438                 if (lpos == body_pos - 1
439                     && row->pos() < body_pos - 1
440                     && is_space) {
441                         new_level = (rtl_par) ? 1 : 0;
442                         new_rtl = new_rtl0 = rtl_par;
443                 } else if (new_rtl0)
444                         new_level = (new_rtl) ? 1 : 2;
445                 else
446                         new_level = (rtl_par) ? 2 : 0;
447
448                 if (is_space && new_level >= level) {
449                         new_level = level;
450                         new_rtl = rtl;
451                         new_rtl0 = rtl0;
452                 }
453
454                 int new_level2 = new_level;
455
456                 if (level == new_level && rtl0 != new_rtl0) {
457                         --new_level2;
458                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
459                 } else if (level < new_level) {
460                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
461                         if (new_level > rtl_par)
462                                 bidi_same_direction = false;
463                 } else
464                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
465                 rtl = new_rtl;
466                 rtl0 = new_rtl0;
467                 bidi_levels[lpos - bidi_start] = new_level;
468
469                 while (level > new_level2) {
470                         pos_type old_lpos = stack[--level];
471                         int delta = lpos - old_lpos - 1;
472                         if (level % 2)
473                                 delta = -delta;
474                         log2vis_list[lpos - bidi_start] += delta;
475                         log2vis_list[old_lpos - bidi_start] += delta;
476                 }
477                 while (level < new_level)
478                         stack[level++] = lpos;
479         }
480
481         while (level > 0) {
482                 pos_type const old_lpos = stack[--level];
483                 int delta = bidi_end - old_lpos;
484                 if (level % 2)
485                         delta = -delta;
486                 log2vis_list[old_lpos - bidi_start] += delta;
487         }
488
489         pos_type vpos = bidi_start - 1;
490         for (pos_type lpos = bidi_start;
491              lpos <= bidi_end; ++lpos) {
492                 vpos += log2vis_list[lpos - bidi_start];
493                 vis2log_list[vpos - bidi_start] = lpos;
494                 log2vis_list[lpos - bidi_start] = vpos;
495         }
496 }
497
498
499 // This method requires a previous call to ComputeBidiTables()
500 bool LyXText::isBoundary(Buffer const * buf, Paragraph const & par,
501                          pos_type pos) const
502 {
503         if (!lyxrc.rtl_support || pos == 0)
504                 return false;
505
506         if (!bidi_InRange(pos - 1)) {
507                 /// This can happen if pos is the first char of a row.
508                 /// Returning false in this case is incorrect!
509                 return false;
510         }
511
512         bool const rtl = bidi_level(pos - 1) % 2;
513         bool const rtl2 = bidi_InRange(pos)
514                 ? bidi_level(pos) % 2
515                 : par.isRightToLeftPar(buf->params);
516         return rtl != rtl2;
517 }
518
519
520 bool LyXText::isBoundary(Buffer const * buf, Paragraph const & par,
521                          pos_type pos, LyXFont const & font) const
522 {
523         if (!lyxrc.rtl_support)
524                 return false;    // This is just for speedup
525
526         bool const rtl = font.isVisibleRightToLeft();
527         bool const rtl2 = bidi_InRange(pos)
528                 ? bidi_level(pos) % 2
529                 : par.isRightToLeftPar(buf->params);
530         return rtl != rtl2;
531 }
532
533
534 int LyXText::leftMargin(Row const & row) const
535 {
536         InsetOld * ins;
537
538         if (row.pos() < row.par()->size())
539                 if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
540                     (ins = row.par()->getInset(row.pos())) &&
541                     (ins->needFullRow() || ins->display()))
542                         return LEFT_MARGIN;
543
544         LyXTextClass const & tclass =
545                 bv()->buffer()->params.getLyXTextClass();
546         LyXLayout_ptr const & layout = row.par()->layout();
547
548         string parindent = layout->parindent;
549
550         int x = LEFT_MARGIN;
551
552         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
553
554         // this is the way, LyX handles the LaTeX-Environments.
555         // I have had this idea very late, so it seems to be a
556         // later added hack and this is true
557         if (!row.par()->getDepth()) {
558                 if (row.par()->layout() == tclass.defaultLayout()) {
559                         // find the previous same level paragraph
560                         if (row.par() != ownerParagraphs().begin()) {
561                                 ParagraphList::iterator newpit =
562                                         depthHook(row.par(), ownerParagraphs(),
563                                                   row.par()->getDepth());
564                                 if (newpit == row.par() &&
565                                     newpit->layout()->nextnoindent)
566                                         parindent.erase();
567                         }
568                 }
569         } else {
570                 // find the next level paragraph
571
572                 ParagraphList::iterator newpar = outerHook(row.par(),
573                                                            ownerParagraphs());
574
575                 // make a corresponding row. Needed to call leftMargin()
576
577                 // check wether it is a sufficent paragraph
578                 if (newpar != ownerParagraphs().end() &&
579                     newpar->layout()->isEnvironment()) {
580                         Row dummyrow;
581                         dummyrow.par(newpar);
582                         dummyrow.pos(newpar->size());
583                         x = leftMargin(dummyrow);
584                 }
585
586                 if (newpar != ownerParagraphs().end() &&
587                     row.par()->layout() == tclass.defaultLayout()) {
588                         if (newpar->params().noindent())
589                                 parindent.erase();
590                         else {
591                                 parindent = newpar->layout()->parindent;
592                         }
593
594                 }
595         }
596
597         LyXFont const labelfont = getLabelFont(bv()->buffer(), row.par());
598         switch (layout->margintype) {
599         case MARGIN_DYNAMIC:
600                 if (!layout->leftmargin.empty()) {
601                         x += font_metrics::signedWidth(layout->leftmargin,
602                                                   tclass.defaultfont());
603                 }
604                 if (!row.par()->getLabelstring().empty()) {
605                         x += font_metrics::signedWidth(layout->labelindent,
606                                                   labelfont);
607                         x += font_metrics::width(row.par()->getLabelstring(),
608                                             labelfont);
609                         x += font_metrics::width(layout->labelsep, labelfont);
610                 }
611                 break;
612         case MARGIN_MANUAL:
613                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
614                 // The width of an empty par, even with manual label, should be 0
615                 if (!row.par()->empty() && row.pos() >= row.par()->beginningOfBody()) {
616                         if (!row.par()->getLabelWidthString().empty()) {
617                                 x += font_metrics::width(row.par()->getLabelWidthString(),
618                                                labelfont);
619                                 x += font_metrics::width(layout->labelsep, labelfont);
620                         }
621                 }
622                 break;
623         case MARGIN_STATIC:
624                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
625                         / (row.par()->getDepth() + 4);
626                 break;
627         case MARGIN_FIRST_DYNAMIC:
628                 if (layout->labeltype == LABEL_MANUAL) {
629                         if (row.pos() >= row.par()->beginningOfBody()) {
630                                 x += font_metrics::signedWidth(layout->leftmargin,
631                                                           labelfont);
632                         } else {
633                                 x += font_metrics::signedWidth(layout->labelindent,
634                                                           labelfont);
635                         }
636                 } else if (row.pos()
637                            // Special case to fix problems with
638                            // theorems (JMarc)
639                            || (layout->labeltype == LABEL_STATIC
640                                && layout->latextype == LATEX_ENVIRONMENT
641                                && !isFirstInSequence(row.par(), ownerParagraphs()))) {
642                         x += font_metrics::signedWidth(layout->leftmargin,
643                                                   labelfont);
644                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
645                            && layout->labeltype != LABEL_BIBLIO
646                            && layout->labeltype !=
647                            LABEL_CENTERED_TOP_ENVIRONMENT) {
648                         x += font_metrics::signedWidth(layout->labelindent,
649                                                   labelfont);
650                         x += font_metrics::width(layout->labelsep, labelfont);
651                         x += font_metrics::width(row.par()->getLabelstring(),
652                                             labelfont);
653                 }
654                 break;
655
656         case MARGIN_RIGHT_ADDRESS_BOX:
657         {
658                 // ok, a terrible hack. The left margin depends on the widest
659                 // row in this paragraph. Do not care about footnotes, they
660                 // are *NOT* allowed in the LaTeX realisation of this layout.
661
662                 // find the first row of this paragraph
663                 RowList::iterator tmprit = rowlist_.begin();
664                 while (tmprit != rowlist_.end()
665                        && tmprit->par() != row.par())
666                         ++tmprit;
667
668                 int minfill = tmprit->fill();
669                 while (boost::next(tmprit) != rowlist_.end() &&
670                        boost::next(tmprit)->par() == row.par()) {
671                         ++tmprit;
672                         if (tmprit->fill() < minfill)
673                                 minfill = tmprit->fill();
674                 }
675
676                 x += font_metrics::signedWidth(layout->leftmargin,
677                         tclass.defaultfont());
678                 x += minfill;
679         }
680         break;
681         }
682
683         if ((workWidth() > 0) &&
684                 !row.par()->params().leftIndent().zero())
685         {
686                 LyXLength const len = row.par()->params().leftIndent();
687                 int const tw = inset_owner ?
688                         inset_owner->latexTextWidth(bv()) : workWidth();
689                 x += len.inPixels(tw);
690         }
691
692         LyXAlignment align;
693
694         if (row.par()->params().align() == LYX_ALIGN_LAYOUT)
695                 align = layout->align;
696         else
697                 align = row.par()->params().align();
698
699         // set the correct parindent
700         if (row.pos() == 0) {
701                 if ((layout->labeltype == LABEL_NO_LABEL
702                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
703                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
704                      || (layout->labeltype == LABEL_STATIC
705                          && layout->latextype == LATEX_ENVIRONMENT
706                          && !isFirstInSequence(row.par(), ownerParagraphs())))
707                     && align == LYX_ALIGN_BLOCK
708                     && !row.par()->params().noindent()
709                         // in tabulars and ert paragraphs are never indented!
710                         && (!row.par()->inInset() || !row.par()->inInset()->owner() ||
711                                 (row.par()->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
712                                  row.par()->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
713                     && (row.par()->layout() != tclass.defaultLayout() ||
714                         bv()->buffer()->params.paragraph_separation ==
715                         BufferParams::PARSEP_INDENT)) {
716                         x += font_metrics::signedWidth(parindent,
717                                                   tclass.defaultfont());
718                 } else if (layout->labeltype == LABEL_BIBLIO) {
719                         // ale970405 Right width for bibitems
720                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
721                 }
722         }
723
724         return x;
725 }
726
727
728 int LyXText::rightMargin(Buffer const & buf, Row const & row) const
729 {
730         InsetOld * ins;
731
732         if (row.pos() < row.par()->size())
733                 if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
734                     (ins = row.par()->getInset(row.pos())) &&
735                     (ins->needFullRow() || ins->display()))
736                         return PAPER_MARGIN;
737
738         LyXTextClass const & tclass = buf.params.getLyXTextClass();
739         LyXLayout_ptr const & layout = row.par()->layout();
740
741         int x = PAPER_MARGIN
742                 + font_metrics::signedWidth(tclass.rightmargin(),
743                                        tclass.defaultfont());
744
745         x += font_metrics::signedWidth(layout->rightmargin,
746                                        tclass.defaultfont())
747                 * 4 / (row.par()->getDepth() + 4);
748         return x;
749 }
750
751
752 int LyXText::labelEnd(Row const & row) const
753 {
754         if (row.par()->layout()->margintype == MARGIN_MANUAL) {
755                 Row tmprow = row;
756                 tmprow.pos(row.par()->size());
757                 // return the beginning of the body
758                 return leftMargin(tmprow);
759         }
760
761         // LabelEnd is only needed if the layout
762         // fills a flushleft label.
763         return 0;
764 }
765
766
767 namespace {
768
769 // this needs special handling - only newlines count as a break point
770 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
771 {
772         for (; i < par.size(); ++i) {
773                 if (par.isNewline(i))
774                         return i;
775         }
776
777         return par.size();
778 }
779
780 };
781
782
783 pos_type LyXText::rowBreakPoint(Row const & row) const
784 {
785         ParagraphList::iterator pit = row.par();
786
787         // maximum pixel width of a row.
788         int width = workWidth() - rightMargin(*bv()->buffer(), row);
789
790         // inset->textWidth() returns -1 via workWidth(),
791         // but why ?
792         if (width < 0)
793                 return pit->size();
794
795         LyXLayout_ptr const & layout = pit->layout();
796
797         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
798                 return addressBreakPoint(row.pos(), *pit);
799
800         pos_type const pos = row.pos();
801         pos_type const body_pos = pit->beginningOfBody();
802         pos_type const last = pit->size();
803         pos_type point = last;
804
805         if (pos == last)
806                 return last;
807
808         // Now we iterate through until we reach the right margin
809         // or the end of the par, then choose the possible break
810         // nearest that.
811
812         int const left = leftMargin(row);
813         int x = left;
814
815         // pixel width since last breakpoint
816         int chunkwidth = 0;
817         bool fullrow = false;
818
819         pos_type i = pos;
820         for (; i < last; ++i) {
821                 if (pit->isNewline(i)) {
822                         point = i;
823                         break;
824                 }
825
826                 char const c = pit->getChar(i);
827
828                 int thiswidth;
829
830                 // add the auto-hfill from label end to the body
831                 if (body_pos && i == body_pos) {
832                         thiswidth = font_metrics::width(layout->labelsep,
833                                 getLabelFont(bv()->buffer(), pit));
834                         if (pit->isLineSeparator(i - 1))
835                                 thiswidth -= singleWidth(pit, i - 1);
836                         int left_margin = labelEnd(row);
837                         if (thiswidth + x < left_margin)
838                                 thiswidth = left_margin - x;
839                         thiswidth += singleWidth(pit, i, c);
840                 } else {
841                         thiswidth = singleWidth(pit, i, c);
842                 }
843
844                 x += thiswidth;
845                 chunkwidth += thiswidth;
846
847                 InsetOld * in = pit->isInset(i) ? pit->getInset(i) : 0;
848                 fullrow = (in && (in->display() || in->needFullRow()));
849
850                 // break before a character that will fall off
851                 // the right of the row
852                 if (x >= width) {
853                         // if no break before or we are at an inset
854                         // that will take up a row, break here
855                         if (point == last || fullrow || chunkwidth >= (width - left)) {
856                                 if (pos < i)
857                                         point = i - 1;
858                                 else
859                                         point = i;
860                         }
861                         break;
862                 }
863
864                 if (!in || in->isChar()) {
865                         // some insets are line separators too
866                         if (pit->isLineSeparator(i)) {
867                                 point = i;
868                                 chunkwidth = 0;
869                         }
870                         continue;
871                 }
872
873                 if (!fullrow)
874                         continue;
875
876                 // full row insets start at a new row
877                 if (i == pos) {
878                         if (pos < last - 1) {
879                                 point = i;
880                                 if (pit->isLineSeparator(i + 1))
881                                         ++point;
882                         } else {
883                                 // to avoid extra rows
884                                 point = last;
885                         }
886                 } else {
887                         point = i - 1;
888                 }
889
890                 return point;
891         }
892
893         if (point == last && x >= width) {
894                 // didn't find one, break at the point we reached the edge
895                 point = i;
896         } else if (i == last && x < width) {
897                 // found one, but we fell off the end of the par, so prefer
898                 // that.
899                 point = last;
900         }
901
902         // manual labels cannot be broken in LaTeX. But we
903         // want to make our on-screen rendering of footnotes
904         // etc. still break
905         if (!fullrow && body_pos && point < body_pos)
906                 point = body_pos - 1;
907
908         return point;
909 }
910
911
912 // returns the minimum space a row needs on the screen in pixel
913 int LyXText::fill(RowList::iterator row, int paper_width) const
914 {
915         if (paper_width < 0)
916                 return 0;
917
918         int w;
919         // get the pure distance
920         pos_type const last = lastPrintablePos(*this, row);
921
922         ParagraphList::iterator pit = row->par();
923         LyXLayout_ptr const & layout = pit->layout();
924
925         // special handling of the right address boxes
926         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
927                 int const tmpfill = row->fill();
928                 row->fill(0); // the minfill in MarginLeft()
929                 w = leftMargin(*row);
930                 row->fill(tmpfill);
931         } else
932                 w = leftMargin(*row);
933
934         pos_type const body_pos = pit->beginningOfBody();
935         pos_type i = row->pos();
936
937         if (! pit->empty() && i <= last) {
938                 // We re-use the font resolution for the entire span when possible
939                 LyXFont font = getFont(bv()->buffer(), pit, i);
940                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
941                 while (i <= last) {
942                         if (body_pos > 0 && i == body_pos) {
943                                 w += font_metrics::width(layout->labelsep, getLabelFont(bv()->buffer(), pit));
944                                 if (pit->isLineSeparator(i - 1))
945                                         w -= singleWidth(pit, i - 1);
946                                 int left_margin = labelEnd(*row);
947                                 if (w < left_margin)
948                                         w = left_margin;
949                         }
950                         { // Manual inlined an optimised version of the common case of "w += singleWidth(pit, i);"
951                                 char const c = pit->getChar(i);
952
953                                 if (IsPrintable(c)) {
954                                         if (i > endPosOfFontSpan) {
955                                                 // We need to get the next font
956                                                 font = getFont(bv()->buffer(), pit, i);
957                                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
958                                         }
959                                         if (! font.language()->RightToLeft()) {
960                                                 w += font_metrics::width(c, font);
961                                         } else {
962                                                 // Fall-back to the normal case
963                                                 w += singleWidth(pit, i, c);
964                                                 // And flush font cache
965                                                 endPosOfFontSpan = 0;
966                                         }
967                                 } else {
968                                         // Fall-back to the normal case
969                                         w += singleWidth(pit, i, c);
970                                         // And flush font cache
971                                         endPosOfFontSpan = 0;
972                                 }
973                         }
974                         ++i;
975                 }
976         }
977         if (body_pos > 0 && body_pos > last) {
978                 w += font_metrics::width(layout->labelsep, getLabelFont(bv()->buffer(), pit));
979                 if (last >= 0 && pit->isLineSeparator(last))
980                         w -= singleWidth(pit, last);
981                 int const left_margin = labelEnd(*row);
982                 if (w < left_margin)
983                         w = left_margin;
984         }
985
986         int const fill = paper_width - w - rightMargin(*bv()->buffer(), *row);
987
988         // If this case happens, it means that our calculation
989         // of the widths of the chars when we do rowBreakPoint()
990         // went wrong for some reason. Typically in list bodies.
991         // Things just about hobble on anyway, though you'll end
992         // up with a "fill_separator" less than zero, which corresponds
993         // to inter-word spacing being too small. Hopefully this problem
994         // will die when the label hacks die.
995         if (lyxerr.debugging() && fill < 0) {
996                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
997                         << " w " << w << " paper_width " << paper_width
998                         << " right margin " << rightMargin(*bv()->buffer(), *row) << endl;
999         }
1000
1001         return fill;
1002 }
1003
1004
1005 // returns the minimum space a manual label needs on the screen in pixel
1006 int LyXText::labelFill(Row const & row) const
1007 {
1008         ParagraphList::iterator pit = row.par();
1009
1010         pos_type last = pit->beginningOfBody();
1011
1012         Assert(last > 0);
1013
1014         // -1 because a label ends either with a space that is in the label,
1015         // or with the beginning of a footnote that is outside the label.
1016         --last;
1017
1018         // a separator at this end does not count
1019         if (pit->isLineSeparator(last))
1020                 --last;
1021
1022         int w = 0;
1023         pos_type i = row.pos();
1024         while (i <= last) {
1025                 w += singleWidth(pit, i);
1026                 ++i;
1027         }
1028
1029         int fill = 0;
1030         string const & labwidstr = pit->params().labelWidthString();
1031         if (!labwidstr.empty()) {
1032                 LyXFont const labfont = getLabelFont(bv()->buffer(), pit);
1033                 int const labwidth = font_metrics::width(labwidstr, labfont);
1034                 fill = max(labwidth - w, 0);
1035         }
1036
1037         return fill;
1038 }
1039
1040
1041 LColor::color LyXText::backgroundColor() const
1042 {
1043         if (inset_owner)
1044                 return inset_owner->backgroundColor();
1045         else
1046                 return LColor::background;
1047 }
1048
1049
1050 void LyXText::setHeightOfRow(RowList::iterator rit)
1051 {
1052         Assert(rit != rows().end());
1053
1054         // get the maximum ascent and the maximum descent
1055         float layoutasc = 0;
1056         float layoutdesc = 0;
1057         float tmptop = 0;
1058         LyXFont tmpfont;
1059         InsetOld * tmpinset = 0;
1060
1061         // ok, let us initialize the maxasc and maxdesc value.
1062         // This depends in LaTeX of the font of the last character
1063         // in the paragraph. The hack below is necessary because
1064         // of the possibility of open footnotes
1065
1066         // Correction: only the fontsize count. The other properties
1067         //  are taken from the layoutfont. Nicer on the screen :)
1068         ParagraphList::iterator pit = rit->par();
1069
1070         LyXLayout_ptr const & layout = pit->layout();
1071
1072         // as max get the first character of this row then it can increase but not
1073         // decrease the height. Just some point to start with so we don't have to
1074         // do the assignment below too often.
1075         LyXFont font = getFont(bv()->buffer(), pit, rit->pos());
1076         LyXFont::FONT_SIZE const tmpsize = font.size();
1077         font = getLayoutFont(bv()->buffer(), pit);
1078         LyXFont::FONT_SIZE const size = font.size();
1079         font.setSize(tmpsize);
1080
1081         LyXFont labelfont = getLabelFont(bv()->buffer(), pit);
1082
1083         float spacing_val = 1.0;
1084         if (!pit->params().spacing().isDefault()) {
1085                 spacing_val = pit->params().spacing().getValue();
1086         } else {
1087                 spacing_val = bv()->buffer()->params.spacing.getValue();
1088         }
1089         //lyxerr << "spacing_val = " << spacing_val << endl;
1090
1091         int maxasc = int(font_metrics::maxAscent(font) *
1092                          layout->spacing.getValue() *
1093                          spacing_val);
1094         int maxdesc = int(font_metrics::maxDescent(font) *
1095                           layout->spacing.getValue() *
1096                           spacing_val);
1097
1098         pos_type const pos_end = lastPos(*this, rit);
1099         int labeladdon = 0;
1100         int maxwidth = 0;
1101
1102         if (!pit->empty()) {
1103                 // Check if any insets are larger
1104                 for (pos_type pos = rit->pos(); pos <= pos_end; ++pos) {
1105                         if (pit->isInset(pos)) {
1106                                 tmpfont = getFont(bv()->buffer(), pit, pos);
1107                                 tmpinset = pit->getInset(pos);
1108                                 if (tmpinset) {
1109 #if 1 // this is needed for deep update on initialitation
1110 #warning inset->update FIXME
1111                                         //tmpinset->update(bv());
1112                                         Dimension dim;
1113                                         MetricsInfo mi(bv(), tmpfont, workWidth());
1114                                         tmpinset->metrics(mi, dim);
1115                                         maxwidth += dim.wid;
1116                                         maxasc = max(maxasc, dim.asc);
1117                                         maxdesc = max(maxdesc, dim.des);
1118 #else
1119                                         maxwidth += tmpinset->width();
1120                                         maxasc = max(maxasc, tmpinset->ascent());
1121                                         maxdesc = max(maxdesc, tmpinset->descent());
1122 #endif
1123                                 }
1124                         } else {
1125                                 // Manual inlined optimised version of common case of "maxwidth += singleWidth(pit, pos);"
1126                                 char const c = pit->getChar(pos);
1127                                 maxwidth += singleWidth(pit, pos, c);
1128                                 
1129                         }
1130                 }
1131         }
1132
1133         // Check if any custom fonts are larger (Asger)
1134         // This is not completely correct, but we can live with the small,
1135         // cosmetic error for now.
1136         LyXFont::FONT_SIZE maxsize =
1137                 pit->highestFontInRange(rit->pos(), pos_end, size);
1138         if (maxsize > font.size()) {
1139                 font.setSize(maxsize);
1140                 maxasc = max(maxasc, font_metrics::maxAscent(font));
1141                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
1142         }
1143
1144         // This is nicer with box insets:
1145         ++maxasc;
1146         ++maxdesc;
1147
1148         rit->ascent_of_text(maxasc);
1149
1150         // is it a top line?
1151         if (!rit->pos()) {
1152
1153                 // some parksips VERY EASY IMPLEMENTATION
1154                 if (bv()->buffer()->params.paragraph_separation ==
1155                         BufferParams::PARSEP_SKIP)
1156                 {
1157                         if (layout->isParagraph()
1158                                 && pit->getDepth() == 0
1159                                 && pit != ownerParagraphs().begin())
1160                         {
1161                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1162                         } else if (pit != ownerParagraphs().begin() &&
1163                                    boost::prior(pit)->layout()->isParagraph() &&
1164                                    boost::prior(pit)->getDepth() == 0)
1165                         {
1166                                 // is it right to use defskip here too? (AS)
1167                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1168                         }
1169                 }
1170
1171                 // the top margin
1172                 if (pit == ownerParagraphs().begin() && !isInInset())
1173                         maxasc += PAPER_MARGIN;
1174
1175                 // add the vertical spaces, that the user added
1176                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1177
1178                 // do not forget the DTP-lines!
1179                 // there height depends on the font of the nearest character
1180                 if (pit->params().lineTop())
1181
1182                         maxasc += 2 * font_metrics::ascent('x', getFont(bv()->buffer(),
1183                                         pit, 0));
1184                 // and now the pagebreaks
1185                 if (pit->params().pagebreakTop())
1186                         maxasc += 3 * defaultRowHeight();
1187
1188                 if (pit->params().startOfAppendix())
1189                         maxasc += 3 * defaultRowHeight();
1190
1191                 // This is special code for the chapter, since the label of this
1192                 // layout is printed in an extra row
1193                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1194                         && bv()->buffer()->params.secnumdepth >= 0)
1195                 {
1196                         float spacing_val = 1.0;
1197                         if (!pit->params().spacing().isDefault()) {
1198                                 spacing_val = pit->params().spacing().getValue();
1199                         } else {
1200                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1201                         }
1202
1203                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1204                                          layout->spacing.getValue() *
1205                                          spacing_val)
1206                                 + int(font_metrics::maxAscent(labelfont) *
1207                                       layout->spacing.getValue() *
1208                                       spacing_val);
1209                 }
1210
1211                 // special code for the top label
1212                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1213                      || layout->labeltype == LABEL_BIBLIO
1214                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1215                     && isFirstInSequence(pit, ownerParagraphs())
1216                     && !pit->getLabelstring().empty())
1217                 {
1218                         float spacing_val = 1.0;
1219                         if (!pit->params().spacing().isDefault()) {
1220                                 spacing_val = pit->params().spacing().getValue();
1221                         } else {
1222                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1223                         }
1224
1225                         labeladdon = int(
1226                                 (font_metrics::maxAscent(labelfont) *
1227                                  layout->spacing.getValue() *
1228                                  spacing_val)
1229                                 +(font_metrics::maxDescent(labelfont) *
1230                                   layout->spacing.getValue() *
1231                                   spacing_val)
1232                                 + layout->topsep * defaultRowHeight()
1233                                 + layout->labelbottomsep * defaultRowHeight());
1234                 }
1235
1236                 // And now the layout spaces, for example before and after
1237                 // a section, or between the items of a itemize or enumerate
1238                 // environment.
1239
1240                 if (!pit->params().pagebreakTop()) {
1241                         ParagraphList::iterator prev =
1242                                 depthHook(pit, ownerParagraphs(),
1243                                           pit->getDepth());
1244                         if (prev != pit && prev->layout() == layout &&
1245                                 prev->getDepth() == pit->getDepth() &&
1246                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1247                         {
1248                                 layoutasc = (layout->itemsep * defaultRowHeight());
1249                         } else if (rit != rows().begin()) {
1250                                 tmptop = layout->topsep;
1251
1252                                 if (boost::prior(pit)->getDepth() >= pit->getDepth())
1253                                         tmptop -= boost::prior(rit)->par()->layout()->bottomsep;
1254
1255                                 if (tmptop > 0)
1256                                         layoutasc = (tmptop * defaultRowHeight());
1257                         } else if (pit->params().lineTop()) {
1258                                 tmptop = layout->topsep;
1259
1260                                 if (tmptop > 0)
1261                                         layoutasc = (tmptop * defaultRowHeight());
1262                         }
1263
1264                         prev = outerHook(pit, ownerParagraphs());
1265                         if (prev != ownerParagraphs().end())  {
1266                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1267                         } else if (pit != ownerParagraphs().begin()) {
1268                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1269                                 if (prior_pit->getDepth() != 0 ||
1270                                     prior_pit->layout() == layout) {
1271                                         maxasc += int(layout->parsep * defaultRowHeight());
1272                                 }
1273                         }
1274                 }
1275         }
1276
1277         // is it a bottom line?
1278         RowList::iterator next_rit = boost::next(rit);
1279         if (next_rit == rows().end() || next_rit->par() != pit) {
1280                 // the bottom margin
1281                 ParagraphList::iterator nextpit = boost::next(pit);
1282                 if (nextpit == ownerParagraphs().end() &&
1283                     !isInInset())
1284                         maxdesc += PAPER_MARGIN;
1285
1286                 // add the vertical spaces, that the user added
1287                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1288
1289                 // do not forget the DTP-lines!
1290                 // there height depends on the font of the nearest character
1291                 if (pit->params().lineBottom())
1292                         maxdesc += 2 * font_metrics::ascent('x',
1293                                                        getFont(bv()->buffer(),
1294                                                                pit,
1295                                                                max(pos_type(0), pit->size() - 1)));
1296
1297                 // and now the pagebreaks
1298                 if (pit->params().pagebreakBottom())
1299                         maxdesc += 3 * defaultRowHeight();
1300
1301                 // and now the layout spaces, for example before and after
1302                 // a section, or between the items of a itemize or enumerate
1303                 // environment
1304                 if (!pit->params().pagebreakBottom()
1305                     && nextpit != ownerParagraphs().end()) {
1306                         ParagraphList::iterator comparepit = pit;
1307                         float usual = 0;
1308                         float unusual = 0;
1309
1310                         if (comparepit->getDepth() > nextpit->getDepth()) {
1311                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1312                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1313                                 if (comparepit->layout()!= nextpit->layout()
1314                                         || nextpit->getLabelWidthString() !=
1315                                         comparepit->getLabelWidthString())
1316                                 {
1317                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1318                                 }
1319                                 if (unusual > usual)
1320                                         layoutdesc = unusual;
1321                                 else
1322                                         layoutdesc = usual;
1323                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1324
1325                                 if (comparepit->layout() != nextpit->layout()
1326                                         || nextpit->getLabelWidthString() !=
1327                                         comparepit->getLabelWidthString())
1328                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1329                         }
1330                 }
1331         }
1332
1333         // incalculate the layout spaces
1334         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1335         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1336
1337         // calculate the new height of the text
1338         height -= rit->height();
1339
1340         rit->height(maxasc + maxdesc + labeladdon);
1341         rit->baseline(maxasc + labeladdon);
1342
1343         height += rit->height();
1344
1345         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1346
1347         int x = 0;
1348         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1349                 int dummy;
1350                 // this IS needed
1351                 rit->width(maxwidth);
1352                 prepareToPrint(rit, x, dummy, dummy, dummy, false);
1353         }
1354         rit->width(int(maxwidth + x));
1355         if (inset_owner) {
1356                 width = max(0, workWidth());
1357                 RowList::iterator it = rows().begin();
1358                 RowList::iterator end = rows().end();
1359                 for (; it != end; ++it) {
1360                         if (it->width() > width)
1361                                 width = it->width();
1362                 }
1363         }
1364 }
1365
1366
1367 // Appends the implicit specified paragraph before the specified row,
1368 // start at the implicit given position
1369 void LyXText::appendParagraph(RowList::iterator rowit)
1370 {
1371         Assert(rowit != rowlist_.end());
1372
1373         pos_type const last = rowit->par()->size();
1374         bool done = false;
1375
1376         do {
1377                 pos_type z = rowBreakPoint(*rowit);
1378
1379                 RowList::iterator tmprow = rowit;
1380
1381                 if (z < last) {
1382                         ++z;
1383                         Row newrow(rowit->par(), z);
1384                         rowit = rowlist_.insert(boost::next(rowit), newrow);
1385                 } else {
1386                         done = true;
1387                 }
1388
1389                 // Set the dimensions of the row
1390                 // fixed fill setting now by calling inset->update() in
1391                 // SingleWidth when needed!
1392                 tmprow->fill(fill(tmprow, workWidth()));
1393                 setHeightOfRow(tmprow);
1394
1395         } while (!done);
1396 }
1397
1398
1399 void LyXText::breakAgain(RowList::iterator rit)
1400 {
1401         Assert(rit != rows().end());
1402
1403         bool not_ready = true;
1404
1405         do  {
1406                 pos_type z = rowBreakPoint(*rit);
1407                 RowList::iterator tmprit = rit;
1408                 RowList::iterator end = rows().end();
1409
1410                 if (z < rit->par()->size()) {
1411                         RowList::iterator next_rit = boost::next(rit);
1412
1413                         if (next_rit == end ||
1414                             (next_rit != end &&
1415                              next_rit->par() != rit->par())) {
1416                                 // insert a new row
1417                                 ++z;
1418                                 Row newrow(rit->par(), z);
1419                                 rit = rowlist_.insert(next_rit, newrow);
1420                         } else  {
1421                                 ++rit;
1422                                 ++z;
1423                                 if (rit->pos() == z)
1424                                         not_ready = false; // the rest will not change
1425                                 else {
1426                                         rit->pos(z);
1427                                 }
1428                         }
1429                 } else {
1430                         // if there are some rows too much, delete them
1431                         // only if you broke the whole paragraph!
1432                         RowList::iterator tmprit2 = rit;
1433                         while (boost::next(tmprit2) != end
1434                                && boost::next(tmprit2)->par() == rit->par()) {
1435                                 ++tmprit2;
1436                         }
1437                         while (tmprit2 != rit) {
1438                                 --tmprit2;
1439                                 removeRow(boost::next(tmprit2));
1440                         }
1441                         not_ready = false;
1442                 }
1443
1444                 // set the dimensions of the row
1445                 tmprit->fill(fill(tmprit, workWidth()));
1446                 setHeightOfRow(tmprit);
1447         } while (not_ready);
1448 }
1449
1450
1451 // this is just a little changed version of break again
1452 void LyXText::breakAgainOneRow(RowList::iterator rit)
1453 {
1454         Assert(rit != rows().end());
1455
1456         pos_type z = rowBreakPoint(*rit);
1457         RowList::iterator tmprit = rit;
1458         RowList::iterator end = rows().end();
1459
1460         if (z < rit->par()->size()) {
1461                 RowList::iterator next_rit = boost::next(rit);
1462
1463                 if (next_rit == end ||
1464                     (next_rit != end &&
1465                      next_rit->par() != rit->par())) {
1466                         // insert a new row
1467                         ++z;
1468                         Row newrow(rit->par(), z);
1469                         rit = rowlist_.insert(next_rit, newrow);
1470                 } else  {
1471                         ++rit;
1472                         ++z;
1473                         if (rit->pos() != z)
1474                                 rit->pos(z);
1475                 }
1476         } else {
1477                 // if there are some rows too much, delete them
1478                 // only if you broke the whole paragraph!
1479                 RowList::iterator tmprit2 = rit;
1480                 while (boost::next(tmprit2) != end
1481                        && boost::next(tmprit2)->par() == rit->par()) {
1482                         ++tmprit2;
1483                 }
1484                 while (tmprit2 != rit) {
1485                         --tmprit2;
1486                         removeRow(boost::next(tmprit2));
1487                 }
1488         }
1489
1490         // set the dimensions of the row
1491         tmprit->fill(fill(tmprit, workWidth()));
1492         setHeightOfRow(tmprit);
1493 }
1494
1495
1496 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1497 {
1498         // allow only if at start or end, or all previous is new text
1499         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1500                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1501                 return;
1502
1503         LyXTextClass const & tclass =
1504                 bv()->buffer()->params.getLyXTextClass();
1505         LyXLayout_ptr const & layout = cursor.par()->layout();
1506
1507         // this is only allowed, if the current paragraph is not empty or caption
1508         // and if it has not the keepempty flag active
1509         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1510            && layout->labeltype != LABEL_SENSITIVE)
1511                 return;
1512
1513         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1514
1515         // Always break behind a space
1516         //
1517         // It is better to erase the space (Dekel)
1518         if (cursor.pos() < cursor.par()->size()
1519              && cursor.par()->isLineSeparator(cursor.pos()))
1520            cursor.par()->erase(cursor.pos());
1521         // cursor.pos(cursor.pos() + 1);
1522
1523         // break the paragraph
1524         if (keep_layout)
1525                 keep_layout = 2;
1526         else
1527                 keep_layout = layout->isEnvironment();
1528
1529         // we need to set this before we insert the paragraph. IMO the
1530         // breakParagraph call should return a bool if it inserts the
1531         // paragraph before or behind and we should react on that one
1532         // but we can fix this in 1.3.0 (Jug 20020509)
1533         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1534         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(),
1535                          cursor.pos(), keep_layout);
1536
1537         // well this is the caption hack since one caption is really enough
1538         if (layout->labeltype == LABEL_SENSITIVE) {
1539                 if (!cursor.pos())
1540                         // set to standard-layout
1541                         cursor.par()->applyLayout(tclass.defaultLayout());
1542                 else
1543                         // set to standard-layout
1544                         boost::next(cursor.par())->applyLayout(tclass.defaultLayout());
1545         }
1546
1547         // if the cursor is at the beginning of a row without prior newline,
1548         // move one row up!
1549         // This touches only the screen-update. Otherwise we would may have
1550         // an empty row on the screen
1551         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1552             && !cursorRow()->par()->isNewline(cursor.pos() - 1))
1553         {
1554                 cursorLeft(bv());
1555         }
1556
1557         postPaint();
1558
1559         removeParagraph(cursorRow());
1560
1561         // set the dimensions of the cursor row
1562         cursorRow()->fill(fill(cursorRow(), workWidth()));
1563
1564         setHeightOfRow(cursorRow());
1565
1566 #warning Trouble Point! (Lgb)
1567         // When ::breakParagraph is called from within an inset we must
1568         // ensure that the correct ParagraphList is used. Today that is not
1569         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1570         ParagraphList::iterator next_par = boost::next(cursor.par());
1571
1572         while (!next_par->empty() && next_par->isNewline(0))
1573                 next_par->erase(0);
1574
1575         insertParagraph(next_par, boost::next(cursorRow()));
1576         updateCounters();
1577
1578         // This check is necessary. Otherwise the new empty paragraph will
1579         // be deleted automatically. And it is more friendly for the user!
1580         if (cursor.pos() || isempty)
1581                 setCursor(next_par, 0);
1582         else
1583                 setCursor(cursor.par(), 0);
1584
1585         if (boost::next(cursorRow()) != rows().end())
1586                 breakAgain(boost::next(cursorRow()));
1587
1588         need_break_row = rows().end();
1589 }
1590
1591
1592 // Just a macro to make some thing easier.
1593 void LyXText::redoParagraph()
1594 {
1595         clearSelection();
1596         redoParagraphs(cursor, boost::next(cursor.par()));
1597         setCursorIntern(cursor.par(), cursor.pos());
1598 }
1599
1600
1601 // insert a character, moves all the following breaks in the
1602 // same Paragraph one to the right and make a rebreak
1603 void LyXText::insertChar(char c)
1604 {
1605         recordUndo(bv(), Undo::INSERT, cursor.par());
1606
1607         // When the free-spacing option is set for the current layout,
1608         // disable the double-space checking
1609
1610         bool const freeSpacing = cursorRow()->par()->layout()->free_spacing ||
1611                 cursorRow()->par()->isFreeSpacing();
1612
1613         if (lyxrc.auto_number) {
1614                 static string const number_operators = "+-/*";
1615                 static string const number_unary_operators = "+-";
1616                 static string const number_seperators = ".,:";
1617
1618                 if (current_font.number() == LyXFont::ON) {
1619                         if (!IsDigit(c) && !contains(number_operators, c) &&
1620                             !(contains(number_seperators, c) &&
1621                               cursor.pos() >= 1 &&
1622                               cursor.pos() < cursor.par()->size() &&
1623                               getFont(bv()->buffer(),
1624                                       cursor.par(),
1625                                       cursor.pos()).number() == LyXFont::ON &&
1626                               getFont(bv()->buffer(),
1627                                       cursor.par(),
1628                                       cursor.pos() - 1).number() == LyXFont::ON)
1629                            )
1630                                 number(bv()); // Set current_font.number to OFF
1631                 } else if (IsDigit(c) &&
1632                            real_current_font.isVisibleRightToLeft()) {
1633                         number(bv()); // Set current_font.number to ON
1634
1635                         if (cursor.pos() > 0) {
1636                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1637                                 if (contains(number_unary_operators, c) &&
1638                                     (cursor.pos() == 1 ||
1639                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1640                                      cursor.par()->isNewline(cursor.pos() - 2))
1641                                   ) {
1642                                         setCharFont(bv()->buffer(),
1643                                                     cursor.par(),
1644                                                     cursor.pos() - 1,
1645                                                     current_font);
1646                                 } else if (contains(number_seperators, c) &&
1647                                            cursor.pos() >= 2 &&
1648                                            getFont(bv()->buffer(),
1649                                                    cursor.par(),
1650                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1651                                         setCharFont(bv()->buffer(),
1652                                                     cursor.par(),
1653                                                     cursor.pos() - 1,
1654                                                     current_font);
1655                                 }
1656                         }
1657                 }
1658         }
1659
1660
1661         // First check, if there will be two blanks together or a blank at
1662         // the beginning of a paragraph.
1663         // I decided to handle blanks like normal characters, the main
1664         // difference are the special checks when calculating the row.fill
1665         // (blank does not count at the end of a row) and the check here
1666
1667         // The bug is triggered when we type in a description environment:
1668         // The current_font is not changed when we go from label to main text
1669         // and it should (along with realtmpfont) when we type the space.
1670         // CHECK There is a bug here! (Asger)
1671
1672         LyXFont realtmpfont = real_current_font;
1673         LyXFont rawtmpfont = current_font;
1674         // store the current font.  This is because of the use of cursor
1675         // movements. The moving cursor would refresh the current font
1676
1677         // Get the font that is used to calculate the baselineskip
1678         pos_type const lastpos = cursor.par()->size();
1679         LyXFont rawparfont =
1680                 cursor.par()->getFontSettings(bv()->buffer()->params,
1681                                               lastpos - 1);
1682
1683         bool jumped_over_space = false;
1684
1685         if (!freeSpacing && IsLineSeparatorChar(c)) {
1686                 if ((cursor.pos() > 0
1687                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1688                     || (cursor.pos() > 0
1689                         && cursor.par()->isNewline(cursor.pos() - 1))
1690                     || (cursor.pos() == 0)) {
1691                         static bool sent_space_message = false;
1692                         if (!sent_space_message) {
1693                                 if (cursor.pos() == 0)
1694                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1695                                 else
1696                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1697                                 sent_space_message = true;
1698                         }
1699                         charInserted();
1700                         return;
1701                 }
1702         }
1703
1704         // the display inset stuff
1705         if (cursorRow()->pos() < cursorRow()->par()->size()
1706             && cursorRow()->par()->isInset(cursorRow()->pos())) {
1707                 InsetOld * inset = cursorRow()->par()->getInset(cursorRow()->pos());
1708                 if (inset && (inset->display() || inset->needFullRow())) {
1709                         // force a new break
1710                         cursorRow()->fill(-1); // to force a new break
1711                 }
1712         }
1713
1714         // get the cursor row fist
1715         RowList::iterator row = cursorRow();
1716         if (c != Paragraph::META_INSET) {
1717                 // Here case LyXText::InsertInset  already inserted the character
1718                 cursor.par()->insertChar(cursor.pos(), c);
1719         }
1720         setCharFont(bv()->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1721
1722         if (!jumped_over_space) {
1723                 // refresh the positions
1724                 RowList::iterator tmprow = row;
1725                 while (boost::next(tmprow) != rows().end() &&
1726                        boost::next(tmprow)->par() == row->par()) {
1727                         ++tmprow;
1728                         tmprow->pos(tmprow->pos() + 1);
1729                 }
1730         }
1731
1732         // Is there a break one row above
1733         if (row != rows().begin() &&
1734             boost::prior(row)->par() == row->par()
1735             && (cursor.par()->isLineSeparator(cursor.pos())
1736                 || cursor.par()->isNewline(cursor.pos())
1737                 || ((cursor.pos() + 1 < cursor.par()->size()) &&
1738                     cursor.par()->isInset(cursor.pos() + 1))
1739                 || cursorRow()->fill() == -1))
1740         {
1741                 pos_type z = rowBreakPoint(*boost::prior(row));
1742
1743                 if (z >= row->pos()) {
1744                         row->pos(z + 1);
1745
1746                         // set the dimensions of the row above
1747                         boost::prior(row)->fill(fill(
1748                                                    boost::prior(row),
1749                                                    workWidth()));
1750
1751                         setHeightOfRow(boost::prior(row));
1752
1753                         postPaint();
1754
1755                         breakAgainOneRow(row);
1756
1757                         current_font = rawtmpfont;
1758                         real_current_font = realtmpfont;
1759                         setCursor(cursor.par(), cursor.pos() + 1,
1760                                   false, cursor.boundary());
1761                         // cursor MUST be in row now.
1762
1763                         RowList::iterator next_row = boost::next(row);
1764                         if (next_row != rows().end() &&
1765                             next_row->par() == row->par())
1766                                 need_break_row = next_row;
1767                         else
1768                                 need_break_row = rows().end();
1769
1770                         // check, wether the last characters font has changed.
1771                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1772                             && rawparfont != rawtmpfont)
1773                                 redoHeightOfParagraph();
1774
1775                         charInserted();
1776                         return;
1777                 }
1778         }
1779
1780         // recalculate the fill of the row
1781         if (row->fill() >= 0) {
1782                 // needed because a newline will set fill to -1. Otherwise
1783                 // we would not get a rebreak!
1784                 row->fill(fill(row, workWidth()));
1785         }
1786
1787         if (c == Paragraph::META_INSET || row->fill() < 0) {
1788                 postPaint();
1789                 breakAgainOneRow(row);
1790
1791                 RowList::iterator next_row = boost::next(row);
1792
1793                 // will the cursor be in another row now?
1794                 if (lastPos(*this, row) <= cursor.pos() + 1 &&
1795                     next_row != rows().end()) {
1796                         if (next_row != rows().end() &&
1797                             next_row->par() == row->par()) {
1798                                 // this should always be true
1799                                 ++row;
1800                         }
1801
1802                         breakAgainOneRow(row);
1803                 }
1804                 current_font = rawtmpfont;
1805                 real_current_font = realtmpfont;
1806
1807                 setCursor(cursor.par(), cursor.pos() + 1, false,
1808                           cursor.boundary());
1809                 if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
1810                     != cursor.boundary())
1811                         setCursor(cursor.par(), cursor.pos(), false,
1812                           !cursor.boundary());
1813
1814                 next_row = boost::next(row);
1815
1816                 if (next_row != rows().end() &&
1817                     next_row->par() == row->par())
1818                         need_break_row = next_row;
1819                 else
1820                         need_break_row = rows().end();
1821         } else {
1822                 // FIXME: similar code is duplicated all over - make resetHeightOfRow
1823                 setHeightOfRow(row);
1824                 postPaint();
1825
1826                 current_font = rawtmpfont;
1827                 real_current_font = realtmpfont;
1828                 setCursor(cursor.par(), cursor.pos() + 1, false,
1829                           cursor.boundary());
1830         }
1831
1832         // check, wether the last characters font has changed.
1833         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1834             && rawparfont != rawtmpfont) {
1835                 redoHeightOfParagraph();
1836         }
1837
1838         charInserted();
1839 }
1840
1841
1842 void LyXText::charInserted()
1843 {
1844         // Here we could call FinishUndo for every 20 characters inserted.
1845         // This is from my experience how emacs does it. (Lgb)
1846         static unsigned int counter;
1847         if (counter < 20) {
1848                 ++counter;
1849         } else {
1850                 finishUndo();
1851                 counter = 0;
1852         }
1853 }
1854
1855
1856 void LyXText::prepareToPrint(RowList::iterator rit, int & x,
1857                              int & fill_separator,
1858                              int & fill_hfill,
1859                              int & fill_label_hfill,
1860                              bool bidi) const
1861 {
1862         int w = rit->fill();
1863         fill_hfill = 0;
1864         fill_label_hfill = 0;
1865         fill_separator = 0;
1866         fill_label_hfill = 0;
1867
1868         ParagraphList::iterator pit = rit->par();
1869
1870         bool const is_rtl =
1871                 pit->isRightToLeftPar(bv()->buffer()->params);
1872         if (is_rtl)
1873                 x = workWidth() > 0 ? rightMargin(*bv()->buffer(), *rit) : 0;
1874         else
1875                 x = workWidth() > 0 ? leftMargin(*rit) : 0;
1876
1877         // is there a manual margin with a manual label
1878         LyXLayout_ptr const & layout = pit->layout();
1879
1880         if (layout->margintype == MARGIN_MANUAL
1881             && layout->labeltype == LABEL_MANUAL) {
1882                 /// We might have real hfills in the label part
1883                 int nlh = numberOfLabelHfills(*this, rit);
1884
1885                 // A manual label par (e.g. List) has an auto-hfill
1886                 // between the label text and the body of the
1887                 // paragraph too.
1888                 // But we don't want to do this auto hfill if the par
1889                 // is empty.
1890                 if (!pit->empty())
1891                         ++nlh;
1892
1893                 if (nlh && !pit->getLabelWidthString().empty()) {
1894                         fill_label_hfill = int(labelFill(*rit) / nlh);
1895                 }
1896         }
1897
1898         // are there any hfills in the row?
1899         int const nh = numberOfHfills(*this, rit);
1900
1901         if (nh) {
1902                 if (w > 0)
1903                         fill_hfill = w / nh;
1904         // we don't have to look at the alignment if it is ALIGN_LEFT and
1905         // if the row is already larger then the permitted width as then
1906         // we force the LEFT_ALIGN'edness!
1907         } else if (int(rit->width()) < workWidth()) {
1908                 // is it block, flushleft or flushright?
1909                 // set x how you need it
1910                 int align;
1911                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1912                         align = layout->align;
1913                 } else {
1914                         align = pit->params().align();
1915                 }
1916
1917                 // center displayed insets
1918                 InsetOld * inset = 0;
1919                 if (rit->pos() < pit->size()
1920                     && pit->isInset(rit->pos())
1921                     && (inset = pit->getInset(rit->pos()))
1922                     && (inset->display())) // || (inset->scroll() < 0)))
1923                     align = (inset->lyxCode() == InsetOld::MATHMACRO_CODE)
1924                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1925                 // ERT insets should always be LEFT ALIGNED on screen
1926                 inset = pit->inInset();
1927                 if (inset && inset->owner() &&
1928                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1929                 {
1930                         align = LYX_ALIGN_LEFT;
1931                 }
1932
1933                 switch (align) {
1934             case LYX_ALIGN_BLOCK:
1935             {
1936                         int const ns = numberOfSeparators(*this, rit);
1937                         RowList::iterator next_row = boost::next(rit);
1938                         ParagraphList::iterator next_pit = next_row->par();
1939
1940                         if (ns && next_row != rowlist_.end() &&
1941                             next_pit == pit &&
1942                             !(next_pit->isNewline(next_row->pos() - 1))
1943                             && !(next_pit->isInset(next_row->pos()) &&
1944                                  next_pit->getInset(next_row->pos()) &&
1945                                  next_pit->getInset(next_row->pos())->display())
1946                                 ) {
1947                                 fill_separator = w / ns;
1948                         } else if (is_rtl) {
1949                                 x += w;
1950                         }
1951                         break;
1952             }
1953             case LYX_ALIGN_RIGHT:
1954                         x += w;
1955                         break;
1956             case LYX_ALIGN_CENTER:
1957                         x += w / 2;
1958                         break;
1959                 }
1960         }
1961         if (!bidi)
1962                 return;
1963
1964         computeBidiTables(bv()->buffer(), rit);
1965         if (is_rtl) {
1966                 pos_type body_pos = pit->beginningOfBody();
1967                 pos_type last = lastPos(*this, rit);
1968
1969                 if (body_pos > 0 &&
1970                     (body_pos - 1 > last ||
1971                      !pit->isLineSeparator(body_pos - 1))) {
1972                         x += font_metrics::width(layout->labelsep,
1973                                             getLabelFont(bv()->buffer(),
1974                                                          pit));
1975                         if (body_pos - 1 <= last)
1976                                 x += fill_label_hfill;
1977                 }
1978         }
1979 }
1980
1981
1982 // important for the screen
1983
1984
1985 // the cursor set functions have a special mechanism. When they
1986 // realize, that you left an empty paragraph, they will delete it.
1987 // They also delete the corresponding row
1988
1989 void LyXText::cursorRightOneWord()
1990 {
1991         ::cursorRightOneWord(cursor, ownerParagraphs());
1992         setCursor(cursor.par(), cursor.pos());
1993 }
1994
1995
1996 // Skip initial whitespace at end of word and move cursor to *start*
1997 // of prior word, not to end of next prior word.
1998 void LyXText::cursorLeftOneWord()
1999 {
2000         LyXCursor tmpcursor = cursor;
2001         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
2002         setCursor(tmpcursor.par(), tmpcursor.pos());
2003 }
2004
2005
2006 void LyXText::selectWord(word_location loc)
2007 {
2008         LyXCursor from = cursor;
2009         LyXCursor to;
2010         ::getWord(from, to, loc, ownerParagraphs());
2011         if (cursor != from)
2012                 setCursor(from.par(), from.pos());
2013         if (to == from)
2014                 return;
2015         selection.cursor = cursor;
2016         setCursor(to.par(), to.pos());
2017         setSelection();
2018 }
2019
2020
2021 // Select the word currently under the cursor when no
2022 // selection is currently set
2023 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2024 {
2025         if (!selection.set()) {
2026                 selectWord(loc);
2027                 return selection.set();
2028         }
2029         return false;
2030 }
2031
2032
2033 void LyXText::acceptChange()
2034 {
2035         if (!selection.set() && cursor.par()->size())
2036                 return;
2037
2038         if (selection.start.par() == selection.end.par()) {
2039                 LyXCursor & startc = selection.start;
2040                 LyXCursor & endc = selection.end;
2041                 recordUndo(bv(), Undo::INSERT, startc.par());
2042                 startc.par()->acceptChange(startc.pos(), endc.pos());
2043                 finishUndo();
2044                 clearSelection();
2045                 redoParagraphs(startc, boost::next(startc.par()));
2046                 setCursorIntern(startc.par(), 0);
2047         }
2048 #warning handle multi par selection
2049 }
2050
2051
2052 void LyXText::rejectChange()
2053 {
2054         if (!selection.set() && cursor.par()->size())
2055                 return;
2056
2057         if (selection.start.par() == selection.end.par()) {
2058                 LyXCursor & startc = selection.start;
2059                 LyXCursor & endc = selection.end;
2060                 recordUndo(bv(), Undo::INSERT, startc.par());
2061                 startc.par()->rejectChange(startc.pos(), endc.pos());
2062                 finishUndo();
2063                 clearSelection();
2064                 redoParagraphs(startc, boost::next(startc.par()));
2065                 setCursorIntern(startc.par(), 0);
2066         }
2067 #warning handle multi par selection
2068 }
2069
2070
2071 // This function is only used by the spellchecker for NextWord().
2072 // It doesn't handle LYX_ACCENTs and probably never will.
2073 WordLangTuple const
2074 LyXText::selectNextWordToSpellcheck(float & value)
2075 {
2076         if (the_locking_inset) {
2077                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2078                 if (!word.word().empty()) {
2079                         value += float(cursor.y());
2080                         value /= float(height);
2081                         return word;
2082                 }
2083                 // we have to go on checking so move cursor to the next char
2084                 if (cursor.pos() == cursor.par()->size()) {
2085                         if (boost::next(cursor.par()) == ownerParagraphs().end())
2086                                 return word;
2087                         cursor.par(boost::next(cursor.par()));
2088                         cursor.pos(0);
2089                 } else
2090                         cursor.pos(cursor.pos() + 1);
2091         }
2092         ParagraphList::iterator tmppit = cursor.par();
2093
2094         // If this is not the very first word, skip rest of
2095         // current word because we are probably in the middle
2096         // of a word if there is text here.
2097         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
2098                 while (cursor.pos() < cursor.par()->size()
2099                        && cursor.par()->isLetter(cursor.pos()))
2100                         cursor.pos(cursor.pos() + 1);
2101         }
2102
2103         // Now, skip until we have real text (will jump paragraphs)
2104         while (true) {
2105                 ParagraphList::iterator cpit = cursor.par();
2106                 pos_type const cpos(cursor.pos());
2107
2108                 if (cpos == cpit->size()) {
2109                         if (boost::next(cpit) != ownerParagraphs().end()) {
2110                                 cursor.par(boost::next(cpit));
2111                                 cursor.pos(0);
2112                                 continue;
2113                         }
2114                         break;
2115                 }
2116
2117                 bool const is_good_inset = cpit->isInset(cpos)
2118                         && cpit->getInset(cpos)->allowSpellcheck();
2119
2120                 if (!isDeletedText(*cpit, cpos)
2121                     && (is_good_inset || cpit->isLetter(cpos)))
2122                         break;
2123
2124                 cursor.pos(cpos + 1);
2125         }
2126
2127         // now check if we hit an inset so it has to be a inset containing text!
2128         if (cursor.pos() < cursor.par()->size() &&
2129             cursor.par()->isInset(cursor.pos())) {
2130                 // lock the inset!
2131                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
2132                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
2133                 // now call us again to do the above trick
2134                 // but obviously we have to start from down below ;)
2135                 return bv()->text->selectNextWordToSpellcheck(value);
2136         }
2137
2138         // Update the value if we changed paragraphs
2139         if (cursor.par() != tmppit) {
2140                 setCursor(cursor.par(), cursor.pos());
2141                 value = float(cursor.y())/float(height);
2142         }
2143
2144         // Start the selection from here
2145         selection.cursor = cursor;
2146
2147         string lang_code(
2148                 getFont(bv()->buffer(), cursor.par(), cursor.pos())
2149                         .language()->code());
2150         // and find the end of the word (insets like optional hyphens
2151         // and ligature break are part of a word)
2152         while (cursor.pos() < cursor.par()->size()
2153                && cursor.par()->isLetter(cursor.pos())
2154                && !isDeletedText(*cursor.par(), cursor.pos()))
2155                 cursor.pos(cursor.pos() + 1);
2156
2157         // Finally, we copy the word to a string and return it
2158         string str;
2159         if (selection.cursor.pos() < cursor.pos()) {
2160                 pos_type i;
2161                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2162                         if (!cursor.par()->isInset(i))
2163                                 str += cursor.par()->getChar(i);
2164                 }
2165         }
2166         return WordLangTuple(str, lang_code);
2167 }
2168
2169
2170 // This one is also only for the spellchecker
2171 void LyXText::selectSelectedWord()
2172 {
2173         if (the_locking_inset) {
2174                 the_locking_inset->selectSelectedWord(bv());
2175                 return;
2176         }
2177         // move cursor to the beginning
2178         setCursor(selection.cursor.par(), selection.cursor.pos());
2179
2180         // set the sel cursor
2181         selection.cursor = cursor;
2182
2183         // now find the end of the word
2184         while (cursor.pos() < cursor.par()->size()
2185                && (cursor.par()->isLetter(cursor.pos())))
2186                 cursor.pos(cursor.pos() + 1);
2187
2188         setCursor(cursor.par(), cursor.pos());
2189
2190         // finally set the selection
2191         setSelection();
2192 }
2193
2194
2195 // Delete from cursor up to the end of the current or next word.
2196 void LyXText::deleteWordForward()
2197 {
2198         if (cursor.par()->empty())
2199                 cursorRight(bv());
2200         else {
2201                 LyXCursor tmpcursor = cursor;
2202                 selection.set(true); // to avoid deletion
2203                 cursorRightOneWord();
2204                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2205                 selection.cursor = cursor;
2206                 cursor = tmpcursor;
2207                 setSelection();
2208
2209                 // Great, CutSelection() gets rid of multiple spaces.
2210                 cutSelection(true, false);
2211         }
2212 }
2213
2214
2215 // Delete from cursor to start of current or prior word.
2216 void LyXText::deleteWordBackward()
2217 {
2218         if (cursor.par()->empty())
2219                 cursorLeft(bv());
2220         else {
2221                 LyXCursor tmpcursor = cursor;
2222                 selection.set(true); // to avoid deletion
2223                 cursorLeftOneWord();
2224                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2225                 selection.cursor = cursor;
2226                 cursor = tmpcursor;
2227                 setSelection();
2228                 cutSelection(true, false);
2229         }
2230 }
2231
2232
2233 // Kill to end of line.
2234 void LyXText::deleteLineForward()
2235 {
2236         if (cursor.par()->empty())
2237                 // Paragraph is empty, so we just go to the right
2238                 cursorRight(bv());
2239         else {
2240                 LyXCursor tmpcursor = cursor;
2241                 // We can't store the row over a regular setCursor
2242                 // so we set it to 0 and reset it afterwards.
2243                 selection.set(true); // to avoid deletion
2244                 cursorEnd();
2245                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2246                 selection.cursor = cursor;
2247                 cursor = tmpcursor;
2248                 setSelection();
2249                 // What is this test for ??? (JMarc)
2250                 if (!selection.set()) {
2251                         deleteWordForward();
2252                 } else {
2253                         cutSelection(true, false);
2254                 }
2255         }
2256 }
2257
2258
2259 void LyXText::changeCase(LyXText::TextCase action)
2260 {
2261         LyXCursor from;
2262         LyXCursor to;
2263
2264         if (selection.set()) {
2265                 from = selection.start;
2266                 to = selection.end;
2267         } else {
2268                 from = cursor;
2269                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
2270                 setCursor(to.par(), to.pos() + 1);
2271         }
2272
2273         recordUndo(bv(), Undo::ATOMIC, from.par(), to.par());
2274
2275         pos_type pos = from.pos();
2276         ParagraphList::iterator pit = from.par();
2277
2278         while (pit != ownerParagraphs().end() &&
2279                (pos != to.pos() || pit != to.par())) {
2280                 if (pos == pit->size()) {
2281                         ++pit;
2282                         pos = 0;
2283                         continue;
2284                 }
2285                 unsigned char c = pit->getChar(pos);
2286                 if (!IsInsetChar(c)) {
2287                         switch (action) {
2288                         case text_lowercase:
2289                                 c = lowercase(c);
2290                                 break;
2291                         case text_capitalization:
2292                                 c = uppercase(c);
2293                                 action = text_lowercase;
2294                                 break;
2295                         case text_uppercase:
2296                                 c = uppercase(c);
2297                                 break;
2298                         }
2299                 }
2300 #warning changes
2301                 pit->setChar(pos, c);
2302                 checkParagraph(pit, pos);
2303
2304                 ++pos;
2305         }
2306
2307         if (getRow(to) != getRow(from))
2308                 postPaint();
2309 }
2310
2311
2312 void LyXText::Delete()
2313 {
2314         // this is a very easy implementation
2315
2316         LyXCursor old_cursor = cursor;
2317         int const old_cur_par_id = old_cursor.par()->id();
2318         int const old_cur_par_prev_id =
2319                 (old_cursor.par() != ownerParagraphs().begin() ?
2320                  boost::prior(old_cursor.par())->id() : -1);
2321
2322         // just move to the right
2323         cursorRight(bv());
2324
2325         // CHECK Look at the comment here.
2326         // This check is not very good...
2327         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2328         // and that can very well delete the par or par->previous in
2329         // old_cursor. Will a solution where we compare paragraph id's
2330         //work better?
2331         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2332             == old_cur_par_prev_id
2333             && cursor.par()->id() != old_cur_par_id) {
2334                 // delete-empty-paragraph-mechanism has done it
2335                 return;
2336         }
2337
2338         // if you had success make a backspace
2339         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2340                 LyXCursor tmpcursor = cursor;
2341                 // to make sure undo gets the right cursor position
2342                 cursor = old_cursor;
2343                 recordUndo(bv(), Undo::DELETE, cursor.par());
2344                 cursor = tmpcursor;
2345                 backspace();
2346         }
2347 }
2348
2349
2350 void LyXText::backspace()
2351 {
2352         // Get the font that is used to calculate the baselineskip
2353         pos_type lastpos = cursor.par()->size();
2354         LyXFont rawparfont =
2355                 cursor.par()->getFontSettings(bv()->buffer()->params,
2356                                               lastpos - 1);
2357
2358         if (cursor.pos() == 0) {
2359                 // The cursor is at the beginning of a paragraph,
2360                 // so the the backspace will collapse two paragraphs into one.
2361
2362                 // but it's not allowed unless it's new
2363                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2364                         return;
2365
2366                 // we may paste some paragraphs
2367
2368                 // is it an empty paragraph?
2369
2370                 if ((lastpos == 0
2371                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2372                         // This is an empty paragraph and we delete it just by moving the cursor one step
2373                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2374                         // of the paragraph.
2375
2376                         if (cursor.par() != ownerParagraphs().begin()) {
2377                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2378                                 if (cursor.par()->layout() == tmppit->layout()
2379                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2380                                         // Inherit bottom DTD from the paragraph below.
2381                                         // (the one we are deleting)
2382                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2383                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2384                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2385                                 }
2386
2387                                 cursorLeft(bv());
2388
2389                                 // the layout things can change the height of a row !
2390                                 int const tmpheight = cursorRow()->height();
2391                                 setHeightOfRow(cursorRow());
2392                                 if (cursorRow()->height() != tmpheight)
2393                                         postPaint();
2394                                 return;
2395                         }
2396                 }
2397
2398                 if (cursor.par() != ownerParagraphs().begin()) {
2399                         recordUndo(bv(), Undo::DELETE,
2400                                 boost::prior(cursor.par()),
2401                                 cursor.par());
2402                 }
2403
2404                 ParagraphList::iterator tmppit = cursor.par();
2405                 RowList::iterator tmprow = cursorRow();
2406
2407                 // We used to do cursorLeftIntern() here, but it is
2408                 // not a good idea since it triggers the auto-delete
2409                 // mechanism. So we do a cursorLeftIntern()-lite,
2410                 // without the dreaded mechanism. (JMarc)
2411                 if (cursor.par() != ownerParagraphs().begin()) {
2412                         // steps into the above paragraph.
2413                         setCursorIntern(boost::prior(cursor.par()),
2414                                         boost::prior(cursor.par())->size(),
2415                                         false);
2416                 }
2417
2418                 // Pasting is not allowed, if the paragraphs have different
2419                 // layout. I think it is a real bug of all other
2420                 // word processors to allow it. It confuses the user.
2421                 // Even so with a footnote paragraph and a non-footnote
2422                 // paragraph. I will not allow pasting in this case,
2423                 // because the user would be confused if the footnote behaves
2424                 // different wether it is open or closed.
2425
2426                 //      Correction: Pasting is always allowed with standard-layout
2427                 LyXTextClass const & tclass =
2428                         bv()->buffer()->params.getLyXTextClass();
2429
2430                 if (cursor.par() != tmppit
2431                     && (cursor.par()->layout() == tmppit->layout()
2432                         || tmppit->layout() == tclass.defaultLayout())
2433                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2434                         removeParagraph(tmprow);
2435                         removeRow(tmprow);
2436                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2437
2438                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2439                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2440                         // strangely enough it seems that commenting out the line above removes
2441                         // most or all of the segfaults. I will however also try to move the
2442                         // two Remove... lines in front of the PasteParagraph too.
2443                         else
2444                                 if (cursor.pos())
2445                                         cursor.pos(cursor.pos() - 1);
2446
2447                         postPaint();
2448
2449                         // remove the lost paragraph
2450                         // This one is not safe, since the paragraph that the tmprow and the
2451                         // following rows belong to has been deleted by the PasteParagraph
2452                         // above. The question is... could this be moved in front of the
2453                         // PasteParagraph?
2454                         //RemoveParagraph(tmprow);
2455                         //RemoveRow(tmprow);
2456
2457                         // This rebuilds the rows.
2458                         appendParagraph(cursorRow());
2459                         updateCounters();
2460
2461                         // the row may have changed, block, hfills etc.
2462                         setCursor(cursor.par(), cursor.pos(), false);
2463                 }
2464         } else {
2465                 // this is the code for a normal backspace, not pasting
2466                 // any paragraphs
2467                 recordUndo(bv(), Undo::DELETE, cursor.par());
2468                 // We used to do cursorLeftIntern() here, but it is
2469                 // not a good idea since it triggers the auto-delete
2470                 // mechanism. So we do a cursorLeftIntern()-lite,
2471                 // without the dreaded mechanism. (JMarc)
2472                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2473                                 false, cursor.boundary());
2474
2475                 if (cursor.par()->isInset(cursor.pos())) {
2476                         // force complete redo when erasing display insets
2477                         // this is a cruel method but safe..... Matthias
2478                         if (cursor.par()->getInset(cursor.pos())->display() ||
2479                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2480                                 cursor.par()->erase(cursor.pos());
2481                                 redoParagraph();
2482                                 return;
2483                         }
2484                 }
2485
2486                 RowList::iterator row = cursorRow();
2487                 int y = cursor.y() - row->baseline();
2488                 pos_type z;
2489                 // remember that a space at the end of a row doesnt count
2490                 // when calculating the fill
2491                 if (cursor.pos() < lastPos(*this, row) ||
2492                     !cursor.par()->isLineSeparator(cursor.pos())) {
2493                         row->fill(row->fill() + singleWidth(
2494                                                             cursor.par(),
2495                                                             cursor.pos()));
2496                 }
2497
2498                 // some special code when deleting a newline. This is similar
2499                 // to the behavior when pasting paragraphs
2500                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2501                         cursor.par()->erase(cursor.pos());
2502                         // refresh the positions
2503                         RowList::iterator tmprow = row;
2504                         while (boost::next(tmprow) != rows().end() &&
2505                                boost::next(tmprow)->par() == row->par()) {
2506                                 ++tmprow;
2507                                 tmprow->pos(tmprow->pos() - 1);
2508                         }
2509                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2510                                 cursor.pos(cursor.pos() - 1);
2511
2512                         if (cursor.pos() < cursor.par()->size()
2513                             && !cursor.par()->isSeparator(cursor.pos())) {
2514                                 cursor.par()->insertChar(cursor.pos(), ' ');
2515                                 setCharFont(bv()->buffer(), cursor.par(),
2516                                             cursor.pos(), current_font);
2517                                 // refresh the positions
2518                                 tmprow = row;
2519                                 while (boost::next(tmprow) != rows().end() &&
2520                                        boost::next(tmprow)->par() == row->par()) {
2521                                         ++tmprow;
2522                                         tmprow->pos(tmprow->pos() + 1);
2523                                 }
2524                         }
2525                 } else {
2526                         cursor.par()->erase(cursor.pos());
2527
2528                         // refresh the positions
2529                         RowList::iterator tmprow = row;
2530                         while (boost::next(tmprow) != rows().end() &&
2531                                boost::next(tmprow)->par() == row->par()) {
2532                                 ++tmprow;
2533                                 tmprow->pos(tmprow->pos() - 1);
2534                         }
2535
2536                         // delete newlines at the beginning of paragraphs
2537                         while (!cursor.par()->empty() &&
2538                                cursor.pos() < cursor.par()->size() &&
2539                                cursor.par()->isNewline(cursor.pos()) &&
2540                                cursor.pos() == cursor.par()->beginningOfBody()) {
2541                                 cursor.par()->erase(cursor.pos());
2542                                 // refresh the positions
2543                                 tmprow = row;
2544                                 while (boost::next(tmprow) != rows().end() &&
2545                                        boost::next(tmprow)->par() == row->par()) {
2546                                         ++tmprow;
2547                                         tmprow->pos(tmprow->pos() - 1);
2548                                 }
2549                         }
2550                 }
2551
2552                 // is there a break one row above
2553                 if (row != rows().begin() && boost::prior(row)->par() == row->par()) {
2554                         z = rowBreakPoint(*boost::prior(row));
2555                         if (z >= row->pos()) {
2556                                 row->pos(z + 1);
2557
2558                                 RowList::iterator tmprow = boost::prior(row);
2559
2560                                 // maybe the current row is now empty
2561                                 if (row->pos() >= row->par()->size()) {
2562                                         // remove it
2563                                         removeRow(row);
2564                                         need_break_row = rows().end();
2565                                 } else {
2566                                         breakAgainOneRow(row);
2567                                         if (boost::next(row) != rows().end() &&
2568                                             boost::next(row)->par() == row->par())
2569                                                 need_break_row = boost::next(row);
2570                                         else
2571                                                 need_break_row = rows().end();
2572                                 }
2573
2574                                 // set the dimensions of the row above
2575                                 y -= tmprow->height();
2576                                 tmprow->fill(fill(tmprow, workWidth()));
2577                                 setHeightOfRow(tmprow);
2578                                 postPaint();
2579
2580                                 setCursor(cursor.par(), cursor.pos(),
2581                                           false, cursor.boundary());
2582                                 //current_font = rawtmpfont;
2583                                 //real_current_font = realtmpfont;
2584                                 // check, whether the last character's font has changed.
2585                                 if (rawparfont !=
2586                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2587                                                                   cursor.par()->size() - 1))
2588                                         redoHeightOfParagraph();
2589                                 return;
2590                         }
2591                 }
2592
2593                 // break the cursor row again
2594                 if (boost::next(row) != rows().end() &&
2595                     boost::next(row)->par() == row->par() &&
2596                     (lastPos(*this, row) == row->par()->size() - 1 ||
2597                      rowBreakPoint(*row) != lastPos(*this, row))) {
2598
2599                         // it can happen that a paragraph loses one row
2600                         // without a real breakup. This is when a word
2601                         // is to long to be broken. Well, I don t care this
2602                         // hack ;-)
2603                         if (lastPos(*this, row) == row->par()->size() - 1)
2604                                 removeRow(boost::next(row));
2605
2606                         postPaint();
2607
2608                         breakAgainOneRow(row);
2609                         // will the cursor be in another row now?
2610                         if (boost::next(row) != rows().end() &&
2611                             boost::next(row)->par() == row->par() &&
2612                             lastPos(*this, row) <= cursor.pos()) {
2613                                 ++row;
2614                                 breakAgainOneRow(row);
2615                         }
2616
2617                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2618
2619                         if (boost::next(row) != rows().end() &&
2620                             boost::next(row)->par() == row->par())
2621                                 need_break_row = boost::next(row);
2622                         else
2623                                 need_break_row = rows().end();
2624                 } else  {
2625                         // set the dimensions of the row
2626                         row->fill(fill(row, workWidth()));
2627                         setHeightOfRow(row);
2628                         postPaint();
2629                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2630                 }
2631         }
2632
2633         // current_font = rawtmpfont;
2634         // real_current_font = realtmpfont;
2635
2636         if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
2637             != cursor.boundary())
2638                 setCursor(cursor.par(), cursor.pos(), false,
2639                           !cursor.boundary());
2640
2641         lastpos = cursor.par()->size();
2642         if (cursor.pos() == lastpos)
2643                 setCurrentFont();
2644
2645         // check, whether the last characters font has changed.
2646         if (rawparfont !=
2647             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2648                 redoHeightOfParagraph();
2649         }
2650 }
2651
2652
2653 RowList::iterator LyXText::cursorRow() const
2654 {
2655         return getRow(cursor.par(), cursor.pos());
2656 }
2657
2658
2659 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2660 {
2661         return getRow(cur.par(), cur.pos());
2662 }
2663
2664
2665 RowList::iterator
2666 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2667 {
2668         if (rows().empty())
2669                 return rowlist_.end();
2670
2671         // find the first row of the specified paragraph
2672         RowList::iterator rit = rowlist_.begin();
2673         RowList::iterator end = rowlist_.end();
2674         while (boost::next(rit) != end && rit->par() != pit) {
2675                 ++rit;
2676         }
2677
2678         // now find the wanted row
2679         while (rit->pos() < pos
2680                && boost::next(rit) != end
2681                && boost::next(rit)->par() == pit
2682                && boost::next(rit)->pos() <= pos) {
2683                 ++rit;
2684         }
2685
2686         return rit;
2687 }
2688
2689
2690 // returns pointer to a specified row
2691 RowList::iterator
2692 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2693 {
2694         y = 0;
2695
2696         if (rows().empty())
2697                 return rowlist_.end();
2698
2699         // find the first row of the specified paragraph
2700         RowList::iterator rit = rowlist_.begin();
2701         RowList::iterator end = rowlist_.end();
2702         while (boost::next(rit) != end && rit->par() != pit) {
2703                 y += rit->height();
2704                 ++rit;
2705         }
2706
2707         // now find the wanted row
2708         while (rit->pos() < pos
2709                && boost::next(rit) != end
2710                && boost::next(rit)->par() == pit
2711                && boost::next(rit)->pos() <= pos) {
2712                 y += rit->height();
2713                 ++rit;
2714         }
2715
2716         return rit;
2717 }
2718
2719
2720 // returns pointer to some fancy row 'below' specified row
2721 RowList::iterator LyXText::cursorIRow() const
2722 {
2723         int y = 0;
2724         return getRow(cursor.par(), cursor.pos(), y);
2725 }
2726
2727
2728 RowList::iterator LyXText::getRowNearY(int & y) const
2729 {
2730         RowList::iterator rit = anchor_row_;
2731         RowList::iterator const beg = rows().begin();
2732         RowList::iterator const end = rows().end();
2733
2734         if (rows().empty()) {
2735                 y = 0;
2736                 return end;
2737         }
2738         if (rit == end)
2739                 rit = beg;
2740
2741         int tmpy = rit->y();
2742
2743         if (tmpy <= y) {
2744                 while (rit != end && tmpy <= y) {
2745                         tmpy += rit->height();
2746                         ++rit;
2747                 }
2748                 if (rit != beg) {
2749                         --rit;
2750                         tmpy -= rit->height();
2751                 }
2752         } else {
2753                 while (rit != beg && tmpy > y) {
2754                         --rit;
2755                         tmpy -= rit->height();
2756                 }
2757         }
2758         if (tmpy < 0 || rit == end) {
2759                 tmpy = 0;
2760                 rit = beg;
2761         }
2762
2763         // return the rel y
2764         y = tmpy;
2765
2766         return rit;
2767 }
2768
2769
2770 int LyXText::getDepth() const
2771 {
2772         return cursor.par()->getDepth();
2773 }