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