]> git.lyx.org Git - lyx.git/blob - src/text.C
use doubles again for x-coordinates. They are needed after all...
[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(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(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
821         // We re-use the font resolution for the entire font span when possible
822         LyXFont font = getFont(pit, i);
823         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
824
825         for (; i < last; ++i) {
826                 if (pit->isNewline(i)) {
827                         point = i;
828                         break;
829                 }
830
831                 char const c = pit->getChar(i);
832
833                 int thiswidth;
834
835                 // add the auto-hfill from label end to the body
836                 if (body_pos && i == body_pos) {
837                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
838                         if (pit->isLineSeparator(i - 1))
839                                 thiswidth -= singleWidth(pit, i - 1);
840                         int left_margin = labelEnd(row);
841                         if (thiswidth + x < left_margin)
842                                 thiswidth = left_margin - x;
843                         thiswidth += singleWidth(pit, i, c);
844                 } else {
845                         // Manual inlined optimised version of common case of "thiswidth = singleWidth(pit, i, c);"
846                         if (IsPrintable(c)) {
847                                 if (pos > endPosOfFontSpan) {
848                                         // We need to get the next font
849                                         font = getFont(pit, i);
850                                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
851                                 }
852                                 if (! font.language()->RightToLeft()) {
853                                         thiswidth = font_metrics::width(c, font);
854                                 } else {
855                                         // Fall-back to normal case
856                                         thiswidth = singleWidth(pit, i, c);
857                                         // And flush font cache
858                                         endPosOfFontSpan = 0;
859                                 }
860                         } else {
861                                 // Fall-back to normal case
862                                 thiswidth = singleWidth(pit, i, c);
863                                 // And flush font cache
864                                 endPosOfFontSpan = 0;
865                         }
866                 }
867
868                 x += thiswidth;
869                 chunkwidth += thiswidth;
870
871                 InsetOld * in = pit->isInset(i) ? pit->getInset(i) : 0;
872                 fullrow = (in && (in->display() || in->needFullRow()));
873
874                 // break before a character that will fall off
875                 // the right of the row
876                 if (x >= width) {
877                         // if no break before or we are at an inset
878                         // that will take up a row, break here
879                         if (point == last || fullrow || chunkwidth >= (width - left)) {
880                                 if (pos < i)
881                                         point = i - 1;
882                                 else
883                                         point = i;
884                         }
885                         break;
886                 }
887
888                 if (!in || in->isChar()) {
889                         // some insets are line separators too
890                         if (pit->isLineSeparator(i)) {
891                                 point = i;
892                                 chunkwidth = 0;
893                         }
894                         continue;
895                 }
896
897                 if (!fullrow)
898                         continue;
899
900                 // full row insets start at a new row
901                 if (i == pos) {
902                         if (pos < last - 1) {
903                                 point = i;
904                                 if (pit->isLineSeparator(i + 1))
905                                         ++point;
906                         } else {
907                                 // to avoid extra rows
908                                 point = last;
909                         }
910                 } else {
911                         point = i - 1;
912                 }
913
914                 return point;
915         }
916
917         if (point == last && x >= width) {
918                 // didn't find one, break at the point we reached the edge
919                 point = i;
920         } else if (i == last && x < width) {
921                 // found one, but we fell off the end of the par, so prefer
922                 // that.
923                 point = last;
924         }
925
926         // manual labels cannot be broken in LaTeX. But we
927         // want to make our on-screen rendering of footnotes
928         // etc. still break
929         if (!fullrow && body_pos && point < body_pos)
930                 point = body_pos - 1;
931
932         return point;
933 }
934
935
936 // returns the minimum space a row needs on the screen in pixel
937 int LyXText::fill(RowList::iterator row, int paper_width) const
938 {
939         if (paper_width < 0)
940                 return 0;
941
942         int w;
943         // get the pure distance
944         pos_type const last = lastPrintablePos(*this, row);
945
946         ParagraphList::iterator pit = row->par();
947         LyXLayout_ptr const & layout = pit->layout();
948
949         // special handling of the right address boxes
950         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
951                 int const tmpfill = row->fill();
952                 row->fill(0); // the minfill in MarginLeft()
953                 w = leftMargin(*row);
954                 row->fill(tmpfill);
955         } else
956                 w = leftMargin(*row);
957
958         pos_type const body_pos = pit->beginningOfBody();
959         pos_type i = row->pos();
960
961         if (! pit->empty() && i <= last) {
962                 // We re-use the font resolution for the entire span when possible
963                 LyXFont font = getFont(pit, i);
964                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
965                 while (i <= last) {
966                         if (body_pos > 0 && i == body_pos) {
967                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
968                                 if (pit->isLineSeparator(i - 1))
969                                         w -= singleWidth(pit, i - 1);
970                                 int left_margin = labelEnd(*row);
971                                 if (w < left_margin)
972                                         w = left_margin;
973                         }
974                         { // Manual inlined an optimised version of the common case of "w += singleWidth(pit, i);"
975                                 char const c = pit->getChar(i);
976
977                                 if (IsPrintable(c)) {
978                                         if (i > endPosOfFontSpan) {
979                                                 // We need to get the next font
980                                                 font = getFont(pit, i);
981                                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
982                                         }
983                                         if (! font.language()->RightToLeft()) {
984                                                 w += font_metrics::width(c, font);
985                                         } else {
986                                                 // Fall-back to the normal case
987                                                 w += singleWidth(pit, i, c);
988                                                 // And flush font cache
989                                                 endPosOfFontSpan = 0;
990                                         }
991                                 } else {
992                                         // Fall-back to the normal case
993                                         w += singleWidth(pit, i, c);
994                                         // And flush font cache
995                                         endPosOfFontSpan = 0;
996                                 }
997                         }
998                         ++i;
999                 }
1000         }
1001         if (body_pos > 0 && body_pos > last) {
1002                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
1003                 if (last >= 0 && pit->isLineSeparator(last))
1004                         w -= singleWidth(pit, last);
1005                 int const left_margin = labelEnd(*row);
1006                 if (w < left_margin)
1007                         w = left_margin;
1008         }
1009
1010         int const fill = paper_width - w - rightMargin(*bv()->buffer(), *row);
1011
1012         // If this case happens, it means that our calculation
1013         // of the widths of the chars when we do rowBreakPoint()
1014         // went wrong for some reason. Typically in list bodies.
1015         // Things just about hobble on anyway, though you'll end
1016         // up with a "fill_separator" less than zero, which corresponds
1017         // to inter-word spacing being too small. Hopefully this problem
1018         // will die when the label hacks die.
1019         if (lyxerr.debugging() && fill < 0) {
1020                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
1021                         << " w " << w << " paper_width " << paper_width
1022                         << " right margin " << rightMargin(*bv()->buffer(), *row) << endl;
1023         }
1024         return fill;
1025 }
1026
1027
1028 // returns the minimum space a manual label needs on the screen in pixel
1029 int LyXText::labelFill(Row const & row) const
1030 {
1031         ParagraphList::iterator pit = row.par();
1032
1033         pos_type last = pit->beginningOfBody();
1034
1035         Assert(last > 0);
1036
1037         // -1 because a label ends either with a space that is in the label,
1038         // or with the beginning of a footnote that is outside the label.
1039         --last;
1040
1041         // a separator at this end does not count
1042         if (pit->isLineSeparator(last))
1043                 --last;
1044
1045         int w = 0;
1046         pos_type i = row.pos();
1047         while (i <= last) {
1048                 w += singleWidth(pit, i);
1049                 ++i;
1050         }
1051
1052         int fill = 0;
1053         string const & labwidstr = pit->params().labelWidthString();
1054         if (!labwidstr.empty()) {
1055                 LyXFont const labfont = getLabelFont(pit);
1056                 int const labwidth = font_metrics::width(labwidstr, labfont);
1057                 fill = max(labwidth - w, 0);
1058         }
1059
1060         return fill;
1061 }
1062
1063
1064 LColor::color LyXText::backgroundColor() const
1065 {
1066         if (inset_owner)
1067                 return inset_owner->backgroundColor();
1068         else
1069                 return LColor::background;
1070 }
1071
1072
1073 void LyXText::setHeightOfRow(RowList::iterator rit)
1074 {
1075         Assert(rit != rows().end());
1076
1077         // get the maximum ascent and the maximum descent
1078         float layoutasc = 0;
1079         float layoutdesc = 0;
1080         float tmptop = 0;
1081
1082         // ok, let us initialize the maxasc and maxdesc value.
1083         // This depends in LaTeX of the font of the last character
1084         // in the paragraph. The hack below is necessary because
1085         // of the possibility of open footnotes
1086
1087         // Correction: only the fontsize count. The other properties
1088         //  are taken from the layoutfont. Nicer on the screen :)
1089         ParagraphList::iterator pit = rit->par();
1090
1091         LyXLayout_ptr const & layout = pit->layout();
1092
1093         // as max get the first character of this row then it can increase but not
1094         // decrease the height. Just some point to start with so we don't have to
1095         // do the assignment below too often.
1096         LyXFont font = getFont(pit, rit->pos());
1097         LyXFont::FONT_SIZE const tmpsize = font.size();
1098         font = getLayoutFont(pit);
1099         LyXFont::FONT_SIZE const size = font.size();
1100         font.setSize(tmpsize);
1101
1102         LyXFont labelfont = getLabelFont(pit);
1103
1104         float spacing_val = 1.0;
1105         if (!pit->params().spacing().isDefault()) {
1106                 spacing_val = pit->params().spacing().getValue();
1107         } else {
1108                 spacing_val = bv()->buffer()->params.spacing.getValue();
1109         }
1110         //lyxerr << "spacing_val = " << spacing_val << endl;
1111
1112         int maxasc = int(font_metrics::maxAscent(font) *
1113                          layout->spacing.getValue() *
1114                          spacing_val);
1115         int maxdesc = int(font_metrics::maxDescent(font) *
1116                           layout->spacing.getValue() *
1117                           spacing_val);
1118
1119         pos_type const pos_end = lastPos(*this, rit);
1120         int labeladdon = 0;
1121         int maxwidth = 0;
1122
1123         if (!pit->empty()) {
1124                 // We re-use the font resolution for the entire font span when possible
1125                 LyXFont font = getFont(pit, rit->pos());
1126                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(rit->pos());
1127
1128                 // Optimisation
1129                 Paragraph const & par = *pit;
1130
1131                 // Check if any insets are larger
1132                 for (pos_type pos = rit->pos(); pos <= pos_end; ++pos) {
1133                         // Manual inlined optimised version of common case of "maxwidth += singleWidth(pit, pos);"
1134                         char const c = par.getChar(pos);
1135
1136                         if (IsPrintable(c)) {
1137                                 if (pos > endPosOfFontSpan) {
1138                                         // We need to get the next font
1139                                         font = getFont(pit, pos);
1140                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
1141                                 }
1142                                 if (! font.language()->RightToLeft()) {
1143                                         maxwidth += font_metrics::width(c, font);
1144                                 } else {
1145                                         // Fall-back to normal case
1146                                         maxwidth += singleWidth(pit, pos, c);
1147                                         // And flush font cache
1148                                         endPosOfFontSpan = 0;
1149                                 }
1150                         } else {
1151                                 // Special handling of insets - are any larger?
1152                                 if (par.isInset(pos)) {
1153                                         LyXFont const tmpfont = getFont(pit, pos);
1154                                         InsetOld const * tmpinset = par.getInset(pos);
1155                                         if (tmpinset) {
1156 #if 1 // this is needed for deep update on initialitation
1157 #warning inset->update FIXME
1158                                                 //tmpinset->update(bv());
1159                                                 Dimension dim;
1160                                                 MetricsInfo mi(bv(), tmpfont, workWidth());
1161                                                 tmpinset->metrics(mi, dim);
1162                                                 maxwidth += dim.wid;
1163                                                 maxasc = max(maxasc, dim.asc);
1164                                                 maxdesc = max(maxdesc, dim.des);
1165 #else
1166                                                 maxwidth += tmpinset->width();
1167                                                 maxasc = max(maxasc, tmpinset->ascent());
1168                                                 maxdesc = max(maxdesc, tmpinset->descent());
1169 #endif
1170                                         } 
1171                                 } else {
1172                                         // Fall-back to normal case
1173                                         maxwidth += singleWidth(pit, pos, c);
1174                                         // And flush font cache
1175                                         endPosOfFontSpan = 0;
1176                                 }
1177                         }
1178                 }
1179         }
1180
1181         // Check if any custom fonts are larger (Asger)
1182         // This is not completely correct, but we can live with the small,
1183         // cosmetic error for now.
1184         LyXFont::FONT_SIZE maxsize =
1185                 pit->highestFontInRange(rit->pos(), pos_end, size);
1186         if (maxsize > font.size()) {
1187                 font.setSize(maxsize);
1188                 maxasc = max(maxasc, font_metrics::maxAscent(font));
1189                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
1190         }
1191
1192         // This is nicer with box insets:
1193         ++maxasc;
1194         ++maxdesc;
1195
1196         rit->ascent_of_text(maxasc);
1197
1198         // is it a top line?
1199         if (!rit->pos()) {
1200
1201                 // some parksips VERY EASY IMPLEMENTATION
1202                 if (bv()->buffer()->params.paragraph_separation ==
1203                         BufferParams::PARSEP_SKIP)
1204                 {
1205                         if (layout->isParagraph()
1206                                 && pit->getDepth() == 0
1207                                 && pit != ownerParagraphs().begin())
1208                         {
1209                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1210                         } else if (pit != ownerParagraphs().begin() &&
1211                                    boost::prior(pit)->layout()->isParagraph() &&
1212                                    boost::prior(pit)->getDepth() == 0)
1213                         {
1214                                 // is it right to use defskip here too? (AS)
1215                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1216                         }
1217                 }
1218
1219                 // the top margin
1220                 if (pit == ownerParagraphs().begin() && !isInInset())
1221                         maxasc += PAPER_MARGIN;
1222
1223                 // add the vertical spaces, that the user added
1224                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1225
1226                 // do not forget the DTP-lines!
1227                 // there height depends on the font of the nearest character
1228                 if (pit->params().lineTop())
1229
1230                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1231                 // and now the pagebreaks
1232                 if (pit->params().pagebreakTop())
1233                         maxasc += 3 * defaultRowHeight();
1234
1235                 if (pit->params().startOfAppendix())
1236                         maxasc += 3 * defaultRowHeight();
1237
1238                 // This is special code for the chapter, since the label of this
1239                 // layout is printed in an extra row
1240                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1241                         && bv()->buffer()->params.secnumdepth >= 0)
1242                 {
1243                         float spacing_val = 1.0;
1244                         if (!pit->params().spacing().isDefault()) {
1245                                 spacing_val = pit->params().spacing().getValue();
1246                         } else {
1247                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1248                         }
1249
1250                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1251                                          layout->spacing.getValue() *
1252                                          spacing_val)
1253                                 + int(font_metrics::maxAscent(labelfont) *
1254                                       layout->spacing.getValue() *
1255                                       spacing_val);
1256                 }
1257
1258                 // special code for the top label
1259                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1260                      || layout->labeltype == LABEL_BIBLIO
1261                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1262                     && isFirstInSequence(pit, ownerParagraphs())
1263                     && !pit->getLabelstring().empty())
1264                 {
1265                         float spacing_val = 1.0;
1266                         if (!pit->params().spacing().isDefault()) {
1267                                 spacing_val = pit->params().spacing().getValue();
1268                         } else {
1269                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1270                         }
1271
1272                         labeladdon = int(
1273                                 (font_metrics::maxAscent(labelfont) *
1274                                  layout->spacing.getValue() *
1275                                  spacing_val)
1276                                 +(font_metrics::maxDescent(labelfont) *
1277                                   layout->spacing.getValue() *
1278                                   spacing_val)
1279                                 + layout->topsep * defaultRowHeight()
1280                                 + layout->labelbottomsep * defaultRowHeight());
1281                 }
1282
1283                 // And now the layout spaces, for example before and after
1284                 // a section, or between the items of a itemize or enumerate
1285                 // environment.
1286
1287                 if (!pit->params().pagebreakTop()) {
1288                         ParagraphList::iterator prev =
1289                                 depthHook(pit, ownerParagraphs(),
1290                                           pit->getDepth());
1291                         if (prev != pit && prev->layout() == layout &&
1292                                 prev->getDepth() == pit->getDepth() &&
1293                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1294                         {
1295                                 layoutasc = (layout->itemsep * defaultRowHeight());
1296                         } else if (rit != rows().begin()) {
1297                                 tmptop = layout->topsep;
1298
1299                                 if (boost::prior(pit)->getDepth() >= pit->getDepth())
1300                                         tmptop -= boost::prior(rit)->par()->layout()->bottomsep;
1301
1302                                 if (tmptop > 0)
1303                                         layoutasc = (tmptop * defaultRowHeight());
1304                         } else if (pit->params().lineTop()) {
1305                                 tmptop = layout->topsep;
1306
1307                                 if (tmptop > 0)
1308                                         layoutasc = (tmptop * defaultRowHeight());
1309                         }
1310
1311                         prev = outerHook(pit, ownerParagraphs());
1312                         if (prev != ownerParagraphs().end())  {
1313                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1314                         } else if (pit != ownerParagraphs().begin()) {
1315                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1316                                 if (prior_pit->getDepth() != 0 ||
1317                                     prior_pit->layout() == layout) {
1318                                         maxasc += int(layout->parsep * defaultRowHeight());
1319                                 }
1320                         }
1321                 }
1322         }
1323
1324         // is it a bottom line?
1325         RowList::iterator next_rit = boost::next(rit);
1326         if (next_rit == rows().end() || next_rit->par() != pit) {
1327                 // the bottom margin
1328                 ParagraphList::iterator nextpit = boost::next(pit);
1329                 if (nextpit == ownerParagraphs().end() &&
1330                     !isInInset())
1331                         maxdesc += PAPER_MARGIN;
1332
1333                 // add the vertical spaces, that the user added
1334                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1335
1336                 // do not forget the DTP-lines!
1337                 // there height depends on the font of the nearest character
1338                 if (pit->params().lineBottom())
1339                         maxdesc += 2 * font_metrics::ascent('x',
1340                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1341
1342                 // and now the pagebreaks
1343                 if (pit->params().pagebreakBottom())
1344                         maxdesc += 3 * defaultRowHeight();
1345
1346                 // and now the layout spaces, for example before and after
1347                 // a section, or between the items of a itemize or enumerate
1348                 // environment
1349                 if (!pit->params().pagebreakBottom()
1350                     && nextpit != ownerParagraphs().end()) {
1351                         ParagraphList::iterator comparepit = pit;
1352                         float usual = 0;
1353                         float unusual = 0;
1354
1355                         if (comparepit->getDepth() > nextpit->getDepth()) {
1356                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1357                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1358                                 if (comparepit->layout()!= nextpit->layout()
1359                                         || nextpit->getLabelWidthString() !=
1360                                         comparepit->getLabelWidthString())
1361                                 {
1362                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1363                                 }
1364                                 if (unusual > usual)
1365                                         layoutdesc = unusual;
1366                                 else
1367                                         layoutdesc = usual;
1368                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1369
1370                                 if (comparepit->layout() != nextpit->layout()
1371                                         || nextpit->getLabelWidthString() !=
1372                                         comparepit->getLabelWidthString())
1373                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1374                         }
1375                 }
1376         }
1377
1378         // incalculate the layout spaces
1379         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1380         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1381
1382         // calculate the new height of the text
1383         height -= rit->height();
1384
1385         rit->height(maxasc + maxdesc + labeladdon);
1386         rit->baseline(maxasc + labeladdon);
1387
1388         height += rit->height();
1389
1390         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1391
1392         double x = 0;
1393         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1394                 double dummy;
1395                 // this IS needed
1396                 rit->width(maxwidth);
1397                 prepareToPrint(rit, x, dummy, dummy, dummy, false);
1398         }
1399         rit->width(int(maxwidth + x));
1400         if (inset_owner) {
1401                 width = max(0, workWidth());
1402                 RowList::iterator it = rows().begin();
1403                 RowList::iterator end = rows().end();
1404                 for (; it != end; ++it) {
1405                         if (it->width() > width)
1406                                 width = it->width();
1407                 }
1408         }
1409 }
1410
1411
1412 // Appends the implicit specified paragraph before the specified row,
1413 // start at the implicit given position
1414 void LyXText::appendParagraph(RowList::iterator rowit)
1415 {
1416         Assert(rowit != rowlist_.end());
1417
1418         pos_type const last = rowit->par()->size();
1419         bool done = false;
1420
1421         do {
1422                 pos_type z = rowBreakPoint(*rowit);
1423
1424                 RowList::iterator tmprow = rowit;
1425
1426                 if (z < last) {
1427                         ++z;
1428                         Row newrow(rowit->par(), z);
1429                         rowit = rowlist_.insert(boost::next(rowit), newrow);
1430                 } else {
1431                         done = true;
1432                 }
1433
1434                 // Set the dimensions of the row
1435                 // fixed fill setting now by calling inset->update() in
1436                 // SingleWidth when needed!
1437                 tmprow->fill(fill(tmprow, workWidth()));
1438                 setHeightOfRow(tmprow);
1439
1440         } while (!done);
1441 }
1442
1443
1444 void LyXText::breakAgain(RowList::iterator rit)
1445 {
1446         Assert(rit != rows().end());
1447
1448         bool not_ready = true;
1449
1450         do  {
1451                 pos_type z = rowBreakPoint(*rit);
1452                 RowList::iterator tmprit = rit;
1453                 RowList::iterator end = rows().end();
1454
1455                 if (z < rit->par()->size()) {
1456                         RowList::iterator next_rit = boost::next(rit);
1457
1458                         if (next_rit == end ||
1459                             (next_rit != end &&
1460                              next_rit->par() != rit->par())) {
1461                                 // insert a new row
1462                                 ++z;
1463                                 Row newrow(rit->par(), z);
1464                                 rit = rowlist_.insert(next_rit, newrow);
1465                         } else  {
1466                                 ++rit;
1467                                 ++z;
1468                                 if (rit->pos() == z)
1469                                         not_ready = false; // the rest will not change
1470                                 else {
1471                                         rit->pos(z);
1472                                 }
1473                         }
1474                 } else {
1475                         // if there are some rows too much, delete them
1476                         // only if you broke the whole paragraph!
1477                         RowList::iterator tmprit2 = rit;
1478                         while (boost::next(tmprit2) != end
1479                                && boost::next(tmprit2)->par() == rit->par()) {
1480                                 ++tmprit2;
1481                         }
1482                         while (tmprit2 != rit) {
1483                                 --tmprit2;
1484                                 removeRow(boost::next(tmprit2));
1485                         }
1486                         not_ready = false;
1487                 }
1488
1489                 // set the dimensions of the row
1490                 tmprit->fill(fill(tmprit, workWidth()));
1491                 setHeightOfRow(tmprit);
1492         } while (not_ready);
1493 }
1494
1495
1496 // this is just a little changed version of break again
1497 void LyXText::breakAgainOneRow(RowList::iterator rit)
1498 {
1499         Assert(rit != rows().end());
1500
1501         pos_type z = rowBreakPoint(*rit);
1502         RowList::iterator tmprit = rit;
1503         RowList::iterator end = rows().end();
1504
1505         if (z < rit->par()->size()) {
1506                 RowList::iterator next_rit = boost::next(rit);
1507
1508                 if (next_rit == end ||
1509                     (next_rit != end &&
1510                      next_rit->par() != rit->par())) {
1511                         // insert a new row
1512                         ++z;
1513                         Row newrow(rit->par(), z);
1514                         rit = rowlist_.insert(next_rit, newrow);
1515                 } else  {
1516                         ++rit;
1517                         ++z;
1518                         if (rit->pos() != z)
1519                                 rit->pos(z);
1520                 }
1521         } else {
1522                 // if there are some rows too much, delete them
1523                 // only if you broke the whole paragraph!
1524                 RowList::iterator tmprit2 = rit;
1525                 while (boost::next(tmprit2) != end
1526                        && boost::next(tmprit2)->par() == rit->par()) {
1527                         ++tmprit2;
1528                 }
1529                 while (tmprit2 != rit) {
1530                         --tmprit2;
1531                         removeRow(boost::next(tmprit2));
1532                 }
1533         }
1534
1535         // set the dimensions of the row
1536         tmprit->fill(fill(tmprit, workWidth()));
1537         setHeightOfRow(tmprit);
1538 }
1539
1540
1541 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1542 {
1543         // allow only if at start or end, or all previous is new text
1544         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1545                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1546                 return;
1547
1548         LyXTextClass const & tclass =
1549                 bv()->buffer()->params.getLyXTextClass();
1550         LyXLayout_ptr const & layout = cursor.par()->layout();
1551
1552         // this is only allowed, if the current paragraph is not empty or caption
1553         // and if it has not the keepempty flag active
1554         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1555            && layout->labeltype != LABEL_SENSITIVE)
1556                 return;
1557
1558         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1559
1560         // Always break behind a space
1561         //
1562         // It is better to erase the space (Dekel)
1563         if (cursor.pos() < cursor.par()->size()
1564              && cursor.par()->isLineSeparator(cursor.pos()))
1565            cursor.par()->erase(cursor.pos());
1566         // cursor.pos(cursor.pos() + 1);
1567
1568         // break the paragraph
1569         if (keep_layout)
1570                 keep_layout = 2;
1571         else
1572                 keep_layout = layout->isEnvironment();
1573
1574         // we need to set this before we insert the paragraph. IMO the
1575         // breakParagraph call should return a bool if it inserts the
1576         // paragraph before or behind and we should react on that one
1577         // but we can fix this in 1.3.0 (Jug 20020509)
1578         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1579         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(),
1580                          cursor.pos(), keep_layout);
1581
1582         // well this is the caption hack since one caption is really enough
1583         if (layout->labeltype == LABEL_SENSITIVE) {
1584                 if (!cursor.pos())
1585                         // set to standard-layout
1586                         cursor.par()->applyLayout(tclass.defaultLayout());
1587                 else
1588                         // set to standard-layout
1589                         boost::next(cursor.par())->applyLayout(tclass.defaultLayout());
1590         }
1591
1592         // if the cursor is at the beginning of a row without prior newline,
1593         // move one row up!
1594         // This touches only the screen-update. Otherwise we would may have
1595         // an empty row on the screen
1596         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1597             && !cursorRow()->par()->isNewline(cursor.pos() - 1))
1598         {
1599                 cursorLeft(bv());
1600         }
1601
1602         postPaint();
1603
1604         removeParagraph(cursorRow());
1605
1606         // set the dimensions of the cursor row
1607         cursorRow()->fill(fill(cursorRow(), workWidth()));
1608
1609         setHeightOfRow(cursorRow());
1610
1611 #warning Trouble Point! (Lgb)
1612         // When ::breakParagraph is called from within an inset we must
1613         // ensure that the correct ParagraphList is used. Today that is not
1614         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1615         ParagraphList::iterator next_par = boost::next(cursor.par());
1616
1617         while (!next_par->empty() && next_par->isNewline(0))
1618                 next_par->erase(0);
1619
1620         insertParagraph(next_par, boost::next(cursorRow()));
1621         updateCounters();
1622
1623         // This check is necessary. Otherwise the new empty paragraph will
1624         // be deleted automatically. And it is more friendly for the user!
1625         if (cursor.pos() || isempty)
1626                 setCursor(next_par, 0);
1627         else
1628                 setCursor(cursor.par(), 0);
1629
1630         if (boost::next(cursorRow()) != rows().end())
1631                 breakAgain(boost::next(cursorRow()));
1632 }
1633
1634
1635 // Just a macro to make some thing easier.
1636 void LyXText::redoParagraph()
1637 {
1638         clearSelection();
1639         redoParagraphs(cursor, boost::next(cursor.par()));
1640         setCursorIntern(cursor.par(), cursor.pos());
1641 }
1642
1643
1644 // insert a character, moves all the following breaks in the
1645 // same Paragraph one to the right and make a rebreak
1646 void LyXText::insertChar(char c)
1647 {
1648         recordUndo(bv(), Undo::INSERT, cursor.par());
1649
1650         // When the free-spacing option is set for the current layout,
1651         // disable the double-space checking
1652
1653         bool const freeSpacing = cursorRow()->par()->layout()->free_spacing ||
1654                 cursorRow()->par()->isFreeSpacing();
1655
1656         if (lyxrc.auto_number) {
1657                 static string const number_operators = "+-/*";
1658                 static string const number_unary_operators = "+-";
1659                 static string const number_seperators = ".,:";
1660
1661                 if (current_font.number() == LyXFont::ON) {
1662                         if (!IsDigit(c) && !contains(number_operators, c) &&
1663                             !(contains(number_seperators, c) &&
1664                               cursor.pos() >= 1 &&
1665                               cursor.pos() < cursor.par()->size() &&
1666                               getFont(cursor.par(), cursor.pos()).number() == LyXFont::ON &&
1667                               getFont(cursor.par(), cursor.pos() - 1).number() == LyXFont::ON)
1668                            )
1669                                 number(bv()); // Set current_font.number to OFF
1670                 } else if (IsDigit(c) &&
1671                            real_current_font.isVisibleRightToLeft()) {
1672                         number(bv()); // Set current_font.number to ON
1673
1674                         if (cursor.pos() > 0) {
1675                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1676                                 if (contains(number_unary_operators, c) &&
1677                                     (cursor.pos() == 1 ||
1678                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1679                                      cursor.par()->isNewline(cursor.pos() - 2))
1680                                   ) {
1681                                         setCharFont(
1682                                                     cursor.par(),
1683                                                     cursor.pos() - 1,
1684                                                     current_font);
1685                                 } else if (contains(number_seperators, c) &&
1686                                            cursor.pos() >= 2 &&
1687                                            getFont(
1688                                                    cursor.par(),
1689                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1690                                         setCharFont(
1691                                                     cursor.par(),
1692                                                     cursor.pos() - 1,
1693                                                     current_font);
1694                                 }
1695                         }
1696                 }
1697         }
1698
1699
1700         // First check, if there will be two blanks together or a blank at
1701         // the beginning of a paragraph.
1702         // I decided to handle blanks like normal characters, the main
1703         // difference are the special checks when calculating the row.fill
1704         // (blank does not count at the end of a row) and the check here
1705
1706         // The bug is triggered when we type in a description environment:
1707         // The current_font is not changed when we go from label to main text
1708         // and it should (along with realtmpfont) when we type the space.
1709         // CHECK There is a bug here! (Asger)
1710
1711         LyXFont realtmpfont = real_current_font;
1712         LyXFont rawtmpfont = current_font;
1713         // store the current font.  This is because of the use of cursor
1714         // movements. The moving cursor would refresh the current font
1715
1716         // Get the font that is used to calculate the baselineskip
1717         pos_type const lastpos = cursor.par()->size();
1718         LyXFont rawparfont =
1719                 cursor.par()->getFontSettings(bv()->buffer()->params,
1720                                               lastpos - 1);
1721
1722         bool jumped_over_space = false;
1723
1724         if (!freeSpacing && IsLineSeparatorChar(c)) {
1725                 if ((cursor.pos() > 0
1726                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1727                     || (cursor.pos() > 0
1728                         && cursor.par()->isNewline(cursor.pos() - 1))
1729                     || (cursor.pos() == 0)) {
1730                         static bool sent_space_message = false;
1731                         if (!sent_space_message) {
1732                                 if (cursor.pos() == 0)
1733                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1734                                 else
1735                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1736                                 sent_space_message = true;
1737                         }
1738                         charInserted();
1739                         return;
1740                 }
1741         }
1742
1743         // the display inset stuff
1744         if (cursorRow()->pos() < cursorRow()->par()->size()
1745             && cursorRow()->par()->isInset(cursorRow()->pos())) {
1746                 InsetOld * inset = cursorRow()->par()->getInset(cursorRow()->pos());
1747                 if (inset && (inset->display() || inset->needFullRow())) {
1748                         // force a new break
1749                         cursorRow()->fill(-1); // to force a new break
1750                 }
1751         }
1752
1753         // get the cursor row fist
1754         RowList::iterator row = cursorRow();
1755         if (c != Paragraph::META_INSET) {
1756                 // Here case LyXText::InsertInset  already inserted the character
1757                 cursor.par()->insertChar(cursor.pos(), c);
1758         }
1759         setCharFont(cursor.par(), cursor.pos(), rawtmpfont);
1760
1761         if (!jumped_over_space) {
1762                 // refresh the positions
1763                 RowList::iterator tmprow = row;
1764                 while (boost::next(tmprow) != rows().end() &&
1765                        boost::next(tmprow)->par() == row->par()) {
1766                         ++tmprow;
1767                         tmprow->pos(tmprow->pos() + 1);
1768                 }
1769         }
1770
1771         // Is there a break one row above
1772         if (row != rows().begin() &&
1773             boost::prior(row)->par() == row->par()
1774             && (cursor.par()->isLineSeparator(cursor.pos())
1775                 || cursor.par()->isNewline(cursor.pos())
1776                 || ((cursor.pos() + 1 < cursor.par()->size()) &&
1777                     cursor.par()->isInset(cursor.pos() + 1))
1778                 || cursorRow()->fill() == -1))
1779         {
1780                 pos_type z = rowBreakPoint(*boost::prior(row));
1781
1782                 if (z >= row->pos()) {
1783                         row->pos(z + 1);
1784
1785                         // set the dimensions of the row above
1786                         boost::prior(row)->fill(fill(
1787                                                    boost::prior(row),
1788                                                    workWidth()));
1789
1790                         setHeightOfRow(boost::prior(row));
1791
1792                         postPaint();
1793
1794                         breakAgainOneRow(row);
1795
1796                         current_font = rawtmpfont;
1797                         real_current_font = realtmpfont;
1798                         setCursor(cursor.par(), cursor.pos() + 1,
1799                                   false, cursor.boundary());
1800
1801                         // cursor MUST be in row now.
1802                         // check, wether the last characters font has changed.
1803                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1804                             && rawparfont != rawtmpfont)
1805                                 redoHeightOfParagraph();
1806
1807                         charInserted();
1808                         return;
1809                 }
1810         }
1811
1812         // recalculate the fill of the row
1813         if (row->fill() >= 0) {
1814                 // needed because a newline will set fill to -1. Otherwise
1815                 // we would not get a rebreak!
1816                 row->fill(fill(row, workWidth()));
1817         }
1818
1819         if (c == Paragraph::META_INSET || row->fill() < 0) {
1820                 postPaint();
1821                 breakAgainOneRow(row);
1822
1823                 RowList::iterator next_row = boost::next(row);
1824
1825                 // will the cursor be in another row now?
1826                 if (lastPos(*this, row) <= cursor.pos() + 1 &&
1827                     next_row != rows().end()) {
1828                         if (next_row != rows().end() &&
1829                             next_row->par() == row->par()) {
1830                                 // this should always be true
1831                                 ++row;
1832                         }
1833
1834                         breakAgainOneRow(row);
1835                 }
1836                 current_font = rawtmpfont;
1837                 real_current_font = realtmpfont;
1838
1839                 setCursor(cursor.par(), cursor.pos() + 1, false,
1840                           cursor.boundary());
1841                 if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
1842                     != cursor.boundary())
1843                         setCursor(cursor.par(), cursor.pos(), false,
1844                           !cursor.boundary());
1845         } else {
1846                 // FIXME: similar code is duplicated all over - make resetHeightOfRow
1847                 setHeightOfRow(row);
1848                 postPaint();
1849
1850                 current_font = rawtmpfont;
1851                 real_current_font = realtmpfont;
1852                 setCursor(cursor.par(), cursor.pos() + 1, false,
1853                           cursor.boundary());
1854         }
1855
1856         // check, wether the last characters font has changed.
1857         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1858             && rawparfont != rawtmpfont) {
1859                 redoHeightOfParagraph();
1860         }
1861
1862         charInserted();
1863 }
1864
1865
1866 void LyXText::charInserted()
1867 {
1868         // Here we could call FinishUndo for every 20 characters inserted.
1869         // This is from my experience how emacs does it. (Lgb)
1870         static unsigned int counter;
1871         if (counter < 20) {
1872                 ++counter;
1873         } else {
1874                 finishUndo();
1875                 counter = 0;
1876         }
1877 }
1878
1879
1880 void LyXText::prepareToPrint(RowList::iterator rit, double & x,
1881                              double & fill_separator,
1882                              double & fill_hfill,
1883                              double & fill_label_hfill,
1884                              bool bidi) const
1885 {
1886         double w = rit->fill();
1887         fill_hfill = 0;
1888         fill_label_hfill = 0;
1889         fill_separator = 0;
1890         fill_label_hfill = 0;
1891
1892         ParagraphList::iterator pit = rit->par();
1893
1894         bool const is_rtl =
1895                 pit->isRightToLeftPar(bv()->buffer()->params);
1896         if (is_rtl)
1897                 x = workWidth() > 0 ? rightMargin(*bv()->buffer(), *rit) : 0;
1898         else
1899                 x = workWidth() > 0 ? leftMargin(*rit) : 0;
1900
1901         // is there a manual margin with a manual label
1902         LyXLayout_ptr const & layout = pit->layout();
1903
1904         if (layout->margintype == MARGIN_MANUAL
1905             && layout->labeltype == LABEL_MANUAL) {
1906                 /// We might have real hfills in the label part
1907                 int nlh = numberOfLabelHfills(*this, rit);
1908
1909                 // A manual label par (e.g. List) has an auto-hfill
1910                 // between the label text and the body of the
1911                 // paragraph too.
1912                 // But we don't want to do this auto hfill if the par
1913                 // is empty.
1914                 if (!pit->empty())
1915                         ++nlh;
1916
1917                 if (nlh && !pit->getLabelWidthString().empty()) {
1918                         fill_label_hfill = labelFill(*rit) / double(nlh);
1919                 }
1920         }
1921
1922         // are there any hfills in the row?
1923         int const nh = numberOfHfills(*this, rit);
1924
1925         if (nh) {
1926                 if (w > 0)
1927                         fill_hfill = w / nh;
1928         // we don't have to look at the alignment if it is ALIGN_LEFT and
1929         // if the row is already larger then the permitted width as then
1930         // we force the LEFT_ALIGN'edness!
1931         } else if (int(rit->width()) < workWidth()) {
1932                 // is it block, flushleft or flushright?
1933                 // set x how you need it
1934                 int align;
1935                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1936                         align = layout->align;
1937                 } else {
1938                         align = pit->params().align();
1939                 }
1940
1941                 // center displayed insets
1942                 InsetOld * inset = 0;
1943                 if (rit->pos() < pit->size()
1944                     && pit->isInset(rit->pos())
1945                     && (inset = pit->getInset(rit->pos()))
1946                     && (inset->display())) // || (inset->scroll() < 0)))
1947                     align = (inset->lyxCode() == InsetOld::MATHMACRO_CODE)
1948                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1949                 // ERT insets should always be LEFT ALIGNED on screen
1950                 inset = pit->inInset();
1951                 if (inset && inset->owner() &&
1952                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1953                 {
1954                         align = LYX_ALIGN_LEFT;
1955                 }
1956
1957                 switch (align) {
1958             case LYX_ALIGN_BLOCK:
1959             {
1960                         int const ns = numberOfSeparators(*this, rit);
1961                         RowList::iterator next_row = boost::next(rit);
1962                         ParagraphList::iterator next_pit = next_row->par();
1963
1964                         if (ns && next_row != rowlist_.end() &&
1965                             next_pit == pit &&
1966                             !(next_pit->isNewline(next_row->pos() - 1))
1967                             && !(next_pit->isInset(next_row->pos()) &&
1968                                  next_pit->getInset(next_row->pos()) &&
1969                                  next_pit->getInset(next_row->pos())->display())
1970                                 ) {
1971                                 fill_separator = w / ns;
1972                         } else if (is_rtl) {
1973                                 x += w;
1974                         }
1975                         break;
1976             }
1977             case LYX_ALIGN_RIGHT:
1978                         x += w;
1979                         break;
1980             case LYX_ALIGN_CENTER:
1981                         x += w / 2;
1982                         break;
1983                 }
1984         }
1985         if (!bidi)
1986                 return;
1987
1988         computeBidiTables(bv()->buffer(), rit);
1989         if (is_rtl) {
1990                 pos_type body_pos = pit->beginningOfBody();
1991                 pos_type last = lastPos(*this, rit);
1992
1993                 if (body_pos > 0 &&
1994                     (body_pos - 1 > last ||
1995                      !pit->isLineSeparator(body_pos - 1))) {
1996                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1997                         if (body_pos - 1 <= last)
1998                                 x += fill_label_hfill;
1999                 }
2000         }
2001 }
2002
2003
2004 // important for the screen
2005
2006
2007 // the cursor set functions have a special mechanism. When they
2008 // realize, that you left an empty paragraph, they will delete it.
2009 // They also delete the corresponding row
2010
2011 void LyXText::cursorRightOneWord()
2012 {
2013         ::cursorRightOneWord(cursor, ownerParagraphs());
2014         setCursor(cursor.par(), cursor.pos());
2015 }
2016
2017
2018 // Skip initial whitespace at end of word and move cursor to *start*
2019 // of prior word, not to end of next prior word.
2020 void LyXText::cursorLeftOneWord()
2021 {
2022         LyXCursor tmpcursor = cursor;
2023         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
2024         setCursor(tmpcursor.par(), tmpcursor.pos());
2025 }
2026
2027
2028 void LyXText::selectWord(word_location loc)
2029 {
2030         LyXCursor from = cursor;
2031         LyXCursor to;
2032         ::getWord(from, to, loc, ownerParagraphs());
2033         if (cursor != from)
2034                 setCursor(from.par(), from.pos());
2035         if (to == from)
2036                 return;
2037         selection.cursor = cursor;
2038         setCursor(to.par(), to.pos());
2039         setSelection();
2040 }
2041
2042
2043 // Select the word currently under the cursor when no
2044 // selection is currently set
2045 bool LyXText::selectWordWhenUnderCursor(word_location loc)
2046 {
2047         if (!selection.set()) {
2048                 selectWord(loc);
2049                 return selection.set();
2050         }
2051         return false;
2052 }
2053
2054
2055 void LyXText::acceptChange()
2056 {
2057         if (!selection.set() && cursor.par()->size())
2058                 return;
2059
2060         if (selection.start.par() == selection.end.par()) {
2061                 LyXCursor & startc = selection.start;
2062                 LyXCursor & endc = selection.end;
2063                 recordUndo(bv(), Undo::INSERT, startc.par());
2064                 startc.par()->acceptChange(startc.pos(), endc.pos());
2065                 finishUndo();
2066                 clearSelection();
2067                 redoParagraphs(startc, boost::next(startc.par()));
2068                 setCursorIntern(startc.par(), 0);
2069         }
2070 #warning handle multi par selection
2071 }
2072
2073
2074 void LyXText::rejectChange()
2075 {
2076         if (!selection.set() && cursor.par()->size())
2077                 return;
2078
2079         if (selection.start.par() == selection.end.par()) {
2080                 LyXCursor & startc = selection.start;
2081                 LyXCursor & endc = selection.end;
2082                 recordUndo(bv(), Undo::INSERT, startc.par());
2083                 startc.par()->rejectChange(startc.pos(), endc.pos());
2084                 finishUndo();
2085                 clearSelection();
2086                 redoParagraphs(startc, boost::next(startc.par()));
2087                 setCursorIntern(startc.par(), 0);
2088         }
2089 #warning handle multi par selection
2090 }
2091
2092
2093 // This function is only used by the spellchecker for NextWord().
2094 // It doesn't handle LYX_ACCENTs and probably never will.
2095 WordLangTuple const
2096 LyXText::selectNextWordToSpellcheck(float & value)
2097 {
2098         if (the_locking_inset) {
2099                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
2100                 if (!word.word().empty()) {
2101                         value += float(cursor.y());
2102                         value /= float(height);
2103                         return word;
2104                 }
2105                 // we have to go on checking so move cursor to the next char
2106                 if (cursor.pos() == cursor.par()->size()) {
2107                         if (boost::next(cursor.par()) == ownerParagraphs().end())
2108                                 return word;
2109                         cursor.par(boost::next(cursor.par()));
2110                         cursor.pos(0);
2111                 } else
2112                         cursor.pos(cursor.pos() + 1);
2113         }
2114         ParagraphList::iterator tmppit = cursor.par();
2115
2116         // If this is not the very first word, skip rest of
2117         // current word because we are probably in the middle
2118         // of a word if there is text here.
2119         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
2120                 while (cursor.pos() < cursor.par()->size()
2121                        && cursor.par()->isLetter(cursor.pos()))
2122                         cursor.pos(cursor.pos() + 1);
2123         }
2124
2125         // Now, skip until we have real text (will jump paragraphs)
2126         while (true) {
2127                 ParagraphList::iterator cpit = cursor.par();
2128                 pos_type const cpos(cursor.pos());
2129
2130                 if (cpos == cpit->size()) {
2131                         if (boost::next(cpit) != ownerParagraphs().end()) {
2132                                 cursor.par(boost::next(cpit));
2133                                 cursor.pos(0);
2134                                 continue;
2135                         }
2136                         break;
2137                 }
2138
2139                 bool const is_good_inset = cpit->isInset(cpos)
2140                         && cpit->getInset(cpos)->allowSpellcheck();
2141
2142                 if (!isDeletedText(*cpit, cpos)
2143                     && (is_good_inset || cpit->isLetter(cpos)))
2144                         break;
2145
2146                 cursor.pos(cpos + 1);
2147         }
2148
2149         // now check if we hit an inset so it has to be a inset containing text!
2150         if (cursor.pos() < cursor.par()->size() &&
2151             cursor.par()->isInset(cursor.pos())) {
2152                 // lock the inset!
2153                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
2154                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
2155                 // now call us again to do the above trick
2156                 // but obviously we have to start from down below ;)
2157                 return bv()->text->selectNextWordToSpellcheck(value);
2158         }
2159
2160         // Update the value if we changed paragraphs
2161         if (cursor.par() != tmppit) {
2162                 setCursor(cursor.par(), cursor.pos());
2163                 value = float(cursor.y())/float(height);
2164         }
2165
2166         // Start the selection from here
2167         selection.cursor = cursor;
2168
2169         string lang_code = getFont(cursor.par(), cursor.pos()).language()->code();
2170         // and find the end of the word (insets like optional hyphens
2171         // and ligature break are part of a word)
2172         while (cursor.pos() < cursor.par()->size()
2173                && cursor.par()->isLetter(cursor.pos())
2174                && !isDeletedText(*cursor.par(), cursor.pos()))
2175                 cursor.pos(cursor.pos() + 1);
2176
2177         // Finally, we copy the word to a string and return it
2178         string str;
2179         if (selection.cursor.pos() < cursor.pos()) {
2180                 pos_type i;
2181                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2182                         if (!cursor.par()->isInset(i))
2183                                 str += cursor.par()->getChar(i);
2184                 }
2185         }
2186         return WordLangTuple(str, lang_code);
2187 }
2188
2189
2190 // This one is also only for the spellchecker
2191 void LyXText::selectSelectedWord()
2192 {
2193         if (the_locking_inset) {
2194                 the_locking_inset->selectSelectedWord(bv());
2195                 return;
2196         }
2197         // move cursor to the beginning
2198         setCursor(selection.cursor.par(), selection.cursor.pos());
2199
2200         // set the sel cursor
2201         selection.cursor = cursor;
2202
2203         // now find the end of the word
2204         while (cursor.pos() < cursor.par()->size()
2205                && (cursor.par()->isLetter(cursor.pos())))
2206                 cursor.pos(cursor.pos() + 1);
2207
2208         setCursor(cursor.par(), cursor.pos());
2209
2210         // finally set the selection
2211         setSelection();
2212 }
2213
2214
2215 // Delete from cursor up to the end of the current or next word.
2216 void LyXText::deleteWordForward()
2217 {
2218         if (cursor.par()->empty())
2219                 cursorRight(bv());
2220         else {
2221                 LyXCursor tmpcursor = cursor;
2222                 selection.set(true); // to avoid deletion
2223                 cursorRightOneWord();
2224                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2225                 selection.cursor = cursor;
2226                 cursor = tmpcursor;
2227                 setSelection();
2228
2229                 // Great, CutSelection() gets rid of multiple spaces.
2230                 cutSelection(true, false);
2231         }
2232 }
2233
2234
2235 // Delete from cursor to start of current or prior word.
2236 void LyXText::deleteWordBackward()
2237 {
2238         if (cursor.par()->empty())
2239                 cursorLeft(bv());
2240         else {
2241                 LyXCursor tmpcursor = cursor;
2242                 selection.set(true); // to avoid deletion
2243                 cursorLeftOneWord();
2244                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2245                 selection.cursor = cursor;
2246                 cursor = tmpcursor;
2247                 setSelection();
2248                 cutSelection(true, false);
2249         }
2250 }
2251
2252
2253 // Kill to end of line.
2254 void LyXText::deleteLineForward()
2255 {
2256         if (cursor.par()->empty())
2257                 // Paragraph is empty, so we just go to the right
2258                 cursorRight(bv());
2259         else {
2260                 LyXCursor tmpcursor = cursor;
2261                 // We can't store the row over a regular setCursor
2262                 // so we set it to 0 and reset it afterwards.
2263                 selection.set(true); // to avoid deletion
2264                 cursorEnd();
2265                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
2266                 selection.cursor = cursor;
2267                 cursor = tmpcursor;
2268                 setSelection();
2269                 // What is this test for ??? (JMarc)
2270                 if (!selection.set()) {
2271                         deleteWordForward();
2272                 } else {
2273                         cutSelection(true, false);
2274                 }
2275         }
2276 }
2277
2278
2279 void LyXText::changeCase(LyXText::TextCase action)
2280 {
2281         LyXCursor from;
2282         LyXCursor to;
2283
2284         if (selection.set()) {
2285                 from = selection.start;
2286                 to = selection.end;
2287         } else {
2288                 from = cursor;
2289                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
2290                 setCursor(to.par(), to.pos() + 1);
2291         }
2292
2293         recordUndo(bv(), Undo::ATOMIC, from.par(), to.par());
2294
2295         pos_type pos = from.pos();
2296         ParagraphList::iterator pit = from.par();
2297
2298         while (pit != ownerParagraphs().end() &&
2299                (pos != to.pos() || pit != to.par())) {
2300                 if (pos == pit->size()) {
2301                         ++pit;
2302                         pos = 0;
2303                         continue;
2304                 }
2305                 unsigned char c = pit->getChar(pos);
2306                 if (!IsInsetChar(c)) {
2307                         switch (action) {
2308                         case text_lowercase:
2309                                 c = lowercase(c);
2310                                 break;
2311                         case text_capitalization:
2312                                 c = uppercase(c);
2313                                 action = text_lowercase;
2314                                 break;
2315                         case text_uppercase:
2316                                 c = uppercase(c);
2317                                 break;
2318                         }
2319                 }
2320 #warning changes
2321                 pit->setChar(pos, c);
2322                 checkParagraph(pit, pos);
2323
2324                 ++pos;
2325         }
2326
2327         if (getRow(to) != getRow(from))
2328                 postPaint();
2329 }
2330
2331
2332 void LyXText::Delete()
2333 {
2334         // this is a very easy implementation
2335
2336         LyXCursor old_cursor = cursor;
2337         int const old_cur_par_id = old_cursor.par()->id();
2338         int const old_cur_par_prev_id =
2339                 (old_cursor.par() != ownerParagraphs().begin() ?
2340                  boost::prior(old_cursor.par())->id() : -1);
2341
2342         // just move to the right
2343         cursorRight(bv());
2344
2345         // CHECK Look at the comment here.
2346         // This check is not very good...
2347         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2348         // and that can very well delete the par or par->previous in
2349         // old_cursor. Will a solution where we compare paragraph id's
2350         //work better?
2351         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2352             == old_cur_par_prev_id
2353             && cursor.par()->id() != old_cur_par_id) {
2354                 // delete-empty-paragraph-mechanism has done it
2355                 return;
2356         }
2357
2358         // if you had success make a backspace
2359         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2360                 LyXCursor tmpcursor = cursor;
2361                 // to make sure undo gets the right cursor position
2362                 cursor = old_cursor;
2363                 recordUndo(bv(), Undo::DELETE, cursor.par());
2364                 cursor = tmpcursor;
2365                 backspace();
2366         }
2367 }
2368
2369
2370 void LyXText::backspace()
2371 {
2372         // Get the font that is used to calculate the baselineskip
2373         pos_type lastpos = cursor.par()->size();
2374         LyXFont rawparfont =
2375                 cursor.par()->getFontSettings(bv()->buffer()->params,
2376                                               lastpos - 1);
2377
2378         if (cursor.pos() == 0) {
2379                 // The cursor is at the beginning of a paragraph,
2380                 // so the the backspace will collapse two paragraphs into one.
2381
2382                 // but it's not allowed unless it's new
2383                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2384                         return;
2385
2386                 // we may paste some paragraphs
2387
2388                 // is it an empty paragraph?
2389
2390                 if ((lastpos == 0
2391                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2392                         // This is an empty paragraph and we delete it just by moving the cursor one step
2393                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2394                         // of the paragraph.
2395
2396                         if (cursor.par() != ownerParagraphs().begin()) {
2397                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2398                                 if (cursor.par()->layout() == tmppit->layout()
2399                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2400                                         // Inherit bottom DTD from the paragraph below.
2401                                         // (the one we are deleting)
2402                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2403                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2404                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2405                                 }
2406
2407                                 cursorLeft(bv());
2408
2409                                 // the layout things can change the height of a row !
2410                                 int const tmpheight = cursorRow()->height();
2411                                 setHeightOfRow(cursorRow());
2412                                 if (cursorRow()->height() != tmpheight)
2413                                         postPaint();
2414                                 return;
2415                         }
2416                 }
2417
2418                 if (cursor.par() != ownerParagraphs().begin()) {
2419                         recordUndo(bv(), Undo::DELETE,
2420                                 boost::prior(cursor.par()),
2421                                 cursor.par());
2422                 }
2423
2424                 ParagraphList::iterator tmppit = cursor.par();
2425                 RowList::iterator tmprow = cursorRow();
2426
2427                 // We used to do cursorLeftIntern() here, but it is
2428                 // not a good idea since it triggers the auto-delete
2429                 // mechanism. So we do a cursorLeftIntern()-lite,
2430                 // without the dreaded mechanism. (JMarc)
2431                 if (cursor.par() != ownerParagraphs().begin()) {
2432                         // steps into the above paragraph.
2433                         setCursorIntern(boost::prior(cursor.par()),
2434                                         boost::prior(cursor.par())->size(),
2435                                         false);
2436                 }
2437
2438                 // Pasting is not allowed, if the paragraphs have different
2439                 // layout. I think it is a real bug of all other
2440                 // word processors to allow it. It confuses the user.
2441                 // Even so with a footnote paragraph and a non-footnote
2442                 // paragraph. I will not allow pasting in this case,
2443                 // because the user would be confused if the footnote behaves
2444                 // different wether it is open or closed.
2445
2446                 //      Correction: Pasting is always allowed with standard-layout
2447                 LyXTextClass const & tclass =
2448                         bv()->buffer()->params.getLyXTextClass();
2449
2450                 if (cursor.par() != tmppit
2451                     && (cursor.par()->layout() == tmppit->layout()
2452                         || tmppit->layout() == tclass.defaultLayout())
2453                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2454                         removeParagraph(tmprow);
2455                         removeRow(tmprow);
2456                         mergeParagraph(bv()->buffer()->params, bv()->buffer()->paragraphs, cursor.par());
2457
2458                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2459                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2460                         // strangely enough it seems that commenting out the line above removes
2461                         // most or all of the segfaults. I will however also try to move the
2462                         // two Remove... lines in front of the PasteParagraph too.
2463                         else
2464                                 if (cursor.pos())
2465                                         cursor.pos(cursor.pos() - 1);
2466
2467                         postPaint();
2468
2469                         // remove the lost paragraph
2470                         // This one is not safe, since the paragraph that the tmprow and the
2471                         // following rows belong to has been deleted by the PasteParagraph
2472                         // above. The question is... could this be moved in front of the
2473                         // PasteParagraph?
2474                         //RemoveParagraph(tmprow);
2475                         //RemoveRow(tmprow);
2476
2477                         // This rebuilds the rows.
2478                         appendParagraph(cursorRow());
2479                         updateCounters();
2480
2481                         // the row may have changed, block, hfills etc.
2482                         setCursor(cursor.par(), cursor.pos(), false);
2483                 }
2484         } else {
2485                 // this is the code for a normal backspace, not pasting
2486                 // any paragraphs
2487                 recordUndo(bv(), Undo::DELETE, cursor.par());
2488                 // We used to do cursorLeftIntern() here, but it is
2489                 // not a good idea since it triggers the auto-delete
2490                 // mechanism. So we do a cursorLeftIntern()-lite,
2491                 // without the dreaded mechanism. (JMarc)
2492                 setCursorIntern(cursor.par(), cursor.pos()- 1,
2493                                 false, cursor.boundary());
2494
2495                 if (cursor.par()->isInset(cursor.pos())) {
2496                         // force complete redo when erasing display insets
2497                         // this is a cruel method but safe..... Matthias
2498                         if (cursor.par()->getInset(cursor.pos())->display() ||
2499                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2500                                 cursor.par()->erase(cursor.pos());
2501                                 redoParagraph();
2502                                 return;
2503                         }
2504                 }
2505
2506                 RowList::iterator row = cursorRow();
2507                 int y = cursor.y() - row->baseline();
2508                 pos_type z;
2509                 // remember that a space at the end of a row doesnt count
2510                 // when calculating the fill
2511                 if (cursor.pos() < lastPos(*this, row) ||
2512                     !cursor.par()->isLineSeparator(cursor.pos())) {
2513                         row->fill(row->fill() + singleWidth(
2514                                                             cursor.par(),
2515                                                             cursor.pos()));
2516                 }
2517
2518                 // some special code when deleting a newline. This is similar
2519                 // to the behavior when pasting paragraphs
2520                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2521                         cursor.par()->erase(cursor.pos());
2522                         // refresh the positions
2523                         RowList::iterator tmprow = row;
2524                         while (boost::next(tmprow) != rows().end() &&
2525                                boost::next(tmprow)->par() == row->par()) {
2526                                 ++tmprow;
2527                                 tmprow->pos(tmprow->pos() - 1);
2528                         }
2529                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2530                                 cursor.pos(cursor.pos() - 1);
2531
2532                         if (cursor.pos() < cursor.par()->size()
2533                             && !cursor.par()->isSeparator(cursor.pos())) {
2534                                 cursor.par()->insertChar(cursor.pos(), ' ');
2535                                 setCharFont(cursor.par(), cursor.pos(), current_font);
2536                                 // refresh the positions
2537                                 tmprow = row;
2538                                 while (boost::next(tmprow) != rows().end() &&
2539                                        boost::next(tmprow)->par() == row->par()) {
2540                                         ++tmprow;
2541                                         tmprow->pos(tmprow->pos() + 1);
2542                                 }
2543                         }
2544                 } else {
2545                         cursor.par()->erase(cursor.pos());
2546
2547                         // refresh the positions
2548                         RowList::iterator tmprow = row;
2549                         while (boost::next(tmprow) != rows().end() &&
2550                                boost::next(tmprow)->par() == row->par()) {
2551                                 ++tmprow;
2552                                 tmprow->pos(tmprow->pos() - 1);
2553                         }
2554
2555                         // delete newlines at the beginning of paragraphs
2556                         while (!cursor.par()->empty() &&
2557                                cursor.pos() < cursor.par()->size() &&
2558                                cursor.par()->isNewline(cursor.pos()) &&
2559                                cursor.pos() == cursor.par()->beginningOfBody()) {
2560                                 cursor.par()->erase(cursor.pos());
2561                                 // refresh the positions
2562                                 tmprow = row;
2563                                 while (boost::next(tmprow) != rows().end() &&
2564                                        boost::next(tmprow)->par() == row->par()) {
2565                                         ++tmprow;
2566                                         tmprow->pos(tmprow->pos() - 1);
2567                                 }
2568                         }
2569                 }
2570
2571                 // is there a break one row above
2572                 if (row != rows().begin() && boost::prior(row)->par() == row->par()) {
2573                         z = rowBreakPoint(*boost::prior(row));
2574                         if (z >= row->pos()) {
2575                                 row->pos(z + 1);
2576
2577                                 RowList::iterator tmprow = boost::prior(row);
2578
2579                                 // maybe the current row is now empty
2580                                 if (row->pos() >= row->par()->size()) {
2581                                         // remove it
2582                                         removeRow(row);
2583                                 } else {
2584                                         breakAgainOneRow(row);
2585                                 }
2586
2587                                 // set the dimensions of the row above
2588                                 y -= tmprow->height();
2589                                 tmprow->fill(fill(tmprow, workWidth()));
2590                                 setHeightOfRow(tmprow);
2591                                 postPaint();
2592
2593                                 setCursor(cursor.par(), cursor.pos(),
2594                                           false, cursor.boundary());
2595                                 //current_font = rawtmpfont;
2596                                 //real_current_font = realtmpfont;
2597                                 // check, whether the last character's font has changed.
2598                                 if (rawparfont !=
2599                                     cursor.par()->getFontSettings(bv()->buffer()->params,
2600                                                                   cursor.par()->size() - 1))
2601                                         redoHeightOfParagraph();
2602                                 return;
2603                         }
2604                 }
2605
2606                 // break the cursor row again
2607                 if (boost::next(row) != rows().end() &&
2608                     boost::next(row)->par() == row->par() &&
2609                     (lastPos(*this, row) == row->par()->size() - 1 ||
2610                      rowBreakPoint(*row) != lastPos(*this, row))) {
2611
2612                         // it can happen that a paragraph loses one row
2613                         // without a real breakup. This is when a word
2614                         // is to long to be broken. Well, I don t care this
2615                         // hack ;-)
2616                         if (lastPos(*this, row) == row->par()->size() - 1)
2617                                 removeRow(boost::next(row));
2618
2619                         postPaint();
2620
2621                         breakAgainOneRow(row);
2622                         // will the cursor be in another row now?
2623                         if (boost::next(row) != rows().end() &&
2624                             boost::next(row)->par() == row->par() &&
2625                             lastPos(*this, row) <= cursor.pos()) {
2626                                 ++row;
2627                                 breakAgainOneRow(row);
2628                         }
2629
2630                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2631                 } else  {
2632                         // set the dimensions of the row
2633                         row->fill(fill(row, workWidth()));
2634                         setHeightOfRow(row);
2635                         postPaint();
2636                         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
2637                 }
2638         }
2639
2640         // current_font = rawtmpfont;
2641         // real_current_font = realtmpfont;
2642
2643         if (isBoundary(bv()->buffer(), *cursor.par(), cursor.pos())
2644             != cursor.boundary())
2645                 setCursor(cursor.par(), cursor.pos(), false,
2646                           !cursor.boundary());
2647
2648         lastpos = cursor.par()->size();
2649         if (cursor.pos() == lastpos)
2650                 setCurrentFont();
2651
2652         // check, whether the last characters font has changed.
2653         if (rawparfont !=
2654             cursor.par()->getFontSettings(bv()->buffer()->params, lastpos - 1)) {
2655                 redoHeightOfParagraph();
2656         }
2657 }
2658
2659
2660 RowList::iterator LyXText::cursorRow() const
2661 {
2662         return getRow(cursor.par(), cursor.pos());
2663 }
2664
2665
2666 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2667 {
2668         return getRow(cur.par(), cur.pos());
2669 }
2670
2671
2672 RowList::iterator
2673 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2674 {
2675         if (rows().empty())
2676                 return rowlist_.end();
2677
2678         // find the first row of the specified paragraph
2679         RowList::iterator rit = rowlist_.begin();
2680         RowList::iterator end = rowlist_.end();
2681         while (boost::next(rit) != end && rit->par() != pit) {
2682                 ++rit;
2683         }
2684
2685         // now find the wanted row
2686         while (rit->pos() < pos
2687                && boost::next(rit) != end
2688                && boost::next(rit)->par() == pit
2689                && boost::next(rit)->pos() <= pos) {
2690                 ++rit;
2691         }
2692
2693         return rit;
2694 }
2695
2696
2697 // returns pointer to a specified row
2698 RowList::iterator
2699 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2700 {
2701         y = 0;
2702
2703         if (rows().empty())
2704                 return rowlist_.end();
2705
2706         // find the first row of the specified paragraph
2707         RowList::iterator rit = rowlist_.begin();
2708         RowList::iterator end = rowlist_.end();
2709         while (boost::next(rit) != end && rit->par() != pit) {
2710                 y += rit->height();
2711                 ++rit;
2712         }
2713
2714         // now find the wanted row
2715         while (rit->pos() < pos
2716                && boost::next(rit) != end
2717                && boost::next(rit)->par() == pit
2718                && boost::next(rit)->pos() <= pos) {
2719                 y += rit->height();
2720                 ++rit;
2721         }
2722
2723         return rit;
2724 }
2725
2726
2727 // returns pointer to some fancy row 'below' specified row
2728 RowList::iterator LyXText::cursorIRow() const
2729 {
2730         int y = 0;
2731         return getRow(cursor.par(), cursor.pos(), y);
2732 }
2733
2734
2735 RowList::iterator LyXText::getRowNearY(int & y) const
2736 {
2737         RowList::iterator rit = anchor_row_;
2738         RowList::iterator const beg = rows().begin();
2739         RowList::iterator const end = rows().end();
2740
2741         if (rows().empty()) {
2742                 y = 0;
2743                 return end;
2744         }
2745         if (rit == end)
2746                 rit = beg;
2747
2748         int tmpy = rit->y();
2749
2750         if (tmpy <= y) {
2751                 while (rit != end && tmpy <= y) {
2752                         tmpy += rit->height();
2753                         ++rit;
2754                 }
2755                 if (rit != beg) {
2756                         --rit;
2757                         tmpy -= rit->height();
2758                 }
2759         } else {
2760                 while (rit != beg && tmpy > y) {
2761                         --rit;
2762                         tmpy -= rit->height();
2763                 }
2764         }
2765         if (tmpy < 0 || rit == end) {
2766                 tmpy = 0;
2767                 rit = beg;
2768         }
2769
2770         // return the rel y
2771         y = tmpy;
2772
2773         return rit;
2774 }
2775
2776
2777 int LyXText::getDepth() const
2778 {
2779         return cursor.par()->getDepth();
2780 }