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