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