]> git.lyx.org Git - lyx.git/blob - src/text2.C
ws changes only
[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
24 #include "buffer.h"
25 #include "buffer_funcs.h"
26 #include "bufferparams.h"
27 #include "BufferView.h"
28 #include "Bullet.h"
29 #include "counters.h"
30 #include "CutAndPaste.h"
31 #include "debug.h"
32 #include "errorlist.h"
33 #include "Floating.h"
34 #include "FloatList.h"
35 #include "funcrequest.h"
36 #include "gettext.h"
37 #include "language.h"
38 #include "lyxrc.h"
39 #include "lyxrow.h"
40 #include "lyxrow_funcs.h"
41 #include "metricsinfo.h"
42 #include "paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "undo_funcs.h"
46 #include "vspace.h"
47
48 #include "frontends/font_metrics.h"
49 #include "frontends/LyXView.h"
50
51 #include "insets/insetbibitem.h"
52 #include "insets/insetenv.h"
53 #include "insets/insetfloat.h"
54 #include "insets/insetwrap.h"
55
56 #include "support/lstrings.h"
57 #include "support/textutils.h"
58 #include "support/tostr.h"
59 #include "support/std_sstream.h"
60
61 #include <boost/tuple/tuple.hpp>
62
63 using lyx::pos_type;
64 using lyx::paroffset_type;
65 using lyx::support::bformat;
66
67 using std::endl;
68 using std::ostringstream;
69 using std::string;
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(0, 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         BOOST_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 = cursorPar();
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(getPar(send_cur));
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, getPar(sstart_cur), 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 = getPar(sstart_cur);
337         ParagraphList::iterator epit = boost::next(getPar(send_cur));
338
339         BufferParams const & bufparams = bv()->buffer()->params();
340         LyXLayout_ptr const & lyxlayout =
341                 bufparams.getLyXTextClass()[layout];
342
343         do {
344                 pit->applyLayout(lyxlayout);
345                 makeFontEntriesLayoutSpecific(bufparams, *pit);
346                 pit->params().spaceTop(lyxlayout->fill_top ?
347                                          VSpace(VSpace::VFILL)
348                                          : VSpace(VSpace::NONE));
349                 pit->params().spaceBottom(lyxlayout->fill_bottom ?
350                                             VSpace(VSpace::VFILL)
351                                             : VSpace(VSpace::NONE));
352                 if (lyxlayout->margintype == MARGIN_MANUAL)
353                         pit->setLabelWidthString(lyxlayout->labelstring());
354                 cur.par(std::distance(ownerParagraphs().begin(), pit));
355                 ++pit;
356         } while (pit != epit);
357
358         return endpit;
359 }
360
361
362 // set layout over selection and make a total rebreak of those paragraphs
363 void LyXText::setLayout(string const & layout)
364 {
365         LyXCursor tmpcursor = cursor;  // store the current cursor
366
367         // if there is no selection just set the layout
368         // of the current paragraph
369         if (!selection.set()) {
370                 selection.start = cursor;  // dummy selection
371                 selection.end = cursor;
372         }
373
374         // special handling of new environment insets
375         BufferParams const & params = bv()->buffer()->params();
376         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
377         if (lyxlayout->is_environment) {
378                 // move everything in a new environment inset
379                 lyxerr << "setting layout " << layout << endl;
380                 bv()->owner()->dispatch(FuncRequest(LFUN_HOME));
381                 bv()->owner()->dispatch(FuncRequest(LFUN_ENDSEL));
382                 bv()->owner()->dispatch(FuncRequest(LFUN_CUT));
383                 InsetOld * inset = new InsetEnvironment(params, layout);
384                 if (bv()->insertInset(inset)) {
385                         //inset->edit(bv());
386                         //bv()->owner()->dispatch(FuncRequest(LFUN_PASTE));
387                 }
388                 else
389                         delete inset;
390                 return;
391         }
392
393         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
394                                                    selection.end, layout);
395         redoParagraphs(getPar(selection.start), endpit);
396
397         // we have to reset the selection, because the
398         // geometry could have changed
399         setCursor(selection.start.par(), selection.start.pos(), false);
400         selection.cursor = cursor;
401         setCursor(selection.end.par(), selection.end.pos(), false);
402         updateCounters();
403         clearSelection();
404         setSelection();
405         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
406 }
407
408
409 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
410 {
411         ParagraphList::iterator pit = cursorPar();
412         ParagraphList::iterator end = cursorPar();
413         ParagraphList::iterator start = pit;
414
415         if (selection.set()) {
416                 pit = getPar(selection.start);
417                 end = getPar(selection.end);
418                 start = pit;
419         }
420
421         ParagraphList::iterator pastend = boost::next(end);
422
423         if (!test_only)
424                 recordUndo(bv(), Undo::ATOMIC, start, end);
425
426         bool changed = false;
427
428         int prev_after_depth = 0;
429 #warning parlist ... could be nicer ?
430         if (start != ownerParagraphs().begin()) {
431                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
432         }
433
434         while (true) {
435                 int const depth = pit->params().depth();
436                 if (type == bv_funcs::INC_DEPTH) {
437                         if (depth < prev_after_depth
438                             && pit->layout()->labeltype != LABEL_BIBLIO) {
439                                 changed = true;
440                                 if (!test_only)
441                                         pit->params().depth(depth + 1);
442                         }
443                 } else if (depth) {
444                         changed = true;
445                         if (!test_only)
446                                 pit->params().depth(depth - 1);
447                 }
448
449                 prev_after_depth = pit->getMaxDepthAfter();
450
451                 if (pit == end) {
452                         break;
453                 }
454
455                 ++pit;
456         }
457
458         if (test_only)
459                 return changed;
460
461         redoParagraphs(start, pastend);
462
463         // We need to actually move the text->cursor. I don't
464         // understand why ...
465         LyXCursor tmpcursor = cursor;
466
467         // we have to reset the visual selection because the
468         // geometry could have changed
469         if (selection.set()) {
470                 setCursor(selection.start.par(), selection.start.pos());
471                 selection.cursor = cursor;
472                 setCursor(selection.end.par(), selection.end.pos());
473         }
474
475         // this handles the counter labels, and also fixes up
476         // depth values for follow-on (child) paragraphs
477         updateCounters();
478
479         setSelection();
480         setCursor(tmpcursor.par(), tmpcursor.pos());
481
482         return changed;
483 }
484
485
486 // set font over selection and make a total rebreak of those paragraphs
487 void LyXText::setFont(LyXFont const & font, bool toggleall)
488 {
489         // if there is no selection just set the current_font
490         if (!selection.set()) {
491                 // Determine basis font
492                 LyXFont layoutfont;
493                 if (cursor.pos() < cursorPar()->beginningOfBody()) {
494                         layoutfont = getLabelFont(cursorPar());
495                 } else {
496                         layoutfont = getLayoutFont(cursorPar());
497                 }
498                 // Update current font
499                 real_current_font.update(font,
500                                          bv()->buffer()->params().language,
501                                          toggleall);
502
503                 // Reduce to implicit settings
504                 current_font = real_current_font;
505                 current_font.reduce(layoutfont);
506                 // And resolve it completely
507                 real_current_font.realize(layoutfont);
508
509                 return;
510         }
511
512         LyXCursor tmpcursor = cursor; // store the current cursor
513
514         // ok we have a selection. This is always between sel_start_cursor
515         // and sel_end cursor
516
517         recordUndo(bv(), Undo::ATOMIC, getPar(selection.start), getPar(selection.end));
518         freezeUndo();
519         cursor = selection.start;
520         while (cursor.par() != selection.end.par() ||
521                cursor.pos() < selection.end.pos())
522         {
523                 if (cursor.pos() < cursorPar()->size()) {
524                         // an open footnote should behave like a closed one
525                         setCharFont(cursorPar(), cursor.pos(), font, toggleall);
526                         cursor.pos(cursor.pos() + 1);
527                 } else {
528                         cursor.pos(0);
529                         cursor.par(cursor.par() + 1);
530                 }
531         }
532         unFreezeUndo();
533
534         redoParagraph(getPar(selection.start));
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         //BOOST_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(cursorPar(), cursorRow()->pos());
670 }
671
672
673 void LyXText::cursorEnd()
674 {
675         setCursor(cursorPar(), 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(cursorPar(), 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(cursorPar(), 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(getPar(selection.end));
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, getPar(selection.start),
791                 boost::prior(undoendpit));
792
793
794         int tmppit = selection.end.par();
795
796         while (tmppit != selection.start.par() - 1) {
797                 setCursor(tmppit, 0);
798
799                 ParagraphList::iterator const pit = cursorPar();
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;
823         }
824
825         redoParagraphs(getPar(selection.start), 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 namespace {
839
840 string expandLabel(LyXTextClass const & textclass,
841         LyXLayout_ptr const & layout, bool appendix)
842 {
843         string fmt = appendix ?
844                 layout->labelstring_appendix() : layout->labelstring();
845
846         // handle 'inherited level parts' in 'fmt',
847         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
848         size_t const i = fmt.find('@', 0);
849         if (i != string::npos) {
850                 size_t const j = fmt.find('@', i + 1);
851                 if (j != string::npos) {
852                         string parent(fmt, i + 1, j - i - 1);
853                         string label = expandLabel(textclass, textclass[parent], appendix);
854                         fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
855                 }
856         }
857
858         return textclass.counters().counterLabel(fmt);
859 }
860
861
862 void incrementItemDepth(ParagraphList::iterator pit,
863                         ParagraphList::iterator first_pit)
864 {
865         int const cur_labeltype = pit->layout()->labeltype;
866
867         if (cur_labeltype != LABEL_ENUMERATE &&
868             cur_labeltype != LABEL_ITEMIZE)
869                 return;
870
871         int const cur_depth = pit->getDepth();
872
873         ParagraphList::iterator prev_pit = boost::prior(pit);
874         while (true) {
875                 int const prev_depth = prev_pit->getDepth();
876                 int const prev_labeltype = prev_pit->layout()->labeltype;
877                 if (prev_depth == 0 && cur_depth > 0) {
878                         if (prev_labeltype == cur_labeltype) {
879                                 pit->itemdepth = prev_pit->itemdepth + 1;
880                         }
881                         break;
882                 } else if (prev_depth < cur_depth) {
883                         if (prev_labeltype == cur_labeltype) {
884                                 pit->itemdepth = prev_pit->itemdepth + 1;
885                                 break;
886                         }
887                 } else if (prev_depth == cur_depth) {
888                         if (prev_labeltype == cur_labeltype) {
889                                 pit->itemdepth = prev_pit->itemdepth;
890                                 break;
891                         }
892                 }
893                 if (prev_pit == first_pit)
894                         break;
895
896                 --prev_pit;
897         }
898 }
899
900
901 void resetEnumCounterIfNeeded(ParagraphList::iterator pit,
902                               ParagraphList::iterator firstpit,
903                               Counters & counters)
904 {
905         if (pit == firstpit)
906                 return;
907
908         int const cur_depth = pit->getDepth();
909         ParagraphList::iterator prev_pit = boost::prior(pit);
910         while (true) {
911                 int const prev_depth = prev_pit->getDepth();
912                 int const prev_labeltype = prev_pit->layout()->labeltype;
913                 if (prev_depth <= cur_depth) {
914                         if (prev_labeltype != LABEL_ENUMERATE) {
915                                 switch (pit->itemdepth) {
916                                 case 0:
917                                         counters.reset("enumi");
918                                 case 1:
919                                         counters.reset("enumii");
920                                 case 2:
921                                         counters.reset("enumiii");
922                                 case 3:
923                                         counters.reset("enumiv");
924                                 }
925                         }
926                         break;
927                 }
928
929                 if (prev_pit == firstpit)
930                         break;
931
932                 --prev_pit;
933         }
934 }
935
936 } // anon namespace
937
938
939 // set the counter of a paragraph. This includes the labels
940 void LyXText::setCounter(Buffer const & buf, ParagraphList::iterator pit)
941 {
942         BufferParams const & bufparams = buf.params();
943         LyXTextClass const & textclass = bufparams.getLyXTextClass();
944         LyXLayout_ptr const & layout = pit->layout();
945         ParagraphList::iterator first_pit = ownerParagraphs().begin();
946         Counters & counters = textclass.counters();
947
948         // Always reset
949         pit->itemdepth = 0;
950
951         if (pit == first_pit) {
952                 pit->params().appendix(pit->params().startOfAppendix());
953         } else {
954                 pit->params().appendix(boost::prior(pit)->params().appendix());
955                 if (!pit->params().appendix() &&
956                     pit->params().startOfAppendix()) {
957                         pit->params().appendix(true);
958                         textclass.counters().reset();
959                 }
960
961                 // Maybe we have to increment the item depth.
962                 incrementItemDepth(pit, first_pit);
963         }
964
965         // erase what was there before
966         pit->params().labelString(string());
967
968         if (layout->margintype == MARGIN_MANUAL) {
969                 if (pit->params().labelWidthString().empty())
970                         pit->setLabelWidthString(layout->labelstring());
971         } else {
972                 pit->setLabelWidthString(string());
973         }
974
975         // is it a layout that has an automatic label?
976         if (layout->labeltype == LABEL_COUNTER) {
977                 BufferParams const & bufparams = buf.params();
978                 LyXTextClass const & textclass = bufparams.getLyXTextClass();
979                 counters.step(layout->counter);
980                 string label = expandLabel(textclass, layout, pit->params().appendix());
981                 pit->params().labelString(label);
982         } else if (layout->labeltype == LABEL_ITEMIZE) {
983                 // At some point of time we should do something more
984                 // clever here, like:
985                 //   pit->params().labelString(
986                 //    bufparams.user_defined_bullet(pit->itemdepth).getText());
987                 // for now, use a simple hardcoded label
988                 string itemlabel;
989                 switch (pit->itemdepth) {
990                 case 0:
991                         itemlabel = "*";
992                         break;
993                 case 1:
994                         itemlabel = "-";
995                         break;
996                 case 2:
997                         itemlabel = "@";
998                         break;
999                 case 3:
1000                         itemlabel = "·";
1001                         break;
1002                 }
1003
1004                 pit->params().labelString(itemlabel);
1005         } else if (layout->labeltype == LABEL_ENUMERATE) {
1006                 // Maybe we have to reset the enumeration counter.
1007                 resetEnumCounterIfNeeded(pit, first_pit, counters);
1008
1009                 // FIXME
1010                 // Yes I know this is a really, really! bad solution
1011                 // (Lgb)
1012                 string enumcounter = "enum";
1013
1014                 switch (pit->itemdepth) {
1015                 case 2:
1016                         enumcounter += 'i';
1017                 case 1:
1018                         enumcounter += 'i';
1019                 case 0:
1020                         enumcounter += 'i';
1021                         break;
1022                 case 3:
1023                         enumcounter += "iv";
1024                         break;
1025                 default:
1026                         // not a valid enumdepth...
1027                         break;
1028                 }
1029
1030                 counters.step(enumcounter);
1031
1032                 pit->params().labelString(counters.enumLabel(enumcounter));
1033         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
1034                 counters.step("bibitem");
1035                 int number = counters.value("bibitem");
1036                 if (pit->bibitem()) {
1037                         pit->bibitem()->setCounter(number);
1038                         pit->params().labelString(layout->labelstring());
1039                 }
1040                 // In biblio should't be following counters but...
1041         } else {
1042                 string s = buf.B_(layout->labelstring());
1043
1044                 // the caption hack:
1045                 if (layout->labeltype == LABEL_SENSITIVE) {
1046                         ParagraphList::iterator end = ownerParagraphs().end();
1047                         ParagraphList::iterator tmppit = pit;
1048                         InsetOld * in = 0;
1049                         bool isOK = false;
1050                         while (tmppit != end && tmppit->inInset()
1051                                // the single '=' is intended below
1052                                && (in = tmppit->inInset()->owner()))
1053                         {
1054                                 if (in->lyxCode() == InsetOld::FLOAT_CODE ||
1055                                     in->lyxCode() == InsetOld::WRAP_CODE) {
1056                                         isOK = true;
1057                                         break;
1058                                 } else {
1059                                         Paragraph const * owner = &ownerPar(buf, in);
1060                                         tmppit = first_pit;
1061                                         for ( ; tmppit != end; ++tmppit)
1062                                                 if (&*tmppit == owner)
1063                                                         break;
1064                                 }
1065                         }
1066
1067                         if (isOK) {
1068                                 string type;
1069
1070                                 if (in->lyxCode() == InsetOld::FLOAT_CODE)
1071                                         type = static_cast<InsetFloat*>(in)->params().type;
1072                                 else if (in->lyxCode() == InsetOld::WRAP_CODE)
1073                                         type = static_cast<InsetWrap*>(in)->params().type;
1074                                 else
1075                                         BOOST_ASSERT(false);
1076
1077                                 Floating const & fl = textclass.floats().getType(type);
1078
1079                                 counters.step(fl.type());
1080
1081                                 // Doesn't work... yet.
1082                                 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
1083                         } else {
1084                                 // par->SetLayout(0);
1085                                 // s = layout->labelstring;
1086                                 s = _("Senseless: ");
1087                         }
1088                 }
1089                 pit->params().labelString(s);
1090
1091         }
1092 }
1093
1094
1095 // Updates all counters. Paragraphs with changed label string will be rebroken
1096 void LyXText::updateCounters()
1097 {
1098         // start over
1099         bv()->buffer()->params().getLyXTextClass().counters().reset();
1100
1101         ParagraphList::iterator beg = ownerParagraphs().begin();
1102         ParagraphList::iterator end = ownerParagraphs().end();
1103         for (ParagraphList::iterator pit = beg; pit != end; ++pit) {
1104                 string const oldLabel = pit->params().labelString();
1105
1106                 size_t maxdepth = 0;
1107                 if (pit != beg)
1108                         maxdepth = boost::prior(pit)->getMaxDepthAfter();
1109
1110                 if (pit->params().depth() > maxdepth)
1111                         pit->params().depth(maxdepth);
1112
1113                 // setCounter can potentially change the labelString.
1114                 setCounter(*bv()->buffer(), pit);
1115
1116                 string const & newLabel = pit->params().labelString();
1117
1118                 if (oldLabel != newLabel)
1119                         redoParagraph(pit);
1120         }
1121 }
1122
1123
1124 void LyXText::insertInset(InsetOld * inset)
1125 {
1126         if (!cursorPar()->insetAllowed(inset->lyxCode()))
1127                 return;
1128         recordUndo(bv(), Undo::ATOMIC, cursorPar());
1129         freezeUndo();
1130         cursorPar()->insertInset(cursor.pos(), inset);
1131         // Just to rebreak and refresh correctly.
1132         // The character will not be inserted a second time
1133         insertChar(Paragraph::META_INSET);
1134         // If we enter a highly editable inset the cursor should be before
1135         // the inset. After an Undo LyX tries to call inset->edit(...)
1136         // and fails if the cursor is behind the inset and getInset
1137         // does not return the inset!
1138         if (isHighlyEditableInset(inset))
1139                 cursorLeft(true);
1140         unFreezeUndo();
1141 }
1142
1143
1144 void LyXText::cutSelection(bool doclear, bool realcut)
1145 {
1146         // Stuff what we got on the clipboard. Even if there is no selection.
1147
1148         // There is a problem with having the stuffing here in that the
1149         // larger the selection the slower LyX will get. This can be
1150         // solved by running the line below only when the selection has
1151         // finished. The solution used currently just works, to make it
1152         // faster we need to be more clever and probably also have more
1153         // calls to stuffClipboard. (Lgb)
1154         bv()->stuffClipboard(selectionAsString(*bv()->buffer(), true));
1155
1156         // This doesn't make sense, if there is no selection
1157         if (!selection.set())
1158                 return;
1159
1160         // OK, we have a selection. This is always between selection.start
1161         // and selection.end
1162
1163         // make sure that the depth behind the selection are restored, too
1164         ParagraphList::iterator endpit = boost::next(getPar(selection.end.par()));
1165         ParagraphList::iterator undoendpit = endpit;
1166         ParagraphList::iterator pars_end = ownerParagraphs().end();
1167
1168         if (endpit != pars_end && endpit->getDepth()) {
1169                 while (endpit != pars_end && endpit->getDepth()) {
1170                         ++endpit;
1171                         undoendpit = endpit;
1172                 }
1173         } else if (endpit != pars_end) {
1174                 // because of parindents etc.
1175                 ++endpit;
1176         }
1177
1178         recordUndo(bv(), Undo::DELETE, getPar(selection.start),
1179                    boost::prior(undoendpit));
1180
1181         endpit = getPar(selection.end.par());
1182         int endpos = selection.end.pos();
1183
1184         BufferParams const & bufparams = bv()->buffer()->params();
1185         boost::tie(endpit, endpos) = realcut ?
1186                 CutAndPaste::cutSelection(bufparams,
1187                                           ownerParagraphs(),
1188                                           getPar(selection.start.par()), endpit,
1189                                           selection.start.pos(), endpos,
1190                                           bufparams.textclass,
1191                                           doclear)
1192                 : CutAndPaste::eraseSelection(bufparams,
1193                                               ownerParagraphs(),
1194                                               getPar(selection.start.par()), endpit,
1195                                               selection.start.pos(), endpos,
1196                                               doclear);
1197         // sometimes necessary
1198         if (doclear)
1199                 getPar(selection.start.par())->stripLeadingSpaces();
1200
1201         redoParagraphs(getPar(selection.start.par()), boost::next(endpit));
1202         // cutSelection can invalidate the cursor so we need to set
1203         // it anew. (Lgb)
1204         // we prefer the end for when tracking changes
1205         cursor.pos(endpos);
1206         cursor.par(parOffset(endpit));
1207
1208         // need a valid cursor. (Lgb)
1209         clearSelection();
1210
1211         setCursor(cursorPar(), cursor.pos());
1212         selection.cursor = cursor;
1213         updateCounters();
1214 }
1215
1216
1217 void LyXText::copySelection()
1218 {
1219         // stuff the selection onto the X clipboard, from an explicit copy request
1220         bv()->stuffClipboard(selectionAsString(*bv()->buffer(), true));
1221
1222         // this doesnt make sense, if there is no selection
1223         if (!selection.set())
1224                 return;
1225
1226         // ok we have a selection. This is always between selection.start
1227         // and sel_end cursor
1228
1229         // copy behind a space if there is one
1230         while (getPar(selection.start)->size() > selection.start.pos()
1231                && getPar(selection.start)->isLineSeparator(selection.start.pos())
1232                && (selection.start.par() != selection.end.par()
1233                    || selection.start.pos() < selection.end.pos()))
1234                 selection.start.pos(selection.start.pos() + 1);
1235
1236         CutAndPaste::copySelection(getPar(selection.start.par()),
1237                                    getPar(selection.end.par()),
1238                                    selection.start.pos(), selection.end.pos(),
1239                                    bv()->buffer()->params().textclass);
1240 }
1241
1242
1243 void LyXText::pasteSelection(size_t sel_index)
1244 {
1245         // this does not make sense, if there is nothing to paste
1246         if (!CutAndPaste::checkPastePossible())
1247                 return;
1248
1249         recordUndo(bv(), Undo::INSERT, cursorPar());
1250
1251         ParagraphList::iterator endpit;
1252         PitPosPair ppp;
1253
1254         ErrorList el;
1255
1256         boost::tie(ppp, endpit) =
1257                 CutAndPaste::pasteSelection(*bv()->buffer(),
1258                                             ownerParagraphs(),
1259                                             cursorPar(), cursor.pos(),
1260                                             bv()->buffer()->params().textclass,
1261                                             sel_index, el);
1262         bufferErrors(*bv()->buffer(), el);
1263         bv()->showErrorList(_("Paste"));
1264
1265         redoParagraphs(cursorPar(), endpit);
1266
1267         setCursor(cursor.par(), cursor.pos());
1268         clearSelection();
1269
1270         selection.cursor = cursor;
1271         setCursor(ppp.first, ppp.second);
1272         setSelection();
1273         updateCounters();
1274 }
1275
1276
1277 void LyXText::setSelectionRange(lyx::pos_type length)
1278 {
1279         if (!length)
1280                 return;
1281
1282         selection.cursor = cursor;
1283         while (length--)
1284                 cursorRight(bv());
1285         setSelection();
1286 }
1287
1288
1289 // simple replacing. The font of the first selected character is used
1290 void LyXText::replaceSelectionWithString(string const & str)
1291 {
1292         recordUndo(bv(), Undo::ATOMIC);
1293         freezeUndo();
1294
1295         if (!selection.set()) { // create a dummy selection
1296                 selection.end = cursor;
1297                 selection.start = cursor;
1298         }
1299
1300         // Get font setting before we cut
1301         pos_type pos = selection.end.pos();
1302         LyXFont const font = getPar(selection.start)
1303                 ->getFontSettings(bv()->buffer()->params(),
1304                                   selection.start.pos());
1305
1306         // Insert the new string
1307         string::const_iterator cit = str.begin();
1308         string::const_iterator end = str.end();
1309         for (; cit != end; ++cit) {
1310                 getPar(selection.end)->insertChar(pos, (*cit), font);
1311                 ++pos;
1312         }
1313
1314         // Cut the selection
1315         cutSelection(true, false);
1316
1317         unFreezeUndo();
1318 }
1319
1320
1321 // needed to insert the selection
1322 void LyXText::insertStringAsLines(string const & str)
1323 {
1324         ParagraphList::iterator pit = cursorPar();
1325         pos_type pos = cursor.pos();
1326         ParagraphList::iterator endpit = boost::next(cursorPar());
1327
1328         recordUndo(bv(), Undo::ATOMIC);
1329
1330         // only to be sure, should not be neccessary
1331         clearSelection();
1332
1333         bv()->buffer()->insertStringAsLines(pit, pos, current_font, str);
1334
1335         redoParagraphs(cursorPar(), endpit);
1336         setCursor(cursorPar(), cursor.pos());
1337         selection.cursor = cursor;
1338         setCursor(pit, pos);
1339         setSelection();
1340 }
1341
1342
1343 // turns double-CR to single CR, others where converted into one
1344 // blank. Then InsertStringAsLines is called
1345 void LyXText::insertStringAsParagraphs(string const & str)
1346 {
1347         string linestr(str);
1348         bool newline_inserted = false;
1349         string::size_type const siz = linestr.length();
1350
1351         for (string::size_type i = 0; i < siz; ++i) {
1352                 if (linestr[i] == '\n') {
1353                         if (newline_inserted) {
1354                                 // we know that \r will be ignored by
1355                                 // InsertStringA. Of course, it is a dirty
1356                                 // trick, but it works...
1357                                 linestr[i - 1] = '\r';
1358                                 linestr[i] = '\n';
1359                         } else {
1360                                 linestr[i] = ' ';
1361                                 newline_inserted = true;
1362                         }
1363                 } else if (IsPrintable(linestr[i])) {
1364                         newline_inserted = false;
1365                 }
1366         }
1367         insertStringAsLines(linestr);
1368 }
1369
1370
1371 void LyXText::setCursor(ParagraphList::iterator pit, pos_type pos)
1372 {
1373         setCursor(parOffset(pit), pos);
1374 }
1375
1376
1377 bool LyXText::setCursor(paroffset_type par, pos_type pos, bool setfont, bool boundary)
1378 {
1379         LyXCursor old_cursor = cursor;
1380         setCursorIntern(par, pos, setfont, boundary);
1381         return deleteEmptyParagraphMechanism(old_cursor);
1382 }
1383
1384
1385 void LyXText::redoCursor()
1386 {
1387 #warning maybe the same for selections?
1388         setCursor(cursor, cursor.par(), cursor.pos(), cursor.boundary());
1389 }
1390
1391
1392 void LyXText::setCursor(LyXCursor & cur, paroffset_type par,
1393         pos_type pos, bool boundary)
1394 {
1395         BOOST_ASSERT(par != int(ownerParagraphs().size()));
1396
1397         cur.par(par);
1398         cur.pos(pos);
1399         cur.boundary(boundary);
1400
1401         // no rows, no fun...
1402         if (ownerParagraphs().begin()->rows.empty())
1403                 return;
1404
1405         // get the cursor y position in text
1406
1407         ParagraphList::iterator pit = getPar(par);
1408         RowList::iterator row = getRow(pit, pos);
1409         int y = row->y();
1410
1411         // y is now the beginning of the cursor row
1412         y += row->baseline();
1413         // y is now the cursor baseline
1414         cur.y(y);
1415
1416         pos_type last = lastPos(*pit, row);
1417
1418         // None of these should happen, but we're scaredy-cats
1419         if (pos > pit->size()) {
1420                 lyxerr << "dont like 1, pos: " << pos << " size: " << pit->size() << endl;
1421                 pos = 0;
1422                 cur.pos(0);
1423         } else if (pos > last + 1) {
1424                 lyxerr << "dont like 2 please report" << endl;
1425                 // This shouldn't happen.
1426                 pos = last + 1;
1427                 cur.pos(pos);
1428         } else if (pos < row->pos()) {
1429                 lyxerr << "dont like 3 please report" << endl;
1430                 pos = row->pos();
1431                 cur.pos(pos);
1432         }
1433
1434         // now get the cursors x position
1435         float x = getCursorX(pit, row, pos, last, boundary);
1436         cur.x(int(x));
1437         cur.x_fix(cur.x());
1438 }
1439
1440
1441 float LyXText::getCursorX(ParagraphList::iterator pit, RowList::iterator rit,
1442                           pos_type pos, pos_type last, bool boundary) const
1443 {
1444         pos_type cursor_vpos    = 0;
1445         double x                = rit->x();
1446         double fill_separator   = rit->fill_separator();
1447         double fill_hfill       = rit->fill_hfill();
1448         double fill_label_hfill = rit->fill_label_hfill();
1449         pos_type const rit_pos  = rit->pos();
1450
1451         if (last < rit_pos)
1452                 cursor_vpos = rit_pos;
1453         else if (pos > last && !boundary)
1454                 cursor_vpos = (pit->isRightToLeftPar(bv()->buffer()->params()))
1455                         ? rit_pos : last + 1;
1456         else if (pos > rit_pos && (pos > last || boundary))
1457                 // Place cursor after char at (logical) position pos - 1
1458                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1459                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1460         else
1461                 // Place cursor before char at (logical) position pos
1462                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1463                         ? log2vis(pos) : log2vis(pos) + 1;
1464
1465         pos_type body_pos = pit->beginningOfBody();
1466         if (body_pos > 0 &&
1467             (body_pos - 1 > last || !pit->isLineSeparator(body_pos - 1)))
1468                 body_pos = 0;
1469
1470         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1471                 pos_type pos = vis2log(vpos);
1472                 if (body_pos > 0 && pos == body_pos - 1) {
1473                         x += fill_label_hfill +
1474                                 font_metrics::width(
1475                                         pit->layout()->labelsep, getLabelFont(pit));
1476                         if (pit->isLineSeparator(body_pos - 1))
1477                                 x -= singleWidth(pit, body_pos - 1);
1478                 }
1479
1480                 if (hfillExpansion(*pit, rit, pos)) {
1481                         x += singleWidth(pit, pos);
1482                         if (pos >= body_pos)
1483                                 x += fill_hfill;
1484                         else
1485                                 x += fill_label_hfill;
1486                 } else if (pit->isSeparator(pos)) {
1487                         x += singleWidth(pit, pos);
1488                         if (pos >= body_pos)
1489                                 x += fill_separator;
1490                 } else
1491                         x += singleWidth(pit, pos);
1492         }
1493         return x;
1494 }
1495
1496
1497 void LyXText::setCursorIntern(paroffset_type par,
1498                               pos_type pos, bool setfont, bool boundary)
1499 {
1500         setCursor(cursor, par, pos, boundary);
1501         if (setfont)
1502                 setCurrentFont();
1503 }
1504
1505
1506 void LyXText::setCurrentFont()
1507 {
1508         pos_type pos = cursor.pos();
1509         ParagraphList::iterator pit = cursorPar();
1510
1511         if (cursor.boundary() && pos > 0)
1512                 --pos;
1513
1514         if (pos > 0) {
1515                 if (pos == pit->size())
1516                         --pos;
1517                 else // potentional bug... BUG (Lgb)
1518                         if (pit->isSeparator(pos)) {
1519                                 if (pos > cursorRow()->pos() &&
1520                                     bidi_level(pos) % 2 ==
1521                                     bidi_level(pos - 1) % 2)
1522                                         --pos;
1523                                 else if (pos + 1 < pit->size())
1524                                         ++pos;
1525                         }
1526         }
1527
1528         BufferParams const & bufparams = bv()->buffer()->params();
1529         current_font = pit->getFontSettings(bufparams, pos);
1530         real_current_font = getFont(pit, pos);
1531
1532         if (cursor.pos() == pit->size() &&
1533             isBoundary(*bv()->buffer(), *pit, cursor.pos()) &&
1534             !cursor.boundary()) {
1535                 Language const * lang =
1536                         pit->getParLanguage(bufparams);
1537                 current_font.setLanguage(lang);
1538                 current_font.setNumber(LyXFont::OFF);
1539                 real_current_font.setLanguage(lang);
1540                 real_current_font.setNumber(LyXFont::OFF);
1541         }
1542 }
1543
1544
1545 // returns the column near the specified x-coordinate of the row
1546 // x is set to the real beginning of this column
1547 pos_type LyXText::getColumnNearX(ParagraphList::iterator pit,
1548         RowList::iterator rit, int & x, bool & boundary) const
1549 {
1550         double tmpx             = rit->x();
1551         double fill_separator   = rit->fill_separator();
1552         double fill_hfill       = rit->fill_hfill();
1553         double fill_label_hfill = rit->fill_label_hfill();
1554
1555         pos_type vc = rit->pos();
1556         pos_type last = lastPos(*pit, rit);
1557         pos_type c = 0;
1558         LyXLayout_ptr const & layout = pit->layout();
1559
1560         bool left_side = false;
1561
1562         pos_type body_pos = pit->beginningOfBody();
1563         double last_tmpx = tmpx;
1564
1565         if (body_pos > 0 &&
1566             (body_pos - 1 > last ||
1567              !pit->isLineSeparator(body_pos - 1)))
1568                 body_pos = 0;
1569
1570         // check for empty row
1571         if (!pit->size()) {
1572                 x = int(tmpx);
1573                 return 0;
1574         }
1575
1576         while (vc <= last && tmpx <= x) {
1577                 c = vis2log(vc);
1578                 last_tmpx = tmpx;
1579                 if (body_pos > 0 && c == body_pos - 1) {
1580                         tmpx += fill_label_hfill +
1581                                 font_metrics::width(layout->labelsep, getLabelFont(pit));
1582                         if (pit->isLineSeparator(body_pos - 1))
1583                                 tmpx -= singleWidth(pit, body_pos - 1);
1584                 }
1585
1586                 if (hfillExpansion(*pit, rit, c)) {
1587                         tmpx += singleWidth(pit, c);
1588                         if (c >= body_pos)
1589                                 tmpx += fill_hfill;
1590                         else
1591                                 tmpx += fill_label_hfill;
1592                 } else if (pit->isSeparator(c)) {
1593                         tmpx += singleWidth(pit, c);
1594                         if (c >= body_pos)
1595                                 tmpx += fill_separator;
1596                 } else {
1597                         tmpx += singleWidth(pit, c);
1598                 }
1599                 ++vc;
1600         }
1601
1602         if ((tmpx + last_tmpx) / 2 > x) {
1603                 tmpx = last_tmpx;
1604                 left_side = true;
1605         }
1606
1607         if (vc > last + 1)  // This shouldn't happen.
1608                 vc = last + 1;
1609
1610         boundary = false;
1611         // This (rtl_support test) is not needed, but gives
1612         // some speedup if rtl_support == false
1613         bool const lastrow = lyxrc.rtl_support
1614                         && boost::next(rit) == pit->rows.end();
1615
1616         // If lastrow is false, we don't need to compute
1617         // the value of rtl.
1618         bool const rtl = (lastrow)
1619                 ? pit->isRightToLeftPar(bv()->buffer()->params())
1620                 : false;
1621         if (lastrow &&
1622                  ((rtl  &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1623                   (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1624                 c = last + 1;
1625         else if (vc == rit->pos()) {
1626                 c = vis2log(vc);
1627                 if (bidi_level(c) % 2 == 1)
1628                         ++c;
1629         } else {
1630                 c = vis2log(vc - 1);
1631                 bool const rtl = (bidi_level(c) % 2 == 1);
1632                 if (left_side == rtl) {
1633                         ++c;
1634                         boundary = isBoundary(*bv()->buffer(), *pit, c);
1635                 }
1636         }
1637
1638         if (rit->pos() <= last && c > last && pit->isNewline(last)) {
1639                 if (bidi_level(last) % 2 == 0)
1640                         tmpx -= singleWidth(pit, last);
1641                 else
1642                         tmpx += singleWidth(pit, last);
1643                 c = last;
1644         }
1645
1646         c -= rit->pos();
1647         x = int(tmpx);
1648         return c;
1649 }
1650
1651
1652 void LyXText::setCursorFromCoordinates(int x, int y)
1653 {
1654         LyXCursor old_cursor = cursor;
1655         setCursorFromCoordinates(cursor, x, y);
1656         setCurrentFont();
1657         deleteEmptyParagraphMechanism(old_cursor);
1658 }
1659
1660
1661 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1662 {
1663         // Get the row first.
1664         ParagraphList::iterator pit;
1665         RowList::iterator rit = getRowNearY(y, pit);
1666         y = rit->y();
1667
1668         bool bound = false;
1669         pos_type const column = getColumnNearX(pit, rit, x, bound);
1670         cur.par(parOffset(pit));
1671         cur.pos(rit->pos() + column);
1672         cur.x(x);
1673         cur.y(y + rit->baseline());
1674
1675         cur.boundary(bound);
1676 }
1677
1678
1679 void LyXText::cursorLeft(bool internal)
1680 {
1681         if (cursor.pos() > 0) {
1682                 bool boundary = cursor.boundary();
1683                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1684                 if (!internal && !boundary &&
1685                     isBoundary(*bv()->buffer(), *cursorPar(), cursor.pos() + 1))
1686                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1687         } else if (cursor.par() != 0) {
1688                 // steps into the paragraph above
1689                 setCursor(cursor.par() - 1, boost::prior(cursorPar())->size());
1690         }
1691 }
1692
1693
1694 void LyXText::cursorRight(bool internal)
1695 {
1696         bool const at_end = (cursor.pos() == cursorPar()->size());
1697         bool const at_newline = !at_end &&
1698                 cursorPar()->isNewline(cursor.pos());
1699
1700         if (!internal && cursor.boundary() && !at_newline)
1701                 setCursor(cursor.par(), cursor.pos(), true, false);
1702         else if (!at_end) {
1703                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1704                 if (!internal &&
1705                     isBoundary(*bv()->buffer(), *cursorPar(), cursor.pos()))
1706                         setCursor(cursor.par(), cursor.pos(), true, true);
1707         } else if (cursor.par() + 1 != int(ownerParagraphs().size()))
1708                 setCursor(cursor.par() + 1, 0);
1709 }
1710
1711
1712 void LyXText::cursorUp(bool selecting)
1713 {
1714 #if 1
1715         int x = cursor.x_fix();
1716         int y = cursor.y() - cursorRow()->baseline() - 1;
1717         setCursorFromCoordinates(x, y);
1718         if (!selecting) {
1719                 int topy = bv_owner->top_y();
1720                 int y1 = cursor.y() - topy;
1721                 int y2 = y1;
1722                 y -= topy;
1723                 InsetOld * inset_hit = checkInsetHit(x, y1);
1724                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1725                         inset_hit->localDispatch(
1726                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1727                 }
1728         }
1729 #else
1730         lyxerr << "cursorUp: y " << cursor.y() << " bl: " <<
1731                 cursorRow()->baseline() << endl;
1732         setCursorFromCoordinates(cursor.x_fix(),
1733                 cursor.y() - cursorRow()->baseline() - 1);
1734 #endif
1735 }
1736
1737
1738 void LyXText::cursorDown(bool selecting)
1739 {
1740 #if 1
1741         int x = cursor.x_fix();
1742         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1743         setCursorFromCoordinates(x, y);
1744         if (!selecting && cursorRow() == cursorIRow()) {
1745                 int topy = bv_owner->top_y();
1746                 int y1 = cursor.y() - topy;
1747                 int y2 = y1;
1748                 y -= topy;
1749                 InsetOld * inset_hit = checkInsetHit(x, y1);
1750                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1751                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
1752                         inset_hit->localDispatch(cmd);
1753                 }
1754         }
1755 #else
1756         setCursorFromCoordinates(cursor.x_fix(),
1757                  cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1);
1758 #endif
1759 }
1760
1761
1762 void LyXText::cursorUpParagraph()
1763 {
1764         if (cursor.pos() > 0)
1765                 setCursor(cursorPar(), 0);
1766         else if (cursorPar() != ownerParagraphs().begin())
1767                 setCursor(boost::prior(cursorPar()), 0);
1768 }
1769
1770
1771 void LyXText::cursorDownParagraph()
1772 {
1773         ParagraphList::iterator par = cursorPar();
1774         ParagraphList::iterator next_par = boost::next(par);
1775
1776         if (next_par != ownerParagraphs().end())
1777                 setCursor(next_par, 0);
1778         else
1779                 setCursor(par, par->size());
1780 }
1781
1782
1783 // fix the cursor `cur' after a characters has been deleted at `where'
1784 // position. Called by deleteEmptyParagraphMechanism
1785 void LyXText::fixCursorAfterDelete(LyXCursor & cur, LyXCursor const & where)
1786 {
1787         // if cursor is not in the paragraph where the delete occured,
1788         // do nothing
1789         if (cur.par() != where.par())
1790                 return;
1791
1792         // if cursor position is after the place where the delete occured,
1793         // update it
1794         if (cur.pos() > where.pos())
1795                 cur.pos(cur.pos()-1);
1796
1797         // check also if we don't want to set the cursor on a spot behind the
1798         // pagragraph because we erased the last character.
1799         if (cur.pos() > getPar(cur)->size())
1800                 cur.pos(getPar(cur)->size());
1801
1802         // recompute row et al. for this cursor
1803         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
1804 }
1805
1806
1807 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
1808 {
1809         // Would be wrong to delete anything if we have a selection.
1810         if (selection.set())
1811                 return false;
1812
1813         // Don't do anything if the cursor is invalid
1814         if (old_cursor.par() == -1)
1815                 return false;
1816
1817         // We allow all kinds of "mumbo-jumbo" when freespacing.
1818         ParagraphList::iterator const old_pit = getPar(old_cursor);
1819         if (old_pit->isFreeSpacing())
1820                 return false;
1821
1822         /* Ok I'll put some comments here about what is missing.
1823            I have fixed BackSpace (and thus Delete) to not delete
1824            double-spaces automagically. I have also changed Cut,
1825            Copy and Paste to hopefully do some sensible things.
1826            There are still some small problems that can lead to
1827            double spaces stored in the document file or space at
1828            the beginning of paragraphs. This happens if you have
1829            the cursor between to spaces and then save. Or if you
1830            cut and paste and the selection have a space at the
1831            beginning and then save right after the paste. I am
1832            sure none of these are very hard to fix, but I will
1833            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
1834            that I can get some feedback. (Lgb)
1835         */
1836
1837         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
1838         // delete the LineSeparator.
1839         // MISSING
1840
1841         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
1842         // delete the LineSeparator.
1843         // MISSING
1844
1845         // If the pos around the old_cursor were spaces, delete one of them.
1846         if (old_cursor.par() != cursor.par()
1847             || old_cursor.pos() != cursor.pos()) {
1848
1849                 // Only if the cursor has really moved
1850                 if (old_cursor.pos() > 0
1851                     && old_cursor.pos() < old_pit->size()
1852                     && old_pit->isLineSeparator(old_cursor.pos())
1853                     && old_pit->isLineSeparator(old_cursor.pos() - 1)) {
1854                         bool erased = old_pit->erase(old_cursor.pos() - 1);
1855                         redoParagraph(old_pit);
1856
1857                         if (!erased)
1858                                 return false;
1859 #ifdef WITH_WARNINGS
1860 #warning This will not work anymore when we have multiple views of the same buffer
1861 // In this case, we will have to correct also the cursors held by
1862 // other bufferviews. It will probably be easier to do that in a more
1863 // automated way in LyXCursor code. (JMarc 26/09/2001)
1864 #endif
1865                         // correct all cursors held by the LyXText
1866                         fixCursorAfterDelete(cursor, old_cursor);
1867                         fixCursorAfterDelete(selection.cursor, old_cursor);
1868                         fixCursorAfterDelete(selection.start, old_cursor);
1869                         fixCursorAfterDelete(selection.end, old_cursor);
1870                         return false;
1871                 }
1872         }
1873
1874         // don't delete anything if this is the ONLY paragraph!
1875         if (ownerParagraphs().size() == 1)
1876                 return false;
1877
1878         // Do not delete empty paragraphs with keepempty set.
1879         if (old_pit->allowEmpty())
1880                 return false;
1881
1882         // only do our magic if we changed paragraph
1883         if (old_cursor.par() == cursor.par())
1884                 return false;
1885
1886         // record if we have deleted a paragraph
1887         // we can't possibly have deleted a paragraph before this point
1888         bool deleted = false;
1889
1890         if (old_pit->empty() ||
1891             (old_pit->size() == 1 && old_pit->isLineSeparator(0))) {
1892                 // ok, we will delete something
1893                 LyXCursor tmpcursor;
1894
1895                 deleted = true;
1896
1897                 bool selection_position_was_oldcursor_position =
1898                         selection.cursor.par() == old_cursor.par()
1899                         && selection.cursor.pos() == old_cursor.pos();
1900
1901                 tmpcursor = cursor;
1902                 cursor = old_cursor; // that undo can restore the right cursor position
1903
1904                 ParagraphList::iterator endpit = boost::next(old_pit);
1905                 while (endpit != ownerParagraphs().end() && endpit->getDepth())
1906                         ++endpit;
1907
1908                 recordUndo(bv(), Undo::DELETE, old_pit, boost::prior(endpit));
1909                 cursor = tmpcursor;
1910
1911                 // delete old par
1912                 ownerParagraphs().erase(old_pit);
1913                 redoParagraph();
1914
1915                 // correct cursor y
1916                 setCursorIntern(cursor.par(), cursor.pos());
1917
1918                 if (selection_position_was_oldcursor_position) {
1919                         // correct selection
1920                         selection.cursor = cursor;
1921                 }
1922         }
1923         if (!deleted) {
1924                 if (old_pit->stripLeadingSpaces()) {
1925                         redoParagraph(old_pit);
1926                         // correct cursor y
1927                         setCursorIntern(cursor.par(), cursor.pos());
1928                         selection.cursor = cursor;
1929                 }
1930         }
1931         return deleted;
1932 }
1933
1934
1935 ParagraphList & LyXText::ownerParagraphs() const
1936 {
1937         return *paragraphs_;
1938 }
1939
1940
1941 bool LyXText::isInInset() const
1942 {
1943         // Sub-level has non-null bv owner and non-null inset owner.
1944         return inset_owner != 0;
1945 }
1946
1947
1948 int defaultRowHeight()
1949 {
1950         LyXFont const font(LyXFont::ALL_SANE);
1951         return int(font_metrics::maxAscent(font)
1952                  + font_metrics::maxDescent(font) * 1.5);
1953 }