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