]> git.lyx.org Git - lyx.git/blob - src/text2.C
If I ever see another licence blurb again, it'll be too soon...
[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 "FloatList.h"
41 #include "language.h"
42 #include "ParagraphParameters.h"
43 #include "counters.h"
44 #include "lyxrow_funcs.h"
45 #include "metricsinfo.h"
46 #include "paragraph_funcs.h"
47
48 #include "insets/insetbibitem.h"
49 #include "insets/insetenv.h"
50 #include "insets/insetfloat.h"
51 #include "insets/insetwrap.h"
52
53 #include "support/LAssert.h"
54 #include "support/textutils.h"
55 #include "support/lstrings.h"
56
57 #include <boost/tuple/tuple.hpp>
58
59 #include <algorithm>
60
61 using namespace lyx::support;
62
63 using std::vector;
64 using std::copy;
65 using std::endl;
66 using std::find;
67 using std::pair;
68 using lyx::pos_type;
69
70
71 LyXText::LyXText(BufferView * bv, InsetText * inset, bool ininset,
72           ParagraphList & paragraphs)
73         : height(0), width(0), anchor_y_(0),
74           inset_owner(inset), the_locking_inset(0), bv_owner(bv),
75           in_inset_(ininset), paragraphs_(paragraphs)
76 {
77 }
78
79
80 void LyXText::init(BufferView * bview)
81 {
82         bv_owner = bview;
83
84         ParagraphList::iterator const beg = ownerParagraphs().begin();
85         ParagraphList::iterator const end = ownerParagraphs().end();
86         for (ParagraphList::iterator pit = beg; pit != end; ++pit)
87                 pit->rows.clear();
88
89         width = 0;
90         height = 0;
91
92         anchor_y_ = 0;
93
94         current_font = getFont(beg, 0);
95
96         redoParagraphs(beg, end);
97         setCursorIntern(beg, 0);
98         selection.cursor = cursor;
99
100         updateCounters();
101 }
102
103
104 // Gets the fully instantiated font at a given position in a paragraph
105 // Basically the same routine as Paragraph::getFont() in paragraph.C.
106 // The difference is that this one is used for displaying, and thus we
107 // are allowed to make cosmetic improvements. For instance make footnotes
108 // smaller. (Asger)
109 LyXFont LyXText::getFont(ParagraphList::iterator pit, pos_type pos) const
110 {
111         Assert(pos >= 0);
112
113         LyXLayout_ptr const & layout = pit->layout();
114 #warning broken?
115         BufferParams const & params = bv()->buffer()->params;
116
117         // We specialize the 95% common case:
118         if (!pit->getDepth()) {
119                 if (layout->labeltype == LABEL_MANUAL
120                     && pos < pit->beginningOfBody()) {
121                         // 1% goes here
122                         LyXFont f = pit->getFontSettings(params, pos);
123                         if (pit->inInset())
124                                 pit->inInset()->getDrawFont(f);
125                         return f.realize(layout->reslabelfont);
126                 } else {
127                         LyXFont f = pit->getFontSettings(params, pos);
128                         if (pit->inInset())
129                                 pit->inInset()->getDrawFont(f);
130                         return f.realize(layout->resfont);
131                 }
132         }
133
134         // The uncommon case need not be optimized as much
135
136         LyXFont layoutfont;
137
138         if (pos < pit->beginningOfBody()) {
139                 // 1% goes here
140                 layoutfont = layout->labelfont;
141         } else {
142                 // 99% goes here
143                 layoutfont = layout->font;
144         }
145
146         LyXFont tmpfont = pit->getFontSettings(params, pos);
147         tmpfont.realize(layoutfont);
148
149         if (pit->inInset())
150                 pit->inInset()->getDrawFont(tmpfont);
151
152         // Realize with the fonts of lesser depth.
153         tmpfont.realize(outerFont(pit, ownerParagraphs()));
154         tmpfont.realize(defaultfont_);
155
156         return tmpfont;
157 }
158
159
160 LyXFont LyXText::getLayoutFont(ParagraphList::iterator pit) const
161 {
162         LyXLayout_ptr const & layout = pit->layout();
163
164         if (!pit->getDepth())
165                 return layout->resfont;
166
167         LyXFont font = layout->font;
168         // Realize with the fonts of lesser depth.
169         font.realize(outerFont(pit, ownerParagraphs()));
170         font.realize(defaultfont_);
171
172         return font;
173 }
174
175
176 LyXFont LyXText::getLabelFont(ParagraphList::iterator pit) const
177 {
178         LyXLayout_ptr const & layout = pit->layout();
179
180         if (!pit->getDepth())
181                 return layout->reslabelfont;
182
183         LyXFont font = layout->labelfont;
184         // Realize with the fonts of lesser depth.
185         font.realize(outerFont(pit, ownerParagraphs()));
186         font.realize(defaultfont_);
187
188         return font;
189 }
190
191
192 void LyXText::setCharFont(ParagraphList::iterator pit,
193                           pos_type pos, LyXFont const & fnt,
194                           bool toggleall)
195 {
196         BufferParams const & params = bv()->buffer()->params;
197         LyXFont font = getFont(pit, pos);
198         font.update(fnt, params.language, toggleall);
199         // Let the insets convert their font
200         if (pit->isInset(pos)) {
201                 InsetOld * inset = pit->getInset(pos);
202                 if (isEditableInset(inset)) {
203                         static_cast<UpdatableInset *>(inset)
204                                 ->setFont(bv(), fnt, toggleall, true);
205                 }
206         }
207
208         // Plug through to version below:
209         setCharFont(pit, pos, font);
210 }
211
212
213 void LyXText::setCharFont(
214         ParagraphList::iterator pit, pos_type pos, LyXFont const & fnt)
215 {
216         LyXFont font = fnt;
217         LyXLayout_ptr const & layout = pit->layout();
218
219         // Get concrete layout font to reduce against
220         LyXFont layoutfont;
221
222         if (pos < pit->beginningOfBody())
223                 layoutfont = layout->labelfont;
224         else
225                 layoutfont = layout->font;
226
227         // Realize against environment font information
228         if (pit->getDepth()) {
229                 ParagraphList::iterator tp = pit;
230                 while (!layoutfont.resolved() &&
231                        tp != ownerParagraphs().end() &&
232                        tp->getDepth()) {
233                         tp = outerHook(tp, ownerParagraphs());
234                         if (tp != ownerParagraphs().end())
235                                 layoutfont.realize(tp->layout()->font);
236                 }
237         }
238
239         layoutfont.realize(defaultfont_);
240
241         // Now, reduce font against full layout font
242         font.reduce(layoutfont);
243
244         pit->setFont(pos, font);
245 }
246
247
248 InsetOld * LyXText::getInset() const
249 {
250         ParagraphList::iterator pit = cursor.par();
251         pos_type const pos = cursor.pos();
252
253         if (pos < pit->size() && pit->isInset(pos)) {
254                 return pit->getInset(pos);
255         }
256         return 0;
257 }
258
259
260 void LyXText::toggleInset()
261 {
262         InsetOld * inset = getInset();
263         // is there an editable inset at cursor position?
264         if (!isEditableInset(inset)) {
265                 // No, try to see if we are inside a collapsable inset
266                 if (inset_owner && inset_owner->owner()
267                     && inset_owner->owner()->isOpen()) {
268                         bv()->unlockInset(inset_owner->owner());
269                         inset_owner->owner()->close(bv());
270                         bv()->getLyXText()->cursorRight(bv());
271                 }
272                 return;
273         }
274         //bv()->owner()->message(inset->editMessage());
275
276         // do we want to keep this?? (JMarc)
277         if (!isHighlyEditableInset(inset))
278                 recordUndo(bv(), Undo::ATOMIC);
279
280         if (inset->isOpen())
281                 inset->close(bv());
282         else
283                 inset->open(bv());
284
285         bv()->updateInset();
286 }
287
288
289 /* used in setlayout */
290 // Asger is not sure we want to do this...
291 void LyXText::makeFontEntriesLayoutSpecific(BufferParams const & params,
292                                             Paragraph & par)
293 {
294         LyXLayout_ptr const & layout = par.layout();
295         pos_type const psize = par.size();
296
297         LyXFont layoutfont;
298         for (pos_type pos = 0; pos < psize; ++pos) {
299                 if (pos < par.beginningOfBody())
300                         layoutfont = layout->labelfont;
301                 else
302                         layoutfont = layout->font;
303
304                 LyXFont tmpfont = par.getFontSettings(params, pos);
305                 tmpfont.reduce(layoutfont);
306                 par.setFont(pos, tmpfont);
307         }
308 }
309
310
311 ParagraphList::iterator
312 LyXText::setLayout(LyXCursor & cur, LyXCursor & sstart_cur,
313                    LyXCursor & send_cur,
314                    string const & layout)
315 {
316         ParagraphList::iterator endpit = boost::next(send_cur.par());
317         ParagraphList::iterator undoendpit = endpit;
318         ParagraphList::iterator pars_end = ownerParagraphs().end();
319
320         if (endpit != pars_end && endpit->getDepth()) {
321                 while (endpit != pars_end && endpit->getDepth()) {
322                         ++endpit;
323                         undoendpit = endpit;
324                 }
325         } else if (endpit != pars_end) {
326                 // because of parindents etc.
327                 ++endpit;
328         }
329
330         recordUndo(bv(), Undo::ATOMIC, sstart_cur.par(), boost::prior(undoendpit));
331
332         // ok we have a selection. This is always between sstart_cur
333         // and sel_end cursor
334         cur = sstart_cur;
335         ParagraphList::iterator pit = sstart_cur.par();
336         ParagraphList::iterator epit = boost::next(send_cur.par());
337
338         LyXLayout_ptr const & lyxlayout =
339                 bv()->buffer()->params.getLyXTextClass()[layout];
340
341         do {
342                 pit->applyLayout(lyxlayout);
343                 makeFontEntriesLayoutSpecific(bv()->buffer()->params, *pit);
344                 pit->params().spaceTop(lyxlayout->fill_top ?
345                                          VSpace(VSpace::VFILL)
346                                          : VSpace(VSpace::NONE));
347                 pit->params().spaceBottom(lyxlayout->fill_bottom ?
348                                             VSpace(VSpace::VFILL)
349                                             : VSpace(VSpace::NONE));
350                 if (lyxlayout->margintype == MARGIN_MANUAL)
351                         pit->setLabelWidthString(lyxlayout->labelstring());
352                 cur.par(pit);
353                 ++pit;
354         } while (pit != epit);
355
356         return endpit;
357 }
358
359
360 // set layout over selection and make a total rebreak of those paragraphs
361 void LyXText::setLayout(string const & layout)
362 {
363         LyXCursor tmpcursor = cursor;  // store the current cursor
364
365         // if there is no selection just set the layout
366         // of the current paragraph
367         if (!selection.set()) {
368                 selection.start = cursor;  // dummy selection
369                 selection.end = cursor;
370         }
371
372         // special handling of new environment insets
373         BufferParams const & params = bv()->buffer()->params;
374         LyXLayout_ptr const & lyxlayout = params.getLyXTextClass()[layout];
375         if (lyxlayout->is_environment) {
376                 // move everything in a new environment inset
377                 lyxerr << "setting layout " << layout << endl;
378                 bv()->owner()->dispatch(FuncRequest(LFUN_HOME));
379                 bv()->owner()->dispatch(FuncRequest(LFUN_ENDSEL));
380                 bv()->owner()->dispatch(FuncRequest(LFUN_CUT));
381                 InsetOld * inset = new InsetEnvironment(params, layout);
382                 if (bv()->insertInset(inset)) {
383                         //inset->edit(bv());
384                         //bv()->owner()->dispatch(FuncRequest(LFUN_PASTE));
385                 }
386                 else
387                         delete inset;
388                 return;
389         }
390
391         ParagraphList::iterator endpit = setLayout(cursor, selection.start,
392                                                    selection.end, layout);
393         redoParagraphs(selection.start.par(), endpit);
394
395         // we have to reset the selection, because the
396         // geometry could have changed
397         setCursor(selection.start.par(), selection.start.pos(), false);
398         selection.cursor = cursor;
399         setCursor(selection.end.par(), selection.end.pos(), false);
400         updateCounters();
401         clearSelection();
402         setSelection();
403         setCursor(tmpcursor.par(), tmpcursor.pos(), true);
404 }
405
406
407 bool LyXText::changeDepth(bv_funcs::DEPTH_CHANGE type, bool test_only)
408 {
409         ParagraphList::iterator pit = cursor.par();
410         ParagraphList::iterator end = cursor.par();
411         ParagraphList::iterator start = pit;
412
413         if (selection.set()) {
414                 pit = selection.start.par();
415                 end = selection.end.par();
416                 start = pit;
417         }
418
419         ParagraphList::iterator pastend = boost::next(end);
420
421         if (!test_only)
422                 recordUndo(bv(), Undo::ATOMIC, start, end);
423
424         bool changed = false;
425
426         int prev_after_depth = 0;
427 #warning parlist ... could be nicer ?
428         if (start != ownerParagraphs().begin()) {
429                 prev_after_depth = boost::prior(start)->getMaxDepthAfter();
430         }
431
432         while (true) {
433                 int const depth = pit->params().depth();
434                 if (type == bv_funcs::INC_DEPTH) {
435                         if (depth < prev_after_depth
436                             && pit->layout()->labeltype != LABEL_BIBLIO) {
437                                 changed = true;
438                                 if (!test_only)
439                                         pit->params().depth(depth + 1);
440                         }
441                 } else if (depth) {
442                         changed = true;
443                         if (!test_only)
444                                 pit->params().depth(depth - 1);
445                 }
446
447                 prev_after_depth = pit->getMaxDepthAfter();
448
449                 if (pit == end) {
450                         break;
451                 }
452
453                 ++pit;
454         }
455
456         if (test_only)
457                 return changed;
458
459         redoParagraphs(start, pastend);
460
461         // We need to actually move the text->cursor. I don't
462         // understand why ...
463         LyXCursor tmpcursor = cursor;
464
465         // we have to reset the visual selection because the
466         // geometry could have changed
467         if (selection.set()) {
468                 setCursor(selection.start.par(), selection.start.pos());
469                 selection.cursor = cursor;
470                 setCursor(selection.end.par(), selection.end.pos());
471         }
472
473         // this handles the counter labels, and also fixes up
474         // depth values for follow-on (child) paragraphs
475         updateCounters();
476
477         setSelection();
478         setCursor(tmpcursor.par(), tmpcursor.pos());
479
480         return changed;
481 }
482
483
484 // set font over selection and make a total rebreak of those paragraphs
485 void LyXText::setFont(LyXFont const & font, bool toggleall)
486 {
487         // if there is no selection just set the current_font
488         if (!selection.set()) {
489                 // Determine basis font
490                 LyXFont layoutfont;
491                 if (cursor.pos() < cursor.par()->beginningOfBody()) {
492                         layoutfont = getLabelFont(cursor.par());
493                 } else {
494                         layoutfont = getLayoutFont(cursor.par());
495                 }
496                 // Update current font
497                 real_current_font.update(font,
498                                          bv()->buffer()->params.language,
499                                          toggleall);
500
501                 // Reduce to implicit settings
502                 current_font = real_current_font;
503                 current_font.reduce(layoutfont);
504                 // And resolve it completely
505                 real_current_font.realize(layoutfont);
506
507                 return;
508         }
509
510         LyXCursor tmpcursor = cursor; // store the current cursor
511
512         // ok we have a selection. This is always between sel_start_cursor
513         // and sel_end cursor
514
515         recordUndo(bv(), Undo::ATOMIC, selection.start.par(), selection.end.par());
516         freezeUndo();
517         cursor = selection.start;
518         while (cursor.par() != selection.end.par() ||
519                cursor.pos() < selection.end.pos())
520         {
521                 if (cursor.pos() < cursor.par()->size()) {
522                         // an open footnote should behave like a closed one
523                         setCharFont(cursor.par(), cursor.pos(),
524                                     font, toggleall);
525                         cursor.pos(cursor.pos() + 1);
526                 } else {
527                         cursor.pos(0);
528                         cursor.par(boost::next(cursor.par()));
529                 }
530         }
531         unFreezeUndo();
532
533         redoParagraph(selection.start.par());
534
535         // we have to reset the selection, because the
536         // geometry could have changed, but we keep
537         // it for user convenience
538         setCursor(selection.start.par(), selection.start.pos());
539         selection.cursor = cursor;
540         setCursor(selection.end.par(), selection.end.pos());
541         setSelection();
542         setCursor(tmpcursor.par(), tmpcursor.pos(), true,
543                   tmpcursor.boundary());
544 }
545
546
547 // rebreaks all paragraphs between the specified pars
548 // This function is needed after SetLayout and SetFont etc.
549 void LyXText::redoParagraphs(ParagraphList::iterator start,
550   ParagraphList::iterator end)
551 {
552         for ( ; start != end; ++start)
553                 redoParagraph(start);
554 }
555
556
557 void LyXText::redoParagraph(ParagraphList::iterator pit)
558 {
559         RowList::iterator rit = pit->rows.begin();
560         RowList::iterator end = pit->rows.end();
561
562         // remove rows of paragraph, keep track of height changes
563         for (int i = 0; rit != end; ++rit, ++i)
564                 height -= rit->height();
565         pit->rows.clear();
566
567         // redo insets
568         InsetList::iterator ii = pit->insetlist.begin();
569         InsetList::iterator iend = pit->insetlist.end();
570         for (; ii != iend; ++ii) {
571                 Dimension dim;
572                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
573                 ii->inset->metrics(mi, dim);
574         }
575
576         // rebreak the paragraph
577         for (pos_type z = 0; z < pit->size() + 1; ) {
578                 Row row(z);
579                 z = rowBreakPoint(pit, row) + 1;
580                 row.end(z);
581                 pit->rows.push_back(row);
582         }
583
584         // set height and fill of rows
585         for (rit = pit->rows.begin(); rit != end; ++rit) {
586                 rit->fill(fill(pit, rit, workWidth()));
587                 prepareToPrint(pit, rit);
588                 setHeightOfRow(pit, rit);
589                 height += rit->height();
590         }
591
592         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
593 }
594
595
596 void LyXText::fullRebreak()
597 {
598         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
599         redoCursor();
600         selection.cursor = cursor;
601 }
602
603
604 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
605 {
606         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
607         //      << " workWidth: " << workWidth() << endl;
608         //Assert(mi.base.textwidth);
609
610         // rebuild row cache
611         width  = 0;
612         ///height = 0;
613
614         //anchor_y_ = 0;
615         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
616         updateRowPositions();
617
618         // final dimension
619         dim.asc = firstRow()->ascent_of_text();
620         dim.des = height - dim.asc;
621         dim.wid = std::max(mi.base.textwidth, int(width));
622 }
623
624
625 // important for the screen
626
627
628 // the cursor set functions have a special mechanism. When they
629 // realize, that you left an empty paragraph, they will delete it.
630 // They also delete the corresponding row
631
632 // need the selection cursor:
633 void LyXText::setSelection()
634 {
635         TextCursor::setSelection();
636 }
637
638
639
640 void LyXText::clearSelection()
641 {
642         TextCursor::clearSelection();
643
644         // reset this in the bv_owner!
645         if (bv_owner && bv_owner->text)
646                 bv_owner->text->xsel_cache.set(false);
647 }
648
649
650 void LyXText::cursorHome()
651 {
652         setCursor(cursor.par(), cursorRow()->pos());
653 }
654
655
656 void LyXText::cursorEnd()
657 {
658         if (cursor.par()->empty())
659                 return;
660
661         RowList::iterator rit = cursorRow();
662         RowList::iterator next_rit = boost::next(rit);
663         RowList::iterator end = boost::next(rit);
664         ParagraphList::iterator pit = cursor.par();
665         pos_type last_pos = lastPos(*pit, rit);
666
667         if (next_rit == end) {
668                 ++last_pos;
669         } else {
670                 if (pit->empty() ||
671                     (pit->getChar(last_pos) != ' ' && !pit->isNewline(last_pos))) {
672                         ++last_pos;
673                 }
674         }
675
676         setCursor(pit, last_pos);
677 }
678
679
680 void LyXText::cursorTop()
681 {
682         setCursor(ownerParagraphs().begin(), 0);
683 }
684
685
686 void LyXText::cursorBottom()
687 {
688         ParagraphList::iterator lastpit =
689                 boost::prior(ownerParagraphs().end());
690         setCursor(lastpit, lastpit->size());
691 }
692
693
694 void LyXText::toggleFree(LyXFont const & font, bool toggleall)
695 {
696         // If the mask is completely neutral, tell user
697         if (font == LyXFont(LyXFont::ALL_IGNORE)) {
698                 // Could only happen with user style
699                 bv()->owner()->message(_("No font change defined. Use Character under the Layout menu to define font change."));
700                 return;
701         }
702
703         // Try implicit word selection
704         // If there is a change in the language the implicit word selection
705         // is disabled.
706         LyXCursor resetCursor = cursor;
707         bool implicitSelection = (font.language() == ignore_language
708                                   && font.number() == LyXFont::IGNORE)
709                 ? selectWordWhenUnderCursor(lyx::WHOLE_WORD_STRICT) : false;
710
711         // Set font
712         setFont(font, toggleall);
713
714         // Implicit selections are cleared afterwards
715         //and cursor is set to the original position.
716         if (implicitSelection) {
717                 clearSelection();
718                 cursor = resetCursor;
719                 setCursor(cursor.par(), cursor.pos());
720                 selection.cursor = cursor;
721         }
722 }
723
724
725 string LyXText::getStringToIndex()
726 {
727         // Try implicit word selection
728         // If there is a change in the language the implicit word selection
729         // is disabled.
730         LyXCursor const reset_cursor = cursor;
731         bool const implicitSelection =
732                 selectWordWhenUnderCursor(lyx::PREVIOUS_WORD);
733
734         string idxstring;
735         if (!selection.set())
736                 bv()->owner()->message(_("Nothing to index!"));
737         else if (selection.start.par() != selection.end.par())
738                 bv()->owner()->message(_("Cannot index more than one paragraph!"));
739         else
740                 idxstring = selectionAsString(bv()->buffer(), false);
741
742         // Reset cursors to their original position.
743         cursor = reset_cursor;
744         setCursor(cursor.par(), cursor.pos());
745         selection.cursor = cursor;
746
747         // Clear the implicit selection.
748         if (implicitSelection)
749                 clearSelection();
750
751         return idxstring;
752 }
753
754
755 // the DTP switches for paragraphs. LyX will store them in the first
756 // physical paragraph. When a paragraph is broken, the top settings rest,
757 // the bottom settings are given to the new one. So I can make sure,
758 // they do not duplicate themself and you cannnot make dirty things with
759 // them!
760
761 void LyXText::setParagraph(bool line_top, bool line_bottom,
762                            bool pagebreak_top, bool pagebreak_bottom,
763                            VSpace const & space_top,
764                            VSpace const & space_bottom,
765                            Spacing const & spacing,
766                            LyXAlignment align,
767                            string const & labelwidthstring,
768                            bool noindent)
769 {
770         LyXCursor tmpcursor = cursor;
771         if (!selection.set()) {
772                 selection.start = cursor;
773                 selection.end = cursor;
774         }
775
776         // make sure that the depth behind the selection are restored, too
777         ParagraphList::iterator endpit = boost::next(selection.end.par());
778         ParagraphList::iterator undoendpit = endpit;
779         ParagraphList::iterator pars_end = ownerParagraphs().end();
780
781         if (endpit != pars_end && endpit->getDepth()) {
782                 while (endpit != pars_end && endpit->getDepth()) {
783                         ++endpit;
784                         undoendpit = endpit;
785                 }
786         } else if (endpit != pars_end) {
787                 // because of parindents etc.
788                 ++endpit;
789         }
790
791         recordUndo(bv(), Undo::ATOMIC, selection.start.par(),
792                 boost::prior(undoendpit));
793
794
795         ParagraphList::iterator tmppit = selection.end.par();
796
797         while (tmppit != boost::prior(selection.start.par())) {
798                 setCursor(tmppit, 0);
799
800                 ParagraphList::iterator pit = cursor.par();
801                 ParagraphParameters & params = pit->params();
802
803                 params.lineTop(line_top);
804                 params.lineBottom(line_bottom);
805                 params.pagebreakTop(pagebreak_top);
806                 params.pagebreakBottom(pagebreak_bottom);
807                 params.spaceTop(space_top);
808                 params.spaceBottom(space_bottom);
809                 params.spacing(spacing);
810                 // does the layout allow the new alignment?
811                 LyXLayout_ptr const & layout = pit->layout();
812
813                 if (align == LYX_ALIGN_LAYOUT)
814                         align = layout->align;
815                 if (align & layout->alignpossible) {
816                         if (align == layout->align)
817                                 params.align(LYX_ALIGN_LAYOUT);
818                         else
819                                 params.align(align);
820                 }
821                 pit->setLabelWidthString(labelwidthstring);
822                 params.noindent(noindent);
823                 tmppit = boost::prior(pit);
824         }
825
826         redoParagraphs(selection.start.par(), endpit);
827
828         clearSelection();
829         setCursor(selection.start.par(), selection.start.pos());
830         selection.cursor = cursor;
831         setCursor(selection.end.par(), selection.end.pos());
832         setSelection();
833         setCursor(tmpcursor.par(), tmpcursor.pos());
834         if (inset_owner)
835                 bv()->updateInset();
836 }
837
838
839 // set the counter of a paragraph. This includes the labels
840 void LyXText::setCounter(Buffer const * buf, ParagraphList::iterator pit)
841 {
842         LyXTextClass const & textclass = buf->params.getLyXTextClass();
843         LyXLayout_ptr const & layout = pit->layout();
844
845         if (pit != ownerParagraphs().begin()) {
846
847                 pit->params().appendix(boost::prior(pit)->params().appendix());
848                 if (!pit->params().appendix() &&
849                     pit->params().startOfAppendix()) {
850                         pit->params().appendix(true);
851                         textclass.counters().reset();
852                 }
853                 pit->enumdepth = boost::prior(pit)->enumdepth;
854                 pit->itemdepth = boost::prior(pit)->itemdepth;
855         } else {
856                 pit->params().appendix(pit->params().startOfAppendix());
857                 pit->enumdepth = 0;
858                 pit->itemdepth = 0;
859         }
860
861         // Maybe we have to increment the enumeration depth.
862         // BUT, enumeration in a footnote is considered in isolation from its
863         //      surrounding paragraph so don't increment if this is the
864         //      first line of the footnote
865         // AND, bibliographies can't have their depth changed ie. they
866         //      are always of depth 0
867         if (pit != ownerParagraphs().begin()
868             && boost::prior(pit)->getDepth() < pit->getDepth()
869             && boost::prior(pit)->layout()->labeltype == LABEL_COUNTER_ENUMI
870             && pit->enumdepth < 3
871             && layout->labeltype != LABEL_BIBLIO) {
872                 pit->enumdepth++;
873         }
874
875         // Maybe we have to decrement the enumeration depth, see note above
876         if (pit != ownerParagraphs().begin()
877             && boost::prior(pit)->getDepth() > pit->getDepth()
878             && layout->labeltype != LABEL_BIBLIO) {
879                 pit->enumdepth = depthHook(pit, ownerParagraphs(),
880                                            pit->getDepth())->enumdepth;
881         }
882
883         if (!pit->params().labelString().empty()) {
884                 pit->params().labelString(string());
885         }
886
887         if (layout->margintype == MARGIN_MANUAL) {
888                 if (pit->params().labelWidthString().empty())
889                         pit->setLabelWidthString(layout->labelstring());
890         } else {
891                 pit->setLabelWidthString(string());
892         }
893
894         // is it a layout that has an automatic label?
895         if (layout->labeltype >= LABEL_COUNTER_CHAPTER) {
896                 int const i = layout->labeltype - LABEL_COUNTER_CHAPTER;
897
898                 ostringstream s;
899
900                 if (i >= 0 && i <= buf->params.secnumdepth) {
901                         string numbertype;
902                         string langtype;
903
904                         textclass.counters().step(layout->latexname());
905
906                         // Is there a label? Useful for Chapter layout
907                         if (!pit->params().appendix()) {
908                                 s << buf->B_(layout->labelstring());
909                         } else {
910                                 s << buf->B_(layout->labelstring_appendix());
911                         }
912
913                         // Use of an integer is here less than elegant. For now.
914                         int head = textclass.maxcounter() - LABEL_COUNTER_CHAPTER;
915                         if (!pit->params().appendix()) {
916                                 numbertype = "sectioning";
917                         } else {
918                                 numbertype = "appendix";
919                                 if (pit->isRightToLeftPar(buf->params))
920                                         langtype = "hebrew";
921                                 else
922                                         langtype = "latin";
923                         }
924
925                         s << " "
926                           << textclass.counters()
927                                 .numberLabel(layout->latexname(),
928                                              numbertype, langtype, head);
929
930                         pit->params().labelString(STRCONV(s.str()));
931
932                         // reset enum counters
933                         textclass.counters().reset("enum");
934                 } else if (layout->labeltype < LABEL_COUNTER_ENUMI) {
935                         textclass.counters().reset("enum");
936                 } else if (layout->labeltype == LABEL_COUNTER_ENUMI) {
937                         // FIXME
938                         // Yes I know this is a really, really! bad solution
939                         // (Lgb)
940                         string enumcounter("enum");
941
942                         switch (pit->enumdepth) {
943                         case 2:
944                                 enumcounter += 'i';
945                         case 1:
946                                 enumcounter += 'i';
947                         case 0:
948                                 enumcounter += 'i';
949                                 break;
950                         case 3:
951                                 enumcounter += "iv";
952                                 break;
953                         default:
954                                 // not a valid enumdepth...
955                                 break;
956                         }
957
958                         textclass.counters().step(enumcounter);
959
960                         s << textclass.counters()
961                                 .numberLabel(enumcounter, "enumeration");
962                         pit->params().labelString(STRCONV(s.str()));
963                 }
964         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
965                 textclass.counters().step("bibitem");
966                 int number = textclass.counters().value("bibitem");
967                 if (pit->bibitem()) {
968                         pit->bibitem()->setCounter(number);
969                         pit->params().labelString(layout->labelstring());
970                 }
971                 // In biblio should't be following counters but...
972         } else {
973                 string s = buf->B_(layout->labelstring());
974
975                 // the caption hack:
976                 if (layout->labeltype == LABEL_SENSITIVE) {
977                         ParagraphList::iterator end = ownerParagraphs().end();
978                         ParagraphList::iterator tmppit = pit;
979                         InsetOld * in = 0;
980                         bool isOK = false;
981                         while (tmppit != end && tmppit->inInset()
982                                // the single '=' is intended below
983                                && (in = tmppit->inInset()->owner()))
984                         {
985                                 if (in->lyxCode() == InsetOld::FLOAT_CODE ||
986                                     in->lyxCode() == InsetOld::WRAP_CODE) {
987                                         isOK = true;
988                                         break;
989                                 } else {
990                                         tmppit = ownerParagraphs().begin();
991                                         for ( ; tmppit != end; ++tmppit)
992                                                 if (&*tmppit == in->parOwner())
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         int y = 0;
1344         RowList::iterator row = getRow(pit, pos, y);
1345         RowList::iterator old_row = row;
1346         // if we are before the first char of this row and are still in the
1347         // same paragraph and there is a previous row then put the cursor on
1348         // the end of the previous row
1349         cur.iy(y + row->baseline());
1350         if (row != pit->rows.begin()
1351             && pos
1352             && pos < pit->size()
1353             && pit->getChar(pos) == Paragraph::META_INSET) {
1354                 InsetOld * ins = pit->getInset(pos);
1355                 if (ins && (ins->needFullRow() || ins->display())) {
1356                         --row;
1357                         y -= row->height();
1358                 }
1359         }
1360
1361         // y is now the beginning of the cursor row
1362         y += row->baseline();
1363         // y is now the cursor baseline
1364         cur.y(y);
1365
1366         pos_type last = lastPrintablePos(*pit, old_row);
1367
1368         // None of these should happen, but we're scaredy-cats
1369         if (pos > pit->size()) {
1370                 lyxerr << "dont like 1, pos: " << pos << " size: " << pit->size() << endl;
1371                 pos = 0;
1372                 cur.pos(0);
1373         } else if (pos > last + 1) {
1374                 lyxerr << "dont like 2 please report" << endl;
1375                 // This shouldn't happen.
1376                 pos = last + 1;
1377                 cur.pos(pos);
1378         } else if (pos < row->pos()) {
1379                 lyxerr << "dont like 3 please report" << endl;
1380                 pos = row->pos();
1381                 cur.pos(pos);
1382         }
1383
1384         // now get the cursors x position
1385         float x = getCursorX(pit, row, pos, last, boundary);
1386         cur.x(int(x));
1387         cur.x_fix(cur.x());
1388         if (old_row != row) {
1389                 x = getCursorX(pit, old_row, pos, last, boundary);
1390                 cur.ix(int(x));
1391         } else
1392                 cur.ix(cur.x());
1393 /* We take out this for the time being because 1) the redraw code is not
1394    prepared to this yet and 2) because some good policy has yet to be decided
1395    while editting: for instance how to act on rows being created/deleted
1396    because of DEPM.
1397 */
1398 #if 0
1399         //if the cursor is in a visible row, anchor to it
1400         int topy = top_y();
1401         if (topy < y && y < topy + bv()->workHeight())
1402                 anchor_row(row);
1403 #endif
1404 }
1405
1406
1407 float LyXText::getCursorX(ParagraphList::iterator pit, RowList::iterator rit,
1408                           pos_type pos, pos_type last, bool boundary) const
1409 {
1410         pos_type cursor_vpos    = 0;
1411         double x                = rit->x();
1412         double fill_separator   = rit->fill_separator();
1413         double fill_hfill       = rit->fill_hfill();
1414         double fill_label_hfill = rit->fill_label_hfill();
1415         pos_type const rit_pos  = rit->pos();
1416
1417         if (last < rit_pos)
1418                 cursor_vpos = rit_pos;
1419         else if (pos > last && !boundary)
1420                 cursor_vpos = (pit->isRightToLeftPar(bv()->buffer()->params))
1421                         ? rit_pos : last + 1;
1422         else if (pos > rit_pos && (pos > last || boundary))
1423                 // Place cursor after char at (logical) position pos - 1
1424                 cursor_vpos = (bidi_level(pos - 1) % 2 == 0)
1425                         ? log2vis(pos - 1) + 1 : log2vis(pos - 1);
1426         else
1427                 // Place cursor before char at (logical) position pos
1428                 cursor_vpos = (bidi_level(pos) % 2 == 0)
1429                         ? log2vis(pos) : log2vis(pos) + 1;
1430
1431         pos_type body_pos = pit->beginningOfBody();
1432         if (body_pos > 0 &&
1433             (body_pos - 1 > last || !pit->isLineSeparator(body_pos - 1)))
1434                 body_pos = 0;
1435
1436         for (pos_type vpos = rit_pos; vpos < cursor_vpos; ++vpos) {
1437                 pos_type pos = vis2log(vpos);
1438                 if (body_pos > 0 && pos == body_pos - 1) {
1439                         x += fill_label_hfill +
1440                                 font_metrics::width(
1441                                         pit->layout()->labelsep, getLabelFont(pit));
1442                         if (pit->isLineSeparator(body_pos - 1))
1443                                 x -= singleWidth(pit, body_pos - 1);
1444                 }
1445
1446                 if (hfillExpansion(*pit, rit, pos)) {
1447                         x += singleWidth(pit, pos);
1448                         if (pos >= body_pos)
1449                                 x += fill_hfill;
1450                         else
1451                                 x += fill_label_hfill;
1452                 } else if (pit->isSeparator(pos)) {
1453                         x += singleWidth(pit, pos);
1454                         if (pos >= body_pos)
1455                                 x += fill_separator;
1456                 } else
1457                         x += singleWidth(pit, pos);
1458         }
1459         return x;
1460 }
1461
1462
1463 void LyXText::setCursorIntern(ParagraphList::iterator pit,
1464                               pos_type pos, bool setfont, bool boundary)
1465 {
1466         setCursor(cursor, pit, pos, boundary);
1467         if (setfont)
1468                 setCurrentFont();
1469 }
1470
1471
1472 void LyXText::setCurrentFont()
1473 {
1474         pos_type pos = cursor.pos();
1475         ParagraphList::iterator pit = cursor.par();
1476
1477         if (cursor.boundary() && pos > 0)
1478                 --pos;
1479
1480         if (pos > 0) {
1481                 if (pos == pit->size())
1482                         --pos;
1483                 else // potentional bug... BUG (Lgb)
1484                         if (pit->isSeparator(pos)) {
1485                                 if (pos > cursorRow()->pos() &&
1486                                     bidi_level(pos) % 2 ==
1487                                     bidi_level(pos - 1) % 2)
1488                                         --pos;
1489                                 else if (pos + 1 < pit->size())
1490                                         ++pos;
1491                         }
1492         }
1493
1494         current_font = pit->getFontSettings(bv()->buffer()->params, pos);
1495         real_current_font = getFont(pit, pos);
1496
1497         if (cursor.pos() == pit->size() &&
1498             isBoundary(bv()->buffer(), *pit, cursor.pos()) &&
1499             !cursor.boundary()) {
1500                 Language const * lang =
1501                         pit->getParLanguage(bv()->buffer()->params);
1502                 current_font.setLanguage(lang);
1503                 current_font.setNumber(LyXFont::OFF);
1504                 real_current_font.setLanguage(lang);
1505                 real_current_font.setNumber(LyXFont::OFF);
1506         }
1507 }
1508
1509
1510 // returns the column near the specified x-coordinate of the row
1511 // x is set to the real beginning of this column
1512 pos_type LyXText::getColumnNearX(ParagraphList::iterator pit,
1513         RowList::iterator rit, int & x, bool & boundary) const
1514 {
1515         double tmpx             = rit->x();
1516         double fill_separator   = rit->fill_separator();
1517         double fill_hfill       = rit->fill_hfill();
1518         double fill_label_hfill = rit->fill_label_hfill();
1519
1520         pos_type vc = rit->pos();
1521         pos_type last = lastPrintablePos(*pit, rit);
1522         pos_type c = 0;
1523         LyXLayout_ptr const & layout = pit->layout();
1524
1525         bool left_side = false;
1526
1527         pos_type body_pos = pit->beginningOfBody();
1528         double last_tmpx = tmpx;
1529
1530         if (body_pos > 0 &&
1531             (body_pos - 1 > last ||
1532              !pit->isLineSeparator(body_pos - 1)))
1533                 body_pos = 0;
1534
1535         // check for empty row
1536         if (!pit->size()) {
1537                 x = int(tmpx);
1538                 return 0;
1539         }
1540
1541         while (vc <= last && tmpx <= x) {
1542                 c = vis2log(vc);
1543                 last_tmpx = tmpx;
1544                 if (body_pos > 0 && c == body_pos - 1) {
1545                         tmpx += fill_label_hfill +
1546                                 font_metrics::width(layout->labelsep, getLabelFont(pit));
1547                         if (pit->isLineSeparator(body_pos - 1))
1548                                 tmpx -= singleWidth(pit, body_pos - 1);
1549                 }
1550
1551                 if (hfillExpansion(*pit, rit, c)) {
1552                         tmpx += singleWidth(pit, c);
1553                         if (c >= body_pos)
1554                                 tmpx += fill_hfill;
1555                         else
1556                                 tmpx += fill_label_hfill;
1557                 } else if (pit->isSeparator(c)) {
1558                         tmpx += singleWidth(pit, c);
1559                         if (c >= body_pos)
1560                                 tmpx += fill_separator;
1561                 } else {
1562                         tmpx += singleWidth(pit, c);
1563                 }
1564                 ++vc;
1565         }
1566
1567         if ((tmpx + last_tmpx) / 2 > x) {
1568                 tmpx = last_tmpx;
1569                 left_side = true;
1570         }
1571
1572         if (vc > last + 1)  // This shouldn't happen.
1573                 vc = last + 1;
1574
1575         boundary = false;
1576         // This (rtl_support test) is not needed, but gives
1577         // some speedup if rtl_support == false
1578         bool const lastrow = lyxrc.rtl_support
1579                         && boost::next(rit) == pit->rows.end();
1580
1581         // If lastrow is false, we don't need to compute
1582         // the value of rtl.
1583         bool const rtl = (lastrow)
1584                 ? pit->isRightToLeftPar(bv()->buffer()->params)
1585                 : false;
1586         if (lastrow &&
1587                  ((rtl  &&  left_side && vc == rit->pos() && x < tmpx - 5) ||
1588                   (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
1589                 c = last + 1;
1590         else if (vc == rit->pos()) {
1591                 c = vis2log(vc);
1592                 if (bidi_level(c) % 2 == 1)
1593                         ++c;
1594         } else {
1595                 c = vis2log(vc - 1);
1596                 bool const rtl = (bidi_level(c) % 2 == 1);
1597                 if (left_side == rtl) {
1598                         ++c;
1599                         boundary = isBoundary(bv()->buffer(), *pit, c);
1600                 }
1601         }
1602
1603         if (rit->pos() <= last && c > last && pit->isNewline(last)) {
1604                 if (bidi_level(last) % 2 == 0)
1605                         tmpx -= singleWidth(pit, last);
1606                 else
1607                         tmpx += singleWidth(pit, last);
1608                 c = last;
1609         }
1610
1611         c -= rit->pos();
1612         x = int(tmpx);
1613         return c;
1614 }
1615
1616
1617 void LyXText::setCursorFromCoordinates(int x, int y)
1618 {
1619         LyXCursor old_cursor = cursor;
1620         setCursorFromCoordinates(cursor, x, y);
1621         setCurrentFont();
1622         deleteEmptyParagraphMechanism(old_cursor);
1623 }
1624
1625
1626 namespace {
1627
1628         /**
1629          * return true if the cursor given is at the end of a row,
1630          * and the next row is filled by an inset that spans an entire
1631          * row.
1632          */
1633         bool beforeFullRowInset(LyXText & lt, LyXCursor const & cur)
1634         {
1635                 RowList::iterator row = lt.getRow(cur);
1636                 RowList::iterator next = boost::next(row);
1637
1638                 if (next == cur.par()->rows.end() || next->pos() != cur.pos())
1639                         return false;
1640
1641                 if (cur.pos() == cur.par()->size() || !cur.par()->isInset(cur.pos()))
1642                         return false;
1643
1644                 InsetOld const * inset = cur.par()->getInset(cur.pos());
1645                 if (inset->needFullRow() || inset->display())
1646                         return true;
1647
1648                 return false;
1649         }
1650 }
1651
1652
1653 void LyXText::setCursorFromCoordinates(LyXCursor & cur, int x, int y)
1654 {
1655         // Get the row first.
1656         ParagraphList::iterator pit;
1657         RowList::iterator rit = getRowNearY(y, pit);
1658         bool bound = false;
1659         pos_type const column = getColumnNearX(pit, rit, x, bound);
1660         cur.par(pit);
1661         cur.pos(rit->pos() + column);
1662         cur.x(x);
1663         cur.y(y + rit->baseline());
1664
1665         if (beforeFullRowInset(*this, cur)) {
1666                 pos_type const last = lastPrintablePos(*pit, rit);
1667                 RowList::iterator next_rit = rit;
1668                 ParagraphList::iterator next_pit = pit;
1669                 nextRow(next_pit, next_rit);
1670                 cur.ix(int(getCursorX(pit, next_rit, cur.pos(), last, bound)));
1671                 cur.iy(y + rit->height() + next_rit->baseline());
1672         } else {
1673                 cur.iy(cur.y());
1674                 cur.ix(cur.x());
1675         }
1676         cur.boundary(bound);
1677 }
1678
1679
1680 void LyXText::cursorLeft(bool internal)
1681 {
1682         if (cursor.pos() > 0) {
1683                 bool boundary = cursor.boundary();
1684                 setCursor(cursor.par(), cursor.pos() - 1, true, false);
1685                 if (!internal && !boundary &&
1686                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos() + 1))
1687                         setCursor(cursor.par(), cursor.pos() + 1, true, true);
1688         } else if (cursor.par() != ownerParagraphs().begin()) {
1689                 // steps into the paragraph above
1690                 ParagraphList::iterator pit = boost::prior(cursor.par());
1691                 setCursor(pit, pit->size());
1692         }
1693 }
1694
1695
1696 void LyXText::cursorRight(bool internal)
1697 {
1698         bool const at_end = (cursor.pos() == cursor.par()->size());
1699         bool const at_newline = !at_end &&
1700                 cursor.par()->isNewline(cursor.pos());
1701
1702         if (!internal && cursor.boundary() && !at_newline)
1703                 setCursor(cursor.par(), cursor.pos(), true, false);
1704         else if (!at_end) {
1705                 setCursor(cursor.par(), cursor.pos() + 1, true, false);
1706                 if (!internal &&
1707                     isBoundary(bv()->buffer(), *cursor.par(), cursor.pos()))
1708                         setCursor(cursor.par(), cursor.pos(), true, true);
1709         } else if (boost::next(cursor.par()) != ownerParagraphs().end())
1710                 setCursor(boost::next(cursor.par()), 0);
1711 }
1712
1713
1714 void LyXText::cursorUp(bool selecting)
1715 {
1716 #if 1
1717         int x = cursor.x_fix();
1718         int y = cursor.y() - cursorRow()->baseline() - 1;
1719         setCursorFromCoordinates(x, y);
1720         if (!selecting) {
1721                 int topy = top_y();
1722                 int y1 = cursor.iy() - topy;
1723                 int y2 = y1;
1724                 y -= topy;
1725                 InsetOld * inset_hit = checkInsetHit(x, y1);
1726                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1727                         inset_hit->localDispatch(
1728                                 FuncRequest(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none));
1729                 }
1730         }
1731 #else
1732         lyxerr << "cursorUp: y " << cursor.y() << " bl: " <<
1733                 cursorRow()->baseline() << endl;
1734         setCursorFromCoordinates(cursor.x_fix(),
1735                 cursor.y() - cursorRow()->baseline() - 1);
1736 #endif
1737 }
1738
1739
1740 void LyXText::cursorDown(bool selecting)
1741 {
1742 #if 1
1743         int x = cursor.x_fix();
1744         int y = cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1;
1745         setCursorFromCoordinates(x, y);
1746         if (!selecting && cursorRow() == cursorIRow()) {
1747                 int topy = top_y();
1748                 int y1 = cursor.iy() - topy;
1749                 int y2 = y1;
1750                 y -= topy;
1751                 InsetOld * inset_hit = checkInsetHit(x, y1);
1752                 if (inset_hit && isHighlyEditableInset(inset_hit)) {
1753                         FuncRequest cmd(bv(), LFUN_INSET_EDIT, x, y - (y2 - y1), mouse_button::none);
1754                         inset_hit->localDispatch(cmd);
1755                 }
1756         }
1757 #else
1758         setCursorFromCoordinates(cursor.x_fix(),
1759                  cursor.y() - cursorRow()->baseline() + cursorRow()->height() + 1);
1760 #endif
1761 }
1762
1763
1764 void LyXText::cursorUpParagraph()
1765 {
1766         if (cursor.pos() > 0)
1767                 setCursor(cursor.par(), 0);
1768         else if (cursor.par() != ownerParagraphs().begin())
1769                 setCursor(boost::prior(cursor.par()), 0);
1770 }
1771
1772
1773 void LyXText::cursorDownParagraph()
1774 {
1775         ParagraphList::iterator par = cursor.par();
1776         ParagraphList::iterator next_par = boost::next(par);
1777
1778         if (next_par != ownerParagraphs().end())
1779                 setCursor(next_par, 0);
1780         else
1781                 setCursor(par, par->size());
1782 }
1783
1784
1785 // fix the cursor `cur' after a characters has been deleted at `where'
1786 // position. Called by deleteEmptyParagraphMechanism
1787 void LyXText::fixCursorAfterDelete(LyXCursor & cur, LyXCursor const & where)
1788 {
1789         // if cursor is not in the paragraph where the delete occured,
1790         // do nothing
1791         if (cur.par() != where.par())
1792                 return;
1793
1794         // if cursor position is after the place where the delete occured,
1795         // update it
1796         if (cur.pos() > where.pos())
1797                 cur.pos(cur.pos()-1);
1798
1799         // check also if we don't want to set the cursor on a spot behind the
1800         // pagragraph because we erased the last character.
1801         if (cur.pos() > cur.par()->size())
1802                 cur.pos(cur.par()->size());
1803
1804         // recompute row et al. for this cursor
1805         setCursor(cur, cur.par(), cur.pos(), cur.boundary());
1806 }
1807
1808
1809 bool LyXText::deleteEmptyParagraphMechanism(LyXCursor const & old_cursor)
1810 {
1811         // Would be wrong to delete anything if we have a selection.
1812         if (selection.set())
1813                 return false;
1814
1815         // We allow all kinds of "mumbo-jumbo" when freespacing.
1816         if (old_cursor.par()->isFreeSpacing())
1817                 return false;
1818
1819         /* Ok I'll put some comments here about what is missing.
1820            I have fixed BackSpace (and thus Delete) to not delete
1821            double-spaces automagically. I have also changed Cut,
1822            Copy and Paste to hopefully do some sensible things.
1823            There are still some small problems that can lead to
1824            double spaces stored in the document file or space at
1825            the beginning of paragraphs. This happens if you have
1826            the cursor between to spaces and then save. Or if you
1827            cut and paste and the selection have a space at the
1828            beginning and then save right after the paste. I am
1829            sure none of these are very hard to fix, but I will
1830            put out 1.1.4pre2 with FIX_DOUBLE_SPACE defined so
1831            that I can get some feedback. (Lgb)
1832         */
1833
1834         // If old_cursor.pos() == 0 and old_cursor.pos()(1) == LineSeparator
1835         // delete the LineSeparator.
1836         // MISSING
1837
1838         // If old_cursor.pos() == 1 and old_cursor.pos()(0) == LineSeparator
1839         // delete the LineSeparator.
1840         // MISSING
1841
1842         // If the pos around the old_cursor were spaces, delete one of them.
1843         if (old_cursor.par() != cursor.par()
1844             || old_cursor.pos() != cursor.pos()) {
1845
1846                 // Only if the cursor has really moved
1847                 if (old_cursor.pos() > 0
1848                     && old_cursor.pos() < old_cursor.par()->size()
1849                     && old_cursor.par()->isLineSeparator(old_cursor.pos())
1850                     && old_cursor.par()->isLineSeparator(old_cursor.pos() - 1)) {
1851                         bool erased = old_cursor.par()->erase(old_cursor.pos() - 1);
1852                         redoParagraph(old_cursor.par());
1853
1854                         if (!erased)
1855                                 return false;
1856 #ifdef WITH_WARNINGS
1857 #warning This will not work anymore when we have multiple views of the same buffer
1858 // In this case, we will have to correct also the cursors held by
1859 // other bufferviews. It will probably be easier to do that in a more
1860 // automated way in LyXCursor code. (JMarc 26/09/2001)
1861 #endif
1862                         // correct all cursors held by the LyXText
1863                         fixCursorAfterDelete(cursor, old_cursor);
1864                         fixCursorAfterDelete(selection.cursor, old_cursor);
1865                         fixCursorAfterDelete(selection.start, old_cursor);
1866                         fixCursorAfterDelete(selection.end, old_cursor);
1867                         return false;
1868                 }
1869         }
1870
1871         // don't delete anything if this is the ONLY paragraph!
1872         if (ownerParagraphs().size() == 1)
1873                 return false;
1874
1875         // Do not delete empty paragraphs with keepempty set.
1876         if (old_cursor.par()->allowEmpty())
1877                 return false;
1878
1879         // only do our magic if we changed paragraph
1880         if (old_cursor.par() == cursor.par())
1881                 return false;
1882
1883         // record if we have deleted a paragraph
1884         // we can't possibly have deleted a paragraph before this point
1885         bool deleted = false;
1886
1887         if (old_cursor.par()->empty() ||
1888             (old_cursor.par()->size() == 1 &&
1889              old_cursor.par()->isLineSeparator(0))) {
1890                 // ok, we will delete something
1891                 LyXCursor tmpcursor;
1892
1893                 deleted = true;
1894
1895                 bool selection_position_was_oldcursor_position = (
1896                         selection.cursor.par()  == old_cursor.par()
1897                         && selection.cursor.pos() == old_cursor.pos());
1898
1899                 tmpcursor = cursor;
1900                 cursor = old_cursor; // that undo can restore the right cursor position
1901
1902                 ParagraphList::iterator endpit = boost::next(old_cursor.par());
1903                 while (endpit != ownerParagraphs().end() && endpit->getDepth())
1904                         ++endpit;
1905         
1906                 recordUndo(bv(), Undo::DELETE, old_cursor.par(), boost::prior(endpit));
1907                 cursor = tmpcursor;
1908
1909                 // delete old par
1910                 ownerParagraphs().erase(old_cursor.par());
1911                 redoParagraph();
1912
1913                 // correct cursor y
1914                 setCursorIntern(cursor.par(), cursor.pos());
1915
1916                 if (selection_position_was_oldcursor_position) {
1917                         // correct selection
1918                         selection.cursor = cursor;
1919                 }
1920         }
1921         if (!deleted) {
1922                 if (old_cursor.par()->stripLeadingSpaces()) {
1923                         redoParagraph(old_cursor.par());
1924                         // correct cursor y
1925                         setCursorIntern(cursor.par(), cursor.pos());
1926                         selection.cursor = cursor;
1927                 }
1928         }
1929         return deleted;
1930 }
1931
1932
1933 ParagraphList & LyXText::ownerParagraphs() const
1934 {
1935         return paragraphs_;
1936 }
1937
1938
1939 bool LyXText::isInInset() const
1940 {
1941         // Sub-level has non-null bv owner and non-null inset owner.
1942         return inset_owner != 0;
1943 }
1944
1945
1946 int defaultRowHeight()
1947 {
1948         LyXFont const font(LyXFont::ALL_SANE);
1949         return int(font_metrics::maxAscent(font)
1950                  + font_metrics::maxDescent(font) * 1.5);
1951 }