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