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