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