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