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