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