]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
1673de181799a5dcfc87ab67666709a553219cae
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXAction.h"
42 #include "lyxfind.h"
43 #include "Layout.h"
44 #include "LyXRC.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "RowPainter.h"
50 #include "Session.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
54 #include "TexRow.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
66
67 #include "mathed/MathData.h"
68
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
76
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/Package.h"
85 #include "support/types.h"
86
87 #include <cerrno>
88 #include <fstream>
89 #include <functional>
90 #include <iterator>
91 #include <sstream>
92 #include <vector>
93
94 using namespace std;
95 using namespace lyx::support;
96
97 namespace lyx {
98
99 namespace Alert = frontend::Alert;
100
101 namespace {
102
103 /// Return an inset of this class if it exists at the current cursor position
104 template <class T>
105 T * getInsetByCode(Cursor const & cur, InsetCode code)
106 {
107         DocIterator it = cur;
108         Inset * inset = it.nextInset();
109         if (inset && inset->lyxCode() == code)
110                 return static_cast<T*>(inset);
111         return 0;
112 }
113
114
115 /// Note that comparing contents can only be used for InsetCommand
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117         docstring const & contents)
118 {
119         DocIterator tmpdit = dit;
120
121         while (tmpdit) {
122                 Inset const * inset = tmpdit.nextInset();
123                 if (inset) {
124                         bool const valid_code = std::find(codes.begin(), codes.end(),
125                                 inset->lyxCode()) != codes.end();
126                         InsetCommand const * ic = inset->asInsetCommand();
127                         bool const same_or_no_contents =  contents.empty()
128                                 || (ic && (ic->getFirstNonOptParam() == contents));
129
130                         if (valid_code && same_or_no_contents) {
131                                 dit = tmpdit;
132                                 return true;
133                         }
134                 }
135                 tmpdit.forwardInset();
136         }
137
138         return false;
139 }
140
141
142 /// Looks for next inset with one of the given codes.
143 /// Note that same_content can only be used for InsetCommand
144 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145         bool same_content)
146 {
147         docstring contents;
148         DocIterator tmpdit = dit;
149         tmpdit.forwardInset();
150         if (!tmpdit)
151                 return false;
152
153         Inset const * inset = tmpdit.nextInset();
154         if (same_content && inset) {
155                 InsetCommand const * ic = inset->asInsetCommand();
156                 if (ic) {
157                         bool const valid_code = std::find(codes.begin(), codes.end(),
158                                 ic->lyxCode()) != codes.end();
159                         if (valid_code)
160                                 contents = ic->getFirstNonOptParam();
161                 }
162         }
163
164         if (!findNextInset(tmpdit, codes, contents)) {
165                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166                         Inset * inset = &tmpdit.bottom().inset();
167                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
168                         if (!findNextInset(tmpdit, codes, contents))
169                                 return false;
170                 } else {
171                         return false;
172                 }
173         }
174
175         dit = tmpdit;
176         return true;
177 }
178
179
180 /// Looks for next inset with the given code
181 void findInset(DocIterator & dit, InsetCode code, bool same_content)
182 {
183         findInset(dit, vector<InsetCode>(1, code), same_content);
184 }
185
186
187 /// Moves cursor to the next inset with one of the given codes.
188 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
189                bool same_content)
190 {
191         Cursor tmpcur = bv->cursor();
192         if (!findInset(tmpcur, codes, same_content)) {
193                 bv->cursor().message(_("No more insets"));
194                 return;
195         }
196
197         tmpcur.clearSelection();
198         bv->setCursor(tmpcur);
199         bv->showCursor();
200 }
201
202
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
205 {
206         gotoInset(bv, vector<InsetCode>(1, code), same_content);
207 }
208
209
210 /// A map from a Text to the associated text metrics
211 typedef map<Text const *, TextMetrics> TextMetricsCache;
212
213 enum ScreenUpdateStrategy {
214         NoScreenUpdate,
215         SingleParUpdate,
216         FullScreenUpdate,
217         DecorationUpdate
218 };
219
220 } // namespace
221
222
223 /////////////////////////////////////////////////////////////////////
224 //
225 // BufferView
226 //
227 /////////////////////////////////////////////////////////////////////
228
229 struct BufferView::Private
230 {
231         Private(BufferView & bv) : update_strategy_(NoScreenUpdate),
232                 wh_(0), cursor_(bv),
233                 anchor_pit_(0), anchor_ypos_(0),
234                 inlineCompletionUniqueChars_(0),
235                 last_inset_(0), clickable_inset_(false),
236                 mouse_position_cache_(),
237                 bookmark_edit_position_(-1), gui_(0),
238                 horiz_scroll_offset_(0), repaint_caret_row_(false)
239         {
240                 xsel_cache_.set = false;
241         }
242
243         ///
244         ScrollbarParameters scrollbarParameters_;
245         ///
246         ScreenUpdateStrategy update_strategy_;
247         ///
248         CoordCache coord_cache_;
249
250         /// Estimated average par height for scrollbar.
251         int wh_;
252         /// this is used to handle XSelection events in the right manner.
253         struct {
254                 CursorSlice cursor;
255                 CursorSlice anchor;
256                 bool set;
257         } xsel_cache_;
258         ///
259         Cursor cursor_;
260         ///
261         pit_type anchor_pit_;
262         ///
263         int anchor_ypos_;
264         ///
265         vector<int> par_height_;
266
267         ///
268         DocIterator inlineCompletionPos_;
269         ///
270         docstring inlineCompletion_;
271         ///
272         size_t inlineCompletionUniqueChars_;
273
274         /// keyboard mapping object.
275         Intl intl_;
276
277         /// last visited inset.
278         /** kept to send setMouseHover(false).
279           * Not owned, so don't delete.
280           */
281         Inset const * last_inset_;
282         /// are we hovering something that we can click
283         bool clickable_inset_;
284
285         /// position of the mouse at the time of the last mouse move
286         /// This is used to update the hovering status of inset in
287         /// cases where the buffer is scrolled, but the mouse didn't move.
288         Point mouse_position_cache_;
289
290         // cache for id of the paragraph which was edited the last time
291         int bookmark_edit_position_;
292
293         mutable TextMetricsCache text_metrics_;
294
295         /// Whom to notify.
296         /** Not owned, so don't delete.
297           */
298         frontend::GuiBufferViewDelegate * gui_;
299
300         /// Cache for Find Next
301         FuncRequest search_request_cache_;
302
303         ///
304         map<string, Inset *> edited_insets_;
305
306         /// When the row where the cursor lies is scrolled, this
307         /// contains the scroll offset
308         int horiz_scroll_offset_;
309         /// a slice pointing to the start of the row where the cursor
310         /// is (at last draw time)
311         CursorSlice current_row_slice_;
312         /// a slice pointing to the start of the row where cursor was
313         /// at previous draw event
314         CursorSlice last_row_slice_;
315
316         /// a slice pointing to where the cursor has been drawn after the current
317         /// draw() call.
318         CursorSlice caret_slice_;
319         /// indicates whether the caret slice needs to be repainted in this draw() run.
320         bool repaint_caret_row_;
321 };
322
323
324 BufferView::BufferView(Buffer & buf)
325         : width_(0), height_(0), full_screen_(false), buffer_(buf),
326       d(new Private(*this))
327 {
328         d->xsel_cache_.set = false;
329         d->intl_.initKeyMapper(lyxrc.use_kbmap);
330
331         d->cursor_.setBuffer(&buf);
332         d->cursor_.push(buffer_.inset());
333         d->cursor_.resetAnchor();
334         d->cursor_.setCurrentFont();
335
336         buffer_.updatePreviews();
337 }
338
339
340 BufferView::~BufferView()
341 {
342         // current buffer is going to be switched-off, save cursor pos
343         // Ideally, the whole cursor stack should be saved, but session
344         // currently can only handle bottom (whole document) level pit and pos.
345         // That is to say, if a cursor is in a nested inset, it will be
346         // restore to the left of the top level inset.
347         LastFilePosSection::FilePos fp;
348         fp.pit = d->cursor_.bottom().pit();
349         fp.pos = d->cursor_.bottom().pos();
350         theSession().lastFilePos().save(buffer_.fileName(), fp);
351
352         if (d->last_inset_)
353                 d->last_inset_->setMouseHover(this, false);
354
355         delete d;
356 }
357
358
359 int BufferView::rightMargin() const
360 {
361         // The value used to be hardcoded to 10, which is 0.1in at 100dpi
362         int const default_margin = Length(0.1, Length::IN).inPixels(0);
363         // The additional test for the case the outliner is opened.
364         if (!full_screen_ || !lyxrc.full_screen_limit
365             || width_ < lyxrc.full_screen_width + 2 * default_margin)
366                 return default_margin;
367
368         return (width_ - lyxrc.full_screen_width) / 2;
369 }
370
371
372 int BufferView::leftMargin() const
373 {
374         return rightMargin();
375 }
376
377
378 int BufferView::inPixels(Length const & len) const
379 {
380         Font const font = buffer().params().getFont();
381         return len.inPixels(workWidth(), theFontMetrics(font).em());
382 }
383
384
385 bool BufferView::isTopScreen() const
386 {
387         return 0 == d->scrollbarParameters_.min;
388 }
389
390
391 bool BufferView::isBottomScreen() const
392 {
393         return 0 == d->scrollbarParameters_.max;
394 }
395
396
397 Intl & BufferView::getIntl()
398 {
399         return d->intl_;
400 }
401
402
403 Intl const & BufferView::getIntl() const
404 {
405         return d->intl_;
406 }
407
408
409 CoordCache & BufferView::coordCache()
410 {
411         return d->coord_cache_;
412 }
413
414
415 CoordCache const & BufferView::coordCache() const
416 {
417         return d->coord_cache_;
418 }
419
420
421 Buffer & BufferView::buffer()
422 {
423         return buffer_;
424 }
425
426
427 Buffer const & BufferView::buffer() const
428 {
429         return buffer_;
430 }
431
432
433 bool BufferView::needsFitCursor() const
434 {
435         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
436                 frontend::FontMetrics const & fm =
437                         theFontMetrics(d->cursor_.getFont().fontInfo());
438                 int const asc = fm.maxAscent();
439                 int const des = fm.maxDescent();
440                 Point const p = getPos(d->cursor_);
441                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
442                         return false;
443         }
444         return true;
445 }
446
447
448 void BufferView::processUpdateFlags(Update::flags flags)
449 {
450         // This is close to a hot-path.
451         LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags()"
452                 << "[fitcursor = " << (flags & Update::FitCursor)
453                 << ", forceupdate = " << (flags & Update::Force)
454                 << ", singlepar = " << (flags & Update::SinglePar)
455                 << "]  buffer: " << &buffer_);
456
457         // FIXME Does this really need doing here? It's done in updateBuffer, and
458         // if the Buffer doesn't need updating, then do the macros?
459         buffer_.updateMacros();
460
461         // Now do the first drawing step if needed. This consists on updating
462         // the CoordCache in updateMetrics().
463         // The second drawing step is done in WorkArea::redraw() if needed.
464         // FIXME: is this still true now that Buffer::changed() is used all over?
465
466         // Case when no explicit update is requested.
467         if (!flags) {
468                 // no need to redraw anything.
469                 d->update_strategy_ = NoScreenUpdate;
470                 return;
471         }
472
473         if (flags == Update::Decoration) {
474                 d->update_strategy_ = DecorationUpdate;
475                 buffer_.changed(false);
476                 return;
477         }
478
479         if (flags == Update::FitCursor
480                 || flags == (Update::Decoration | Update::FitCursor)) {
481                 // tell the frontend to update the screen if needed.
482                 if (needsFitCursor()) {
483                         showCursor();
484                         return;
485                 }
486                 if (flags & Update::Decoration) {
487                         d->update_strategy_ = DecorationUpdate;
488                         buffer_.changed(false);
489                         return;
490                 }
491                 // no screen update is needed in principle, but this
492                 // could change if cursor row needs horizontal scrolling.
493                 d->update_strategy_ = NoScreenUpdate;
494                 buffer_.changed(false);
495                 return;
496         }
497
498         bool const full_metrics = flags & Update::Force || !singleParUpdate();
499
500         if (full_metrics)
501                 // We have to update the full screen metrics.
502                 updateMetrics();
503
504         if (!(flags & Update::FitCursor)) {
505                 // Nothing to do anymore. Trigger a redraw and return
506                 buffer_.changed(false);
507                 return;
508         }
509
510         // updateMetrics() does not update paragraph position
511         // This is done at draw() time. So we need a redraw!
512         buffer_.changed(false);
513
514         if (needsFitCursor()) {
515                 // The cursor is off screen so ensure it is visible.
516                 // refresh it:
517                 showCursor();
518         }
519
520         updateHoveredInset();
521 }
522
523
524 void BufferView::updateScrollbar()
525 {
526         if (height_ == 0 && width_ == 0)
527                 return;
528
529         // We prefer fixed size line scrolling.
530         d->scrollbarParameters_.single_step = defaultRowHeight();
531         // We prefer full screen page scrolling.
532         d->scrollbarParameters_.page_step = height_;
533
534         Text & t = buffer_.text();
535         TextMetrics & tm = d->text_metrics_[&t];
536
537         LYXERR(Debug::GUI, " Updating scrollbar: height: "
538                 << t.paragraphs().size()
539                 << " curr par: " << d->cursor_.bottom().pit()
540                 << " default height " << defaultRowHeight());
541
542         size_t const parsize = t.paragraphs().size();
543         if (d->par_height_.size() != parsize) {
544                 d->par_height_.clear();
545                 // FIXME: We assume a default paragraph height of 2 rows. This
546                 // should probably be pondered with the screen width.
547                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
548         }
549
550         // Look at paragraph heights on-screen
551         pair<pit_type, ParagraphMetrics const *> first = tm.first();
552         pair<pit_type, ParagraphMetrics const *> last = tm.last();
553         for (pit_type pit = first.first; pit <= last.first; ++pit) {
554                 d->par_height_[pit] = tm.parMetrics(pit).height();
555                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
556                         << d->par_height_[pit]);
557         }
558
559         int top_pos = first.second->position() - first.second->ascent();
560         int bottom_pos = last.second->position() + last.second->descent();
561         bool first_visible = first.first == 0 && top_pos >= 0;
562         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
563         if (first_visible && last_visible) {
564                 d->scrollbarParameters_.min = 0;
565                 d->scrollbarParameters_.max = 0;
566                 return;
567         }
568
569         d->scrollbarParameters_.min = top_pos;
570         for (size_t i = 0; i != size_t(first.first); ++i)
571                 d->scrollbarParameters_.min -= d->par_height_[i];
572         d->scrollbarParameters_.max = bottom_pos;
573         for (size_t i = last.first + 1; i != parsize; ++i)
574                 d->scrollbarParameters_.max += d->par_height_[i];
575
576         // The reference is the top position so we remove one page.
577         if (lyxrc.scroll_below_document)
578                 d->scrollbarParameters_.max -= minVisiblePart();
579         else
580                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
581
582         // 0 must be inside the range as it denotes the current position
583         if (d->scrollbarParameters_.max < 0)
584                 d->scrollbarParameters_.max = 0;
585         if (d->scrollbarParameters_.min > 0)
586                 d->scrollbarParameters_.min = 0;
587 }
588
589
590 ScrollbarParameters const & BufferView::scrollbarParameters() const
591 {
592         return d->scrollbarParameters_;
593 }
594
595
596 docstring BufferView::toolTip(int x, int y) const
597 {
598         // Get inset under mouse, if there is one.
599         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
600         if (!covering_inset)
601                 // No inset, no tooltip...
602                 return docstring();
603         return covering_inset->toolTip(*this, x, y);
604 }
605
606
607 string BufferView::contextMenu(int x, int y) const
608 {
609         //If there is a selection, return the containing inset menu
610         if (d->cursor_.selection())
611                 return d->cursor_.inset().contextMenu(*this, x, y);
612
613         // Get inset under mouse, if there is one.
614         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
615         if (covering_inset)
616                 return covering_inset->contextMenu(*this, x, y);
617
618         return buffer_.inset().contextMenu(*this, x, y);
619 }
620
621
622
623 void BufferView::scrollDocView(int const value, bool update)
624 {
625         // The scrollbar values are relative to the top of the screen, therefore the
626         // offset is equal to the target value.
627
628         // No scrolling at all? No need to redraw anything
629         if (value == 0)
630                 return;
631
632         // If the offset is less than 2 screen height, prefer to scroll instead.
633         if (abs(value) <= 2 * height_) {
634                 d->anchor_ypos_ -= value;
635                 buffer_.changed(true);
636                 updateHoveredInset();
637                 return;
638         }
639
640         // cut off at the top
641         if (value <= d->scrollbarParameters_.min) {
642                 DocIterator dit = doc_iterator_begin(&buffer_);
643                 showCursor(dit, false, update);
644                 LYXERR(Debug::SCROLLING, "scroll to top");
645                 return;
646         }
647
648         // cut off at the bottom
649         if (value >= d->scrollbarParameters_.max) {
650                 DocIterator dit = doc_iterator_end(&buffer_);
651                 dit.backwardPos();
652                 showCursor(dit, false, update);
653                 LYXERR(Debug::SCROLLING, "scroll to bottom");
654                 return;
655         }
656
657         // find paragraph at target position
658         int par_pos = d->scrollbarParameters_.min;
659         pit_type i = 0;
660         for (; i != int(d->par_height_.size()); ++i) {
661                 par_pos += d->par_height_[i];
662                 if (par_pos >= value)
663                         break;
664         }
665
666         if (par_pos < value) {
667                 // It seems we didn't find the correct pit so stay on the safe side and
668                 // scroll to bottom.
669                 LYXERR0("scrolling position not found!");
670                 scrollDocView(d->scrollbarParameters_.max, update);
671                 return;
672         }
673
674         DocIterator dit = doc_iterator_begin(&buffer_);
675         dit.pit() = i;
676         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
677         showCursor(dit, false, update);
678 }
679
680
681 // FIXME: this method is not working well.
682 void BufferView::setCursorFromScrollbar()
683 {
684         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
685
686         int const height = 2 * defaultRowHeight();
687         int const first = height;
688         int const last = height_ - height;
689         int newy = 0;
690         Cursor const & oldcur = d->cursor_;
691
692         switch (cursorStatus(oldcur)) {
693         case CUR_ABOVE:
694                 newy = first;
695                 break;
696         case CUR_BELOW:
697                 newy = last;
698                 break;
699         case CUR_INSIDE:
700                 int const y = getPos(oldcur).y_;
701                 newy = min(last, max(y, first));
702                 if (y == newy)
703                         return;
704         }
705         // We reset the cursor because cursorStatus() does not
706         // work when the cursor is within mathed.
707         Cursor cur(*this);
708         cur.reset();
709         tm.setCursorFromCoordinates(cur, 0, newy);
710
711         // update the bufferview cursor and notify insets
712         // FIXME: Care about the d->cursor_ flags to redraw if needed
713         Cursor old = d->cursor_;
714         mouseSetCursor(cur);
715         // the DEPM call in mouseSetCursor() might have destroyed the
716         // paragraph the cursor is in.
717         bool badcursor = old.fixIfBroken();
718         badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
719         if (badcursor)
720                 d->cursor_.fixIfBroken();
721 }
722
723
724 Change const BufferView::getCurrentChange() const
725 {
726         if (!d->cursor_.selection())
727                 return Change(Change::UNCHANGED);
728
729         DocIterator dit = d->cursor_.selectionBegin();
730         // The selected content might have been changed (see #7685)
731         dit = dit.getInnerText();
732         return dit.paragraph().lookupChange(dit.pos());
733 }
734
735
736 // this could be used elsewhere as well?
737 // FIXME: This does not work within mathed!
738 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
739 {
740         Point const p = getPos(dit);
741         if (p.y_ < 0)
742                 return CUR_ABOVE;
743         if (p.y_ > workHeight())
744                 return CUR_BELOW;
745         return CUR_INSIDE;
746 }
747
748
749 void BufferView::bookmarkEditPosition()
750 {
751         // Don't eat cpu time for each keystroke
752         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
753                 return;
754         saveBookmark(0);
755         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
756 }
757
758
759 void BufferView::saveBookmark(unsigned int idx)
760 {
761         // tentatively save bookmark, id and pos will be used to
762         // acturately locate a bookmark in a 'live' lyx session.
763         // pit and pos will be updated with bottom level pit/pos
764         // when lyx exits.
765         if (!buffer_.isInternal()) {
766                 theSession().bookmarks().save(
767                         buffer_.fileName(),
768                         d->cursor_.bottom().pit(),
769                         d->cursor_.bottom().pos(),
770                         d->cursor_.paragraph().id(),
771                         d->cursor_.pos(),
772                         idx
773                         );
774                 if (idx)
775                         // emit message signal.
776                         message(_("Save bookmark"));
777         }
778 }
779
780
781 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
782         int top_id, pos_type top_pos)
783 {
784         bool success = false;
785         DocIterator dit;
786
787         d->cursor_.clearSelection();
788
789         // if a valid par_id is given, try it first
790         // This is the case for a 'live' bookmark when unique paragraph ID
791         // is used to track bookmarks.
792         if (top_id > 0) {
793                 dit = buffer_.getParFromID(top_id);
794                 if (!dit.atEnd()) {
795                         dit.pos() = min(dit.paragraph().size(), top_pos);
796                         // Some slices of the iterator may not be
797                         // reachable (e.g. closed collapsable inset)
798                         // so the dociterator may need to be
799                         // shortened. Otherwise, setCursor may crash
800                         // lyx when the cursor can not be set to these
801                         // insets.
802                         size_t const n = dit.depth();
803                         for (size_t i = 0; i < n; ++i)
804                                 if (!dit[i].inset().editable()) {
805                                         dit.resize(i);
806                                         break;
807                                 }
808                         success = true;
809                 }
810         }
811
812         // if top_id == 0, or searching through top_id failed
813         // This is the case for a 'restored' bookmark when only bottom
814         // (document level) pit was saved. Because of this, bookmark
815         // restoration is inaccurate. If a bookmark was within an inset,
816         // it will be restored to the left of the outmost inset that contains
817         // the bookmark.
818         if (bottom_pit < int(buffer_.paragraphs().size())) {
819                 dit = doc_iterator_begin(&buffer_);
820
821                 dit.pit() = bottom_pit;
822                 dit.pos() = min(bottom_pos, dit.paragraph().size());
823                 success = true;
824         }
825
826         if (success) {
827                 // Note: only bottom (document) level pit is set.
828                 setCursor(dit);
829                 // set the current font.
830                 d->cursor_.setCurrentFont();
831                 // Do not forget to reset the anchor (see #9912)
832                 d->cursor_.resetAnchor();
833                 // To center the screen on this new position we need the
834                 // paragraph position which is computed at draw() time.
835                 // So we need a redraw!
836                 buffer_.changed(false);
837                 if (needsFitCursor())
838                         showCursor();
839         }
840
841         return success;
842 }
843
844
845 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
846 {
847         if (d->cursor_.real_current_font.isRightToLeft()) {
848                 if (d->intl_.keymap == Intl::PRIMARY)
849                         d->intl_.keyMapSec();
850         } else {
851                 if (d->intl_.keymap == Intl::SECONDARY)
852                         d->intl_.keyMapPrim();
853         }
854
855         d->intl_.getTransManager().translateAndInsert(c, t, cur);
856 }
857
858
859 int BufferView::workWidth() const
860 {
861         return width_;
862 }
863
864
865 void BufferView::recenter()
866 {
867         showCursor(d->cursor_, true, true);
868 }
869
870
871 void BufferView::showCursor()
872 {
873         showCursor(d->cursor_, false, true);
874 }
875
876
877 void BufferView::showCursor(DocIterator const & dit,
878         bool recenter, bool update)
879 {
880         if (scrollToCursor(dit, recenter) && update) {
881                 buffer_.changed(true);
882                 updateHoveredInset();
883         }
884 }
885
886
887 void BufferView::scrollToCursor()
888 {
889         if (scrollToCursor(d->cursor_, false)) {
890                 buffer_.changed(true);
891                 updateHoveredInset();
892         }
893 }
894
895
896 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
897 {
898         // We are not properly started yet, delay until resizing is
899         // done.
900         if (height_ == 0)
901                 return false;
902
903         LYXERR(Debug::SCROLLING, "recentering!");
904
905         CursorSlice const & bot = dit.bottom();
906         TextMetrics & tm = d->text_metrics_[bot.text()];
907
908         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
909         int bot_pit = bot.pit();
910         if (bot_pit > max_pit) {
911                 // FIXME: Why does this happen?
912                 LYXERR0("bottom pit is greater that max pit: "
913                         << bot_pit << " > " << max_pit);
914                 bot_pit = max_pit;
915         }
916
917         if (bot_pit == tm.first().first - 1)
918                 tm.newParMetricsUp();
919         else if (bot_pit == tm.last().first + 1)
920                 tm.newParMetricsDown();
921
922         if (tm.contains(bot_pit)) {
923                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
924                 LBUFERR(!pm.rows().empty());
925                 // FIXME: smooth scrolling doesn't work in mathed.
926                 CursorSlice const & cs = dit.innerTextSlice();
927                 int offset = coordOffset(dit).y_;
928                 int ypos = pm.position() + offset;
929                 Dimension const & row_dim =
930                         pm.getRow(cs.pos(), dit.boundary()).dimension();
931                 int scrolled = 0;
932                 if (recenter)
933                         scrolled = scroll(ypos - height_/2);
934
935                 // We try to visualize the whole row, if the row height is larger than
936                 // the screen height, we scroll to a heuristic value of height_ / 4.
937                 // FIXME: This heuristic value should be replaced by a recursive search
938                 // for a row in the inset that can be visualized completely.
939                 else if (row_dim.height() > height_) {
940                         if (ypos < defaultRowHeight())
941                                 scrolled = scroll(ypos - height_ / 4);
942                         else if (ypos > height_ - defaultRowHeight())
943                                 scrolled = scroll(ypos - 3 * height_ / 4);
944                 }
945
946                 // If the top part of the row falls of the screen, we scroll
947                 // up to align the top of the row with the top of the screen.
948                 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
949                         int ynew = row_dim.ascent();
950                         scrolled = scrollUp(ynew - ypos);
951                 }
952
953                 // If the bottom of the row falls of the screen, we scroll down.
954                 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
955                         int ynew = height_ - row_dim.descent();
956                         scrolled = scrollDown(ypos - ynew);
957                 }
958
959                 // else, nothing to do, the cursor is already visible so we just return.
960                 return scrolled != 0;
961         }
962
963         // fix inline completion position
964         if (d->inlineCompletionPos_.fixIfBroken())
965                 d->inlineCompletionPos_ = DocIterator();
966
967         tm.redoParagraph(bot_pit);
968         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
969         int offset = coordOffset(dit).y_;
970
971         d->anchor_pit_ = bot_pit;
972         CursorSlice const & cs = dit.innerTextSlice();
973         Dimension const & row_dim =
974                 pm.getRow(cs.pos(), dit.boundary()).dimension();
975
976         if (recenter)
977                 d->anchor_ypos_ = height_/2;
978         else if (d->anchor_pit_ == 0)
979                 d->anchor_ypos_ = offset + pm.ascent();
980         else if (d->anchor_pit_ == max_pit)
981                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
982         else if (offset > height_)
983                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
984         else
985                 d->anchor_ypos_ = defaultRowHeight() * 2;
986
987         return true;
988 }
989
990
991 void BufferView::makeDocumentClass()
992 {
993         DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
994         buffer_.params().makeDocumentClass();
995         updateDocumentClass(olddc);
996 }
997
998
999 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1000 {
1001         message(_("Converting document to new document class..."));
1002
1003         StableDocIterator backcur(d->cursor_);
1004         ErrorList & el = buffer_.errorList("Class Switch");
1005         cap::switchBetweenClasses(
1006                         olddc, buffer_.params().documentClassPtr(),
1007                         static_cast<InsetText &>(buffer_.inset()), el);
1008
1009         setCursor(backcur.asDocIterator(&buffer_));
1010
1011         buffer_.errors("Class Switch");
1012 }
1013
1014
1015 /** Return the change status at cursor position, taking into account the
1016  * status at each level of the document iterator (a table in a deleted
1017  * footnote is deleted).
1018  * When \param outer is true, the top slice is not looked at.
1019  */
1020 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1021 {
1022         size_t const depth = dit.depth() - (outer ? 1 : 0);
1023
1024         for (size_t i = 0 ; i < depth ; ++i) {
1025                 CursorSlice const & slice = dit[i];
1026                 if (!slice.inset().inMathed()
1027                     && slice.pos() < slice.paragraph().size()) {
1028                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1029                         if (ch != Change::UNCHANGED)
1030                                 return ch;
1031                 }
1032         }
1033         return Change::UNCHANGED;
1034 }
1035
1036
1037 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1038 {
1039         FuncCode const act = cmd.action();
1040
1041         // Can we use a readonly buffer?
1042         if (buffer_.isReadonly()
1043             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1044             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1045                 if (buffer_.hasReadonlyFlag())
1046                         flag.message(from_utf8(N_("Document is read-only")));
1047                 else
1048                         flag.message(from_utf8(N_("Document has been modified externally")));
1049                 flag.setEnabled(false);
1050                 return true;
1051         }
1052
1053         // Are we in a DELETED change-tracking region?
1054         if (lookupChangeType(d->cursor_, true) == Change::DELETED
1055             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1056             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1057                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1058                 flag.setEnabled(false);
1059                 return true;
1060         }
1061
1062         Cursor & cur = d->cursor_;
1063
1064         if (cur.getStatus(cmd, flag))
1065                 return true;
1066
1067         switch (act) {
1068
1069         // FIXME: This is a bit problematic because we don't check if this is
1070         // a document BufferView or not for these LFUNs. We probably have to
1071         // dispatch both to currentBufferView() and, if that fails,
1072         // to documentBufferView(); same as we do now for current Buffer and
1073         // document Buffer. Ideally those LFUN should go to Buffer as they
1074         // operate on the full Buffer and the cursor is only needed either for
1075         // an Undo record or to restore a cursor position. But we don't know
1076         // how to do that inside Buffer of course.
1077         case LFUN_BUFFER_PARAMS_APPLY:
1078         case LFUN_LAYOUT_MODULES_CLEAR:
1079         case LFUN_LAYOUT_MODULE_ADD:
1080         case LFUN_LAYOUT_RELOAD:
1081         case LFUN_TEXTCLASS_APPLY:
1082         case LFUN_TEXTCLASS_LOAD:
1083                 flag.setEnabled(!buffer_.isReadonly());
1084                 break;
1085
1086         case LFUN_UNDO:
1087                 // We do not use the LyXAction flag for readonly because Undo sets the
1088                 // buffer clean/dirty status by itself.
1089                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1090                 break;
1091         case LFUN_REDO:
1092                 // We do not use the LyXAction flag for readonly because Redo sets the
1093                 // buffer clean/dirty status by itself.
1094                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1095                 break;
1096         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1097         case LFUN_FILE_INSERT_PLAINTEXT: {
1098                 docstring const fname = cmd.argument();
1099                 if (!FileName::isAbsolute(to_utf8(fname))) {
1100                         flag.message(_("Absolute filename expected."));
1101                         return false;
1102                 }
1103                 flag.setEnabled(cur.inTexted());
1104                 break;
1105         }
1106         case LFUN_FILE_INSERT:
1107         case LFUN_BOOKMARK_SAVE:
1108                 // FIXME: Actually, these LFUNS should be moved to Text
1109                 flag.setEnabled(cur.inTexted());
1110                 break;
1111
1112         case LFUN_FONT_STATE:
1113         case LFUN_LABEL_INSERT:
1114         case LFUN_INFO_INSERT:
1115         case LFUN_PARAGRAPH_GOTO:
1116         case LFUN_NOTE_NEXT:
1117         case LFUN_REFERENCE_NEXT:
1118         case LFUN_WORD_FIND:
1119         case LFUN_WORD_FIND_FORWARD:
1120         case LFUN_WORD_FIND_BACKWARD:
1121         case LFUN_WORD_REPLACE:
1122         case LFUN_MARK_OFF:
1123         case LFUN_MARK_ON:
1124         case LFUN_MARK_TOGGLE:
1125         case LFUN_SCREEN_RECENTER:
1126         case LFUN_SCREEN_SHOW_CURSOR:
1127         case LFUN_BIBTEX_DATABASE_ADD:
1128         case LFUN_BIBTEX_DATABASE_DEL:
1129         case LFUN_STATISTICS:
1130         case LFUN_KEYMAP_OFF:
1131         case LFUN_KEYMAP_PRIMARY:
1132         case LFUN_KEYMAP_SECONDARY:
1133         case LFUN_KEYMAP_TOGGLE:
1134         case LFUN_INSET_SELECT_ALL:
1135                 flag.setEnabled(true);
1136                 break;
1137
1138         case LFUN_WORD_FINDADV: {
1139                 FindAndReplaceOptions opt;
1140                 istringstream iss(to_utf8(cmd.argument()));
1141                 iss >> opt;
1142                 flag.setEnabled(opt.repl_buf_name.empty()
1143                                 || !buffer_.isReadonly());
1144                 break;
1145         }
1146
1147         case LFUN_LABEL_GOTO:
1148                 flag.setEnabled(!cmd.argument().empty()
1149                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1150                 break;
1151
1152         case LFUN_CHANGES_MERGE:
1153         case LFUN_CHANGE_NEXT:
1154         case LFUN_CHANGE_PREVIOUS:
1155         case LFUN_ALL_CHANGES_ACCEPT:
1156         case LFUN_ALL_CHANGES_REJECT:
1157                 flag.setEnabled(buffer_.areChangesPresent());
1158                 break;
1159
1160         case LFUN_SCREEN_UP:
1161         case LFUN_SCREEN_DOWN:
1162         case LFUN_SCROLL:
1163         case LFUN_SCREEN_UP_SELECT:
1164         case LFUN_SCREEN_DOWN_SELECT:
1165         case LFUN_INSET_FORALL:
1166                 flag.setEnabled(true);
1167                 break;
1168
1169         case LFUN_LAYOUT_TABULAR:
1170                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1171                 break;
1172
1173         case LFUN_LAYOUT:
1174                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1175                 break;
1176
1177         case LFUN_LAYOUT_PARAGRAPH:
1178                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1179                 break;
1180
1181         case LFUN_BRANCH_ADD_INSERT:
1182                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1183                 break;
1184
1185         case LFUN_DIALOG_SHOW_NEW_INSET:
1186                 // FIXME: this is wrong, but I do not understand the
1187                 // intent (JMarc)
1188                 if (cur.inset().lyxCode() == CAPTION_CODE)
1189                         return cur.inset().getStatus(cur, cmd, flag);
1190                 // FIXME we should consider passthru paragraphs too.
1191                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1192                 break;
1193
1194         case LFUN_CITATION_INSERT: {
1195                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1196                 // FIXME: This could turn in a recursive hell.
1197                 // Shouldn't we use Buffer::getStatus() instead?
1198                 flag.setEnabled(lyx::getStatus(fr).enabled());
1199                 break;
1200         }
1201         case LFUN_INSET_APPLY: {
1202                 string const name = cmd.getArg(0);
1203                 Inset * inset = editedInset(name);
1204                 if (inset) {
1205                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1206                         if (!inset->getStatus(cur, fr, flag)) {
1207                                 // Every inset is supposed to handle this
1208                                 LASSERT(false, break);
1209                         }
1210                 } else {
1211                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1212                         flag = lyx::getStatus(fr);
1213                 }
1214                 break;
1215         }
1216
1217         default:
1218                 return false;
1219         }
1220
1221         return true;
1222 }
1223
1224
1225 Inset * BufferView::editedInset(string const & name) const
1226 {
1227         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1228         return it == d->edited_insets_.end() ? 0 : it->second;
1229 }
1230
1231
1232 void BufferView::editInset(string const & name, Inset * inset)
1233 {
1234         d->edited_insets_[name] = inset;
1235 }
1236
1237
1238 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1239 {
1240         LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1241
1242         string const argument = to_utf8(cmd.argument());
1243         Cursor & cur = d->cursor_;
1244         Cursor old = cur;
1245
1246         // Don't dispatch function that does not apply to internal buffers.
1247         if (buffer_.isInternal()
1248             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1249                 return;
1250
1251         // We'll set this back to false if need be.
1252         bool dispatched = true;
1253         buffer_.undo().beginUndoGroup();
1254
1255         FuncCode const act = cmd.action();
1256         switch (act) {
1257
1258         case LFUN_BUFFER_PARAMS_APPLY: {
1259                 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1260                 cur.recordUndoBufferParams();
1261                 istringstream ss(to_utf8(cmd.argument()));
1262                 Lexer lex;
1263                 lex.setStream(ss);
1264                 int const unknown_tokens = buffer_.readHeader(lex);
1265                 if (unknown_tokens != 0) {
1266                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1267                                                 << unknown_tokens << " unknown token"
1268                                                 << (unknown_tokens == 1 ? "" : "s"));
1269                 }
1270                 updateDocumentClass(olddc);
1271
1272                 // We are most certainly here because of a change in the document
1273                 // It is then better to make sure that all dialogs are in sync with
1274                 // current document settings.
1275                 dr.screenUpdate(Update::Force | Update::FitCursor);
1276                 dr.forceBufferUpdate();
1277                 break;
1278         }
1279
1280         case LFUN_LAYOUT_MODULES_CLEAR: {
1281                 // FIXME: this modifies the document in cap::switchBetweenClasses
1282                 //  without calling recordUndo. Fix this before using
1283                 //  recordUndoBufferParams().
1284                 cur.recordUndoFullBuffer();
1285                 buffer_.params().clearLayoutModules();
1286                 makeDocumentClass();
1287                 dr.screenUpdate(Update::Force);
1288                 dr.forceBufferUpdate();
1289                 break;
1290         }
1291
1292         case LFUN_LAYOUT_MODULE_ADD: {
1293                 BufferParams const & params = buffer_.params();
1294                 if (!params.layoutModuleCanBeAdded(argument)) {
1295                         LYXERR0("Module `" << argument <<
1296                                 "' cannot be added due to failed requirements or "
1297                                 "conflicts with installed modules.");
1298                         break;
1299                 }
1300                 // FIXME: this modifies the document in cap::switchBetweenClasses
1301                 //  without calling recordUndo. Fix this before using
1302                 //  recordUndoBufferParams().
1303                 cur.recordUndoFullBuffer();
1304                 buffer_.params().addLayoutModule(argument);
1305                 makeDocumentClass();
1306                 dr.screenUpdate(Update::Force);
1307                 dr.forceBufferUpdate();
1308                 break;
1309         }
1310
1311         case LFUN_TEXTCLASS_APPLY: {
1312                 // since this shortcircuits, the second call is made only if
1313                 // the first fails
1314                 bool const success =
1315                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1316                         LayoutFileList::get().load(argument, buffer_.filePath());
1317                 if (!success) {
1318                         docstring s = bformat(_("The document class `%1$s' "
1319                                                  "could not be loaded."), from_utf8(argument));
1320                         frontend::Alert::error(_("Could not load class"), s);
1321                         break;
1322                 }
1323
1324                 LayoutFile const * old_layout = buffer_.params().baseClass();
1325                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1326
1327                 if (old_layout == new_layout)
1328                         // nothing to do
1329                         break;
1330
1331                 // Save the old, possibly modular, layout for use in conversion.
1332                 // FIXME: this modifies the document in cap::switchBetweenClasses
1333                 //  without calling recordUndo. Fix this before using
1334                 //  recordUndoBufferParams().
1335                 cur.recordUndoFullBuffer();
1336                 buffer_.params().setBaseClass(argument);
1337                 makeDocumentClass();
1338                 dr.screenUpdate(Update::Force);
1339                 dr.forceBufferUpdate();
1340                 break;
1341         }
1342
1343         case LFUN_TEXTCLASS_LOAD: {
1344                 // since this shortcircuits, the second call is made only if
1345                 // the first fails
1346                 bool const success =
1347                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1348                         LayoutFileList::get().load(argument, buffer_.filePath());
1349                 if (!success) {
1350                         docstring s = bformat(_("The document class `%1$s' "
1351                                                  "could not be loaded."), from_utf8(argument));
1352                         frontend::Alert::error(_("Could not load class"), s);
1353                 }
1354                 break;
1355         }
1356
1357         case LFUN_LAYOUT_RELOAD: {
1358                 LayoutFileIndex bc = buffer_.params().baseClassID();
1359                 LayoutFileList::get().reset(bc);
1360                 buffer_.params().setBaseClass(bc);
1361                 makeDocumentClass();
1362                 dr.screenUpdate(Update::Force);
1363                 dr.forceBufferUpdate();
1364                 break;
1365         }
1366
1367         case LFUN_UNDO:
1368                 dr.setMessage(_("Undo"));
1369                 cur.clearSelection();
1370                 if (!cur.textUndo())
1371                         dr.setMessage(_("No further undo information"));
1372                 else
1373                         dr.screenUpdate(Update::Force | Update::FitCursor);
1374                 dr.forceBufferUpdate();
1375                 // we only need to do this if we have deleted or restored a
1376                 // BiBTeX inset. but there is no other place to do it. one
1377                 // obvious idea is to try to do it in a copy constructor for
1378                 // InsetBibTeX, but when that is invoked, the buffer_ member
1379                 // is not yet set. another idea is to look at the InsetLists
1380                 // of the various paragraphs. but we'd have to recurse through
1381                 // the contained insets to make that work. it doesn't seem to
1382                 // be worth it, as this will not happen that often.
1383                 buffer().invalidateBibfileCache();
1384                 buffer().removeBiblioTempFiles();
1385                 break;
1386
1387         case LFUN_REDO:
1388                 dr.setMessage(_("Redo"));
1389                 cur.clearSelection();
1390                 if (!cur.textRedo())
1391                         dr.setMessage(_("No further redo information"));
1392                 else
1393                         dr.screenUpdate(Update::Force | Update::FitCursor);
1394                 dr.forceBufferUpdate();
1395                 // see above
1396                 buffer().invalidateBibfileCache();
1397                 buffer().removeBiblioTempFiles();
1398                 break;
1399
1400         case LFUN_FONT_STATE:
1401                 dr.setMessage(cur.currentState(false));
1402                 break;
1403
1404         case LFUN_BOOKMARK_SAVE:
1405                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1406                 break;
1407
1408         case LFUN_LABEL_GOTO: {
1409                 docstring label = cmd.argument();
1410                 if (label.empty()) {
1411                         InsetRef * inset =
1412                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1413                         if (inset) {
1414                                 label = inset->getParam("reference");
1415                                 // persistent=false: use temp_bookmark
1416                                 saveBookmark(0);
1417                         }
1418                 }
1419                 if (!label.empty()) {
1420                         gotoLabel(label);
1421                         // at the moment, this is redundant, since gotoLabel will
1422                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1423                         // to have it here.
1424                         dr.screenUpdate(Update::Force | Update::FitCursor);
1425                 }
1426                 break;
1427         }
1428
1429         case LFUN_PARAGRAPH_GOTO: {
1430                 int const id = convert<int>(cmd.getArg(0));
1431                 pos_type const pos = convert<int>(cmd.getArg(1));
1432                 if (id < 0)
1433                         break;
1434                 string const str_id_end = cmd.getArg(2);
1435                 string const str_pos_end = cmd.getArg(3);
1436                 int i = 0;
1437                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1438                         b = theBufferList().next(b)) {
1439
1440                         Cursor cur(*this);
1441                         cur.setCursor(b->getParFromID(id));
1442                         if (cur.atEnd()) {
1443                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1444                                 ++i;
1445                                 continue;
1446                         }
1447                         LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1448                                 << " found in buffer `"
1449                                 << b->absFileName() << "'.");
1450
1451                         if (b == &buffer_) {
1452                                 bool success;
1453                                 if (str_id_end.empty() || str_pos_end.empty()) {
1454                                         // Set the cursor
1455                                         cur.pos() = pos;
1456                                         mouseSetCursor(cur);
1457                                         success = true;
1458                                 } else {
1459                                         int const id_end = convert<int>(str_id_end);
1460                                         pos_type const pos_end = convert<int>(str_pos_end);
1461                                         success = setCursorFromEntries({id, pos},
1462                                                                        {id_end, pos_end});
1463                                 }
1464                                 if (success)
1465                                         dr.screenUpdate(Update::Force | Update::FitCursor);
1466                         } else {
1467                                 // Switch to other buffer view and resend cmd
1468                                 lyx::dispatch(FuncRequest(
1469                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1470                                 lyx::dispatch(cmd);
1471                         }
1472                         break;
1473                 }
1474                 break;
1475         }
1476
1477         case LFUN_NOTE_NEXT:
1478                 gotoInset(this, NOTE_CODE, false);
1479                 break;
1480
1481         case LFUN_REFERENCE_NEXT: {
1482                 vector<InsetCode> tmp;
1483                 tmp.push_back(LABEL_CODE);
1484                 tmp.push_back(REF_CODE);
1485                 gotoInset(this, tmp, true);
1486                 break;
1487         }
1488
1489         case LFUN_CHANGE_NEXT:
1490                 findNextChange(this);
1491                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1492                 dr.screenUpdate(Update::Force | Update::FitCursor);
1493                 break;
1494
1495         case LFUN_CHANGE_PREVIOUS:
1496                 findPreviousChange(this);
1497                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1498                 dr.screenUpdate(Update::Force | Update::FitCursor);
1499                 break;
1500
1501         case LFUN_CHANGES_MERGE:
1502                 if (findNextChange(this) || findPreviousChange(this)) {
1503                         dr.screenUpdate(Update::Force | Update::FitCursor);
1504                         dr.forceBufferUpdate();
1505                         showDialog("changes");
1506                 }
1507                 break;
1508
1509         case LFUN_ALL_CHANGES_ACCEPT:
1510                 // select complete document
1511                 cur.reset();
1512                 cur.selHandle(true);
1513                 buffer_.text().cursorBottom(cur);
1514                 // accept everything in a single step to support atomic undo
1515                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1516                 cur.resetAnchor();
1517                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1518                 dr.screenUpdate(Update::Force | Update::FitCursor);
1519                 dr.forceBufferUpdate();
1520                 break;
1521
1522         case LFUN_ALL_CHANGES_REJECT:
1523                 // select complete document
1524                 cur.reset();
1525                 cur.selHandle(true);
1526                 buffer_.text().cursorBottom(cur);
1527                 // reject everything in a single step to support atomic undo
1528                 // Note: reject does not work recursively; the user may have to repeat the operation
1529                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1530                 cur.resetAnchor();
1531                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1532                 dr.screenUpdate(Update::Force | Update::FitCursor);
1533                 dr.forceBufferUpdate();
1534                 break;
1535
1536         case LFUN_WORD_FIND_FORWARD:
1537         case LFUN_WORD_FIND_BACKWARD: {
1538                 // FIXME THREAD
1539                 // Would it maybe be better if this variable were view specific anyway?
1540                 static docstring last_search;
1541                 docstring searched_string;
1542
1543                 if (!cmd.argument().empty()) {
1544                         last_search = cmd.argument();
1545                         searched_string = cmd.argument();
1546                 } else {
1547                         searched_string = last_search;
1548                 }
1549
1550                 if (searched_string.empty())
1551                         break;
1552
1553                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1554                 docstring const data =
1555                         find2string(searched_string, true, false, fw);
1556                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1557                 if (found)
1558                         dr.screenUpdate(Update::Force | Update::FitCursor);
1559                 break;
1560         }
1561
1562         case LFUN_WORD_FIND: {
1563                 FuncRequest req = cmd;
1564                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1565                         req = d->search_request_cache_;
1566                 if (req.argument().empty()) {
1567                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1568                         break;
1569                 }
1570                 if (lyxfind(this, req))
1571                         dr.screenUpdate(Update::Force | Update::FitCursor);
1572
1573                 d->search_request_cache_ = req;
1574                 break;
1575         }
1576
1577         case LFUN_WORD_REPLACE: {
1578                 bool has_deleted = false;
1579                 if (cur.selection()) {
1580                         DocIterator beg = cur.selectionBegin();
1581                         DocIterator end = cur.selectionEnd();
1582                         if (beg.pit() == end.pit()) {
1583                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1584                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1585                                                 has_deleted = true;
1586                                                 break;
1587                                         }
1588                                 }
1589                         }
1590                 }
1591                 if (lyxreplace(this, cmd, has_deleted)) {
1592                         dr.forceBufferUpdate();
1593                         dr.screenUpdate(Update::Force | Update::FitCursor);
1594                 }
1595                 break;
1596         }
1597
1598         case LFUN_WORD_FINDADV: {
1599                 FindAndReplaceOptions opt;
1600                 istringstream iss(to_utf8(cmd.argument()));
1601                 iss >> opt;
1602                 if (findAdv(this, opt)) {
1603                         dr.screenUpdate(Update::Force | Update::FitCursor);
1604                         cur.dispatched();
1605                         dispatched = true;
1606                 } else {
1607                         cur.undispatched();
1608                         dispatched = false;
1609                 }
1610                 break;
1611         }
1612
1613         case LFUN_MARK_OFF:
1614                 cur.clearSelection();
1615                 dr.setMessage(from_utf8(N_("Mark off")));
1616                 break;
1617
1618         case LFUN_MARK_ON:
1619                 cur.clearSelection();
1620                 cur.setMark(true);
1621                 dr.setMessage(from_utf8(N_("Mark on")));
1622                 break;
1623
1624         case LFUN_MARK_TOGGLE:
1625                 cur.selection(false);
1626                 if (cur.mark()) {
1627                         cur.setMark(false);
1628                         dr.setMessage(from_utf8(N_("Mark removed")));
1629                 } else {
1630                         cur.setMark(true);
1631                         dr.setMessage(from_utf8(N_("Mark set")));
1632                 }
1633                 cur.resetAnchor();
1634                 break;
1635
1636         case LFUN_SCREEN_SHOW_CURSOR:
1637                 showCursor();
1638                 break;
1639
1640         case LFUN_SCREEN_RECENTER:
1641                 recenter();
1642                 break;
1643
1644         case LFUN_BIBTEX_DATABASE_ADD: {
1645                 Cursor tmpcur = cur;
1646                 findInset(tmpcur, BIBTEX_CODE, false);
1647                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1648                                                 BIBTEX_CODE);
1649                 if (inset) {
1650                         if (inset->addDatabase(cmd.argument())) {
1651                                 buffer_.invalidateBibfileCache();
1652                                 dr.forceBufferUpdate();
1653                         }
1654                 }
1655                 break;
1656         }
1657
1658         case LFUN_BIBTEX_DATABASE_DEL: {
1659                 Cursor tmpcur = cur;
1660                 findInset(tmpcur, BIBTEX_CODE, false);
1661                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1662                                                 BIBTEX_CODE);
1663                 if (inset) {
1664                         if (inset->delDatabase(cmd.argument())) {
1665                                 buffer_.invalidateBibfileCache();
1666                                 dr.forceBufferUpdate();
1667                         }
1668                 }
1669                 break;
1670         }
1671
1672         case LFUN_STATISTICS: {
1673                 DocIterator from, to;
1674                 if (cur.selection()) {
1675                         from = cur.selectionBegin();
1676                         to = cur.selectionEnd();
1677                 } else {
1678                         from = doc_iterator_begin(&buffer_);
1679                         to = doc_iterator_end(&buffer_);
1680                 }
1681                 buffer_.updateStatistics(from, to);
1682                 int const words = buffer_.wordCount();
1683                 int const chars = buffer_.charCount(false);
1684                 int const chars_blanks = buffer_.charCount(true);
1685                 docstring message;
1686                 if (cur.selection())
1687                         message = _("Statistics for the selection:");
1688                 else
1689                         message = _("Statistics for the document:");
1690                 message += "\n\n";
1691                 if (words != 1)
1692                         message += bformat(_("%1$d words"), words);
1693                 else
1694                         message += _("One word");
1695                 message += "\n";
1696                 if (chars_blanks != 1)
1697                         message += bformat(_("%1$d characters (including blanks)"),
1698                                           chars_blanks);
1699                 else
1700                         message += _("One character (including blanks)");
1701                 message += "\n";
1702                 if (chars != 1)
1703                         message += bformat(_("%1$d characters (excluding blanks)"),
1704                                           chars);
1705                 else
1706                         message += _("One character (excluding blanks)");
1707
1708                 Alert::information(_("Statistics"), message);
1709         }
1710                 break;
1711
1712         case LFUN_SCREEN_UP:
1713         case LFUN_SCREEN_DOWN: {
1714                 Point p = getPos(cur);
1715                 // This code has been commented out to enable to scroll down a
1716                 // document, even if there are large insets in it (see bug #5465).
1717                 /*if (p.y_ < 0 || p.y_ > height_) {
1718                         // The cursor is off-screen so recenter before proceeding.
1719                         showCursor();
1720                         p = getPos(cur);
1721                 }*/
1722                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1723                         ? -height_ : height_);
1724                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1725                         p = Point(0, 0);
1726                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1727                         p = Point(width_, height_);
1728                 bool const in_texted = cur.inTexted();
1729                 cur.setCursor(doc_iterator_begin(cur.buffer()));
1730                 cur.selHandle(false);
1731                 buffer_.changed(true);
1732                 updateHoveredInset();
1733
1734                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1735                         true, act == LFUN_SCREEN_UP);
1736                 //FIXME: what to do with cur.x_target()?
1737                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1738                 cur.finishUndo();
1739
1740                 if (update || cur.mark())
1741                         dr.screenUpdate(Update::Force | Update::FitCursor);
1742                 if (update)
1743                         dr.forceBufferUpdate();
1744                 break;
1745         }
1746
1747         case LFUN_SCROLL: {
1748                 string const scroll_type = cmd.getArg(0);
1749                 int scroll_step = 0;
1750                 if (scroll_type == "line")
1751                         scroll_step = d->scrollbarParameters_.single_step;
1752                 else if (scroll_type == "page")
1753                         scroll_step = d->scrollbarParameters_.page_step;
1754                 else
1755                         return;
1756                 string const scroll_quantity = cmd.getArg(1);
1757                 if (scroll_quantity == "up")
1758                         scrollUp(scroll_step);
1759                 else if (scroll_quantity == "down")
1760                         scrollDown(scroll_step);
1761                 else {
1762                         int const scroll_value = convert<int>(scroll_quantity);
1763                         if (scroll_value)
1764                                 scroll(scroll_step * scroll_value);
1765                 }
1766                 buffer_.changed(true);
1767                 updateHoveredInset();
1768                 dr.forceBufferUpdate();
1769                 break;
1770         }
1771
1772         case LFUN_SCREEN_UP_SELECT: {
1773                 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1774                 cur.selHandle(true);
1775                 if (isTopScreen()) {
1776                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1777                         cur.finishUndo();
1778                         break;
1779                 }
1780                 int y = getPos(cur).y_;
1781                 int const ymin = y - height_ + defaultRowHeight();
1782                 while (y > ymin && cur.up())
1783                         y = getPos(cur).y_;
1784
1785                 cur.finishUndo();
1786                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1787                 break;
1788         }
1789
1790         case LFUN_SCREEN_DOWN_SELECT: {
1791                 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1792                 cur.selHandle(true);
1793                 if (isBottomScreen()) {
1794                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1795                         cur.finishUndo();
1796                         break;
1797                 }
1798                 int y = getPos(cur).y_;
1799                 int const ymax = y + height_ - defaultRowHeight();
1800                 while (y < ymax && cur.down())
1801                         y = getPos(cur).y_;
1802
1803                 cur.finishUndo();
1804                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1805                 break;
1806         }
1807
1808
1809         case LFUN_INSET_SELECT_ALL: {
1810                 // true if all cells are selected
1811                 bool const all_selected = cur.depth() > 1
1812                     && cur.selBegin().at_begin()
1813                     && cur.selEnd().at_end();
1814                 // true if some cells are selected
1815                 bool const cells_selected = cur.depth() > 1
1816                     && cur.selBegin().at_cell_begin()
1817                         && cur.selEnd().at_cell_end();
1818                 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1819                         // All the contents of the inset if selected, or only at
1820                         // least one cell but inset is not a table.
1821                         // Select the inset from outside.
1822                         cur.pop();
1823                         cur.resetAnchor();
1824                         cur.selection(true);
1825                         cur.posForward();
1826                 } else if (cells_selected) {
1827                         // At least one complete cell is selected and inset is a table.
1828                         // Select all cells
1829                         cur.idx() = 0;
1830                         cur.pos() = 0;
1831                         cur.resetAnchor();
1832                         cur.selection(true);
1833                         cur.idx() = cur.lastidx();
1834                         cur.pos() = cur.lastpos();
1835                 } else {
1836                         // select current cell
1837                         cur.pit() = 0;
1838                         cur.pos() = 0;
1839                         cur.resetAnchor();
1840                         cur.selection(true);
1841                         cur.pit() = cur.lastpit();
1842                         cur.pos() = cur.lastpos();
1843                 }
1844                 cur.setCurrentFont();
1845                 dr.screenUpdate(Update::Force);
1846                 break;
1847         }
1848
1849
1850         // This would be in Buffer class if only Cursor did not
1851         // require a bufferview
1852         case LFUN_INSET_FORALL: {
1853                 docstring const name = from_utf8(cmd.getArg(0));
1854                 string const commandstr = cmd.getLongArg(1);
1855                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1856
1857                 // an arbitrary number to limit number of iterations
1858                 const int max_iter = 100000;
1859                 int iterations = 0;
1860                 Cursor & cur = d->cursor_;
1861                 Cursor const savecur = cur;
1862                 cur.reset();
1863                 if (!cur.nextInset())
1864                         cur.forwardInset();
1865                 cur.beginUndoGroup();
1866                 while(cur && iterations < max_iter) {
1867                         Inset * const ins = cur.nextInset();
1868                         if (!ins)
1869                                 break;
1870                         docstring insname = ins->layoutName();
1871                         while (!insname.empty()) {
1872                                 if (insname == name || name == from_utf8("*")) {
1873                                         cur.recordUndo();
1874                                         lyx::dispatch(fr, dr);
1875                                         ++iterations;
1876                                         break;
1877                                 }
1878                                 size_t const i = insname.rfind(':');
1879                                 if (i == string::npos)
1880                                         break;
1881                                 insname = insname.substr(0, i);
1882                         }
1883                         // if we did not delete the inset, skip it
1884                         if (!cur.nextInset() || cur.nextInset() == ins)
1885                                 cur.forwardInset();
1886                 }
1887                 cur = savecur;
1888                 cur.fixIfBroken();
1889                 /** This is a dummy undo record only to remember the cursor
1890                  * that has just been set; this will be used on a redo action
1891                  * (see ticket #10097)
1892
1893                  * FIXME: a better fix would be to have a way to set the
1894                  * cursor value directly, but I am not sure it is worth it.
1895                  */
1896                 cur.recordUndo();
1897                 cur.endUndoGroup();
1898                 dr.screenUpdate(Update::Force);
1899                 dr.forceBufferUpdate();
1900
1901                 if (iterations >= max_iter) {
1902                         dr.setError(true);
1903                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1904                 } else
1905                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1906                 break;
1907         }
1908
1909
1910         case LFUN_BRANCH_ADD_INSERT: {
1911                 docstring branch_name = from_utf8(cmd.getArg(0));
1912                 if (branch_name.empty())
1913                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1914                                                 branch_name.empty())
1915                                 break;
1916
1917                 DispatchResult drtmp;
1918                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1919                 if (drtmp.error()) {
1920                         Alert::warning(_("Branch already exists"), drtmp.message());
1921                         break;
1922                 }
1923                 BranchList & branch_list = buffer_.params().branchlist();
1924                 vector<docstring> const branches =
1925                         getVectorFromString(branch_name, branch_list.separator());
1926                 for (vector<docstring>::const_iterator it = branches.begin();
1927                      it != branches.end(); ++it) {
1928                         branch_name = *it;
1929                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1930                 }
1931                 break;
1932         }
1933
1934         case LFUN_KEYMAP_OFF:
1935                 getIntl().keyMapOn(false);
1936                 break;
1937
1938         case LFUN_KEYMAP_PRIMARY:
1939                 getIntl().keyMapPrim();
1940                 break;
1941
1942         case LFUN_KEYMAP_SECONDARY:
1943                 getIntl().keyMapSec();
1944                 break;
1945
1946         case LFUN_KEYMAP_TOGGLE:
1947                 getIntl().toggleKeyMap();
1948                 break;
1949
1950         case LFUN_DIALOG_SHOW_NEW_INSET: {
1951                 string const name = cmd.getArg(0);
1952                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1953                 if (decodeInsetParam(name, data, buffer_))
1954                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1955                 else
1956                         lyxerr << "Inset type '" << name <<
1957                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1958                 break;
1959         }
1960
1961         case LFUN_CITATION_INSERT: {
1962                 if (argument.empty()) {
1963                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1964                         break;
1965                 }
1966                 // we can have one optional argument, delimited by '|'
1967                 // citation-insert <key>|<text_before>
1968                 // this should be enhanced to also support text_after
1969                 // and citation style
1970                 string arg = argument;
1971                 string opt1;
1972                 if (contains(argument, "|")) {
1973                         arg = token(argument, '|', 0);
1974                         opt1 = token(argument, '|', 1);
1975                 }
1976
1977                 // if our cursor is directly in front of or behind a citation inset,
1978                 // we will instead add the new key to it.
1979                 Inset * inset = cur.nextInset();
1980                 if (!inset || inset->lyxCode() != CITE_CODE)
1981                         inset = cur.prevInset();
1982                 if (inset && inset->lyxCode() == CITE_CODE) {
1983                         InsetCitation * icite = static_cast<InsetCitation *>(inset);
1984                         if (icite->addKey(arg)) {
1985                                 dr.forceBufferUpdate();
1986                                 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1987                                 if (!opt1.empty())
1988                                         LYXERR0("Discarding optional argument to citation-insert.");
1989                         }
1990                         dispatched = true;
1991                         break;
1992                 }
1993                 InsetCommandParams icp(CITE_CODE);
1994                 icp["key"] = from_utf8(arg);
1995                 if (!opt1.empty())
1996                         icp["before"] = from_utf8(opt1);
1997                 string icstr = InsetCommand::params2string(icp);
1998                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1999                 lyx::dispatch(fr);
2000                 break;
2001         }
2002
2003         case LFUN_INSET_APPLY: {
2004                 string const name = cmd.getArg(0);
2005                 Inset * inset = editedInset(name);
2006                 if (!inset) {
2007                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2008                         lyx::dispatch(fr);
2009                         break;
2010                 }
2011                 // put cursor in front of inset.
2012                 if (!setCursorFromInset(inset)) {
2013                         LASSERT(false, break);
2014                 }
2015                 cur.recordUndo();
2016                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2017                 inset->dispatch(cur, fr);
2018                 dr.screenUpdate(cur.result().screenUpdate());
2019                 if (cur.result().needBufferUpdate())
2020                         dr.forceBufferUpdate();
2021                 break;
2022         }
2023
2024         // FIXME:
2025         // The change of language of buffer belongs to the Buffer class.
2026         // We have to do it here because we need a cursor for Undo.
2027         // When Undo::recordUndoBufferParams() is implemented someday
2028         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2029         case LFUN_BUFFER_LANGUAGE: {
2030                 Language const * oldL = buffer_.params().language;
2031                 Language const * newL = languages.getLanguage(argument);
2032                 if (!newL || oldL == newL)
2033                         break;
2034                 if (oldL->rightToLeft() == newL->rightToLeft()) {
2035                         cur.recordUndoFullBuffer();
2036                         buffer_.changeLanguage(oldL, newL);
2037                         cur.setCurrentFont();
2038                         dr.forceBufferUpdate();
2039                 }
2040                 break;
2041         }
2042
2043         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2044         case LFUN_FILE_INSERT_PLAINTEXT: {
2045                 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2046                 string const fname = to_utf8(cmd.argument());
2047                 if (!FileName::isAbsolute(fname))
2048                         dr.setMessage(_("Absolute filename expected."));
2049                 else
2050                         insertPlaintextFile(FileName(fname), as_paragraph);
2051                 break;
2052         }
2053
2054         default:
2055                 // OK, so try the Buffer itself...
2056                 buffer_.dispatch(cmd, dr);
2057                 dispatched = dr.dispatched();
2058                 break;
2059         }
2060
2061         buffer_.undo().endUndoGroup();
2062         dr.dispatched(dispatched);
2063
2064         // NOTE: The code below is copied from Cursor::dispatch. If you
2065         // need to modify this, please update the other one too.
2066
2067         // notify insets we just entered/left
2068         if (cursor() != old) {
2069                 old.beginUndoGroup();
2070                 old.fixIfBroken();
2071                 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2072                 if (badcursor) {
2073                         cursor().fixIfBroken();
2074                         resetInlineCompletionPos();
2075                 }
2076                 old.endUndoGroup();
2077         }
2078 }
2079
2080
2081 docstring const BufferView::requestSelection()
2082 {
2083         Cursor & cur = d->cursor_;
2084
2085         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2086         if (!cur.selection()) {
2087                 d->xsel_cache_.set = false;
2088                 return docstring();
2089         }
2090
2091         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2092         if (!d->xsel_cache_.set ||
2093             cur.top() != d->xsel_cache_.cursor ||
2094             cur.realAnchor().top() != d->xsel_cache_.anchor)
2095         {
2096                 d->xsel_cache_.cursor = cur.top();
2097                 d->xsel_cache_.anchor = cur.realAnchor().top();
2098                 d->xsel_cache_.set = cur.selection();
2099                 return cur.selectionAsString(false);
2100         }
2101         return docstring();
2102 }
2103
2104
2105 void BufferView::clearSelection()
2106 {
2107         d->cursor_.clearSelection();
2108         // Clear the selection buffer. Otherwise a subsequent
2109         // middle-mouse-button paste would use the selection buffer,
2110         // not the more current external selection.
2111         cap::clearSelection();
2112         d->xsel_cache_.set = false;
2113         // The buffer did not really change, but this causes the
2114         // redraw we need because we cleared the selection above.
2115         buffer_.changed(false);
2116 }
2117
2118
2119 void BufferView::resize(int width, int height)
2120 {
2121         // Update from work area
2122         width_ = width;
2123         height_ = height;
2124
2125         // Clear the paragraph height cache.
2126         d->par_height_.clear();
2127         // Redo the metrics.
2128         updateMetrics();
2129 }
2130
2131
2132 Inset const * BufferView::getCoveringInset(Text const & text,
2133                 int x, int y) const
2134 {
2135         TextMetrics & tm = d->text_metrics_[&text];
2136         Inset * inset = tm.checkInsetHit(x, y);
2137         if (!inset)
2138                 return 0;
2139
2140         if (!inset->descendable(*this))
2141                 // No need to go further down if the inset is not
2142                 // descendable.
2143                 return inset;
2144
2145         size_t cell_number = inset->nargs();
2146         // Check all the inner cell.
2147         for (size_t i = 0; i != cell_number; ++i) {
2148                 Text const * inner_text = inset->getText(i);
2149                 if (inner_text) {
2150                         // Try deeper.
2151                         Inset const * inset_deeper =
2152                                 getCoveringInset(*inner_text, x, y);
2153                         if (inset_deeper)
2154                                 return inset_deeper;
2155                 }
2156         }
2157
2158         return inset;
2159 }
2160
2161
2162 void BufferView::updateHoveredInset() const
2163 {
2164         // Get inset under mouse, if there is one.
2165         int const x = d->mouse_position_cache_.x_;
2166         int const y = d->mouse_position_cache_.y_;
2167         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2168
2169         d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2170
2171         if (covering_inset == d->last_inset_)
2172                 // Same inset, no need to do anything...
2173                 return;
2174
2175         bool need_redraw = false;
2176         if (d->last_inset_) {
2177                 // Remove the hint on the last hovered inset (if any).
2178                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2179                 d->last_inset_ = 0;
2180         }
2181
2182         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2183                 need_redraw = true;
2184                 // Only the insets that accept the hover state, do
2185                 // clear the last_inset_, so only set the last_inset_
2186                 // member if the hovered setting is accepted.
2187                 d->last_inset_ = covering_inset;
2188         }
2189
2190         if (need_redraw) {
2191                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2192                                 << d->mouse_position_cache_.x_ << ", "
2193                                 << d->mouse_position_cache_.y_ << ")");
2194
2195                 d->update_strategy_ = DecorationUpdate;
2196
2197                 // This event (moving without mouse click) is not passed further.
2198                 // This should be changed if it is further utilized.
2199                 buffer_.changed(false);
2200         }
2201 }
2202
2203
2204 void BufferView::clearLastInset(Inset * inset) const
2205 {
2206         if (d->last_inset_ != inset) {
2207                 LYXERR0("Wrong last_inset!");
2208                 LATTEST(false);
2209         }
2210         d->last_inset_ = 0;
2211 }
2212
2213
2214 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2215 {
2216         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2217
2218         // This is only called for mouse related events including
2219         // LFUN_FILE_OPEN generated by drag-and-drop.
2220         FuncRequest cmd = cmd0;
2221
2222         Cursor old = cursor();
2223         Cursor cur(*this);
2224         cur.push(buffer_.inset());
2225         cur.selection(d->cursor_.selection());
2226
2227         // Either the inset under the cursor or the
2228         // surrounding Text will handle this event.
2229
2230         // make sure we stay within the screen...
2231         cmd.set_y(min(max(cmd.y(), -1), height_));
2232
2233         d->mouse_position_cache_.x_ = cmd.x();
2234         d->mouse_position_cache_.y_ = cmd.y();
2235
2236         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2237                 updateHoveredInset();
2238                 return;
2239         }
2240
2241         // Build temporary cursor.
2242         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2243         if (inset) {
2244                 // If inset is not editable, cur.pos() might point behind the
2245                 // inset (depending on cmd.x(), cmd.y()). This is needed for
2246                 // editing to fix bug 9628, but e.g. the context menu needs a
2247                 // cursor in front of the inset.
2248                 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2249                      || inset->lyxCode() == SEPARATOR_CODE) &&
2250                     cur.nextInset() != inset && cur.prevInset() == inset)
2251                         cur.posBackward();
2252         } else if (cur.inTexted() && cur.pos()
2253                         && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2254                 // Always place cursor in front of a separator inset.
2255                 cur.posBackward();
2256         }
2257
2258         // Put anchor at the same position.
2259         cur.resetAnchor();
2260
2261         cur.beginUndoGroup();
2262
2263         // Try to dispatch to an non-editable inset near this position
2264         // via the temp cursor. If the inset wishes to change the real
2265         // cursor it has to do so explicitly by using
2266         //  cur.bv().cursor() = cur;  (or similar)
2267         if (inset)
2268                 inset->dispatch(cur, cmd);
2269
2270         // Now dispatch to the temporary cursor. If the real cursor should
2271         // be modified, the inset's dispatch has to do so explicitly.
2272         if (!inset || !cur.result().dispatched())
2273                 cur.dispatch(cmd);
2274
2275         // Notify left insets
2276         if (cur != old) {
2277                 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2278                 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2279                 if (badcursor)
2280                         cursor().fixIfBroken();
2281         }
2282
2283         cur.endUndoGroup();
2284
2285         // Do we have a selection?
2286         theSelection().haveSelection(cursor().selection());
2287
2288         if (cur.needBufferUpdate()) {
2289                 cur.clearBufferUpdate();
2290                 buffer().updateBuffer();
2291         }
2292
2293         // If the command has been dispatched,
2294         if (cur.result().dispatched() || cur.result().screenUpdate())
2295                 processUpdateFlags(cur.result().screenUpdate());
2296 }
2297
2298
2299 int BufferView::minVisiblePart()
2300 {
2301         return 2 * defaultRowHeight();
2302 }
2303
2304
2305 int BufferView::scroll(int y)
2306 {
2307         if (y > 0)
2308                 return scrollDown(y);
2309         if (y < 0)
2310                 return scrollUp(-y);
2311         return 0;
2312 }
2313
2314
2315 int BufferView::scrollDown(int offset)
2316 {
2317         Text * text = &buffer_.text();
2318         TextMetrics & tm = d->text_metrics_[text];
2319         int const ymax = height_ + offset;
2320         while (true) {
2321                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2322                 int bottom_pos = last.second->position() + last.second->descent();
2323                 if (lyxrc.scroll_below_document)
2324                         bottom_pos += height_ - minVisiblePart();
2325                 if (last.first + 1 == int(text->paragraphs().size())) {
2326                         if (bottom_pos <= height_)
2327                                 return 0;
2328                         offset = min(offset, bottom_pos - height_);
2329                         break;
2330                 }
2331                 if (bottom_pos > ymax)
2332                         break;
2333                 tm.newParMetricsDown();
2334         }
2335         d->anchor_ypos_ -= offset;
2336         return -offset;
2337 }
2338
2339
2340 int BufferView::scrollUp(int offset)
2341 {
2342         Text * text = &buffer_.text();
2343         TextMetrics & tm = d->text_metrics_[text];
2344         int ymin = - offset;
2345         while (true) {
2346                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2347                 int top_pos = first.second->position() - first.second->ascent();
2348                 if (first.first == 0) {
2349                         if (top_pos >= 0)
2350                                 return 0;
2351                         offset = min(offset, - top_pos);
2352                         break;
2353                 }
2354                 if (top_pos < ymin)
2355                         break;
2356                 tm.newParMetricsUp();
2357         }
2358         d->anchor_ypos_ += offset;
2359         return offset;
2360 }
2361
2362
2363 bool BufferView::setCursorFromRow(int row)
2364 {
2365         TexRow::TextEntry start, end;
2366         tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2367         LYXERR(Debug::LATEX,
2368                "setCursorFromRow: for row " << row << ", TexRow has found "
2369                "start (id=" << start.id << ",pos=" << start.pos << "), "
2370                "end (id=" << end.id << ",pos=" << end.pos << ")");
2371         return setCursorFromEntries(start, end);
2372 }
2373
2374
2375 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2376                                       TexRow::TextEntry end)
2377 {
2378         DocIterator dit_start, dit_end;
2379         tie(dit_start,dit_end) =
2380                 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2381         if (!dit_start)
2382                 return false;
2383         // Setting selection start
2384         d->cursor_.clearSelection();
2385         setCursor(dit_start);
2386         // Setting selection end
2387         if (dit_end) {
2388                 d->cursor_.resetAnchor();
2389                 setCursorSelectionTo(dit_end);
2390         }
2391         return true;
2392 }
2393
2394
2395 bool BufferView::setCursorFromInset(Inset const * inset)
2396 {
2397         // are we already there?
2398         if (cursor().nextInset() == inset)
2399                 return true;
2400
2401         // Inset is not at cursor position. Find it in the document.
2402         Cursor cur(*this);
2403         cur.reset();
2404         while (cur && cur.nextInset() != inset)
2405                 cur.forwardInset();
2406
2407         if (cur) {
2408                 setCursor(cur);
2409                 return true;
2410         }
2411         return false;
2412 }
2413
2414
2415 void BufferView::gotoLabel(docstring const & label)
2416 {
2417         ListOfBuffers bufs = buffer().allRelatives();
2418         ListOfBuffers::iterator it = bufs.begin();
2419         for (; it != bufs.end(); ++it) {
2420                 Buffer const * buf = *it;
2421
2422                 // find label
2423                 shared_ptr<Toc> toc = buf->tocBackend().toc("label");
2424                 Toc::const_iterator toc_it = toc->begin();
2425                 Toc::const_iterator end = toc->end();
2426                 for (; toc_it != end; ++toc_it) {
2427                         if (label == toc_it->str()) {
2428                                 lyx::dispatch(toc_it->action());
2429                                 return;
2430                         }
2431                 }
2432         }
2433 }
2434
2435
2436 TextMetrics const & BufferView::textMetrics(Text const * t) const
2437 {
2438         return const_cast<BufferView *>(this)->textMetrics(t);
2439 }
2440
2441
2442 TextMetrics & BufferView::textMetrics(Text const * t)
2443 {
2444         LBUFERR(t);
2445         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2446         if (tmc_it == d->text_metrics_.end()) {
2447                 tmc_it = d->text_metrics_.insert(
2448                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2449         }
2450         return tmc_it->second;
2451 }
2452
2453
2454 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2455                 pit_type pit) const
2456 {
2457         return textMetrics(t).parMetrics(pit);
2458 }
2459
2460
2461 int BufferView::workHeight() const
2462 {
2463         return height_;
2464 }
2465
2466
2467 void BufferView::setCursor(DocIterator const & dit)
2468 {
2469         d->cursor_.reset();
2470         size_t const n = dit.depth();
2471         for (size_t i = 0; i < n; ++i)
2472                 dit[i].inset().edit(d->cursor_, true);
2473
2474         d->cursor_.setCursor(dit);
2475         d->cursor_.selection(false);
2476         d->cursor_.setCurrentFont();
2477         // FIXME
2478         // It seems on general grounds as if this is probably needed, but
2479         // it is not yet clear.
2480         // See bug #7394 and r38388.
2481         // d->cursor.resetAnchor();
2482 }
2483
2484
2485 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2486 {
2487         size_t const n = dit.depth();
2488         for (size_t i = 0; i < n; ++i)
2489                 dit[i].inset().edit(d->cursor_, true);
2490
2491         d->cursor_.selection(true);
2492         d->cursor_.setCursorSelectionTo(dit);
2493         d->cursor_.setCurrentFont();
2494 }
2495
2496
2497 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2498 {
2499         // Would be wrong to delete anything if we have a selection.
2500         if (cur.selection())
2501                 return false;
2502
2503         bool need_anchor_change = false;
2504         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2505                 need_anchor_change);
2506
2507         if (need_anchor_change)
2508                 cur.resetAnchor();
2509
2510         if (!changed)
2511                 return false;
2512
2513         d->cursor_ = cur;
2514
2515         // we would rather not do this here, but it needs to be done before
2516         // the changed() signal is sent.
2517         buffer_.updateBuffer();
2518
2519         buffer_.changed(true);
2520         return true;
2521 }
2522
2523
2524 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2525 {
2526         LASSERT(&cur.bv() == this, return false);
2527
2528         if (!select)
2529                 // this event will clear selection so we save selection for
2530                 // persistent selection
2531                 cap::saveSelection(cursor());
2532
2533         d->cursor_.macroModeClose();
2534         // If a macro has been finalized, the cursor might have been broken
2535         cur.fixIfBroken();
2536
2537         // Has the cursor just left the inset?
2538         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2539         if (leftinset)
2540                 d->cursor_.fixIfBroken();
2541
2542         // do the dEPM magic if needed
2543         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2544         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2545         // the leftinset bool would not be necessary (badcursor instead).
2546         bool update = leftinset;
2547
2548         if (select) {
2549                 d->cursor_.setSelection();
2550                 d->cursor_.setCursorSelectionTo(cur);
2551         } else {
2552                 if (d->cursor_.inTexted())
2553                         update |= checkDepm(cur, d->cursor_);
2554                 d->cursor_.resetAnchor();
2555                 d->cursor_.setCursor(cur);
2556                 d->cursor_.clearSelection();
2557         }
2558         d->cursor_.boundary(cur.boundary());
2559         d->cursor_.finishUndo();
2560         d->cursor_.setCurrentFont();
2561         if (update)
2562                 cur.forceBufferUpdate();
2563         return update;
2564 }
2565
2566
2567 void BufferView::putSelectionAt(DocIterator const & cur,
2568                                 int length, bool backwards)
2569 {
2570         d->cursor_.clearSelection();
2571
2572         setCursor(cur);
2573
2574         if (length) {
2575                 if (backwards) {
2576                         d->cursor_.pos() += length;
2577                         d->cursor_.setSelection(d->cursor_, -length);
2578                 } else
2579                         d->cursor_.setSelection(d->cursor_, length);
2580         }
2581 }
2582
2583
2584 bool BufferView::selectIfEmpty(DocIterator & cur)
2585 {
2586         if ((cur.inTexted() && !cur.paragraph().empty())
2587             || (cur.inMathed() && !cur.cell().empty()))
2588                 return false;
2589
2590         pit_type const beg_pit = cur.pit();
2591         if (beg_pit > 0) {
2592                 // The paragraph associated to this item isn't
2593                 // the first one, so it can be selected
2594                 cur.backwardPos();
2595         } else {
2596                 // We have to resort to select the space between the
2597                 // end of this item and the begin of the next one
2598                 cur.forwardPos();
2599         }
2600         if (cur.empty()) {
2601                 // If it is the only item in the document,
2602                 // nothing can be selected
2603                 return false;
2604         }
2605         pit_type const end_pit = cur.pit();
2606         pos_type const end_pos = cur.pos();
2607         d->cursor_.clearSelection();
2608         d->cursor_.reset();
2609         d->cursor_.setCursor(cur);
2610         d->cursor_.pit() = beg_pit;
2611         d->cursor_.pos() = 0;
2612         d->cursor_.selection(false);
2613         d->cursor_.resetAnchor();
2614         d->cursor_.pit() = end_pit;
2615         d->cursor_.pos() = end_pos;
2616         d->cursor_.setSelection();
2617         return true;
2618 }
2619
2620
2621 Cursor & BufferView::cursor()
2622 {
2623         return d->cursor_;
2624 }
2625
2626
2627 Cursor const & BufferView::cursor() const
2628 {
2629         return d->cursor_;
2630 }
2631
2632
2633 pit_type BufferView::anchor_ref() const
2634 {
2635         return d->anchor_pit_;
2636 }
2637
2638
2639 bool BufferView::singleParUpdate()
2640 {
2641         Text & buftext = buffer_.text();
2642         pit_type const bottom_pit = d->cursor_.bottom().pit();
2643         TextMetrics & tm = textMetrics(&buftext);
2644         int old_height = tm.parMetrics(bottom_pit).height();
2645
2646         // make sure inline completion pointer is ok
2647         if (d->inlineCompletionPos_.fixIfBroken())
2648                 d->inlineCompletionPos_ = DocIterator();
2649
2650         // In Single Paragraph mode, rebreak only
2651         // the (main text, not inset!) paragraph containing the cursor.
2652         // (if this paragraph contains insets etc., rebreaking will
2653         // recursively descend)
2654         tm.redoParagraph(bottom_pit);
2655         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2656         if (pm.height() != old_height)
2657                 // Paragraph height has changed so we cannot proceed to
2658                 // the singlePar optimisation.
2659                 return false;
2660
2661         d->update_strategy_ = SingleParUpdate;
2662
2663         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2664                 << " y2: " << pm.position() + pm.descent()
2665                 << " pit: " << bottom_pit
2666                 << " singlepar: 1");
2667         return true;
2668 }
2669
2670
2671 void BufferView::updateMetrics()
2672 {
2673         if (height_ == 0 || width_ == 0)
2674                 return;
2675
2676         Text & buftext = buffer_.text();
2677         pit_type const npit = int(buftext.paragraphs().size());
2678
2679         // Clear out the position cache in case of full screen redraw,
2680         d->coord_cache_.clear();
2681
2682         // Clear out paragraph metrics to avoid having invalid metrics
2683         // in the cache from paragraphs not relayouted below
2684         // The complete text metrics will be redone.
2685         d->text_metrics_.clear();
2686
2687         TextMetrics & tm = textMetrics(&buftext);
2688
2689         // make sure inline completion pointer is ok
2690         if (d->inlineCompletionPos_.fixIfBroken())
2691                 d->inlineCompletionPos_ = DocIterator();
2692
2693         if (d->anchor_pit_ >= npit)
2694                 // The anchor pit must have been deleted...
2695                 d->anchor_pit_ = npit - 1;
2696
2697         // Rebreak anchor paragraph.
2698         tm.redoParagraph(d->anchor_pit_);
2699         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2700
2701         // position anchor
2702         if (d->anchor_pit_ == 0) {
2703                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2704
2705                 // Complete buffer visible? Then it's easy.
2706                 if (scrollRange == 0)
2707                         d->anchor_ypos_ = anchor_pm.ascent();
2708
2709                 // FIXME: Some clever handling needed to show
2710                 // the _first_ paragraph up to the top if the cursor is
2711                 // in the first line.
2712         }
2713         anchor_pm.setPosition(d->anchor_ypos_);
2714
2715         LYXERR(Debug::PAINTING, "metrics: "
2716                 << " anchor pit = " << d->anchor_pit_
2717                 << " anchor ypos = " << d->anchor_ypos_);
2718
2719         // Redo paragraphs above anchor if necessary.
2720         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2721         // We are now just above the anchor paragraph.
2722         pit_type pit1 = d->anchor_pit_ - 1;
2723         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2724                 tm.redoParagraph(pit1);
2725                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2726                 y1 -= pm.descent();
2727                 // Save the paragraph position in the cache.
2728                 pm.setPosition(y1);
2729                 y1 -= pm.ascent();
2730         }
2731
2732         // Redo paragraphs below the anchor if necessary.
2733         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2734         // We are now just below the anchor paragraph.
2735         pit_type pit2 = d->anchor_pit_ + 1;
2736         for (; pit2 < npit && y2 <= height_; ++pit2) {
2737                 tm.redoParagraph(pit2);
2738                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2739                 y2 += pm.ascent();
2740                 // Save the paragraph position in the cache.
2741                 pm.setPosition(y2);
2742                 y2 += pm.descent();
2743         }
2744
2745         LYXERR(Debug::PAINTING, "Metrics: "
2746                 << " anchor pit = " << d->anchor_pit_
2747                 << " anchor ypos = " << d->anchor_ypos_
2748                 << " y1 = " << y1
2749                 << " y2 = " << y2
2750                 << " pit1 = " << pit1
2751                 << " pit2 = " << pit2);
2752
2753         d->update_strategy_ = FullScreenUpdate;
2754
2755         // Now update the positions of insets in the cache.
2756         updatePosCache();
2757
2758         if (lyxerr.debugging(Debug::WORKAREA)) {
2759                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2760                 d->coord_cache_.dump();
2761         }
2762 }
2763
2764
2765 void BufferView::updatePosCache()
2766 {
2767         // this is the "nodraw" drawing stage: only set the positions of the
2768         // insets in metrics cache.
2769         frontend::NullPainter np;
2770         draw(np, false);
2771 }
2772
2773
2774 void BufferView::insertLyXFile(FileName const & fname)
2775 {
2776         LASSERT(d->cursor_.inTexted(), return);
2777
2778         // Get absolute path of file and add ".lyx"
2779         // to the filename if necessary
2780         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2781
2782         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2783         // emit message signal.
2784         message(bformat(_("Inserting document %1$s..."), disp_fn));
2785
2786         docstring res;
2787         Buffer buf(filename.absFileName(), false);
2788         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2789                 ErrorList & el = buffer_.errorList("Parse");
2790                 // Copy the inserted document error list into the current buffer one.
2791                 el = buf.errorList("Parse");
2792                 buffer_.undo().recordUndo(d->cursor_);
2793                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2794                                              buf.params().documentClassPtr(), el);
2795                 res = _("Document %1$s inserted.");
2796         } else {
2797                 res = _("Could not insert document %1$s");
2798         }
2799
2800         buffer_.changed(true);
2801         // emit message signal.
2802         message(bformat(res, disp_fn));
2803 }
2804
2805
2806 Point BufferView::coordOffset(DocIterator const & dit) const
2807 {
2808         int x = 0;
2809         int y = 0;
2810         int lastw = 0;
2811
2812         // Addup contribution of nested insets, from inside to outside,
2813         // keeping the outer paragraph for a special handling below
2814         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2815                 CursorSlice const & sl = dit[i];
2816                 int xx = 0;
2817                 int yy = 0;
2818
2819                 // get relative position inside sl.inset()
2820                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2821
2822                 // Make relative position inside of the edited inset relative to sl.inset()
2823                 x += xx;
2824                 y += yy;
2825
2826                 // In case of an RTL inset, the edited inset will be positioned to the left
2827                 // of xx:yy
2828                 if (sl.text()) {
2829                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2830                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2831                         if (rtl)
2832                                 x -= lastw;
2833                 }
2834
2835                 // remember width for the case that sl.inset() is positioned in an RTL inset
2836                 lastw = sl.inset().dimension(*this).wid;
2837
2838                 //lyxerr << "Cursor::getPos, i: "
2839                 // << i << " x: " << xx << " y: " << y << endl;
2840         }
2841
2842         // Add contribution of initial rows of outermost paragraph
2843         CursorSlice const & sl = dit[0];
2844         TextMetrics const & tm = textMetrics(sl.text());
2845         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2846
2847         LBUFERR(!pm.rows().empty());
2848         y -= pm.rows()[0].ascent();
2849 #if 1
2850         // FIXME: document this mess
2851         size_t rend;
2852         if (sl.pos() > 0 && dit.depth() == 1) {
2853                 int pos = sl.pos();
2854                 if (pos && dit.boundary())
2855                         --pos;
2856 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2857                 rend = pm.pos2row(pos);
2858         } else
2859                 rend = pm.pos2row(sl.pos());
2860 #else
2861         size_t rend = pm.pos2row(sl.pos());
2862 #endif
2863         for (size_t rit = 0; rit != rend; ++rit)
2864                 y += pm.rows()[rit].height();
2865         y += pm.rows()[rend].ascent();
2866
2867         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2868
2869         // Make relative position from the nested inset now bufferview absolute.
2870         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2871         x += xx;
2872
2873         // In the RTL case place the nested inset at the left of the cursor in
2874         // the outer paragraph
2875         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2876         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2877         if (rtl)
2878                 x -= lastw;
2879
2880         return Point(x, y);
2881 }
2882
2883
2884 Point BufferView::getPos(DocIterator const & dit) const
2885 {
2886         if (!paragraphVisible(dit))
2887                 return Point(-1, -1);
2888
2889         CursorSlice const & bot = dit.bottom();
2890         TextMetrics const & tm = textMetrics(bot.text());
2891
2892         // offset from outer paragraph
2893         Point p = coordOffset(dit);
2894         p.y_ += tm.parMetrics(bot.pit()).position();
2895         return p;
2896 }
2897
2898
2899 bool BufferView::paragraphVisible(DocIterator const & dit) const
2900 {
2901         CursorSlice const & bot = dit.bottom();
2902         TextMetrics const & tm = textMetrics(bot.text());
2903
2904         return tm.contains(bot.pit());
2905 }
2906
2907
2908 void BufferView::caretPosAndHeight(Point & p, int & h) const
2909 {
2910         Cursor const & cur = cursor();
2911         Font const font = cur.real_current_font;
2912         frontend::FontMetrics const & fm = theFontMetrics(font);
2913         int const asc = fm.maxAscent();
2914         int const des = fm.maxDescent();
2915         h = asc + des;
2916         p = getPos(cur);
2917         p.y_ -= asc;
2918 }
2919
2920
2921 bool BufferView::cursorInView(Point const & p, int h) const
2922 {
2923         Cursor const & cur = cursor();
2924         // does the cursor touch the screen ?
2925         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2926                 return false;
2927         return true;
2928 }
2929
2930
2931 int BufferView::horizScrollOffset() const
2932 {
2933         return d->horiz_scroll_offset_;
2934 }
2935
2936
2937 int BufferView::horizScrollOffset(Text const * text,
2938                                   pit_type pit, pos_type pos) const
2939 {
2940         // Is this a row that is currently scrolled?
2941         if (!d->current_row_slice_.empty()
2942             && &text->inset() == d->current_row_slice_.inset().asInsetText()
2943             && pit ==  d->current_row_slice_.pit()
2944             && pos ==  d->current_row_slice_.pos())
2945                 return d->horiz_scroll_offset_;
2946         return 0;
2947 }
2948
2949
2950 bool BufferView::hadHorizScrollOffset(Text const * text,
2951                                       pit_type pit, pos_type pos) const
2952 {
2953         return !d->last_row_slice_.empty()
2954                && &text->inset() == d->last_row_slice_.inset().asInsetText()
2955                && pit ==  d->last_row_slice_.pit()
2956                && pos ==  d->last_row_slice_.pos();
2957 }
2958
2959
2960 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2961 {
2962         // nothing to do if the cursor was already on this row
2963         if (d->current_row_slice_ == rowSlice) {
2964                 d->last_row_slice_ = CursorSlice();
2965                 return;
2966         }
2967
2968         // if the (previous) current row was scrolled, we have to
2969         // remember it in order to repaint it next time.
2970         if (d->horiz_scroll_offset_ != 0)
2971                 d->last_row_slice_ = d->current_row_slice_;
2972         else
2973                 d->last_row_slice_ = CursorSlice();
2974
2975         // Since we changed row, the scroll offset is not valid anymore
2976         d->horiz_scroll_offset_ = 0;
2977         d->current_row_slice_ = rowSlice;
2978 }
2979
2980
2981 namespace {
2982
2983 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2984 {
2985         return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
2986                 && row.pos() <= cs.pos() && cs.pos() <= row.endpos();
2987 }
2988
2989 }
2990
2991
2992 bool BufferView::needRepaint(Text const * text, Row const & row) const
2993 {
2994         return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
2995 }
2996
2997
2998 void BufferView::checkCursorScrollOffset()
2999 {
3000         CursorSlice rowSlice = d->cursor_.bottom();
3001         TextMetrics const & tm = textMetrics(rowSlice.text());
3002
3003         // Stop if metrics have not been computed yet, since it means
3004         // that there is nothing to do.
3005         if (!tm.contains(rowSlice.pit()))
3006                 return;
3007         ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3008         Row const & row = pm.getRow(rowSlice.pos(),
3009                                     d->cursor_.boundary() && rowSlice == d->cursor_.top());
3010         rowSlice.pos() = row.pos();
3011
3012         // Set the row on which the cursor lives.
3013         setCurrentRowSlice(rowSlice);
3014
3015         // Current x position of the cursor in pixels
3016         int cur_x = getPos(d->cursor_).x_;
3017
3018         // Horizontal scroll offset of the cursor row in pixels
3019         int offset = d->horiz_scroll_offset_;
3020         int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3021                            + row.right_margin;
3022         if (row.right_x() <= workWidth() - row.right_margin) {
3023                 // Row is narrower than the work area, no offset needed.
3024                 offset = 0;
3025         } else {
3026                 if (cur_x - offset < MARGIN) {
3027                         // cursor would be too far right
3028                         offset = cur_x - MARGIN;
3029                 } else if (cur_x - offset > workWidth() - MARGIN) {
3030                         // cursor would be too far left
3031                         offset = cur_x - workWidth() + MARGIN;
3032                 }
3033                 // Correct the offset to make sure that we do not scroll too much
3034                 if (offset < 0)
3035                         offset = 0;
3036                 if (row.right_x() - offset < workWidth() - row.right_margin)
3037                         offset = row.right_x() - workWidth() + row.right_margin;
3038         }
3039
3040         //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3041
3042         if (offset != d->horiz_scroll_offset_)
3043                 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3044                        << d->horiz_scroll_offset_ << " to " << offset);
3045
3046         if (d->update_strategy_ == NoScreenUpdate
3047             && (offset != d->horiz_scroll_offset_
3048                 || !d->last_row_slice_.empty())) {
3049                 // FIXME: if one uses SingleParUpdate, then home/end
3050                 // will not work on long rows. Why?
3051                 d->update_strategy_ = FullScreenUpdate;
3052         }
3053
3054         d->horiz_scroll_offset_ = offset;
3055 }
3056
3057
3058 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3059 {
3060         if (height_ == 0 || width_ == 0)
3061                 return;
3062         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
3063
3064         Text & text = buffer_.text();
3065         TextMetrics const & tm = d->text_metrics_[&text];
3066         int const y = tm.first().second->position();
3067         PainterInfo pi(this, pain);
3068
3069         CursorSlice const & bottomSlice = d->cursor_.bottom();
3070         /**  A repaint of the previous cursor row is needed if
3071          * 1/ the caret will be painted and is is not the same than the
3072          *    already painted one;
3073          * 2/ the caret will not be painted, but there is already one on
3074          * screen.
3075          */
3076         d->repaint_caret_row_ = (paint_caret && bottomSlice != d->caret_slice_)
3077                 || (! paint_caret && !d->caret_slice_.empty());
3078
3079         // Check whether the row where the cursor lives needs to be scrolled.
3080         // Update the drawing strategy if needed.
3081         checkCursorScrollOffset();
3082
3083         switch (d->update_strategy_) {
3084
3085         case NoScreenUpdate:
3086                 // no screen painting is actually needed. In nodraw stage
3087                 // however, the different coordinates of insets and paragraphs
3088                 // needs to be updated.
3089                 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3090                 pi.full_repaint = false;
3091                 if (pain.isNull()) {
3092                         pi.full_repaint = true;
3093                         tm.draw(pi, 0, y);
3094                 } else if (d->repaint_caret_row_) {
3095                         pi.full_repaint = false;
3096                         tm.draw(pi, 0, y);
3097                 }
3098                 break;
3099
3100         case SingleParUpdate:
3101                 pi.full_repaint = false;
3102                 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3103                 // In general, only the current row of the outermost paragraph
3104                 // will be redrawn. Particular cases where selection spans
3105                 // multiple paragraph are correctly detected in TextMetrics.
3106                 tm.draw(pi, 0, y);
3107                 break;
3108
3109         case DecorationUpdate:
3110                 // FIXME: We should also distinguish DecorationUpdate to avoid text
3111                 // drawing if possible. This is not possible to do easily right now
3112                 // because of the single backing pixmap.
3113
3114         case FullScreenUpdate:
3115
3116                 LYXERR(Debug::PAINTING,
3117                        ((d->update_strategy_ == FullScreenUpdate)
3118                         ? "Strategy: FullScreenUpdate"
3119                         : "Strategy: DecorationUpdate"));
3120
3121                 // The whole screen, including insets, will be refreshed.
3122                 pi.full_repaint = true;
3123
3124                 // Clear background.
3125                 pain.fillRectangle(0, 0, width_, height_,
3126                         pi.backgroundColor(&buffer_.inset()));
3127
3128                 // Draw everything.
3129                 tm.draw(pi, 0, y);
3130
3131                 // and possibly grey out below
3132                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3133                 int const y2 = lastpm.second->position() + lastpm.second->descent();
3134
3135                 if (y2 < height_) {
3136                         Color color = buffer().isInternal()
3137                                 ? Color_background : Color_bottomarea;
3138                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
3139                 }
3140                 break;
3141         }
3142         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
3143
3144         // The scrollbar needs an update.
3145         updateScrollbar();
3146
3147         // Normalize anchor for next time
3148         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3149         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3150         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3151                 ParagraphMetrics const & pm = tm.parMetrics(pit);
3152                 if (pm.position() + pm.descent() > 0) {
3153                         d->anchor_pit_ = pit;
3154                         d->anchor_ypos_ = pm.position();
3155                         break;
3156                 }
3157         }
3158         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3159                 << "  anchor ypos = " << d->anchor_ypos_);
3160
3161         // Remember what has just been done for the next draw() step
3162         if (paint_caret)
3163                 d->caret_slice_ = bottomSlice;
3164         else
3165                 d->caret_slice_ = CursorSlice();
3166 }
3167
3168
3169 void BufferView::message(docstring const & msg)
3170 {
3171         if (d->gui_)
3172                 d->gui_->message(msg);
3173 }
3174
3175
3176 void BufferView::showDialog(string const & name)
3177 {
3178         if (d->gui_)
3179                 d->gui_->showDialog(name, string());
3180 }
3181
3182
3183 void BufferView::showDialog(string const & name,
3184         string const & data, Inset * inset)
3185 {
3186         if (d->gui_)
3187                 d->gui_->showDialog(name, data, inset);
3188 }
3189
3190
3191 void BufferView::updateDialog(string const & name, string const & data)
3192 {
3193         if (d->gui_)
3194                 d->gui_->updateDialog(name, data);
3195 }
3196
3197
3198 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3199 {
3200         d->gui_ = gui;
3201 }
3202
3203
3204 // FIXME: Move this out of BufferView again
3205 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3206 {
3207         if (!fname.isReadableFile()) {
3208                 docstring const error = from_ascii(strerror(errno));
3209                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3210                 docstring const text =
3211                   bformat(_("Could not read the specified document\n"
3212                             "%1$s\ndue to the error: %2$s"), file, error);
3213                 Alert::error(_("Could not read file"), text);
3214                 return docstring();
3215         }
3216
3217         if (!fname.isReadableFile()) {
3218                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3219                 docstring const text =
3220                   bformat(_("%1$s\n is not readable."), file);
3221                 Alert::error(_("Could not open file"), text);
3222                 return docstring();
3223         }
3224
3225         // FIXME UNICODE: We don't know the encoding of the file
3226         docstring file_content = fname.fileContents("UTF-8");
3227         if (file_content.empty()) {
3228                 Alert::error(_("Reading not UTF-8 encoded file"),
3229                              _("The file is not UTF-8 encoded.\n"
3230                                "It will be read as local 8Bit-encoded.\n"
3231                                "If this does not give the correct result\n"
3232                                "then please change the encoding of the file\n"
3233                                "to UTF-8 with a program other than LyX.\n"));
3234                 file_content = fname.fileContents("local8bit");
3235         }
3236
3237         return normalize_c(file_content);
3238 }
3239
3240
3241 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3242 {
3243         docstring const tmpstr = contentsOfPlaintextFile(f);
3244
3245         if (tmpstr.empty())
3246                 return;
3247
3248         Cursor & cur = cursor();
3249         cap::replaceSelection(cur);
3250         buffer_.undo().recordUndo(cur);
3251         if (asParagraph)
3252                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3253         else
3254                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3255
3256         buffer_.changed(true);
3257 }
3258
3259
3260 docstring const & BufferView::inlineCompletion() const
3261 {
3262         return d->inlineCompletion_;
3263 }
3264
3265
3266 size_t const & BufferView::inlineCompletionUniqueChars() const
3267 {
3268         return d->inlineCompletionUniqueChars_;
3269 }
3270
3271
3272 DocIterator const & BufferView::inlineCompletionPos() const
3273 {
3274         return d->inlineCompletionPos_;
3275 }
3276
3277
3278 void BufferView::resetInlineCompletionPos()
3279 {
3280         d->inlineCompletionPos_ = DocIterator();
3281 }
3282
3283
3284 bool samePar(DocIterator const & a, DocIterator const & b)
3285 {
3286         if (a.empty() && b.empty())
3287                 return true;
3288         if (a.empty() || b.empty())
3289                 return false;
3290         if (a.depth() != b.depth())
3291                 return false;
3292         return &a.innerParagraph() == &b.innerParagraph();
3293 }
3294
3295
3296 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3297         docstring const & completion, size_t uniqueChars)
3298 {
3299         uniqueChars = min(completion.size(), uniqueChars);
3300         bool changed = d->inlineCompletion_ != completion
3301                 || d->inlineCompletionUniqueChars_ != uniqueChars;
3302         bool singlePar = true;
3303         d->inlineCompletion_ = completion;
3304         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3305
3306         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3307
3308         // at new position?
3309         DocIterator const & old = d->inlineCompletionPos_;
3310         if (old != pos) {
3311                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3312                 // old or pos are in another paragraph?
3313                 if ((!samePar(cur, pos) && !pos.empty())
3314                     || (!samePar(cur, old) && !old.empty())) {
3315                         singlePar = false;
3316                         //lyxerr << "different paragraph" << std::endl;
3317                 }
3318                 d->inlineCompletionPos_ = pos;
3319         }
3320
3321         // set update flags
3322         if (changed) {
3323                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3324                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3325                 else
3326                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3327         }
3328 }
3329
3330
3331 bool BufferView::clickableInset() const
3332 {
3333         return d->clickable_inset_;
3334 }
3335
3336 } // namespace lyx