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