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