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