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