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