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