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