]> git.lyx.org Git - lyx.git/blob - src/text2.C
remove "deep update"
[lyx.git] / src / text2.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 "LString.h"
15 #include "Lsstream.h"
16 #include "paragraph.h"
17 #include "funcrequest.h"
18 #include "frontends/LyXView.h"
19 #include "undo_funcs.h"
20 #include "buffer.h"
21 #include "buffer_funcs.h"
22 #include "bufferparams.h"
23 #include "errorlist.h"
24 #include "gettext.h"
25 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "frontends/Painter.h"
28 #include "frontends/font_metrics.h"
29 #include "debug.h"
30 #include "lyxrc.h"
31 #include "lyxrow.h"
32 #include "FloatList.h"
33 #include "language.h"
34 #include "ParagraphParameters.h"
35 #include "counters.h"
36 #include "lyxrow_funcs.h"
37 #include "metricsinfo.h"
38 #include "paragraph_funcs.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetenv.h"
42 #include "insets/insetfloat.h"
43 #include "insets/insetwrap.h"
44
45 #include "support/LAssert.h"
46 #include "support/textutils.h"
47 #include "support/lstrings.h"
48
49 #include <boost/tuple/tuple.hpp>
50
51 #include <algorithm>
52
53 using namespace lyx::support;
54
55 using std::vector;
56 using std::copy;
57 using std::endl;
58 using std::find;
59 using std::pair;
60 using lyx::pos_type;
61
62
63 LyXText::LyXText(BufferView * bv)
64         : height(0), width(0), anchor_row_offset_(0),
65           inset_owner(0), the_locking_inset(0), bv_owner(bv)
66 {
67         anchor_row_ = rows().end();
68 }
69
70
71 LyXText::LyXText(BufferView * bv, InsetText * inset)
72         : height(0), width(0), anchor_row_offset_(0),
73           inset_owner(inset), the_locking_inset(0), bv_owner(bv)
74 {
75         anchor_row_ = rows().end();
76 }
77
78
79 void LyXText::init(BufferView * bview)
80 {
81         bv_owner = bview;
82
83         rowlist_.clear();
84         width = height = 0;
85
86         anchor_row_ = rows().end();
87         anchor_row_offset_ = 0;
88
89         current_font = getFont(ownerParagraphs().begin(), 0);
90
91         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
92
93         setCursorIntern(rowlist_.begin()->par(), 0);
94         selection.cursor = cursor;
95
96         updateCounters();
97 }
98
99
100 // Gets the fully instantiated font at a given position in a paragraph
101 // Basically the same routine as Paragraph::getFont() in paragraph.C.
102 // The difference is that this one is used for displaying, and thus we
103 // are allowed to make cosmetic improvements. For instance make footnotes
104 // smaller. (Asger)
105 // If position is -1, we get the layout font of the paragraph.
106 // If position is -2, we get the font of the manual label of the paragraph.
107 LyXFont LyXText::getFont(ParagraphList::iterator pit, pos_type pos) const
108 {
109         Assert(pos >= 0);
110
111         LyXLayout_ptr const & layout = pit->layout();
112 #warning broken?
113         BufferParams const & params = bv()->buffer()->params;
114
115         // We specialize the 95% common case:
116         if (!pit->getDepth()) {
117                 if (layout->labeltype == LABEL_MANUAL
118                     && pos < pit->beginningOfBody()) {
119                         // 1% goes here
120                         LyXFont f = pit->getFontSettings(params, pos);
121                         if (pit->inInset())
122                                 pit->inInset()->getDrawFont(f);
123                         return f.realize(layout->reslabelfont);
124                 } else {
125                         LyXFont f = pit->getFontSettings(params, pos);
126                         if (pit->inInset())
127                                 pit->inInset()->getDrawFont(f);
128                         return f.realize(layout->resfont);
129                 }
130         }
131
132         // The uncommon case need not be optimized as much
133
134         LyXFont layoutfont;
135
136         if (pos < pit->beginningOfBody()) {
137                 // 1% goes here
138                 layoutfont = layout->labelfont;
139         } else {
140                 // 99% goes here
141                 layoutfont = layout->font;
142         }
143
144         LyXFont tmpfont = pit->getFontSettings(params, pos);
145         tmpfont.realize(layoutfont);
146
147         if (pit->inInset())
148                 pit->inInset()->getDrawFont(tmpfont);
149
150         // Realize with the fonts of lesser depth.
151         tmpfont.realize(outerFont(pit, ownerParagraphs()));
152         tmpfont.realize(defaultfont_);
153
154         return tmpfont;
155 }
156
157
158 LyXFont LyXText::getLayoutFont(ParagraphList::iterator pit) const
159 {
160         LyXLayout_ptr const & layout = pit->layout();
161
162         if (!pit->getDepth())
163                 return layout->resfont;
164
165         LyXFont font = layout->font;
166         // Realize with the fonts of lesser depth.
167         font.realize(outerFont(pit, ownerParagraphs()));
168         font.realize(defaultfont_);
169
170         return font;
171 }
172
173
174 LyXFont LyXText::getLabelFont(ParagraphList::iterator pit) const
175 {
176         LyXLayout_ptr const & layout = pit->layout();
177
178         if (!pit->getDepth())
179                 return layout->reslabelfont;
180
181         LyXFont font = layout->labelfont;
182         // Realize with the fonts of lesser depth.
183         font.realize(outerFont(pit, ownerParagraphs()));
184         font.realize(defaultfont_);
185
186         return font;
187 }
188
189
190 void LyXText::setCharFont(ParagraphList::iterator pit,
191                           pos_type pos, LyXFont const & fnt,
192                           bool toggleall)
193 {
194         BufferParams const & params = bv()->buffer()->params;
195         LyXFont font = getFont(pit, pos);
196         font.update(fnt, params.language, toggleall);
197         // Let the insets convert their font
198         if (pit->isInset(pos)) {
199                 InsetOld * inset = pit->getInset(pos);
200                 if (isEditableInset(inset)) {
201                         static_cast<UpdatableInset *>(inset)
202                                 ->setFont(bv(), fnt, toggleall, true);
203                 }
204         }
205
206         // Plug through to version below:
207         setCharFont(pit, pos, font);
208 }
209
210
211 void LyXText::setCharFont(
212         ParagraphList::iterator pit, pos_type pos, LyXFont const & fnt)
213 {
214         LyXFont font = fnt;
215         LyXLayout_ptr const & layout = pit->layout();
216
217         // Get concrete layout font to reduce against
218         LyXFont layoutfont;
219
220         if (pos < pit->beginningOfBody())
221                 layoutfont = layout->labelfont;
222         else
223                 layoutfont = layout->font;
224
225         // Realize against environment font information
226         if (pit->getDepth()) {
227                 ParagraphList::iterator tp = pit;
228                 while (!layoutfont.resolved() &&
229                        tp != ownerParagraphs().end() &&
230                        tp->getDepth()) {
231                         tp = outerHook(tp, ownerParagraphs());
232                         if (tp != ownerParagraphs().end())
233                                 layoutfont.realize(tp->layout()->font);
234                 }
235         }
236
237         layoutfont.realize(defaultfont_);
238
239         // Now, reduce font against full layout font
240         font.reduce(layoutfont);
241
242         pit->setFont(pos, font);
243 }
244
245
246 // removes the row and reset the touched counters
247 void LyXText::removeRow(RowList::iterator rit)
248 {
249         if (anchor_row_ == rit) {
250                 if (rit != rows().begin()) {
251                         anchor_row_ = boost::prior(rit);
252                         anchor_row_offset_ += anchor_row_->height();
253                 } else {
254                         anchor_row_ = boost::next(rit);
255                         anchor_row_offset_ -= rit->height();
256                 }
257         }
258
259         // the text becomes smaller
260         height -= rit->height();
261
262         rowlist_.erase(rit);
263 }
264
265
266 // remove all following rows of the paragraph of the specified row.
267 void LyXText::removeParagraph(RowList::iterator rit)
268 {
269         ParagraphList::iterator tmppit = rit->par();
270         ++rit;
271
272         while (rit != rows().end() && rit->par() == tmppit) {
273                 RowList::iterator tmprit = boost::next(rit);
274                 removeRow(rit);
275                 rit = tmprit;
276         }
277 }
278
279
280 void LyXText::insertParagraph(ParagraphList::iterator pit,
281                               RowList::iterator rit)
282 {
283         // insert a new row, starting at position 0
284         rit = rowlist_.insert(rit, Row(pit, 0));
285
286         // and now append the whole paragraph before the new row
287         appendParagraph(rit);
288 }
289
290
291 InsetOld * LyXText::getInset() const
292 {
293         ParagraphList::iterator pit = cursor.par();
294         pos_type const pos = cursor.pos();
295
296         if (pos < pit->size() && pit->isInset(pos)) {
297                 return pit->getInset(pos);
298         }
299         return 0;
300 }
301
302
303 void LyXText::toggleInset()
304 {
305         InsetOld * inset = getInset();
306         // is there an editable inset at cursor position?
307         if (!isEditableInset(inset)) {
308                 // No, try to see if we are inside a collapsable inset
309                 if (inset_owner && inset_owner->owner()
310                     && inset_owner->owner()->isOpen()) {
311                         bv()->unlockInset(inset_owner->owner());
312                         inset_owner->owner()->close(bv());
313                         bv()->getLyXText()->cursorRight(bv());
314                 }
315                 return;
316         }
317         //bv()->owner()->message(inset->editMessage());
318
319         // do we want to keep this?? (JMarc)
320         if (!isHighlyEditableInset(inset))
321                 recordUndo(bv(), Undo::ATOMIC);
322
323         if (inset->isOpen())
324                 inset->close(bv());
325         else
326                 inset->open(bv());
327
328         bv()->updateInset();
329 }
330
331
332 /* used in setlayout */
333 // Asger is not sure we want to do this...
334 void LyXText::makeFontEntriesLayoutSpecific(BufferParams const & params,
335                                             Paragraph & par)
336 {
337         LyXLayout_ptr const & layout = par.layout();
338         pos_type const psize = par.size();
339
340         LyXFont layoutfont;
341         for (pos_type pos = 0; pos < psize; ++pos) {
342                 if (pos < par.beginningOfBody())
343                         layoutfont = layout->labelfont;
344                 else
345                         layoutfont = layout->font;
346
347                 LyXFont tmpfont = par.getFontSettings(params, pos);
348                 tmpfont.reduce(layoutfont);
349                 par.setFont(pos, tmpfont);
350         }
351 }
352
353
354 ParagraphList::iterator
355 LyXText::setLayout(LyXCursor & cur, LyXCursor & sstart_cur,
356                    LyXCursor & send_cur,
357                    string const & layout)
358 {
359         ParagraphList::iterator endpit = boost::next(send_cur.par());
360         ParagraphList::iterator undoendpit = endpit;
361         ParagraphList::iterator pars_end = ownerParagraphs().end();
362
363         if (endpit != pars_end && endpit->getDepth()) {
364                 while (endpit != pars_end && endpit->getDepth()) {
365                         ++endpit;
366                         undoendpit = endpit;
367                 }
368         } else if (endpit != pars_end) {
369                 // because of parindents etc.
370                 ++endpit;
371         }
372
373         recordUndo(bv(), Undo::ATOMIC, sstart_cur.par(), boost::prior(undoendpit));
374
375         // ok we have a selection. This is always between sstart_cur
376         // and sel_end cursor
377         cur = sstart_cur;
378         ParagraphList::iterator pit = sstart_cur.par();
379         ParagraphList::iterator epit = boost::next(send_cur.par());
380
381         LyXLayout_ptr const & lyxlayout =
382                 bv()->buffer()->params.getLyXTextClass()[layout];
383
384         do {
385                 pit->applyLayout(lyxlayout);
386                 makeFontEntriesLayoutSpecific(bv()->buffer()->params, *pit);
387                 ParagraphList::iterator fppit = pit;
388                 fppit->params().spaceTop(lyxlayout->fill_top ?
389                                          VSpace(VSpace::VFILL)
390                                          : VSpace(VSpace::NONE));
391                 fppit->params().spaceBottom(lyxlayout->fill_bottom ?
392                                             VSpace(VSpace::VFILL)
393                                             : VSpace(VSpace::NONE));
394                 if (lyxlayout->margintype == MARGIN_MANUAL)
395                         pit->setLabelWidthString(lyxlayout->labelstring());
396                 cur.par(pit);
397                 ++pit;
398         } while (pit != epit);
399
400         return endpit;
401 }
402
403
404 // set layout over selection and make a total rebreak of those paragraphs
405 void LyXText::setLayout(string const & layout)
406 {
407         LyXCursor tmpcursor = cursor;  // store the current cursor
408
409         // if there is no selection just set the layout
410         // of the current paragraph
411         if (!selection.set()) {
412                 selection.start = cursor;  // dummy selection
413                 selection.end = cursor;
414         }
415
416         // special handling of new environment insets
417         BufferParams const & params = bv()->buffer()->params;
418         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
419         if (lyxlayout->is_environment) {
420                 // move everything in a new environment inset
421                 lyxerr << "setting layout " << layout << endl;
422                 bv()->owner()->dispatch(FuncRequest(LFUN_HOME));
423                 bv()->owner()->dispatch(FuncRequest(LFUN_ENDSEL));
424                 bv()->owner()->dispatch(FuncRequest(LFUN_CUT));
425                 InsetOld * inset = new InsetEnvironment(params, layout);
426                 if (bv()->insertInset(inset)) {
427                         //inset->edit(bv());
428                         //bv()->owner()->dispatch(FuncRequest(LFUN_PASTE));
429                 }
430                 else
431                         delete inset;
432                 return;
433         }
434
435         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
436                                                    selection.end, layout);
437         redoParagraphs(selection.start.par(), endpit);
438
439         // we have to reset the selection, because the
440         // geometry could have changed
441         setCursor(selection.start.par(), selection.start.pos(), false);
442         selection.cursor = cursor;
443         setCursor(selection.end.par(), selection.end.pos(), false);
444         updateCounters();
445         clearSelection();
446         setSelection();
447         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
448 }
449
450
451 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
452 {
453         ParagraphList::iterator pit(cursor.par());
454         ParagraphList::iterator end(cursor.par());
455         ParagraphList::iterator start = pit;
456
457         if (selection.set()) {
458                 pit = selection.start.par();
459                 end = selection.end.par();
460                 start = pit;
461         }
462
463         ParagraphList::iterator pastend = boost::next(end);
464
465         if (!test_only)
466                 recordUndo(bv(), Undo::ATOMIC, start, end);
467
468         bool changed = false;
469
470         int prev_after_depth = 0;
471 #warning parlist ... could be nicer ?
472         if (start != ownerParagraphs().begin()) {
473                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
474         }
475
476         while (true) {
477                 int const depth = pit->params().depth();
478                 if (type == bv_funcs::INC_DEPTH) {
479                         if (depth < prev_after_depth
480                             && pit->layout()->labeltype != LABEL_BIBLIO) {
481                                 changed = true;
482                                 if (!test_only) {
483                                         pit->params().depth(depth + 1);
484                                 }
485
486                         }
487                 } else if (depth) {
488                         changed = true;
489                         if (!test_only)
490                                 pit->params().depth(depth - 1);
491                 }
492
493                 prev_after_depth = pit->getMaxDepthAfter();
494
495                 if (pit == end) {
496                         break;
497                 }
498
499                 ++pit;
500         }
501
502         if (test_only)
503                 return changed;
504
505
506         redoParagraphs(start, pastend);
507
508         // We need to actually move the text->cursor. I don't
509         // understand why ...
510         LyXCursor tmpcursor = cursor;
511
512         // we have to reset the visual selection because the
513         // geometry could have changed
514         if (selection.set()) {
515                 setCursor(selection.start.par(), selection.start.pos());
516                 selection.cursor = cursor;
517                 setCursor(selection.end.par(), selection.end.pos());
518         }
519
520         // this handles the counter labels, and also fixes up
521         // depth values for follow-on (child) paragraphs
522         updateCounters();
523
524         setSelection();
525         setCursor(tmpcursor.par(), tmpcursor.pos());
526
527         return changed;
528 }
529
530
531 // set font over selection and make a total rebreak of those paragraphs
532 void LyXText::setFont(LyXFont const & font, bool toggleall)
533 {
534         // if there is no selection just set the current_font
535         if (!selection.set()) {
536                 // Determine basis font
537                 LyXFont layoutfont;
538                 if (cursor.pos() < cursor.par()->beginningOfBody()) {
539                         layoutfont = getLabelFont(cursor.par());
540                 } else {
541                         layoutfont = getLayoutFont(cursor.par());
542                 }
543                 // Update current font
544                 real_current_font.update(font,
545                                          bv()->buffer()->params.language,
546                                          toggleall);
547
548                 // Reduce to implicit settings
549                 current_font = real_current_font;
550                 current_font.reduce(layoutfont);
551                 // And resolve it completely
552                 real_current_font.realize(layoutfont);
553
554                 return;
555         }
556
557         LyXCursor tmpcursor = cursor; // store the current cursor
558
559         // ok we have a selection. This is always between sel_start_cursor
560         // and sel_end cursor
561
562         recordUndo(bv(), Undo::ATOMIC, selection.start.par(), selection.end.par());
563         freezeUndo();
564         cursor = selection.start;
565         while (cursor.par() != selection.end.par() ||
566                cursor.pos() < selection.end.pos())
567         {
568                 if (cursor.pos() < cursor.par()->size()) {
569                         // an open footnote should behave like a closed one
570                         setCharFont(cursor.par(), cursor.pos(),
571                                     font, toggleall);
572                         cursor.pos(cursor.pos() + 1);
573                 } else {
574                         cursor.pos(0);
575                         cursor.par(boost::next(cursor.par()));
576                 }
577         }
578         unFreezeUndo();
579
580         redoParagraph(selection.start.par());
581
582         // we have to reset the selection, because the
583         // geometry could have changed, but we keep
584         // it for user convenience
585         setCursor(selection.start.par(), selection.start.pos());
586         selection.cursor = cursor;
587         setCursor(selection.end.par(), selection.end.pos());
588         setSelection();
589         setCursor(tmpcursor.par(), tmpcursor.pos(), true,
590                   tmpcursor.boundary());
591 }
592
593
594 void LyXText::redoHeightOfParagraph()
595 {
596         RowList::iterator tmprow = cursorRow();
597
598         setHeightOfRow(tmprow);
599
600         while (tmprow != rows().begin()
601                && boost::prior(tmprow)->par() == tmprow->par()) {
602                 --tmprow;
603                 setHeightOfRow(tmprow);
604         }
605
606         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
607 }
608
609
610 RowList::iterator LyXText::firstRow(ParagraphList::iterator pit)
611 {
612         RowList::iterator rit;
613         for (rit = rows().begin(); rit != rows().end(); ++rit)
614                 if (rit->par() == pit)
615                         break;
616         return rit;
617 }
618
619
620 // rebreaks all paragraphs between the specified pars
621 // This function is needed after SetLayout and SetFont etc.
622 void LyXText::redoParagraphs(ParagraphList::iterator start,
623   ParagraphList::iterator end)
624 {
625         for ( ; start != end; ++start)
626                 redoParagraph(start);
627 }
628
629
630 void LyXText::redoParagraph(ParagraphList::iterator pit)
631 {
632         RowList::iterator rit = firstRow(pit);
633
634         // remove paragraph from rowlist
635         while (rit != rows().end() && rit->par() == pit) {
636                 RowList::iterator rit2 = rit++;
637                 removeRow(rit2);
638         }
639
640         // reinsert the paragraph
641         // insert a new row, starting at position 0
642         Row newrow(pit, 0);
643         rit = rowlist_.insert(rit, newrow);
644         //newrow.dump("newrow: ");
645
646         // and now append the whole paragraph before the new row
647         pos_type const last = rit->par()->size();
648         bool done = false;
649
650         do {
651                 pos_type z = rowBreakPoint(*rit);
652
653                 RowList::iterator tmprow = rit;
654                 //tmprow->dump("tmprow: ");
655
656                 if (z < last) {
657                         ++z;
658                         Row newrow(rit->par(), z);
659                         //newrow.dump("newrow2: ");
660                         rit = rowlist_.insert(boost::next(rit), newrow);
661                 } else {
662                         done = true;
663                 }
664
665                 // Set the dimensions of the row
666                 // fixed fill setting now by calling inset->update() in
667                 // SingleWidth when needed!
668                 //tmprow->dump("tmprow 1: ");
669                 tmprow->fill(fill(tmprow, workWidth()));
670                 //tmprow->dump("tmprow 2: ");
671                 setHeightOfRow(tmprow);
672                 //tmprow->dump("tmprow 3: ");
673                 height += rit->height();
674
675         } while (!done);
676
677         setHeightOfRow(rows().begin());
678 }
679
680
681 void LyXText::fullRebreak()
682 {
683         lyxerr << "fullRebreak" << endl;
684         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
685         setCursorIntern(cursor.par(), cursor.pos());
686         selection.cursor = cursor;
687 }
688
689
690 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
691 {
692         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth << endl;
693         //Assert(mi.base.textwidth);
694
695         // rebuild row cache
696         rowlist_.clear();
697         width = height = 0;
698
699         anchor_row_ = rows().end();
700         anchor_row_offset_ = 0;
701
702         ParagraphList::iterator pit = ownerParagraphs().begin();
703         ParagraphList::iterator end = ownerParagraphs().end();
704
705         for (; pit != end; ++pit) {
706                 InsetList::iterator ii = pit->insetlist.begin();
707                 InsetList::iterator iend = pit->insetlist.end();
708                 for (; ii != iend; ++ii) {
709                         Dimension dim;
710                         MetricsInfo m = mi;
711 #warning FIXME: pos != 0
712                         m.base.font = getFont(pit, 0);
713                         ii->inset->metrics(m, dim);
714                 }
715
716 #if 1
717                 // insert a new row, starting at position 0
718                 Row newrow(pit, 0);
719                 RowList::iterator rit = rowlist_.insert(rowlist_.end(), newrow);
720
721                 // and now append the whole paragraph before the new row
722                 appendParagraph(rit);
723 #else
724                 redoParagraph(pit);
725 #endif
726         }
727
728         // compute height
729         //lyxerr << "height 0: " << height << endl;
730         //for (RowList::iterator rit = rows().begin(); rit != rows().end(); ++rit) {
731         //      height += rit->height();
732         //}
733         //lyxerr << "height 1: " << height << endl;
734
735         // final dimension
736         dim.asc = rows().begin()->ascent_of_text();
737         dim.des = height - dim.asc;
738         dim.wid = std::max(mi.base.textwidth, int(width));
739 }
740
741
742 void LyXText::partialRebreak()
743 {
744         if (rows().empty()) {
745                 init(bv());
746                 return;
747         }
748         breakAgain(rows().begin());
749 }
750
751
752 // important for the screen
753
754
755 // the cursor set functions have a special mechanism. When they
756 // realize, that you left an empty paragraph, they will delete it.
757 // They also delete the corresponding row
758
759 // need the selection cursor:
760 void LyXText::setSelection()
761 {
762         TextCursor::setSelection();
763 }
764
765
766
767 void LyXText::clearSelection()
768 {
769         TextCursor::clearSelection();
770
771         // reset this in the bv_owner!
772         if (bv_owner && bv_owner->text)
773                 bv_owner->text->xsel_cache.set(false);
774 }
775
776
777 void LyXText::cursorHome()
778 {
779         setCursor(cursor.par(), cursorRow()->pos());
780 }
781
782
783 void LyXText::cursorEnd()
784 {
785         if (cursor.par()->empty())
786                 return;
787
788         RowList::iterator rit = cursorRow();
789         RowList::iterator next_rit = boost::next(rit);
790         ParagraphList::iterator pit = rit->par();
791         pos_type last_pos = lastPos(*this, rit);
792
793         if (next_rit == rows().end() || next_rit->par() != pit) {
794                 ++last_pos;
795         } else {
796                 if (pit->empty() ||
797                     (pit->getChar(last_pos) != ' ' && !pit->isNewline(last_pos))) {
798                         ++last_pos;
799                 }
800         }
801
802         setCursor(pit, last_pos);
803 }
804
805
806 void LyXText::cursorTop()
807 {
808         setCursor(ownerParagraphs().begin(), 0);
809 }
810
811
812 void LyXText::cursorBottom()
813 {
814         ParagraphList::iterator lastpit =
815                 boost::prior(ownerParagraphs().end());
816         setCursor(lastpit, lastpit->size());
817 }
818
819
820 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
821 {
822         // If the mask is completely neutral, tell user
823         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
824                 // Could only happen with user style
825                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
826                 return;
827         }
828
829         // Try implicit word selection
830         // If there is a change in the language the implicit word selection
831         // is disabled.
832         LyXCursor resetCursor = cursor;
833         bool implicitSelection = (font.language() == ignore_language
834                                   && font.number() == LyXFont::IGNORE)
835                 ? selectWordWhenUnderCursor(lyx::WHOLE_WORD_STRICT) : false;
836
837         // Set font
838         setFont(font, toggleall);
839
840         // Implicit selections are cleared afterwards
841         //and cursor is set to the original position.
842         if (implicitSelection) {
843                 clearSelection();
844                 cursor = resetCursor;
845                 setCursor(cursor.par(), cursor.pos());
846                 selection.cursor = cursor;
847         }
848 }
849
850
851 string LyXText::getStringToIndex()
852 {
853         // Try implicit word selection
854         // If there is a change in the language the implicit word selection
855         // is disabled.
856         LyXCursor const reset_cursor = cursor;
857         bool const implicitSelection =
858                 selectWordWhenUnderCursor(lyx::PREVIOUS_WORD);
859
860         string idxstring;
861         if (!selection.set())
862                 bv()->owner()->message(_("Nothing to index!"));
863         else if (selection.start.par() != selection.end.par())
864                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
865         else
866                 idxstring = selectionAsString(bv()->buffer(), false);
867
868         // Reset cursors to their original position.
869         cursor = reset_cursor;
870         setCursor(cursor.par(), cursor.pos());
871         selection.cursor = cursor;
872
873         // Clear the implicit selection.
874         if (implicitSelection)
875                 clearSelection();
876
877         return idxstring;
878 }
879
880
881 // the DTP switches for paragraphs. LyX will store them in the first
882 // physicla paragraph. When a paragraph is broken, the top settings rest,
883 // the bottom settings are given to the new one. So I can make shure,
884 // they do not duplicate themself and you cannnot make dirty things with
885 // them!
886
887 void LyXText::setParagraph(bool line_top, bool line_bottom,
888                            bool pagebreak_top, bool pagebreak_bottom,
889                            VSpace const & space_top,
890                            VSpace const & space_bottom,
891                            Spacing const & spacing,
892                            LyXAlignment align,
893                            string const & labelwidthstring,
894                            bool noindent)
895 {
896         LyXCursor tmpcursor = cursor;
897         if (!selection.set()) {
898                 selection.start = cursor;
899                 selection.end = cursor;
900         }
901
902         // make sure that the depth behind the selection are restored, too
903         ParagraphList::iterator endpit = boost::next(selection.end.par());
904         ParagraphList::iterator undoendpit = endpit;
905         ParagraphList::iterator pars_end = ownerParagraphs().end();
906
907         if (endpit != pars_end && endpit->getDepth()) {
908                 while (endpit != pars_end && endpit->getDepth()) {
909                         ++endpit;
910                         undoendpit = endpit;
911                 }
912         } else if (endpit != pars_end) {
913                 // because of parindents etc.
914                 ++endpit;
915         }
916
917         recordUndo(bv(), Undo::ATOMIC, selection.start.par(),
918                 boost::prior(undoendpit));
919
920
921         ParagraphList::iterator tmppit = selection.end.par();
922
923         while (tmppit != boost::prior(selection.start.par())) {
924                 setCursor(tmppit, 0);
925
926                 ParagraphList::iterator pit = cursor.par();
927                 ParagraphParameters & params = pit->params();
928
929                 params.lineTop(line_top);
930                 params.lineBottom(line_bottom);
931                 params.pagebreakTop(pagebreak_top);
932                 params.pagebreakBottom(pagebreak_bottom);
933                 params.spaceTop(space_top);
934                 params.spaceBottom(space_bottom);
935                 params.spacing(spacing);
936                 // does the layout allow the new alignment?
937                 LyXLayout_ptr const & layout = pit->layout();
938
939                 if (align == LYX_ALIGN_LAYOUT)
940                         align = layout->align;
941                 if (align & layout->alignpossible) {
942                         if (align == layout->align)
943                                 params.align(LYX_ALIGN_LAYOUT);
944                         else
945                                 params.align(align);
946                 }
947                 pit->setLabelWidthString(labelwidthstring);
948                 params.noindent(noindent);
949                 tmppit = boost::prior(pit);
950         }
951
952         redoParagraphs(selection.start.par(), endpit);
953
954         clearSelection();
955         setCursor(selection.start.par(), selection.start.pos());
956         selection.cursor = cursor;
957         setCursor(selection.end.par(), selection.end.pos());
958         setSelection();
959         setCursor(tmpcursor.par(), tmpcursor.pos());
960         if (inset_owner)
961                 bv()->updateInset();
962 }
963
964
965 // set the counter of a paragraph. This includes the labels
966 void LyXText::setCounter(Buffer const * buf, ParagraphList::iterator pit)
967 {
968         LyXTextClass const & textclass = buf->params.getLyXTextClass();
969         LyXLayout_ptr const & layout = pit->layout();
970
971         if (pit != ownerParagraphs().begin()) {
972
973                 pit->params().appendix(boost::prior(pit)->params().appendix());
974                 if (!pit->params().appendix() &&
975                     pit->params().startOfAppendix()) {
976                         pit->params().appendix(true);
977                         textclass.counters().reset();
978                 }
979                 pit->enumdepth = boost::prior(pit)->enumdepth;
980                 pit->itemdepth = boost::prior(pit)->itemdepth;
981         } else {
982                 pit->params().appendix(pit->params().startOfAppendix());
983                 pit->enumdepth = 0;
984                 pit->itemdepth = 0;
985         }
986
987         /* Maybe we have to increment the enumeration depth.
988          * BUT, enumeration in a footnote is considered in isolation from its
989          *      surrounding paragraph so don't increment if this is the
990          *      first line of the footnote
991          * AND, bibliographies can't have their depth changed ie. they
992          *      are always of depth 0
993          */
994         if (pit != ownerParagraphs().begin()
995             && boost::prior(pit)->getDepth() < pit->getDepth()
996             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
997             && pit->enumdepth < 3
998             && layout->labeltype != LABEL_BIBLIO) {
999                 pit->enumdepth++;
1000         }
1001
1002         // Maybe we have to decrement the enumeration depth, see note above
1003         if (pit != ownerParagraphs().begin()
1004             && boost::prior(pit)->getDepth() > pit->getDepth()
1005             && layout->labeltype != LABEL_BIBLIO) {
1006                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
1007                                            pit->getDepth())->enumdepth;
1008         }
1009
1010         if (!pit->params().labelString().empty()) {
1011                 pit->params().labelString(string());
1012         }
1013
1014         if (layout->margintype == MARGIN_MANUAL) {
1015                 if (pit->params().labelWidthString().empty()) {
1016                         pit->setLabelWidthString(layout->labelstring());
1017                 }
1018         } else {
1019                 pit->setLabelWidthString(string());
1020         }
1021
1022         // is it a layout that has an automatic label?
1023         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
1024                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
1025
1026                 ostringstream s;
1027
1028                 if (i >= 0 && i <= buf->params.secnumdepth) {
1029                         string numbertype;
1030                         string langtype;
1031
1032                         textclass.counters().step(layout->latexname());
1033
1034                         // Is there a label? Useful for Chapter layout
1035                         if (!pit->params().appendix()) {
1036                                 s << buf->B_(layout->labelstring());
1037                         } else {
1038                                 s << buf->B_(layout->labelstring_appendix());
1039                         }
1040
1041                         // Use of an integer is here less than elegant. For now.
1042                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
1043                         if (!pit->params().appendix()) {
1044                                 numbertype = "sectioning";
1045                         } else {
1046                                 numbertype = "appendix";
1047                                 if (pit->isRightToLeftPar(buf->params))
1048                                         langtype = "hebrew";
1049                                 else
1050                                         langtype = "latin";
1051                         }
1052
1053                         s << " "
1054                           << textclass.counters()
1055                                 .numberLabel(layout->latexname(),
1056                                              numbertype, langtype, head);
1057
1058                         pit->params().labelString(STRCONV(s.str()));
1059
1060                         // reset enum counters
1061                         textclass.counters().reset("enum");
1062                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
1063                         textclass.counters().reset("enum");
1064                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
1065                         // FIXME
1066                         // Yes I know this is a really, really! bad solution
1067                         // (Lgb)
1068                         string enumcounter("enum");
1069
1070                         switch (pit->enumdepth) {
1071                         case 2:
1072                                 enumcounter += 'i';
1073                         case 1:
1074                                 enumcounter += 'i';
1075                         case 0:
1076                                 enumcounter += 'i';
1077                                 break;
1078                         case 3:
1079                                 enumcounter += "iv";
1080                                 break;
1081                         default:
1082                                 // not a valid enumdepth...
1083                                 break;
1084                         }
1085
1086                         textclass.counters().step(enumcounter);
1087
1088                         s << textclass.counters()
1089                                 .numberLabel(enumcounter, "enumeration");
1090                         pit->params().labelString(STRCONV(s.str()));
1091                 }
1092         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
1093                 textclass.counters().step("bibitem");
1094                 int number = textclass.counters().value("bibitem");
1095                 if (pit->bibitem()) {
1096                         pit->bibitem()->setCounter(number);
1097                         pit->params().labelString(layout->labelstring());
1098                 }
1099                 // In biblio should't be following counters but...
1100         } else {
1101                 string s = buf->B_(layout->labelstring());
1102
1103                 // the caption hack:
1104                 if (layout->labeltype == LABEL_SENSITIVE) {
1105                         ParagraphList::iterator end = ownerParagraphs().end();
1106                         ParagraphList::iterator tmppit = pit;
1107                         InsetOld * in = 0;
1108                         bool isOK = false;
1109                         while (tmppit != end && tmppit->inInset()
1110                                // the single '=' is intended below
1111                                && (in = tmppit->inInset()->owner()))
1112                         {
1113                                 if (in->lyxCode() == InsetOld::FLOAT_CODE ||
1114                                     in->lyxCode() == InsetOld::WRAP_CODE) {
1115                                         isOK = true;
1116                                         break;
1117                                 } else {
1118                                         tmppit = ownerParagraphs().begin();
1119                                         for ( ; tmppit != end; ++tmppit)
1120                                                 if (&*tmppit == in->parOwner())
1121                                                         break;
1122                                 }
1123                         }
1124
1125                         if (isOK) {
1126                                 string type;
1127
1128                                 if (in->lyxCode() == InsetOld::FLOAT_CODE)
1129                                         type = static_cast<InsetFloat*>(in)->params().type;
1130                                 else if (in->lyxCode() == InsetOld::WRAP_CODE)
1131                                         type = static_cast<InsetWrap*>(in)->params().type;
1132                                 else
1133                                         Assert(0);
1134
1135                                 Floating const & fl = textclass.floats().getType(type);
1136
1137                                 textclass.counters().step(fl.type());
1138
1139                                 // Doesn't work... yet.
1140                                 s = bformat(_("%1$s #:"), buf->B_(fl.name()));
1141                         } else {
1142                                 // par->SetLayout(0);
1143                                 // s = layout->labelstring;
1144                                 s = _("Senseless: ");
1145                         }
1146                 }
1147                 pit->params().labelString(s);
1148
1149                 // reset the enumeration counter. They are always reset
1150                 // when there is any other layout between
1151                 // Just fall-through between the cases so that all
1152                 // enum counters deeper than enumdepth is also reset.
1153                 switch (pit->enumdepth) {
1154                 case 0:
1155                         textclass.counters().reset("enumi");
1156                 case 1:
1157                         textclass.counters().reset("enumii");
1158                 case 2:
1159                         textclass.counters().reset("enumiii");
1160                 case 3:
1161                         textclass.counters().reset("enumiv");
1162                 }
1163         }
1164 }
1165
1166
1167 // Updates all counters. Paragraphs with changed label string will be rebroken
1168 void LyXText::updateCounters()
1169 {
1170         RowList::iterator rowit = rows().begin();
1171         ParagraphList::iterator pit = rowit->par();
1172
1173         // CHECK if this is really needed. (Lgb)
1174         bv()->buffer()->params.getLyXTextClass().counters().reset();
1175
1176         ParagraphList::iterator beg = ownerParagraphs().begin();
1177         ParagraphList::iterator end = ownerParagraphs().end();
1178         for (; pit != end; ++pit) {
1179                 while (rowit->par() != pit)
1180                         ++rowit;
1181
1182                 string const oldLabel = pit->params().labelString();
1183
1184                 size_t maxdepth = 0;
1185                 if (pit != beg)
1186                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1187
1188                 if (pit->params().depth() > maxdepth)
1189                         pit->params().depth(maxdepth);
1190
1191                 // setCounter can potentially change the labelString.
1192                 setCounter(bv()->buffer(), pit);
1193
1194                 string const & newLabel = pit->params().labelString();
1195
1196                 if (oldLabel.empty() && !newLabel.empty()) {
1197                         removeParagraph(rowit);
1198                         appendParagraph(rowit);
1199                 }
1200         }
1201 }
1202
1203
1204 void LyXText::insertInset(InsetOld * inset)
1205 {
1206         if (!cursor.par()->insetAllowed(inset->lyxCode()))
1207                 return;
1208         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1209         freezeUndo();
1210         cursor.par()->insertInset(cursor.pos(), inset);
1211         // Just to rebreak and refresh correctly.
1212         // The character will not be inserted a second time
1213         insertChar(Paragraph::META_INSET);
1214         // If we enter a highly editable inset the cursor should be to before
1215         // the inset. This couldn't happen before as Undo was not handled inside
1216         // inset now after the Undo LyX tries to call inset->Edit(...) again
1217         // and cannot do this as the cursor is behind the inset and GetInset
1218         // does not return the inset!
1219         if (isHighlyEditableInset(inset)) {
1220                 cursorLeft(true);
1221         }
1222         unFreezeUndo();
1223 }
1224
1225
1226 void LyXText::cutSelection(bool doclear, bool realcut)
1227 {
1228         // Stuff what we got on the clipboard. Even if there is no selection.
1229
1230         // There is a problem with having the stuffing here in that the
1231         // larger the selection the slower LyX will get. This can be
1232         // solved by running the line below only when the selection has
1233         // finished. The solution used currently just works, to make it
1234         // faster we need to be more clever and probably also have more
1235         // calls to stuffClipboard. (Lgb)
1236         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1237
1238         // This doesn't make sense, if there is no selection
1239         if (!selection.set())
1240                 return;
1241
1242         // OK, we have a selection. This is always between selection.start
1243         // and selection.end
1244
1245         // make sure that the depth behind the selection are restored, too
1246         ParagraphList::iterator endpit = boost::next(selection.end.par());
1247         ParagraphList::iterator undoendpit = endpit;
1248         ParagraphList::iterator pars_end = ownerParagraphs().end();
1249
1250         if (endpit != pars_end && endpit->getDepth()) {
1251                 while (endpit != pars_end && endpit->getDepth()) {
1252                         ++endpit;
1253                         undoendpit = endpit;
1254                 }
1255         } else if (endpit != pars_end) {
1256                 // because of parindents etc.
1257                 ++endpit;
1258         }
1259
1260         recordUndo(bv(), Undo::DELETE, selection.start.par(),
1261                 boost::prior(undoendpit));
1262
1263
1264         endpit = selection.end.par();
1265         int endpos = selection.end.pos();
1266
1267         boost::tie(endpit, endpos) = realcut ?
1268                 CutAndPaste::cutSelection(bv()->buffer()->params,
1269                                           ownerParagraphs(),
1270                                           selection.start.par(), endpit,
1271                                           selection.start.pos(), endpos,
1272                                           bv()->buffer()->params.textclass,
1273                                           doclear)
1274                 : CutAndPaste::eraseSelection(bv()->buffer()->params,
1275                                               ownerParagraphs(),
1276                                               selection.start.par(), endpit,
1277                                               selection.start.pos(), endpos,
1278                                               doclear);
1279         // sometimes necessary
1280         if (doclear)
1281                 selection.start.par()->stripLeadingSpaces();
1282
1283         redoParagraphs(selection.start.par(), boost::next(endpit));
1284 #warning FIXME latent bug
1285         // endpit will be invalidated on redoParagraphs once ParagraphList
1286         // becomes a std::list? There are maybe other places on which this
1287         // can happend? (Ab)
1288         // cutSelection can invalidate the cursor so we need to set
1289         // it anew. (Lgb)
1290         // we prefer the end for when tracking changes
1291         cursor.pos(endpos);
1292         cursor.par(endpit);
1293
1294         // need a valid cursor. (Lgb)
1295         clearSelection();
1296
1297         setCursor(cursor.par(), cursor.pos());
1298         selection.cursor = cursor;
1299         updateCounters();
1300 }
1301
1302
1303 void LyXText::copySelection()
1304 {
1305         // stuff the selection onto the X clipboard, from an explicit copy request
1306         bv()->stuffClipboard(selectionAsString(bv()->buffer(), true));
1307
1308         // this doesnt make sense, if there is no selection
1309         if (!selection.set())
1310                 return;
1311
1312         // ok we have a selection. This is always between selection.start
1313         // and sel_end cursor
1314
1315         // copy behind a space if there is one
1316         while (selection.start.par()->size() > selection.start.pos()
1317                && selection.start.par()->isLineSeparator(selection.start.pos())
1318                && (selection.start.par() != selection.end.par()
1319                    || selection.start.pos() < selection.end.pos()))
1320                 selection.start.pos(selection.start.pos() + 1);
1321
1322         CutAndPaste::copySelection(selection.start.par(),
1323                                    selection.end.par(),
1324                                    selection.start.pos(), selection.end.pos(),
1325                                    bv()->buffer()->params.textclass);
1326 }
1327
1328
1329 void LyXText::pasteSelection(size_t sel_index)
1330 {
1331         // this does not make sense, if there is nothing to paste
1332         if (!CutAndPaste::checkPastePossible())
1333                 return;
1334
1335         recordUndo(bv(), Undo::INSERT, cursor.par());
1336
1337         ParagraphList::iterator endpit;
1338         PitPosPair ppp;
1339
1340         ErrorList el;
1341
1342         boost::tie(ppp, endpit) =
1343                 CutAndPaste::pasteSelection(*bv()->buffer(),
1344                                             ownerParagraphs(),
1345                                             cursor.par(), cursor.pos(),
1346                                             bv()->buffer()->params.textclass,
1347                                             sel_index, el);
1348         bufferErrors(*bv()->buffer(), el);
1349         bv()->showErrorList(_("Paste"));
1350
1351         redoParagraphs(cursor.par(), endpit);
1352
1353         setCursor(cursor.par(), cursor.pos());
1354         clearSelection();
1355
1356         selection.cursor = cursor;
1357         setCursor(ppp.first, ppp.second);
1358         setSelection();
1359         updateCounters();
1360 }
1361
1362
1363 void LyXText::setSelectionRange(lyx::pos_type length)
1364 {
1365         if (!length)
1366                 return;
1367
1368         selection.cursor = cursor;
1369         while (length--)
1370                 cursorRight(bv());
1371         setSelection();
1372 }
1373
1374
1375 // simple replacing. The font of the first selected character is used
1376 void LyXText::replaceSelectionWithString(string const & str)
1377 {
1378         recordUndo(bv(), Undo::ATOMIC);
1379         freezeUndo();
1380
1381         if (!selection.set()) { // create a dummy selection
1382                 selection.end = cursor;
1383                 selection.start = cursor;
1384         }
1385
1386         // Get font setting before we cut
1387         pos_type pos = selection.end.pos();
1388         LyXFont const font = selection.start.par()
1389                 ->getFontSettings(bv()->buffer()->params,
1390                                   selection.start.pos());
1391
1392         // Insert the new string
1393         string::const_iterator cit = str.begin();
1394         string::const_iterator end = str.end();
1395         for (; cit != end; ++cit) {
1396                 selection.end.par()->insertChar(pos, (*cit), font);
1397                 ++pos;
1398         }
1399
1400         // Cut the selection
1401         cutSelection(true, false);
1402
1403         unFreezeUndo();
1404 }
1405
1406
1407 // needed to insert the selection
1408 void LyXText::insertStringAsLines(string const & str)
1409 {
1410         ParagraphList::iterator pit = cursor.par();
1411         pos_type pos = cursor.pos();
1412         ParagraphList::iterator endpit = boost::next(cursor.par());
1413
1414         recordUndo(bv(), Undo::ATOMIC);
1415
1416         // only to be sure, should not be neccessary
1417         clearSelection();
1418
1419         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1420
1421         redoParagraphs(cursor.par(), endpit);
1422         setCursor(cursor.par(), cursor.pos());
1423         selection.cursor = cursor;
1424         setCursor(pit, pos);
1425         setSelection();
1426 }
1427
1428
1429 // turns double-CR to single CR, others where converted into one
1430 // blank. Then InsertStringAsLines is called
1431 void LyXText::insertStringAsParagraphs(string const & str)
1432 {
1433         string linestr(str);
1434         bool newline_inserted = false;
1435         string::size_type const siz = linestr.length();
1436
1437         for (string::size_type i = 0; i < siz; ++i) {
1438                 if (linestr[i] == '\n') {
1439                         if (newline_inserted) {
1440                                 // we know that \r will be ignored by
1441                                 // InsertStringA. Of course, it is a dirty
1442                                 // trick, but it works...
1443                                 linestr[i - 1] = '\r';
1444                                 linestr[i] = '\n';
1445                         } else {
1446                                 linestr[i] = ' ';
1447                                 newline_inserted = true;
1448                         }
1449                 } else if (IsPrintable(linestr[i])) {
1450                         newline_inserted = false;
1451                 }
1452         }
1453         insertStringAsLines(linestr);
1454 }
1455
1456
1457 void LyXText::checkParagraph(ParagraphList::iterator pit, pos_type pos)
1458 {
1459         breakAgain(getRow(pit, pos));
1460         setCursorIntern(cursor.par(), cursor.pos(), false, cursor.boundary());
1461 }
1462
1463
1464 // returns false if inset wasn't found
1465 bool LyXText::updateInset(InsetOld * inset)
1466 {
1467         // first check the current paragraph
1468         int pos = cursor.par()->getPositionOfInset(inset);
1469         if (pos != -1) {
1470                 checkParagraph(cursor.par(), pos);
1471                 return true;
1472         }
1473
1474         // check every paragraph
1475         ParagraphList::iterator par = ownerParagraphs().begin();
1476         ParagraphList::iterator end = ownerParagraphs().end();
1477         for (; par != end; ++par) {
1478                 pos = par->getPositionOfInset(inset);
1479                 if (pos != -1) {
1480                         checkParagraph(par, pos);
1481                         return true;
1482                 }
1483         }
1484
1485         return false;
1486 }
1487
1488
1489 bool LyXText::setCursor(ParagraphList::iterator pit,
1490                         pos_type pos,
1491                         bool setfont, bool boundary)
1492 {
1493         LyXCursor old_cursor = cursor;
1494         setCursorIntern(pit, pos, setfont, boundary);
1495         return deleteEmptyParagraphMechanism(old_cursor);
1496 }
1497
1498
1499 void LyXText::setCursor(LyXCursor & cur, ParagraphList::iterator pit,
1500                         pos_type pos, bool boundary)
1501 {
1502         Assert(pit != ownerParagraphs().end());
1503
1504         cur.par(pit);
1505         cur.pos(pos);
1506         cur.boundary(boundary);
1507         if (rows().empty())
1508                 return;
1509
1510         // get the cursor y position in text
1511         int y = 0;
1512         RowList::iterator row = getRow(pit, pos, y);
1513         RowList::iterator beg = rows().begin();
1514
1515         RowList::iterator old_row = row;
1516         // if we are before the first char of this row and are still in the
1517         // same paragraph and there is a previous row then put the cursor on
1518         // the end of the previous row
1519         cur.iy(y + row->baseline());
1520         if (row != beg &&
1521             pos &&
1522             boost::prior(row)->par() == row->par() &&
1523             pos < pit->size() &&
1524             pit->getChar(pos) == Paragraph::META_INSET) {
1525                 InsetOld * ins = pit->getInset(pos);
1526                 if (ins && (ins->needFullRow() || ins->display())) {
1527                         --row;
1528                         y -= row->height();
1529                 }
1530         }
1531
1532         // y is now the beginning of the cursor row
1533         y += row->baseline();
1534         // y is now the cursor baseline
1535         cur.y(y);
1536
1537         pos_type last = lastPrintablePos(*this, old_row);
1538
1539         // None of these should happen, but we're scaredy-cats
1540         if (pos > pit->size()) {
1541                 lyxerr << "dont like 1 please report" << endl;
1542                 pos = 0;
1543                 cur.pos(0);
1544         } else if (pos > last + 1) {
1545                 lyxerr << "dont like 2 please report" << endl;
1546                 // This shouldn't happen.
1547                 pos = last + 1;
1548                 cur.pos(pos);
1549         } else if (pos < row->pos()) {
1550                 lyxerr << "dont like 3 please report" << endl;
1551                 pos = row->pos();
1552                 cur.pos(pos);
1553         }
1554
1555         // now get the cursors x position
1556         float x = getCursorX(row, pos, last, boundary);
1557         cur.x(int(x));
1558         cur.x_fix(cur.x());
1559         if (old_row != row) {
1560                 x = getCursorX(old_row, pos, last, boundary);
1561                 cur.ix(int(x));
1562         } else
1563                 cur.ix(cur.x());
1564 /* We take out this for the time being because 1) the redraw code is not
1565    prepared to this yet and 2) because some good policy has yet to be decided
1566    while editting: for instance how to act on rows being created/deleted
1567    because of DEPM.
1568 */
1569 #if 0
1570         //if the cursor is in a visible row, anchor to it
1571         int topy = top_y();
1572         if (topy < y && y < topy + bv()->workHeight())
1573                 anchor_row(row);
1574 #endif
1575 }
1576
1577
1578 float LyXText::getCursorX(RowList::iterator rit,
1579                           pos_type pos, pos_type last, bool boundary) const
1580 {
1581         pos_type cursor_vpos = 0;
1582         double x;
1583         double fill_separator;
1584         double fill_hfill;
1585         double fill_label_hfill;
1586         // This call HAS to be here because of the BidiTables!!!
1587         prepareToPrint(rit, x, fill_separator, fill_hfill,
1588                        fill_label_hfill);
1589
1590         ParagraphList::iterator rit_par = rit->par();
1591         pos_type const rit_pos = rit->pos();
1592
1593         if (last < rit_pos)
1594                 cursor_vpos = rit_pos;
1595         else if (pos > last && !boundary)
1596                 cursor_vpos = (rit_par->isRightToLeftPar(bv()->buffer()->params))
1597                         ? rit_pos : last + 1;
1598         else if (pos > rit_pos && (pos > last || boundary))
1599                 /// Place cursor after char at (logical) position pos - 1
1600                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1601                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1602         else
1603                 /// Place cursor before char at (logical) position pos
1604                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1605                         ? log2vis(pos) : log2vis(pos) + 1;
1606
1607         pos_type body_pos = rit_par->beginningOfBody();
1608         if (body_pos > 0 &&
1609             (body_pos - 1 > last || !rit_par->isLineSeparator(body_pos - 1)))
1610                 body_pos = 0;
1611
1612         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1613                 pos_type pos = vis2log(vpos);
1614                 if (body_pos > 0 && pos == body_pos - 1) {
1615                         x += fill_label_hfill +
1616                                 font_metrics::width(
1617                                         rit_par->layout()->labelsep, getLabelFont(rit_par));
1618                         if (rit_par->isLineSeparator(body_pos - 1))
1619                                 x -= singleWidth(rit_par, body_pos - 1);
1620                 }
1621
1622                 if (hfillExpansion(*this, rit, pos)) {
1623                         x += singleWidth(rit_par, pos);
1624                         if (pos >= body_pos)
1625                                 x += fill_hfill;
1626                         else
1627                                 x += fill_label_hfill;
1628                 } else if (rit_par->isSeparator(pos)) {
1629                         x += singleWidth(rit_par, pos);
1630                         if (pos >= body_pos)
1631                                 x += fill_separator;
1632                 } else
1633                         x += singleWidth(rit_par, pos);
1634         }
1635         return x;
1636 }
1637
1638
1639 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1640                               pos_type pos, bool setfont, bool boundary)
1641 {
1642         UpdatableInset * it = pit->inInset();
1643         if (it) {
1644                 if (it != inset_owner) {
1645                         lyxerr[Debug::INSETS] << "InsetText   is " << it
1646                                               << endl
1647                                               << "inset_owner is "
1648                                               << inset_owner << endl;
1649 #ifdef WITH_WARNINGS
1650 #warning I believe this code is wrong. (Lgb)
1651 #warning Jürgen, have a look at this. (Lgb)
1652 #warning Hmmm, I guess you are right but we
1653 #warning should verify when this is needed
1654 #endif
1655                         // Jürgen, would you like to have a look?
1656                         // I guess we need to move the outer cursor
1657                         // and open and lock the inset (bla bla bla)
1658                         // stuff I don't know... so can you have a look?
1659                         // (Lgb)
1660                         // I moved the lyxerr stuff in here so we can see if
1661                         // this is actually really needed and where!
1662                         // (Jug)
1663                         // it->getLyXText(bv())->setCursorIntern(bv(), par, pos, setfont, boundary);
1664                         return;
1665                 }
1666         }
1667
1668         setCursor(cursor, pit, pos, boundary);
1669         if (setfont)
1670                 setCurrentFont();
1671 }
1672
1673
1674 void LyXText::setCurrentFont()
1675 {
1676         pos_type pos = cursor.pos();
1677         ParagraphList::iterator pit = cursor.par();
1678
1679         if (cursor.boundary() && pos > 0)
1680                 --pos;
1681
1682         if (pos > 0) {
1683                 if (pos == pit->size())
1684                         --pos;
1685                 else // potentional bug... BUG (Lgb)
1686                         if (pit->isSeparator(pos)) {
1687                                 if (pos > cursorRow()->pos() &&
1688                                     bidi_level(pos) % 2 ==
1689                                     bidi_level(pos - 1) % 2)
1690                                         --pos;
1691                                 else if (pos + 1 < pit->size())
1692                                         ++pos;
1693                         }
1694         }
1695
1696         current_font = pit->getFontSettings(bv()->buffer()->params, pos);
1697         real_current_font = getFont(pit, pos);
1698
1699         if (cursor.pos() == pit->size() &&
1700             isBoundary(bv()->buffer(), *pit, cursor.pos()) &&
1701             !cursor.boundary()) {
1702                 Language const * lang =
1703                         pit->getParLanguage(bv()->buffer()->params);
1704                 current_font.setLanguage(lang);
1705                 current_font.setNumber(LyXFont::OFF);
1706                 real_current_font.setLanguage(lang);
1707                 real_current_font.setNumber(LyXFont::OFF);
1708         }
1709 }
1710
1711
1712 // returns the column near the specified x-coordinate of the row
1713 // x is set to the real beginning of this column
1714 pos_type
1715 LyXText::getColumnNearX(RowList::iterator rit, int & x, bool & boundary) const
1716 {
1717         double tmpx = 0;
1718         double fill_separator;
1719         double fill_hfill;
1720         double fill_label_hfill;
1721
1722         prepareToPrint(rit, tmpx, fill_separator, fill_hfill, fill_label_hfill);
1723
1724         pos_type vc = rit->pos();
1725         pos_type last = lastPrintablePos(*this, rit);
1726         pos_type c = 0;
1727
1728         ParagraphList::iterator rit_par = rit->par();
1729         LyXLayout_ptr const & layout = rit->par()->layout();
1730
1731         bool left_side = false;
1732
1733         pos_type body_pos = rit_par->beginningOfBody();
1734         double last_tmpx = tmpx;
1735
1736         if (body_pos > 0 &&
1737             (body_pos - 1 > last ||
1738              !rit_par->isLineSeparator(body_pos - 1)))
1739                 body_pos = 0;
1740
1741         // check for empty row
1742         if (!rit_par->size()) {
1743                 x = int(tmpx);
1744                 return 0;
1745         }
1746
1747         while (vc <= last && tmpx <= x) {
1748                 c = vis2log(vc);
1749                 last_tmpx = tmpx;
1750                 if (body_pos > 0 && c == body_pos - 1) {
1751                         tmpx += fill_label_hfill +
1752                                 font_metrics::width(layout->labelsep, getLabelFont(rit_par));
1753                         if (rit_par->isLineSeparator(body_pos - 1))
1754                                 tmpx -= singleWidth(rit_par, body_pos - 1);
1755                 }
1756
1757                 if (hfillExpansion(*this, rit, c)) {
1758                         tmpx += singleWidth(rit_par, c);
1759                         if (c >= body_pos)
1760                                 tmpx += fill_hfill;
1761                         else
1762                                 tmpx += fill_label_hfill;
1763                 } else if (rit_par->isSeparator(c)) {
1764                         tmpx += singleWidth(rit_par, c);
1765                         if (c >= body_pos)
1766                                 tmpx += fill_separator;
1767                 } else {
1768                         tmpx += singleWidth(rit_par, c);
1769                 }
1770                 ++vc;
1771         }
1772
1773         if ((tmpx + last_tmpx) / 2 > x) {
1774                 tmpx = last_tmpx;
1775                 left_side = true;
1776         }
1777
1778         if (vc > last + 1)  // This shouldn't happen.
1779                 vc = last + 1;
1780
1781         boundary = false;
1782         // This (rtl_support test) is not needed, but gives
1783         // some speedup if rtl_support=false
1784         RowList::iterator next_rit = boost::next(rit);
1785
1786         bool const lastrow = lyxrc.rtl_support &&
1787                 (next_rit == rowlist_.end() ||
1788                  next_rit->par() != rit_par);
1789
1790         // If lastrow is false, we don't need to compute
1791         // the value of rtl.
1792         bool const rtl = (lastrow)
1793                 ? rit_par->isRightToLeftPar(bv()->buffer()->params)
1794                 : false;
1795         if (lastrow &&
1796                  ((rtl &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1797                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1798                 c = last + 1;
1799         else if (vc == rit->pos()) {
1800                 c = vis2log(vc);
1801                 if (bidi_level(c) % 2 == 1)
1802                         ++c;
1803         } else {
1804                 c = vis2log(vc - 1);
1805                 bool const rtl = (bidi_level(c) % 2 == 1);
1806                 if (left_side == rtl) {
1807                         ++c;
1808                         boundary = isBoundary(bv()->buffer(), *rit_par, c);
1809                 }
1810         }
1811
1812         if (rit->pos() <= last && c > last
1813             && rit_par->isNewline(last)) {
1814                 if (bidi_level(last) % 2 == 0)
1815                         tmpx -= singleWidth(rit_par, last);
1816                 else
1817                         tmpx += singleWidth(rit_par, last);
1818                 c = last;
1819         }
1820
1821         c -= rit->pos();
1822         x = int(tmpx);
1823         return c;
1824 }
1825
1826
1827 void LyXText::setCursorFromCoordinates(int x, int y)
1828 {
1829         //LyXCursor old_cursor = cursor;
1830         setCursorFromCoordinates(cursor, x, y);
1831         setCurrentFont();
1832 #warning DEPM disabled, otherwise crash when entering new table
1833         //deleteEmptyParagraphMechanism(old_cursor);
1834 }
1835
1836
1837 namespace {
1838
1839         /**
1840          * return true if the cursor given is at the end of a row,
1841          * and the next row is filled by an inset that spans an entire
1842          * row.
1843          */
1844         bool beforeFullRowInset(LyXText & lt, LyXCursor const & cur)
1845         {
1846                 RowList::iterator row = lt.getRow(cur);
1847                 if (boost::next(row) == lt.rows().end())
1848                         return false;
1849
1850                 Row const & next = *boost::next(row);
1851
1852                 if (next.pos() != cur.pos() || next.par() != cur.par())
1853                         return false;
1854
1855                 if (cur.pos() == cur.par()->size()
1856                     || !cur.par()->isInset(cur.pos()))
1857                         return false;
1858
1859                 InsetOld const * inset = cur.par()->getInset(cur.pos());
1860                 if (inset->needFullRow() || inset->display())
1861                         return true;
1862
1863                 return false;
1864         }
1865 }
1866
1867
1868 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1869 {
1870         // Get the row first.
1871
1872         RowList::iterator row = getRowNearY(y);
1873         bool bound = false;
1874         pos_type const column = getColumnNearX(row, x, bound);
1875         cur.par(row->par());
1876         cur.pos(row->pos() + column);
1877         cur.x(x);
1878         cur.y(y + row->baseline());
1879
1880         if (beforeFullRowInset(*this, cur)) {
1881                 pos_type const last = lastPrintablePos(*this, row);
1882                 RowList::iterator next_row = boost::next(row);
1883
1884                 float x = getCursorX(next_row, cur.pos(), last, bound);
1885                 cur.ix(int(x));
1886                 cur.iy(y + row->height() + next_row->baseline());
1887         } else {
1888                 cur.iy(cur.y());
1889                 cur.ix(cur.x());
1890         }
1891         cur.boundary(bound);
1892 }
1893
1894
1895 void LyXText::cursorLeft(bool internal)
1896 {
1897         if (cursor.pos() > 0) {
1898                 bool boundary = cursor.boundary();
1899                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1900                 if (!internal && !boundary &&
1901                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos() + 1))
1902                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1903         } else if (cursor.par() != ownerParagraphs().begin()) {
1904                 // steps into the paragraph above
1905                 ParagraphList::iterator pit = boost::prior(cursor.par());
1906                 setCursor(pit, pit->size());
1907         }
1908 }
1909
1910
1911 void LyXText::cursorRight(bool internal)
1912 {
1913         bool const at_end = (cursor.pos() == cursor.par()->size());
1914         bool const at_newline = !at_end &&
1915                 cursor.par()->isNewline(cursor.pos());
1916
1917         if (!internal && cursor.boundary() && !at_newline)
1918                 setCursor(cursor.par(), cursor.pos(), true, false);
1919         else if (!at_end) {
1920                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1921                 if (!internal &&
1922                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos()))
1923                         setCursor(cursor.par(), cursor.pos(), true, true);
1924         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
1925                 setCursor(boost::next(cursor.par()), 0);
1926 }
1927
1928
1929 void LyXText::cursorUp(bool selecting)
1930 {
1931 #if 1
1932         int x = cursor.x_fix();
1933         int y = cursor.y() - cursorRow()->baseline() - 1;
1934         setCursorFromCoordinates(x, y);
1935         if (!selecting) {
1936                 int topy = top_y();
1937                 int y1 = cursor.iy() - topy;
1938                 int y2 = y1;
1939                 y -= topy;
1940                 InsetOld * inset_hit = checkInsetHit(x, y1);
1941                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1942                         inset_hit->localDispatch(
1943                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1944                 }
1945         }
1946 #else
1947         setCursorFromCoordinates(bv(), cursor.x_fix(),
1948                                  cursor.y() - cursorRow()->baseline() - 1);
1949 #endif
1950 }
1951
1952
1953 void LyXText::cursorDown(bool selecting)
1954 {
1955 #if 1
1956         int x = cursor.x_fix();
1957         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1958         setCursorFromCoordinates(x, y);
1959         if (!selecting && cursorRow() == cursorIRow()) {
1960                 int topy = top_y();
1961                 int y1 = cursor.iy() - topy;
1962                 int y2 = y1;
1963                 y -= topy;
1964                 InsetOld * inset_hit = checkInsetHit(x, y1);
1965                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1966                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
1967                         inset_hit->localDispatch(cmd);
1968                 }
1969         }
1970 #else
1971         setCursorFromCoordinates(bv(), cursor.x_fix(),
1972                                  cursor.y() - cursorRow()->baseline()
1973                                  + cursorRow()->height() + 1);
1974 #endif
1975 }
1976
1977
1978 void LyXText::cursorUpParagraph()
1979 {
1980         if (cursor.pos() > 0)
1981                 setCursor(cursor.par(), 0);
1982         else if (cursor.par() != ownerParagraphs().begin())
1983                 setCursor(boost::prior(cursor.par()), 0);
1984 }
1985
1986
1987 void LyXText::cursorDownParagraph()
1988 {
1989         ParagraphList::iterator par = cursor.par();
1990         ParagraphList::iterator next_par = boost::next(par);
1991
1992         if (next_par != ownerParagraphs().end())
1993                 setCursor(next_par, 0);
1994         else
1995                 setCursor(par, par->size());
1996 }
1997
1998
1999 // fix the cursor `cur' after a characters has been deleted at `where'
2000 // position. Called by deleteEmptyParagraphMechanism
2001 void LyXText::fixCursorAfterDelete(LyXCursor & cur,
2002                                    LyXCursor const & where)
2003 {
2004         // if cursor is not in the paragraph where the delete occured,
2005         // do nothing
2006         if (cur.par() != where.par())
2007                 return;
2008
2009         // if cursor position is after the place where the delete occured,
2010         // update it
2011         if (cur.pos() > where.pos())
2012                 cur.pos(cur.pos()-1);
2013
2014         // check also if we don't want to set the cursor on a spot behind the
2015         // pagragraph because we erased the last character.
2016         if (cur.pos() > cur.par()->size())
2017                 cur.pos(cur.par()->size());
2018
2019         // recompute row et al. for this cursor
2020         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
2021 }
2022
2023
2024 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
2025 {
2026         // Would be wrong to delete anything if we have a selection.
2027         if (selection.set())
2028                 return false;
2029
2030         // We allow all kinds of "mumbo-jumbo" when freespacing.
2031         if (old_cursor.par()->layout()->free_spacing
2032             || old_cursor.par()->isFreeSpacing()) {
2033                 return false;
2034         }
2035
2036         /* Ok I'll put some comments here about what is missing.
2037            I have fixed BackSpace (and thus Delete) to not delete
2038            double-spaces automagically. I have also changed Cut,
2039            Copy and Paste to hopefully do some sensible things.
2040            There are still some small problems that can lead to
2041            double spaces stored in the document file or space at
2042            the beginning of paragraphs. This happens if you have
2043            the cursor betwenn to spaces and then save. Or if you
2044            cut and paste and the selection have a space at the
2045            beginning and then save right after the paste. I am
2046            sure none of these are very hard to fix, but I will
2047            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
2048            that I can get some feedback. (Lgb)
2049         */
2050
2051         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
2052         // delete the LineSeparator.
2053         // MISSING
2054
2055         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
2056         // delete the LineSeparator.
2057         // MISSING
2058
2059         // If the pos around the old_cursor were spaces, delete one of them.
2060         if (old_cursor.par() != cursor.par()
2061             || old_cursor.pos() != cursor.pos()) {
2062                 // Only if the cursor has really moved
2063
2064                 if (old_cursor.pos() > 0
2065                     && old_cursor.pos() < old_cursor.par()->size()
2066                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
2067                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
2068                         old_cursor.par()->erase(old_cursor.pos() - 1);
2069                         redoParagraph(old_cursor.par());
2070
2071 #ifdef WITH_WARNINGS
2072 #warning This will not work anymore when we have multiple views of the same buffer
2073 // In this case, we will have to correct also the cursors held by
2074 // other bufferviews. It will probably be easier to do that in a more
2075 // automated way in LyXCursor code. (JMarc 26/09/2001)
2076 #endif
2077                         // correct all cursors held by the LyXText
2078                         fixCursorAfterDelete(cursor, old_cursor);
2079                         fixCursorAfterDelete(selection.cursor, old_cursor);
2080                         fixCursorAfterDelete(selection.start, old_cursor);
2081                         fixCursorAfterDelete(selection.end, old_cursor);
2082                         fixCursorAfterDelete(last_sel_cursor, old_cursor);
2083                         return false;
2084                 }
2085         }
2086
2087         // don't delete anything if this is the ONLY paragraph!
2088         if (ownerParagraphs().size() == 1)
2089                 return false;
2090
2091         // Do not delete empty paragraphs with keepempty set.
2092         if (old_cursor.par()->allowEmpty())
2093                 return false;
2094
2095         // only do our magic if we changed paragraph
2096         if (old_cursor.par() == cursor.par())
2097                 return false;
2098
2099         // record if we have deleted a paragraph
2100         // we can't possibly have deleted a paragraph before this point
2101         bool deleted = false;
2102
2103         if (old_cursor.par()->empty() ||
2104             (old_cursor.par()->size() == 1 &&
2105              old_cursor.par()->isLineSeparator(0))) {
2106                 // ok, we will delete anything
2107                 LyXCursor tmpcursor;
2108
2109                 deleted = true;
2110
2111                 bool selection_position_was_oldcursor_position = (
2112                         selection.cursor.par()  == old_cursor.par()
2113                         && selection.cursor.pos() == old_cursor.pos());
2114
2115                 if (getRow(old_cursor) != rows().begin()) {
2116                         RowList::iterator prevrow = boost::prior(getRow(old_cursor));
2117                         tmpcursor = cursor;
2118                         cursor = old_cursor; // that undo can restore the right cursor position
2119                         #warning FIXME. --end() iterator is usable here
2120                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2121                         while (endpit != ownerParagraphs().end() &&
2122                                endpit->getDepth()) {
2123                                 ++endpit;
2124                         }
2125
2126                         recordUndo(bv(), Undo::DELETE, old_cursor.par(),
2127                                 boost::prior(endpit));
2128                         cursor = tmpcursor;
2129
2130                         // delete old row
2131                         removeRow(getRow(old_cursor));
2132                         // delete old par
2133                         ownerParagraphs().erase(old_cursor.par());
2134
2135                         /* Breakagain the next par. Needed because of
2136                          * the parindent that can occur or dissappear.
2137                          * The next row can change its height, if
2138                          * there is another layout before */
2139                         RowList::iterator tmprit = boost::next(prevrow);
2140                         if (tmprit != rows().end()) {
2141                                 breakAgain(tmprit);
2142                                 updateCounters();
2143                         }
2144                         setHeightOfRow(prevrow);
2145                 } else {
2146                         RowList::iterator nextrow = boost::next(getRow(old_cursor));
2147
2148                         tmpcursor = cursor;
2149                         cursor = old_cursor; // that undo can restore the right cursor position
2150 #warning FIXME. --end() iterator is usable here
2151                         ParagraphList::iterator endpit = boost::next(old_cursor.par());
2152                         while (endpit != ownerParagraphs().end() &&
2153                                endpit->getDepth()) {
2154                                 ++endpit;
2155                         }
2156
2157                         recordUndo(bv(), Undo::DELETE, old_cursor.par(), boost::prior(endpit));
2158                         cursor = tmpcursor;
2159
2160                         // delete old row
2161                         removeRow(getRow(old_cursor));
2162                         // delete old par
2163                         ownerParagraphs().erase(old_cursor.par());
2164
2165                         /* Breakagain the next par. Needed because of
2166                            the parindent that can occur or dissappear.
2167                            The next row can change its height, if
2168                            there is another layout before */
2169                         if (nextrow != rows().end()) {
2170                                 breakAgain(nextrow);
2171                                 updateCounters();
2172                         }
2173                 }
2174
2175                 // correct cursor y
2176                 setCursorIntern(cursor.par(), cursor.pos());
2177
2178                 if (selection_position_was_oldcursor_position) {
2179                         // correct selection
2180                         selection.cursor = cursor;
2181                 }
2182         }
2183         if (!deleted) {
2184                 if (old_cursor.par()->stripLeadingSpaces()) {
2185                         redoParagraph(old_cursor.par());
2186                         // correct cursor y
2187                         setCursorIntern(cursor.par(), cursor.pos());
2188                         selection.cursor = cursor;
2189                 }
2190         }
2191         return deleted;
2192 }
2193
2194
2195 ParagraphList & LyXText::ownerParagraphs() const
2196 {
2197         if (inset_owner) {
2198                 return inset_owner->paragraphs;
2199         }
2200         return bv_owner->buffer()->paragraphs;
2201 }
2202
2203
2204 bool LyXText::isInInset() const
2205 {
2206         // Sub-level has non-null bv owner and
2207         // non-null inset owner.
2208         return inset_owner != 0 && bv_owner != 0;
2209 }
2210
2211
2212 int defaultRowHeight()
2213 {
2214         LyXFont const font(LyXFont::ALL_SANE);
2215         return int(font_metrics::maxAscent(font)
2216                  + font_metrics::maxDescent(font) * 1.5);
2217 }