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