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