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