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