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