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