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