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