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