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