]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Close to perfect scrolling. Some bugs fixing and behaviour tweaking remains but we...
[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 "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.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 "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "VSpace.h"
53 #include "WordLangTuple.h"
54
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
59
60 #include "frontends/alert.h"
61 #include "frontends/Delegates.h"
62 #include "frontends/FontMetrics.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74 #include "support/Package.h"
75 #include "support/types.h"
76
77 #include <cerrno>
78 #include <fstream>
79 #include <functional>
80 #include <iterator>
81 #include <vector>
82
83 using namespace std;
84 using namespace lyx::support;
85
86 namespace lyx {
87
88 namespace Alert = frontend::Alert;
89
90 namespace {
91
92 /// Return an inset of this class if it exists at the current cursor position
93 template <class T>
94 T * getInsetByCode(Cursor const & cur, InsetCode code)
95 {
96         DocIterator it = cur;
97         Inset * inset = it.nextInset();
98         if (inset && inset->lyxCode() == code)
99                 return static_cast<T*>(inset);
100         return 0;
101 }
102
103
104 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
105         bool same_content);
106
107 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
108         docstring const & contents)
109 {
110         DocIterator tmpdit = dit;
111
112         while (tmpdit) {
113                 Inset const * inset = tmpdit.nextInset();
114                 if (inset
115                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
116                     && (contents.empty() ||
117                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
118                         dit = tmpdit;
119                         return true;
120                 }
121                 tmpdit.forwardInset();
122         }
123
124         return false;
125 }
126
127
128 /// Looks for next inset with one of the given codes.
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
130         bool same_content)
131 {
132         docstring contents;
133         DocIterator tmpdit = dit;
134         tmpdit.forwardInset();
135         if (!tmpdit)
136                 return false;
137
138         if (same_content) {
139                 Inset const * inset = tmpdit.nextInset();
140                 if (inset
141                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
142                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
143                 }
144         }
145
146         if (!findNextInset(tmpdit, codes, contents)) {
147                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
148                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
149                         if (!findNextInset(tmpdit, codes, contents))
150                                 return false;
151                 } else
152                         return false;
153         }
154
155         dit = tmpdit;
156         return true;
157 }
158
159
160 /// Looks for next inset with the given code
161 void findInset(DocIterator & dit, InsetCode code, bool same_content)
162 {
163         findInset(dit, vector<InsetCode>(1, code), same_content);
164 }
165
166
167 /// Moves cursor to the next inset with one of the given codes.
168 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
169                bool same_content)
170 {
171         Cursor tmpcur = bv->cursor();
172         if (!findInset(tmpcur, codes, same_content)) {
173                 bv->cursor().message(_("No more insets"));
174                 return;
175         }
176
177         tmpcur.clearSelection();
178         bv->setCursor(tmpcur);
179 }
180
181
182 /// Moves cursor to the next inset with given code.
183 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
184 {
185         gotoInset(bv, vector<InsetCode>(1, code), same_content);
186 }
187
188
189 /// A map from a Text to the associated text metrics
190 typedef map<Text const *, TextMetrics> TextMetricsCache;
191
192 enum ScreenUpdateStrategy {
193         NoScreenUpdate,
194         SingleParUpdate,
195         FullScreenUpdate,
196         DecorationUpdate
197 };
198
199 } // anon namespace
200
201
202 /////////////////////////////////////////////////////////////////////
203 //
204 // BufferView
205 //
206 /////////////////////////////////////////////////////////////////////
207
208 struct BufferView::Private
209 {
210         Private(BufferView & bv): wh_(0), cursor_(bv),
211                 anchor_pit_(0), anchor_ypos_(0),
212                 last_inset_(0), gui_(0)
213         {}
214
215         ///
216         ScrollbarParameters scrollbarParameters_;
217         ///
218         ScreenUpdateStrategy update_strategy_;
219         ///
220         CoordCache coord_cache_;
221
222         /// Estimated average par height for scrollbar.
223         int wh_;
224         /// this is used to handle XSelection events in the right manner.
225         struct {
226                 CursorSlice cursor;
227                 CursorSlice anchor;
228                 bool set;
229         } xsel_cache_;
230         ///
231         Cursor cursor_;
232         ///
233         pit_type anchor_pit_;
234         ///
235         int anchor_ypos_;
236         ///
237         vector<int> par_height_;
238
239         /// keyboard mapping object.
240         Intl intl_;
241
242         /// last visited inset.
243         /** kept to send setMouseHover(false).
244           * Not owned, so don't delete.
245           */
246         Inset * last_inset_;
247
248         mutable TextMetricsCache text_metrics_;
249
250         /// Whom to notify.
251         /** Not owned, so don't delete.
252           */
253         frontend::GuiBufferViewDelegate * gui_;
254 };
255
256
257 BufferView::BufferView(Buffer & buf)
258         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
259 {
260         d->xsel_cache_.set = false;
261         d->intl_.initKeyMapper(lyxrc.use_kbmap);
262
263         d->cursor_.push(buffer_.inset());
264         d->cursor_.resetAnchor();
265         d->cursor_.setCurrentFont();
266
267         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
268                 graphics::Previews::get().generateBufferPreviews(buffer_);
269 }
270
271
272 BufferView::~BufferView()
273 {
274         // current buffer is going to be switched-off, save cursor pos
275         // Ideally, the whole cursor stack should be saved, but session
276         // currently can only handle bottom (whole document) level pit and pos.
277         // That is to say, if a cursor is in a nested inset, it will be
278         // restore to the left of the top level inset.
279         LastFilePosSection::FilePos fp;
280         fp.pit = d->cursor_.bottom().pit();
281         fp.pos = d->cursor_.bottom().pos();
282         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
283
284         delete d;
285 }
286
287
288 Intl & BufferView::getIntl()
289 {
290         return d->intl_;
291 }
292
293
294 Intl const & BufferView::getIntl() const
295 {
296         return d->intl_;
297 }
298
299
300 CoordCache & BufferView::coordCache()
301 {
302         return d->coord_cache_;
303 }
304
305
306 CoordCache const & BufferView::coordCache() const
307 {
308         return d->coord_cache_;
309 }
310
311
312 Buffer & BufferView::buffer()
313 {
314         return buffer_;
315 }
316
317
318 Buffer const & BufferView::buffer() const
319 {
320         return buffer_;
321 }
322
323
324 bool BufferView::fitCursor()
325 {
326         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
327                 frontend::FontMetrics const & fm =
328                         theFontMetrics(d->cursor_.getFont().fontInfo());
329                 int const asc = fm.maxAscent();
330                 int const des = fm.maxDescent();
331                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
332                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
333                         return false;
334         }
335         return true;
336 }
337
338
339 void BufferView::processUpdateFlags(Update::flags flags)
340 {
341         // last_inset_ points to the last visited inset. This pointer may become
342         // invalid because of keyboard editing. Since all such operations
343         // causes screen update(), I reset last_inset_ to avoid such a problem.
344         d->last_inset_ = 0;
345         // This is close to a hot-path.
346         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
347                 << "[fitcursor = " << (flags & Update::FitCursor)
348                 << ", forceupdate = " << (flags & Update::Force)
349                 << ", singlepar = " << (flags & Update::SinglePar)
350                 << "]  buffer: " << &buffer_);
351
352         // Update macro store
353         if (!(cursor().inMathed() && cursor().inMacroMode()))
354                 buffer_.updateMacros();
355
356         // Now do the first drawing step if needed. This consists on updating
357         // the CoordCache in updateMetrics().
358         // The second drawing step is done in WorkArea::redraw() if needed.
359
360         // Case when no explicit update is requested.
361         if (!flags) {
362                 // no need to redraw anything.
363                 d->update_strategy_ = NoScreenUpdate;
364                 return;
365         }
366
367         if (flags == Update::Decoration) {
368                 d->update_strategy_ = DecorationUpdate;
369                 buffer_.changed();
370                 return;
371         }
372
373         if (flags == Update::FitCursor
374                 || flags == (Update::Decoration | Update::FitCursor)) {
375                 // tell the frontend to update the screen if needed.
376                 if (fitCursor()) {
377                         center();
378                         return;
379                 }
380                 if (flags & Update::Decoration) {
381                         d->update_strategy_ = DecorationUpdate;
382                         buffer_.changed();
383                         return;
384                 }
385                 // no screen update is needed.
386                 d->update_strategy_ = NoScreenUpdate;
387                 return;
388         }
389
390         bool const full_metrics = flags & Update::Force;
391
392         if (full_metrics || !singleParUpdate()) {
393                 if (flags & Update::FitCursor && fitCursor()) {
394                         center();
395                         return;
396                 }
397                 // We have to update the full screen metrics.
398                 updateMetrics();
399         }
400
401         if (!(flags & Update::FitCursor)) {
402                 buffer_.changed();
403                 return;
404         }
405
406         //FIXME: updateMetrics() does not update paragraph position
407         // This is done at draw() time. So we need a redraw!
408
409         buffer_.changed();
410         if (!fitCursor())
411                 // The screen has already been updated thanks to the
412                 // 'buffer_.changed()' call three line above. So no need
413                 // to redraw again.
414                 return;
415
416         // The screen needs to be recentered around the cursor position so
417         // refresh it:
418         center();
419 }
420
421
422 void BufferView::updateScrollbar()
423 {
424         if (height_ == 0)
425                 return;
426
427         Text & t = buffer_.text();
428         TextMetrics & tm = d->text_metrics_[&t];                
429
430         LYXERR(Debug::GUI, " Updating scrollbar: height: "
431                 << t.paragraphs().size()
432                 << " curr par: " << d->cursor_.bottom().pit()
433                 << " default height " << defaultRowHeight());
434
435         int const parsize = int(t.paragraphs().size() - 1);
436         if (d->par_height_.size() != parsize) {
437                 d->par_height_.clear();
438                 // FIXME: We assume a default paragraph height of 4 rows. This
439                 // should probably be pondered with the screen width.
440                 d->par_height_.resize(parsize, defaultRowHeight() * 4);
441         }
442
443         // It would be better to fix the scrollbar to understand
444         // values in [0..1] and divide everything by wh
445
446         // Look at paragraph heights on-screen
447         pit_type first_visible_pit = -1;
448         pair<pit_type, ParagraphMetrics const *> first = tm.first();
449         pair<pit_type, ParagraphMetrics const *> last = tm.last();
450         for (pit_type pit = first.first; pit <= last.first; ++pit) {
451                 ParagraphMetrics const & pm = tm.parMetrics(pit);
452                 d->par_height_[pit] = pm.height();
453                 if (first_visible_pit < 0 && pm.position() + pm.descent() > 0)
454                         first_visible_pit = pit;
455         }
456
457         LYXERR(Debug::SCROLLING, "first_visible_pit " << first_visible_pit);
458
459         d->scrollbarParameters_.height = 0;
460         for (size_t i = 0; i != d->par_height_.size(); ++i) {
461                 d->scrollbarParameters_.height += d->par_height_[i];
462                 if (i != first_visible_pit)
463                         continue;
464                 // FIXME: we should look for the first visible row within
465                 // the deepest inset!
466                 d->scrollbarParameters_.position = d->scrollbarParameters_.height;
467         }
468
469         d->scrollbarParameters_.lineScrollHeight =
470                 tm.parMetrics(first_visible_pit).rows()[0].height();
471 }
472
473
474 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 {
476         return d->scrollbarParameters_;
477 }
478
479
480 void BufferView::scrollDocView(int value)
481 {
482         int const offset = value - d->scrollbarParameters_.position;
483         //TextMetrics & tm = d->text_metrics_[&buffer_.text()];
484         if (abs(offset) <= 3*height_) {
485                 scroll(offset);
486                 return;
487         }
488
489         int par_pos = 0;
490         for (size_t i = 0; i != d->par_height_.size(); ++i) {
491                 par_pos += d->par_height_[i];
492                 if (par_pos >= value) {
493                         d->anchor_pit_ = pit_type(i);
494                         break;
495                 }
496         }
497
498         LYXERR(Debug::SCROLLING, "value = " << value
499                 << "\tanchor_ref_ = " << d->anchor_pit_
500                 << "\tpar_pos = " << par_pos);
501
502         d->anchor_ypos_ = par_pos - value;
503         updateMetrics();
504         buffer_.changed();
505 }
506
507
508 // FIXME: this method is not working well.
509 void BufferView::setCursorFromScrollbar()
510 {
511         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
512
513         int const height = 2 * defaultRowHeight();
514         int const first = height;
515         int const last = height_ - height;
516         Cursor & cur = d->cursor_;
517
518         switch (cursorStatus(cur)) {
519         case CUR_ABOVE:
520                 // We reset the cursor because cursorStatus() does not
521                 // work when the cursor is within mathed.
522                 cur.reset(buffer_.inset());
523                 tm.setCursorFromCoordinates(cur, 0, first);
524                 cur.clearSelection();
525                 break;
526         case CUR_BELOW:
527                 // We reset the cursor because cursorStatus() does not
528                 // work when the cursor is within mathed.
529                 cur.reset(buffer_.inset());
530                 tm.setCursorFromCoordinates(cur, 0, last);
531                 cur.clearSelection();
532                 break;
533         case CUR_INSIDE:
534                 int const y = getPos(cur, cur.boundary()).y_;
535                 int const newy = min(last, max(y, first));
536                 if (y != newy) {
537                         cur.reset(buffer_.inset());
538                         tm.setCursorFromCoordinates(cur, 0, newy);
539                 }
540         }
541 }
542
543
544 Change const BufferView::getCurrentChange() const
545 {
546         if (!d->cursor_.selection())
547                 return Change(Change::UNCHANGED);
548
549         DocIterator dit = d->cursor_.selectionBegin();
550         return dit.paragraph().lookupChange(dit.pos());
551 }
552
553
554 // this could be used elsewhere as well?
555 // FIXME: This does not work within mathed!
556 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
557 {
558         Point const p = getPos(dit, dit.boundary());
559         if (p.y_ < 0)
560                 return CUR_ABOVE;
561         if (p.y_ > workHeight())
562                 return CUR_BELOW;
563         return CUR_INSIDE;
564 }
565
566
567 void BufferView::saveBookmark(unsigned int idx)
568 {
569         // tenatively save bookmark, id and pos will be used to
570         // acturately locate a bookmark in a 'live' lyx session.
571         // pit and pos will be updated with bottom level pit/pos
572         // when lyx exits.
573         LyX::ref().session().bookmarks().save(
574                 buffer_.fileName(),
575                 d->cursor_.bottom().pit(),
576                 d->cursor_.bottom().pos(),
577                 d->cursor_.paragraph().id(),
578                 d->cursor_.pos(),
579                 idx
580         );
581         if (idx)
582                 // emit message signal.
583                 message(_("Save bookmark"));
584 }
585
586
587 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
588         int top_id, pos_type top_pos)
589 {
590         bool success = false;
591         DocIterator doc_it;
592
593         d->cursor_.clearSelection();
594
595         // if a valid par_id is given, try it first
596         // This is the case for a 'live' bookmark when unique paragraph ID
597         // is used to track bookmarks.
598         if (top_id > 0) {
599                 ParIterator par = buffer_.getParFromID(top_id);
600                 if (par != buffer_.par_iterator_end()) {
601                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
602                         // Some slices of the iterator may not be
603                         // reachable (e.g. closed collapsable inset)
604                         // so the dociterator may need to be
605                         // shortened. Otherwise, setCursor may crash
606                         // lyx when the cursor can not be set to these
607                         // insets.
608                         size_t const n = doc_it.depth();
609                         for (size_t i = 0; i < n; ++i)
610                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
611                                         doc_it.resize(i);
612                                         break;
613                                 }
614                         success = true;
615                 }
616         }
617
618         // if top_id == 0, or searching through top_id failed
619         // This is the case for a 'restored' bookmark when only bottom
620         // (document level) pit was saved. Because of this, bookmark
621         // restoration is inaccurate. If a bookmark was within an inset,
622         // it will be restored to the left of the outmost inset that contains
623         // the bookmark.
624         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
625                 doc_it = doc_iterator_begin(buffer_.inset());
626                 doc_it.pit() = bottom_pit;
627                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
628                 success = true;
629         }
630
631         if (success) {
632                 // Note: only bottom (document) level pit is set.
633                 setCursor(doc_it);
634                 // set the current font.
635                 d->cursor_.setCurrentFont();
636                 // To center the screen on this new position we need the
637                 // paragraph position which is computed at draw() time.
638                 // So we need a redraw!
639                 buffer_.changed();
640                 if (fitCursor())
641                         center();
642         }
643
644         return success;
645 }
646
647
648 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
649 {
650         if (lyxrc.rtl_support) {
651                 if (d->cursor_.real_current_font.isRightToLeft()) {
652                         if (d->intl_.keymap == Intl::PRIMARY)
653                                 d->intl_.keyMapSec();
654                 } else {
655                         if (d->intl_.keymap == Intl::SECONDARY)
656                                 d->intl_.keyMapPrim();
657                 }
658         }
659
660         d->intl_.getTransManager().translateAndInsert(c, t, cur);
661 }
662
663
664 int BufferView::workWidth() const
665 {
666         return width_;
667 }
668
669
670 void BufferView::center()
671 {
672         // We are not properly started yet, delay until resizing is
673         // done.
674         if (height_ == 0)
675                 return;
676
677         LYXERR(Debug::SCROLLING, "recentering!");
678
679         CursorSlice & bot = d->cursor_.bottom();
680         TextMetrics & tm = d->text_metrics_[bot.text()];
681
682         int const bot_pit = d->cursor_.bottom().pit();
683         if (bot_pit == tm.first().first - 1)
684                 tm.newParMetricsUp();
685         else if (bot_pit == tm.last().first + 1)
686                 tm.newParMetricsDown();
687
688         if (tm.has(bot_pit)) {
689                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
690                 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
691                 int ypos = pm.position() + offset;
692                 Dimension const & row_dim = d->cursor_.textRow().dimension();
693                 if (ypos - row_dim.ascent() < 0)
694                         scrollUp(- ypos + d->cursor_.textRow().ascent());
695                 else if (ypos + row_dim.descent() > height_)
696                         scrollDown(ypos - height_ + d->cursor_.textRow().descent());
697                 // else, nothing to do, the cursor is already visible so we just return.
698                 return;
699         }
700
701         tm.redoParagraph(bot_pit);
702         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
703         int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
704
705         d->anchor_pit_ = bot_pit;
706
707         if (d->anchor_pit_ == 0)
708                 d->anchor_ypos_ = offset + pm.ascent();
709         else if (d->anchor_pit_ >= pos_type(bot.text()->paragraphs().size() - 1)) {
710                 d->anchor_pit_ = bot.text()->paragraphs().size() - 1;
711                 d->anchor_ypos_ = offset + pm.height() - height_;
712         } else {
713                 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
714         }
715
716         updateMetrics();
717         buffer_.changed();
718 }
719
720
721 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
722 {
723         FuncStatus flag;
724
725         Cursor & cur = d->cursor_;
726
727         switch (cmd.action) {
728
729         case LFUN_UNDO:
730                 flag.enabled(buffer_.undo().hasUndoStack());
731                 break;
732         case LFUN_REDO:
733                 flag.enabled(buffer_.undo().hasRedoStack());
734                 break;
735         case LFUN_FILE_INSERT:
736         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
737         case LFUN_FILE_INSERT_PLAINTEXT:
738         case LFUN_BOOKMARK_SAVE:
739                 // FIXME: Actually, these LFUNS should be moved to Text
740                 flag.enabled(cur.inTexted());
741                 break;
742         case LFUN_FONT_STATE:
743         case LFUN_LABEL_INSERT:
744         case LFUN_INFO_INSERT:
745         case LFUN_PARAGRAPH_GOTO:
746         case LFUN_NOTE_NEXT:
747         case LFUN_REFERENCE_NEXT:
748         case LFUN_WORD_FIND:
749         case LFUN_WORD_REPLACE:
750         case LFUN_MARK_OFF:
751         case LFUN_MARK_ON:
752         case LFUN_MARK_TOGGLE:
753         case LFUN_SCREEN_RECENTER:
754         case LFUN_BIBTEX_DATABASE_ADD:
755         case LFUN_BIBTEX_DATABASE_DEL:
756         case LFUN_WORDS_COUNT:
757         case LFUN_NEXT_INSET_TOGGLE:
758                 flag.enabled(true);
759                 break;
760
761         case LFUN_LABEL_GOTO: {
762                 flag.enabled(!cmd.argument().empty()
763                     || getInsetByCode<InsetRef>(cur, REF_CODE));
764                 break;
765         }
766
767         case LFUN_CHANGES_TRACK:
768                 flag.enabled(true);
769                 flag.setOnOff(buffer_.params().trackChanges);
770                 break;
771
772         case LFUN_CHANGES_OUTPUT:
773                 flag.enabled(true);
774                 flag.setOnOff(buffer_.params().outputChanges);
775                 break;
776
777         case LFUN_CHANGES_MERGE:
778         case LFUN_CHANGE_NEXT:
779         case LFUN_ALL_CHANGES_ACCEPT:
780         case LFUN_ALL_CHANGES_REJECT:
781                 // TODO: context-sensitive enabling of LFUNs
782                 // In principle, these command should only be enabled if there
783                 // is a change in the document. However, without proper
784                 // optimizations, this will inevitably result in poor performance.
785                 flag.enabled(true);
786                 break;
787
788         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
789                 flag.setOnOff(buffer_.params().compressed);
790                 break;
791         }
792         
793         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
794                 flag.setOnOff(buffer_.params().embedded);
795                 break;
796         }
797
798         case LFUN_SCREEN_UP:
799         case LFUN_SCREEN_DOWN:
800                 flag.enabled(true);
801                 break;
802
803         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
804         // everywhere else before this can enabled:
805         case LFUN_SCREEN_UP_SELECT:
806         case LFUN_SCREEN_DOWN_SELECT:
807                 flag.enabled(false);
808                 break;
809
810         case LFUN_LAYOUT_TABULAR:
811                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
812                 break;
813
814         case LFUN_LAYOUT:
815         case LFUN_LAYOUT_PARAGRAPH:
816                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
817                 break;
818
819         case LFUN_INSET_SETTINGS: {
820                 InsetCode code = cur.inset().lyxCode();
821                 bool enable = false;
822                 switch (code) {
823                         case TABULAR_CODE:
824                                 enable = cmd.argument() == "tabular";
825                                 break;
826                         case ERT_CODE:
827                                 enable = cmd.argument() == "ert";
828                                 break;
829                         case FLOAT_CODE:
830                                 enable = cmd.argument() == "float";
831                                 break;
832                         case WRAP_CODE:
833                                 enable = cmd.argument() == "wrap";
834                                 break;
835                         case NOTE_CODE:
836                                 enable = cmd.argument() == "note";
837                                 break;
838                         case BRANCH_CODE:
839                                 enable = cmd.argument() == "branch";
840                                 break;
841                         case BOX_CODE:
842                                 enable = cmd.argument() == "box";
843                                 break;
844                         case LISTINGS_CODE:
845                                 enable = cmd.argument() == "listings";
846                                 break;
847                         default:
848                                 break;
849                 }
850                 flag.enabled(enable);
851                 break;
852         }
853
854         case LFUN_DIALOG_SHOW_NEW_INSET:
855                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
856                         cur.inset().lyxCode() != LISTINGS_CODE);
857                 if (cur.inset().lyxCode() == CAPTION_CODE) {
858                         FuncStatus flag;
859                         if (cur.inset().getStatus(cur, cmd, flag))
860                                 return flag;
861                 }
862                 break;
863
864         default:
865                 flag.enabled(false);
866         }
867
868         return flag;
869 }
870
871
872 Update::flags BufferView::dispatch(FuncRequest const & cmd)
873 {
874         //lyxerr << [ cmd = " << cmd << "]" << endl;
875
876         // Make sure that the cached BufferView is correct.
877         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
878                 << " arg[" << to_utf8(cmd.argument()) << ']'
879                 << " x[" << cmd.x << ']'
880                 << " y[" << cmd.y << ']'
881                 << " button[" << cmd.button() << ']');
882
883         Cursor & cur = d->cursor_;
884         // Default Update flags.
885         Update::flags updateFlags = Update::Force | Update::FitCursor;
886
887         switch (cmd.action) {
888
889         case LFUN_UNDO:
890                 cur.message(_("Undo"));
891                 cur.clearSelection();
892                 if (!cur.textUndo()) {
893                         cur.message(_("No further undo information"));
894                         updateFlags = Update::None;
895                 }
896                 break;
897
898         case LFUN_REDO:
899                 cur.message(_("Redo"));
900                 cur.clearSelection();
901                 if (!cur.textRedo()) {
902                         cur.message(_("No further redo information"));
903                         updateFlags = Update::None;
904                 }
905                 break;
906
907         case LFUN_FONT_STATE:
908                 cur.message(cur.currentState());
909                 break;
910
911         case LFUN_BOOKMARK_SAVE:
912                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
913                 break;
914
915         case LFUN_LABEL_GOTO: {
916                 docstring label = cmd.argument();
917                 if (label.empty()) {
918                         InsetRef * inset =
919                                 getInsetByCode<InsetRef>(d->cursor_,
920                                                          REF_CODE);
921                         if (inset) {
922                                 label = inset->getParam("reference");
923                                 // persistent=false: use temp_bookmark
924                                 saveBookmark(0);
925                         }
926                 }
927
928                 if (!label.empty())
929                         gotoLabel(label);
930                 break;
931         }
932
933         case LFUN_PARAGRAPH_GOTO: {
934                 int const id = convert<int>(to_utf8(cmd.argument()));
935                 int i = 0;
936                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
937                         b = theBufferList().next(b)) {
938
939                         ParIterator par = b->getParFromID(id);
940                         if (par == b->par_iterator_end()) {
941                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
942                         } else {
943                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
944                                         << " found in buffer `"
945                                         << b->absFileName() << "'.");
946
947                                 if (b == &buffer_) {
948                                         // Set the cursor
949                                         setCursor(makeDocIterator(par, 0));
950                                 } else {
951                                         // Switch to other buffer view and resend cmd
952                                         theLyXFunc().dispatch(FuncRequest(
953                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
954                                         theLyXFunc().dispatch(cmd);
955                                         updateFlags = Update::None;
956                                 }
957                                 break;
958                         }
959                         ++i;
960                 }
961                 break;
962         }
963
964         case LFUN_NOTE_NEXT:
965                 gotoInset(this, NOTE_CODE, false);
966                 break;
967
968         case LFUN_REFERENCE_NEXT: {
969                 vector<InsetCode> tmp;
970                 tmp.push_back(LABEL_CODE);
971                 tmp.push_back(REF_CODE);
972                 gotoInset(this, tmp, true);
973                 break;
974         }
975
976         case LFUN_CHANGES_TRACK:
977                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
978                 break;
979
980         case LFUN_CHANGES_OUTPUT:
981                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
982                 if (buffer_.params().outputChanges) {
983                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
984                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
985                                           LaTeXFeatures::isAvailable("xcolor");
986
987                         if (!dvipost && !xcolorsoul) {
988                                 Alert::warning(_("Changes not shown in LaTeX output"),
989                                                _("Changes will not be highlighted in LaTeX output, "
990                                                  "because neither dvipost nor xcolor/soul are installed.\n"
991                                                  "Please install these packages or redefine "
992                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
993                         } else if (!xcolorsoul) {
994                                 Alert::warning(_("Changes not shown in LaTeX output"),
995                                                _("Changes will not be highlighted in LaTeX output "
996                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
997                                                  "Please install both packages or redefine "
998                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
999                         }
1000                 }
1001                 break;
1002
1003         case LFUN_CHANGE_NEXT:
1004                 findNextChange(this);
1005                 break;
1006
1007         case LFUN_CHANGES_MERGE:
1008                 if (findNextChange(this))
1009                         showDialog("changes");
1010                 break;
1011
1012         case LFUN_ALL_CHANGES_ACCEPT:
1013                 // select complete document
1014                 d->cursor_.reset(buffer_.inset());
1015                 d->cursor_.selHandle(true);
1016                 buffer_.text().cursorBottom(d->cursor_);
1017                 // accept everything in a single step to support atomic undo
1018                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1019                 break;
1020
1021         case LFUN_ALL_CHANGES_REJECT:
1022                 // select complete document
1023                 d->cursor_.reset(buffer_.inset());
1024                 d->cursor_.selHandle(true);
1025                 buffer_.text().cursorBottom(d->cursor_);
1026                 // reject everything in a single step to support atomic undo
1027                 // Note: reject does not work recursively; the user may have to repeat the operation
1028                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1029                 break;
1030
1031         case LFUN_WORD_FIND:
1032                 find(this, cmd);
1033                 break;
1034
1035         case LFUN_WORD_REPLACE: {
1036                 bool has_deleted = false;
1037                 if (cur.selection()) {
1038                         DocIterator beg = cur.selectionBegin();
1039                         DocIterator end = cur.selectionEnd();
1040                         if (beg.pit() == end.pit()) {
1041                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1042                                         if (cur.paragraph().isDeleted(p))
1043                                                 has_deleted = true;
1044                                 }
1045                         }
1046                 }
1047                 replace(this, cmd, has_deleted);
1048                 break;
1049         }
1050
1051         case LFUN_MARK_OFF:
1052                 cur.clearSelection();
1053                 cur.resetAnchor();
1054                 cur.message(from_utf8(N_("Mark off")));
1055                 break;
1056
1057         case LFUN_MARK_ON:
1058                 cur.clearSelection();
1059                 cur.mark() = true;
1060                 cur.resetAnchor();
1061                 cur.message(from_utf8(N_("Mark on")));
1062                 break;
1063
1064         case LFUN_MARK_TOGGLE:
1065                 cur.clearSelection();
1066                 if (cur.mark()) {
1067                         cur.mark() = false;
1068                         cur.message(from_utf8(N_("Mark removed")));
1069                 } else {
1070                         cur.mark() = true;
1071                         cur.message(from_utf8(N_("Mark set")));
1072                 }
1073                 cur.resetAnchor();
1074                 break;
1075
1076         case LFUN_SCREEN_RECENTER:
1077                 center();
1078                 break;
1079
1080         case LFUN_BIBTEX_DATABASE_ADD: {
1081                 Cursor tmpcur = d->cursor_;
1082                 findInset(tmpcur, BIBTEX_CODE, false);
1083                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1084                                                 BIBTEX_CODE);
1085                 if (inset) {
1086                         if (inset->addDatabase(to_utf8(cmd.argument())))
1087                                 buffer_.updateBibfilesCache();
1088                 }
1089                 break;
1090         }
1091
1092         case LFUN_BIBTEX_DATABASE_DEL: {
1093                 Cursor tmpcur = d->cursor_;
1094                 findInset(tmpcur, BIBTEX_CODE, false);
1095                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1096                                                 BIBTEX_CODE);
1097                 if (inset) {
1098                         if (inset->delDatabase(to_utf8(cmd.argument())))
1099                                 buffer_.updateBibfilesCache();
1100                 }
1101                 break;
1102         }
1103
1104         case LFUN_WORDS_COUNT: {
1105                 DocIterator from, to;
1106                 if (cur.selection()) {
1107                         from = cur.selectionBegin();
1108                         to = cur.selectionEnd();
1109                 } else {
1110                         from = doc_iterator_begin(buffer_.inset());
1111                         to = doc_iterator_end(buffer_.inset());
1112                 }
1113                 int const count = countWords(from, to);
1114                 docstring message;
1115                 if (count != 1) {
1116                         if (cur.selection())
1117                                 message = bformat(_("%1$d words in selection."),
1118                                           count);
1119                                 else
1120                                         message = bformat(_("%1$d words in document."),
1121                                                           count);
1122                 }
1123                 else {
1124                         if (cur.selection())
1125                                 message = _("One word in selection.");
1126                         else
1127                                 message = _("One word in document.");
1128                 }
1129
1130                 Alert::information(_("Count words"), message);
1131         }
1132                 break;
1133
1134         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1135                 // turn compression on/off
1136                 buffer_.params().compressed = !buffer_.params().compressed;
1137                 break;
1138         
1139         case LFUN_BUFFER_TOGGLE_EMBEDDING:
1140                 // turn embedding on/off
1141                 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1142                 break;
1143
1144         case LFUN_NEXT_INSET_TOGGLE: {
1145                 // this is the real function we want to invoke
1146                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1147                 // if there is an inset at cursor, see whether it
1148                 // wants to toggle.
1149                 Inset * inset = cur.nextInset();
1150                 if (inset) {
1151                         if (inset->isActive()) {
1152                                 Cursor tmpcur = cur;
1153                                 tmpcur.pushBackward(*inset);
1154                                 inset->dispatch(tmpcur, tmpcmd);
1155                                 if (tmpcur.result().dispatched()) {
1156                                         cur.dispatched();
1157                                 }
1158                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1159                                 inset->edit(cur, true);
1160                         }
1161                 }
1162                 // if it did not work, try the underlying inset.
1163                 if (!cur.result().dispatched())
1164                         cur.dispatch(tmpcmd);
1165
1166                 if (cur.result().dispatched())
1167                         cur.clearSelection();
1168
1169                 break;
1170         }
1171
1172         case LFUN_SCREEN_UP:
1173         case LFUN_SCREEN_DOWN: {
1174                 Point p = getPos(cur, cur.boundary());
1175                 if (p.y_ < 0 || p.y_ > height_) {
1176                         // The cursor is off-screen so recenter before proceeding.
1177                         center();
1178                         p = getPos(cur, cur.boundary());
1179                 }
1180                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1181                 cur.reset(buffer_.inset());
1182                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1183                 //FIXME: what to do with cur.x_target()?
1184                 cur.finishUndo();
1185                 // The metrics are already up to date. see scroll()
1186                 updateFlags = Update::None;
1187                 break;
1188         }
1189
1190         case LFUN_SCREEN_UP_SELECT:
1191         case LFUN_SCREEN_DOWN_SELECT: {
1192                 cur.selHandle(true);
1193                 size_t initial_depth = cur.depth();
1194                 Point const p = getPos(cur, cur.boundary());
1195                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1196                 // FIXME: We need to verify if the cursor stayed within an inset...
1197                 //cur.reset(buffer_.inset());
1198                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1199                 cur.finishUndo();
1200                 while (cur.depth() > initial_depth) {
1201                         cur.forwardInset();
1202                 }
1203                 // FIXME: we need to do a redraw again because of the selection
1204                 // But no screen update is needed.
1205                 d->update_strategy_ = NoScreenUpdate;
1206                 buffer_.changed();
1207                 updateFlags = Update::Force | Update::FitCursor;
1208                 break;
1209         }
1210
1211         default:
1212                 updateFlags = Update::None;
1213         }
1214
1215         return updateFlags;
1216 }
1217
1218
1219 docstring const BufferView::requestSelection()
1220 {
1221         Cursor & cur = d->cursor_;
1222
1223         if (!cur.selection()) {
1224                 d->xsel_cache_.set = false;
1225                 return docstring();
1226         }
1227
1228         if (!d->xsel_cache_.set ||
1229             cur.top() != d->xsel_cache_.cursor ||
1230             cur.anchor_.top() != d->xsel_cache_.anchor)
1231         {
1232                 d->xsel_cache_.cursor = cur.top();
1233                 d->xsel_cache_.anchor = cur.anchor_.top();
1234                 d->xsel_cache_.set = cur.selection();
1235                 return cur.selectionAsString(false);
1236         }
1237         return docstring();
1238 }
1239
1240
1241 void BufferView::clearSelection()
1242 {
1243         d->cursor_.clearSelection();
1244         // Clear the selection buffer. Otherwise a subsequent
1245         // middle-mouse-button paste would use the selection buffer,
1246         // not the more current external selection.
1247         cap::clearSelection();
1248         d->xsel_cache_.set = false;
1249         // The buffer did not really change, but this causes the
1250         // redraw we need because we cleared the selection above.
1251         buffer_.changed();
1252 }
1253
1254
1255 void BufferView::resize(int width, int height)
1256 {
1257         // Update from work area
1258         width_ = width;
1259         height_ = height;
1260
1261         // Clear the paragraph height cache.
1262         d->par_height_.clear();
1263
1264         updateMetrics();
1265 }
1266
1267
1268 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1269 {
1270         TextMetrics & tm = d->text_metrics_[&text];
1271         Inset * inset = tm.checkInsetHit(x, y);
1272         if (!inset)
1273                 return 0;
1274
1275         if (!inset->descendable())
1276                 // No need to go further down if the inset is not
1277                 // descendable.
1278                 return inset;
1279
1280         size_t cell_number = inset->nargs();
1281         // Check all the inner cell.
1282         for (size_t i = 0; i != cell_number; ++i) {
1283                 Text const * inner_text = inset->getText(i);
1284                 if (inner_text) {
1285                         // Try deeper.
1286                         Inset const * inset_deeper =
1287                                 getCoveringInset(*inner_text, x, y);
1288                         if (inset_deeper)
1289                                 return inset_deeper;
1290                 }
1291         }
1292
1293         return inset;
1294 }
1295
1296
1297 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1298 {
1299         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1300
1301         // This is only called for mouse related events including
1302         // LFUN_FILE_OPEN generated by drag-and-drop.
1303         FuncRequest cmd = cmd0;
1304
1305         Cursor cur(*this);
1306         cur.push(buffer_.inset());
1307         cur.selection() = d->cursor_.selection();
1308
1309         // Either the inset under the cursor or the
1310         // surrounding Text will handle this event.
1311
1312         // make sure we stay within the screen...
1313         cmd.y = min(max(cmd.y, -1), height_);
1314
1315         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1316
1317                 // Get inset under mouse, if there is one.
1318                 Inset const * covering_inset =
1319                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1320                 if (covering_inset == d->last_inset_)
1321                         // Same inset, no need to do anything...
1322                         return;
1323
1324                 bool need_redraw = false;
1325                 // const_cast because of setMouseHover().
1326                 Inset * inset = const_cast<Inset *>(covering_inset);
1327                 if (d->last_inset_)
1328                         // Remove the hint on the last hovered inset (if any).
1329                         need_redraw |= d->last_inset_->setMouseHover(false);
1330                 if (inset)
1331                         // Highlighted the newly hovered inset (if any).
1332                         need_redraw |= inset->setMouseHover(true);
1333                 d->last_inset_ = inset;
1334                 if (!need_redraw)
1335                         return;
1336
1337                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1338                         << cmd.x << ", " << cmd.y << ")");
1339
1340                 d->update_strategy_ = DecorationUpdate;
1341
1342                 // This event (moving without mouse click) is not passed further.
1343                 // This should be changed if it is further utilized.
1344                 buffer_.changed();
1345                 return;
1346         }
1347
1348         // Build temporary cursor.
1349         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1350
1351         // Put anchor at the same position.
1352         cur.resetAnchor();
1353
1354         // Try to dispatch to an non-editable inset near this position
1355         // via the temp cursor. If the inset wishes to change the real
1356         // cursor it has to do so explicitly by using
1357         //  cur.bv().cursor() = cur;  (or similar)
1358         if (inset)
1359                 inset->dispatch(cur, cmd);
1360
1361         // Now dispatch to the temporary cursor. If the real cursor should
1362         // be modified, the inset's dispatch has to do so explicitly.
1363         if (!cur.result().dispatched())
1364                 cur.dispatch(cmd);
1365
1366         //Do we have a selection?
1367         theSelection().haveSelection(cursor().selection());
1368
1369         // If the command has been dispatched,
1370         if (cur.result().dispatched()
1371                 // an update is asked,
1372                 && cur.result().update())
1373                 processUpdateFlags(cur.result().update());
1374 }
1375
1376
1377 void BufferView::scroll(int y)
1378 {
1379         if (y > 0)
1380                 scrollDown(y);
1381         else if (y < 0)
1382                 scrollUp(-y);
1383 }
1384
1385
1386 void BufferView::scrollDown(int offset)
1387 {
1388         Text * text = &buffer_.text();
1389         TextMetrics & tm = d->text_metrics_[text];
1390         int ymax = height_ + offset;
1391         while (true) {
1392                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1393                 int bottom_pos = last.second->position() + last.second->descent();
1394                 if (last.first + 1 == int(text->paragraphs().size())) {
1395                         if (bottom_pos <= height_)
1396                                 return;
1397                         offset = min(offset, bottom_pos - height_);
1398                         break;
1399                 }
1400                 if (bottom_pos > ymax)
1401                         break;
1402                 tm.newParMetricsDown();
1403         }
1404         d->anchor_ypos_ -= offset;
1405         updateMetrics();
1406         buffer_.changed();
1407 }
1408
1409
1410 void BufferView::scrollUp(int offset)
1411 {
1412         Text * text = &buffer_.text();
1413         TextMetrics & tm = d->text_metrics_[text];
1414         int ymin = - offset;
1415         while (true) {
1416                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1417                 int top_pos = first.second->position() - first.second->ascent();
1418                 if (first.first == 0) {
1419                         if (top_pos >= 0)
1420                                 return;
1421                         offset = min(offset, - top_pos);
1422                         break;
1423                 }
1424                 if (top_pos < ymin)
1425                         break;
1426                 tm.newParMetricsUp();
1427         }
1428         d->anchor_ypos_ += offset;
1429         updateMetrics();
1430         buffer_.changed();
1431 }
1432
1433
1434 void BufferView::setCursorFromRow(int row)
1435 {
1436         int tmpid = -1;
1437         int tmppos = -1;
1438
1439         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1440
1441         d->cursor_.reset(buffer_.inset());
1442         if (tmpid == -1)
1443                 buffer_.text().setCursor(d->cursor_, 0, 0);
1444         else
1445                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1446 }
1447
1448
1449 void BufferView::gotoLabel(docstring const & label)
1450 {
1451         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1452                 vector<docstring> labels;
1453                 it->getLabelList(buffer_, labels);
1454                 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1455                         setCursor(it);
1456                         processUpdateFlags(Update::FitCursor);
1457                         return;
1458                 }
1459         }
1460 }
1461
1462
1463 TextMetrics const & BufferView::textMetrics(Text const * t) const
1464 {
1465         return const_cast<BufferView *>(this)->textMetrics(t);
1466 }
1467
1468
1469 TextMetrics & BufferView::textMetrics(Text const * t)
1470 {
1471         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1472         if (tmc_it == d->text_metrics_.end()) {
1473                 tmc_it = d->text_metrics_.insert(
1474                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1475         }
1476         return tmc_it->second;
1477 }
1478
1479
1480 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1481                 pit_type pit) const
1482 {
1483         return textMetrics(t).parMetrics(pit);
1484 }
1485
1486
1487 int BufferView::workHeight() const
1488 {
1489         return height_;
1490 }
1491
1492
1493 void BufferView::setCursor(DocIterator const & dit)
1494 {
1495         size_t const n = dit.depth();
1496         for (size_t i = 0; i < n; ++i)
1497                 dit[i].inset().edit(d->cursor_, true);
1498
1499         d->cursor_.setCursor(dit);
1500         d->cursor_.selection() = false;
1501 }
1502
1503
1504 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1505 {
1506         // Would be wrong to delete anything if we have a selection.
1507         if (cur.selection())
1508                 return false;
1509
1510         bool need_anchor_change = false;
1511         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1512                 need_anchor_change);
1513
1514         if (need_anchor_change)
1515                 cur.resetAnchor();
1516
1517         if (!changed)
1518                 return false;
1519
1520         updateLabels(buffer_);
1521
1522         updateMetrics();
1523         buffer_.changed();
1524         return true;
1525 }
1526
1527
1528 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1529 {
1530         BOOST_ASSERT(&cur.bv() == this);
1531
1532         if (!select)
1533                 // this event will clear selection so we save selection for
1534                 // persistent selection
1535                 cap::saveSelection(cursor());
1536
1537         // Has the cursor just left the inset?
1538         bool badcursor = false;
1539         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1540         if (leftinset)
1541                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1542
1543         // FIXME: shift-mouse selection doesn't work well across insets.
1544         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1545
1546         // do the dEPM magic if needed
1547         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1548         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1549         // the leftinset bool would not be necessary (badcursor instead).
1550         bool update = leftinset;
1551         if (!do_selection && !badcursor && d->cursor_.inTexted())
1552                 update |= checkDepm(cur, d->cursor_);
1553
1554         // if the cursor was in an empty script inset and the new
1555         // position is in the nucleus of the inset, notifyCursorLeaves
1556         // will kill the script inset itself. So we check all the
1557         // elements of the cursor to make sure that they are correct.
1558         // For an example, see bug 2933:
1559         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1560         // The code below could maybe be moved to a DocIterator method.
1561         //lyxerr << "cur before " << cur <<endl;
1562         DocIterator dit(cur.inset());
1563         dit.push_back(cur.bottom());
1564         size_t i = 1;
1565         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1566                 dit.push_back(cur[i]);
1567                 ++i;
1568         }
1569         //lyxerr << "5 cur after" << dit <<endl;
1570
1571         d->cursor_.setCursor(dit);
1572         d->cursor_.boundary(cur.boundary());
1573         if (do_selection)
1574                 d->cursor_.setSelection();
1575         else
1576                 d->cursor_.clearSelection();
1577
1578         d->cursor_.finishUndo();
1579         d->cursor_.setCurrentFont();
1580         return update;
1581 }
1582
1583
1584 void BufferView::putSelectionAt(DocIterator const & cur,
1585                                 int length, bool backwards)
1586 {
1587         d->cursor_.clearSelection();
1588
1589         setCursor(cur);
1590
1591         if (length) {
1592                 if (backwards) {
1593                         d->cursor_.pos() += length;
1594                         d->cursor_.setSelection(d->cursor_, -length);
1595                 } else
1596                         d->cursor_.setSelection(d->cursor_, length);
1597         }
1598 }
1599
1600
1601 Cursor & BufferView::cursor()
1602 {
1603         return d->cursor_;
1604 }
1605
1606
1607 Cursor const & BufferView::cursor() const
1608 {
1609         return d->cursor_;
1610 }
1611
1612
1613 pit_type BufferView::anchor_ref() const
1614 {
1615         return d->anchor_pit_;
1616 }
1617
1618
1619 bool BufferView::singleParUpdate()
1620 {
1621         Text & buftext = buffer_.text();
1622         pit_type const bottom_pit = d->cursor_.bottom().pit();
1623         TextMetrics & tm = textMetrics(&buftext);
1624         int old_height = tm.parMetrics(bottom_pit).height();
1625
1626         // In Single Paragraph mode, rebreak only
1627         // the (main text, not inset!) paragraph containing the cursor.
1628         // (if this paragraph contains insets etc., rebreaking will
1629         // recursively descend)
1630         tm.redoParagraph(bottom_pit);
1631         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1632         if (pm.height() != old_height)
1633                 // Paragraph height has changed so we cannot proceed to
1634                 // the singlePar optimisation.
1635                 return false;
1636
1637         d->update_strategy_ = SingleParUpdate;
1638
1639         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1640                 << " y2: " << pm.position() + pm.descent()
1641                 << " pit: " << bottom_pit
1642                 << " singlepar: 1");
1643         return true;
1644 }
1645
1646
1647 void BufferView::updateMetrics()
1648 {
1649         Text & buftext = buffer_.text();
1650         pit_type const npit = int(buftext.paragraphs().size());
1651
1652         // Clear out the position cache in case of full screen redraw,
1653         d->coord_cache_.clear();
1654
1655         // Clear out paragraph metrics to avoid having invalid metrics
1656         // in the cache from paragraphs not relayouted below
1657         // The complete text metrics will be redone.
1658         d->text_metrics_.clear();
1659
1660         TextMetrics & tm = textMetrics(&buftext);
1661
1662         // Rebreak anchor paragraph.
1663         tm.redoParagraph(d->anchor_pit_);
1664         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1665         anchor_pm.setPosition(d->anchor_ypos_);
1666
1667         LYXERR(Debug::PAINTING, "metrics: "
1668                 << " anchor pit = " << d->anchor_pit_
1669                 << " anchor ypos = " << d->anchor_ypos_);
1670
1671         // Redo paragraphs above anchor if necessary.
1672         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1673         // We are now just above the anchor paragraph.
1674         pit_type pit1 = d->anchor_pit_ - 1;
1675         for (; pit1 >= 0 && y1 > 0; --pit1) {
1676                 tm.redoParagraph(pit1);
1677                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1678                 y1 -= pm.descent();
1679                 // Save the paragraph position in the cache.
1680                 pm.setPosition(y1);
1681                 y1 -= pm.ascent();
1682         }
1683
1684         // Redo paragraphs below the anchor if necessary.
1685         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1686         // We are now just below the anchor paragraph.
1687         pit_type pit2 = d->anchor_pit_ + 1;
1688         for (; pit2 < npit && y2 < height_; ++pit2) {
1689                 tm.redoParagraph(pit2);
1690                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1691                 y2 += pm.ascent();
1692                 // Save the paragraph position in the cache.
1693                 pm.setPosition(y2);
1694                 y2 += pm.descent();
1695         }
1696
1697         LYXERR(Debug::PAINTING, "Metrics: "
1698                 << " anchor pit = " << d->anchor_pit_
1699                 << " anchor ypos = " << d->anchor_ypos_
1700                 << " y1 = " << y1
1701                 << " y2 = " << y2
1702                 << " pit1 = " << pit1
1703                 << " pit2 = " << pit2);
1704
1705         d->update_strategy_ = FullScreenUpdate;
1706
1707         if (lyxerr.debugging(Debug::WORKAREA)) {
1708                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1709                 d->coord_cache_.dump();
1710         }
1711 }
1712
1713
1714 void BufferView::insertLyXFile(FileName const & fname)
1715 {
1716         BOOST_ASSERT(d->cursor_.inTexted());
1717
1718         // Get absolute path of file and add ".lyx"
1719         // to the filename if necessary
1720         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1721
1722         docstring const disp_fn = makeDisplayPath(filename.absFilename());
1723         // emit message signal.
1724         message(bformat(_("Inserting document %1$s..."), disp_fn));
1725
1726         docstring res;
1727         Buffer buf("", false);
1728         if (buf.loadLyXFile(filename)) {
1729                 ErrorList & el = buffer_.errorList("Parse");
1730                 // Copy the inserted document error list into the current buffer one.
1731                 el = buf.errorList("Parse");
1732                 buffer_.undo().recordUndo(d->cursor_);
1733                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1734                                              buf.params().getTextClassPtr(), el);
1735                 res = _("Document %1$s inserted.");
1736         } else {
1737                 res = _("Could not insert document %1$s");
1738         }
1739
1740         updateMetrics();
1741         buffer_.changed();
1742         // emit message signal.
1743         message(bformat(res, disp_fn));
1744         buffer_.errors("Parse");
1745 }
1746
1747
1748 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1749 {
1750         int x = 0;
1751         int y = 0;
1752         int lastw = 0;
1753
1754         // Addup contribution of nested insets, from inside to outside,
1755         // keeping the outer paragraph for a special handling below
1756         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1757                 CursorSlice const & sl = dit[i];
1758                 int xx = 0;
1759                 int yy = 0;
1760                 
1761                 // get relative position inside sl.inset()
1762                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1763                 
1764                 // Make relative position inside of the edited inset relative to sl.inset()
1765                 x += xx;
1766                 y += yy;
1767                 
1768                 // In case of an RTL inset, the edited inset will be positioned to the left
1769                 // of xx:yy
1770                 if (sl.text()) {
1771                         bool boundary_i = boundary && i + 1 == dit.depth();
1772                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1773                         if (rtl)
1774                                 x -= lastw;
1775                 }
1776
1777                 // remember width for the case that sl.inset() is positioned in an RTL inset
1778                 if (i && dit[i - 1].text()) {
1779                         // If this Inset is inside a Text Inset, retrieve the Dimension
1780                         // from the containing text instead of using Inset::dimension() which
1781                         // might not be implemented.
1782                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1783                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1784                         // to be rewritten in light of the new design.
1785                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1786                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1787                         lastw = dim.wid;
1788                 } else {
1789                         Dimension const dim = sl.inset().dimension(*this);
1790                         lastw = dim.wid;
1791                 }
1792                 
1793                 //lyxerr << "Cursor::getPos, i: "
1794                 // << i << " x: " << xx << " y: " << y << endl;
1795         }
1796
1797         // Add contribution of initial rows of outermost paragraph
1798         CursorSlice const & sl = dit[0];
1799         TextMetrics const & tm = textMetrics(sl.text());
1800         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1801         BOOST_ASSERT(!pm.rows().empty());
1802         y -= pm.rows()[0].ascent();
1803 #if 1
1804         // FIXME: document this mess
1805         size_t rend;
1806         if (sl.pos() > 0 && dit.depth() == 1) {
1807                 int pos = sl.pos();
1808                 if (pos && boundary)
1809                         --pos;
1810 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1811                 rend = pm.pos2row(pos);
1812         } else
1813                 rend = pm.pos2row(sl.pos());
1814 #else
1815         size_t rend = pm.pos2row(sl.pos());
1816 #endif
1817         for (size_t rit = 0; rit != rend; ++rit)
1818                 y += pm.rows()[rit].height();
1819         y += pm.rows()[rend].ascent();
1820         
1821         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1822         
1823         // Make relative position from the nested inset now bufferview absolute.
1824         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1825         x += xx;
1826         
1827         // In the RTL case place the nested inset at the left of the cursor in 
1828         // the outer paragraph
1829         bool boundary_1 = boundary && 1 == dit.depth();
1830         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1831         if (rtl)
1832                 x -= lastw;
1833         
1834         return Point(x, y);
1835 }
1836
1837
1838 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1839 {
1840         CursorSlice const & bot = dit.bottom();
1841         TextMetrics const & tm = textMetrics(bot.text());
1842         if (!tm.has(bot.pit()))
1843                 return Point(-1, -1);
1844
1845         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1846         p.y_ += tm.parMetrics(bot.pit()).position();
1847         return p;
1848 }
1849
1850
1851 void BufferView::draw(frontend::Painter & pain)
1852 {
1853         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1854         Text & text = buffer_.text();
1855         TextMetrics const & tm = d->text_metrics_[&text];
1856         int const y = tm.first().second->position();
1857         PainterInfo pi(this, pain);
1858
1859         switch (d->update_strategy_) {
1860
1861         case NoScreenUpdate:
1862                 // If no screen painting is actually needed, only some the different
1863                 // coordinates of insets and paragraphs needs to be updated.
1864                 pi.full_repaint = true;
1865                 pi.pain.setDrawingEnabled(false);
1866                 tm.draw(pi, 0, y);
1867                 break;
1868
1869         case SingleParUpdate:
1870                 pi.full_repaint = false;
1871                 // In general, only the current row of the outermost paragraph
1872                 // will be redrawn. Particular cases where selection spans
1873                 // multiple paragraph are correctly detected in TextMetrics.
1874                 tm.draw(pi, 0, y);
1875                 break;
1876
1877         case DecorationUpdate:
1878                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1879                 // drawing if possible. This is not possible to do easily right now
1880                 // because of the single backing pixmap.
1881
1882         case FullScreenUpdate:
1883                 // The whole screen, including insets, will be refreshed.
1884                 pi.full_repaint = true;
1885
1886                 // Clear background.
1887                 pain.fillRectangle(0, 0, width_, height_,
1888                         buffer_.inset().backgroundColor());
1889
1890                 // Draw everything.
1891                 tm.draw(pi, 0, y);
1892
1893                 // and possibly grey out below
1894                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1895                 int const y2 = lastpm.second->position() + lastpm.second->descent();
1896                 if (y2 < height_)
1897                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1898                 break;
1899         }
1900         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
1901
1902         // The scrollbar needs an update.
1903         updateScrollbar();
1904
1905         // Normalize anchor for next time
1906         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1907         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1908         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1909                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1910                 if (pm.position() + pm.descent() > 0) {
1911                         d->anchor_pit_ = pit;
1912                         d->anchor_ypos_ = pm.position();
1913                         break;
1914                 }
1915         }
1916         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1917                 << "  anchor ypos = " << d->anchor_ypos_);
1918 }
1919
1920
1921 void BufferView::message(docstring const & msg)
1922 {
1923         if (d->gui_)
1924                 d->gui_->message(msg);
1925 }
1926
1927
1928 void BufferView::showDialog(string const & name)
1929 {
1930         if (d->gui_)
1931                 d->gui_->showDialog(name, string());
1932 }
1933
1934
1935 void BufferView::showDialog(string const & name,
1936         string const & data, Inset * inset)
1937 {
1938         if (d->gui_)
1939                 d->gui_->showDialog(name, data, inset);
1940 }
1941
1942
1943 void BufferView::updateDialog(string const & name, string const & data)
1944 {
1945         if (d->gui_)
1946                 d->gui_->updateDialog(name, data);
1947 }
1948
1949
1950 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1951 {
1952         d->gui_ = gui;
1953 }
1954
1955
1956 // FIXME: Move this out of BufferView again
1957 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1958 {
1959         if (!fname.isReadableFile()) {
1960                 docstring const error = from_ascii(strerror(errno));
1961                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1962                 docstring const text =
1963                   bformat(_("Could not read the specified document\n"
1964                             "%1$s\ndue to the error: %2$s"), file, error);
1965                 Alert::error(_("Could not read file"), text);
1966                 return docstring();
1967         }
1968
1969         if (!fname.isReadableFile()) {
1970                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1971                 docstring const text =
1972                   bformat(_("%1$s\n is not readable."), file);
1973                 Alert::error(_("Could not open file"), text);
1974                 return docstring();
1975         }
1976
1977         // FIXME UNICODE: We don't know the encoding of the file
1978         docstring file_content = fname.fileContents("UTF-8");
1979         if (file_content.empty()) {
1980                 Alert::error(_("Reading not UTF-8 encoded file"),
1981                              _("The file is not UTF-8 encoded.\n"
1982                                "It will be read as local 8Bit-encoded.\n"
1983                                "If this does not give the correct result\n"
1984                                "then please change the encoding of the file\n"
1985                                "to UTF-8 with a program other than LyX.\n"));
1986                 file_content = fname.fileContents("local8bit");
1987         }
1988
1989         return normalize_c(file_content);
1990 }
1991
1992
1993 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1994 {
1995         docstring const tmpstr = contentsOfPlaintextFile(f);
1996
1997         if (tmpstr.empty())
1998                 return;
1999
2000         Cursor & cur = cursor();
2001         cap::replaceSelection(cur);
2002         buffer_.undo().recordUndo(cur);
2003         if (asParagraph)
2004                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2005         else
2006                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2007
2008         updateMetrics();
2009         buffer_.changed();
2010 }
2011
2012 } // namespace lyx