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