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