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