]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
no need for pointers, not even leaking ones...
[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 << BOOST_CURRENT_FUNCTION
865         //       << [ cmd = " << cmd << "]" << endl;
866
867         // Make sure that the cached BufferView is correct.
868         LYXERR(Debug::ACTION, BOOST_CURRENT_FUNCTION
869                 << " action[" << cmd.action << ']'
870                 << " arg[" << to_utf8(cmd.argument()) << ']'
871                 << " x[" << cmd.x << ']'
872                 << " y[" << cmd.y << ']'
873                 << " button[" << cmd.button() << ']');
874
875         Cursor & cur = d->cursor_;
876         // Default Update flags.
877         Update::flags updateFlags = Update::Force | Update::FitCursor;
878
879         switch (cmd.action) {
880
881         case LFUN_UNDO:
882                 cur.message(_("Undo"));
883                 cur.clearSelection();
884                 if (!cur.textUndo()) {
885                         cur.message(_("No further undo information"));
886                         updateFlags = Update::None;
887                 }
888                 break;
889
890         case LFUN_REDO:
891                 cur.message(_("Redo"));
892                 cur.clearSelection();
893                 if (!cur.textRedo()) {
894                         cur.message(_("No further redo information"));
895                         updateFlags = Update::None;
896                 }
897                 break;
898
899         case LFUN_FILE_INSERT:
900                 // FIXME UNICODE
901                 menuInsertLyXFile(to_utf8(cmd.argument()));
902                 break;
903
904         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
905                 // FIXME UNICODE
906                 insertPlaintextFile(to_utf8(cmd.argument()), true);
907                 break;
908
909         case LFUN_FILE_INSERT_PLAINTEXT:
910                 // FIXME UNICODE
911                 insertPlaintextFile(to_utf8(cmd.argument()), false);
912                 break;
913
914         case LFUN_FONT_STATE:
915                 cur.message(cur.currentState());
916                 break;
917
918         case LFUN_BOOKMARK_SAVE:
919                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
920                 break;
921
922         case LFUN_LABEL_GOTO: {
923                 docstring label = cmd.argument();
924                 if (label.empty()) {
925                         InsetRef * inset =
926                                 getInsetByCode<InsetRef>(d->cursor_,
927                                                          REF_CODE);
928                         if (inset) {
929                                 label = inset->getParam("reference");
930                                 // persistent=false: use temp_bookmark
931                                 saveBookmark(0);
932                         }
933                 }
934
935                 if (!label.empty())
936                         gotoLabel(label);
937                 break;
938         }
939
940         case LFUN_PARAGRAPH_GOTO: {
941                 int const id = convert<int>(to_utf8(cmd.argument()));
942                 int i = 0;
943                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
944                         b = theBufferList().next(b)) {
945
946                         ParIterator par = b->getParFromID(id);
947                         if (par == b->par_iterator_end()) {
948                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
949                         } else {
950                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
951                                         << " found in buffer `"
952                                         << b->absFileName() << "'.");
953
954                                 if (b == &buffer_) {
955                                         // Set the cursor
956                                         setCursor(makeDocIterator(par, 0));
957                                 } else {
958                                         // Switch to other buffer view and resend cmd
959                                         theLyXFunc().dispatch(FuncRequest(
960                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
961                                         theLyXFunc().dispatch(cmd);
962                                         updateFlags = Update::None;
963                                 }
964                                 break;
965                         }
966                         ++i;
967                 }
968                 break;
969         }
970
971         case LFUN_NOTE_NEXT:
972                 gotoInset(this, NOTE_CODE, false);
973                 break;
974
975         case LFUN_REFERENCE_NEXT: {
976                 vector<InsetCode> tmp;
977                 tmp.push_back(LABEL_CODE);
978                 tmp.push_back(REF_CODE);
979                 gotoInset(this, tmp, true);
980                 break;
981         }
982
983         case LFUN_CHANGES_TRACK:
984                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
985                 break;
986
987         case LFUN_CHANGES_OUTPUT:
988                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
989                 if (buffer_.params().outputChanges) {
990                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
991                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
992                                           LaTeXFeatures::isAvailable("xcolor");
993
994                         if (!dvipost && !xcolorsoul) {
995                                 Alert::warning(_("Changes not shown in LaTeX output"),
996                                                _("Changes will not be highlighted in LaTeX output, "
997                                                  "because neither dvipost nor xcolor/soul are installed.\n"
998                                                  "Please install these packages or redefine "
999                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1000                         } else if (!xcolorsoul) {
1001                                 Alert::warning(_("Changes not shown in LaTeX output"),
1002                                                _("Changes will not be highlighted in LaTeX output "
1003                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1004                                                  "Please install both packages or redefine "
1005                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1006                         }
1007                 }
1008                 break;
1009
1010         case LFUN_CHANGE_NEXT:
1011                 findNextChange(this);
1012                 break;
1013
1014         case LFUN_CHANGES_MERGE:
1015                 if (findNextChange(this))
1016                         showDialog("changes");
1017                 break;
1018
1019         case LFUN_ALL_CHANGES_ACCEPT:
1020                 // select complete document
1021                 d->cursor_.reset(buffer_.inset());
1022                 d->cursor_.selHandle(true);
1023                 buffer_.text().cursorBottom(d->cursor_);
1024                 // accept everything in a single step to support atomic undo
1025                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1026                 break;
1027
1028         case LFUN_ALL_CHANGES_REJECT:
1029                 // select complete document
1030                 d->cursor_.reset(buffer_.inset());
1031                 d->cursor_.selHandle(true);
1032                 buffer_.text().cursorBottom(d->cursor_);
1033                 // reject everything in a single step to support atomic undo
1034                 // Note: reject does not work recursively; the user may have to repeat the operation
1035                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1036                 break;
1037
1038         case LFUN_WORD_FIND:
1039                 find(this, cmd);
1040                 break;
1041
1042         case LFUN_WORD_REPLACE: {
1043                 bool has_deleted = false;
1044                 if (cur.selection()) {
1045                         DocIterator beg = cur.selectionBegin();
1046                         DocIterator end = cur.selectionEnd();
1047                         if (beg.pit() == end.pit()) {
1048                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1049                                         if (cur.paragraph().isDeleted(p))
1050                                                 has_deleted = true;
1051                                 }
1052                         }
1053                 }
1054                 replace(this, cmd, has_deleted);
1055                 break;
1056         }
1057
1058         case LFUN_MARK_OFF:
1059                 cur.clearSelection();
1060                 cur.resetAnchor();
1061                 cur.message(from_utf8(N_("Mark off")));
1062                 break;
1063
1064         case LFUN_MARK_ON:
1065                 cur.clearSelection();
1066                 cur.mark() = true;
1067                 cur.resetAnchor();
1068                 cur.message(from_utf8(N_("Mark on")));
1069                 break;
1070
1071         case LFUN_MARK_TOGGLE:
1072                 cur.clearSelection();
1073                 if (cur.mark()) {
1074                         cur.mark() = false;
1075                         cur.message(from_utf8(N_("Mark removed")));
1076                 } else {
1077                         cur.mark() = true;
1078                         cur.message(from_utf8(N_("Mark set")));
1079                 }
1080                 cur.resetAnchor();
1081                 break;
1082
1083         case LFUN_SCREEN_RECENTER:
1084                 center();
1085                 break;
1086
1087         case LFUN_BIBTEX_DATABASE_ADD: {
1088                 Cursor tmpcur = d->cursor_;
1089                 findInset(tmpcur, BIBTEX_CODE, false);
1090                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1091                                                 BIBTEX_CODE);
1092                 if (inset) {
1093                         if (inset->addDatabase(to_utf8(cmd.argument())))
1094                                 buffer_.updateBibfilesCache();
1095                 }
1096                 break;
1097         }
1098
1099         case LFUN_BIBTEX_DATABASE_DEL: {
1100                 Cursor tmpcur = d->cursor_;
1101                 findInset(tmpcur, BIBTEX_CODE, false);
1102                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1103                                                 BIBTEX_CODE);
1104                 if (inset) {
1105                         if (inset->delDatabase(to_utf8(cmd.argument())))
1106                                 buffer_.updateBibfilesCache();
1107                 }
1108                 break;
1109         }
1110
1111         case LFUN_WORDS_COUNT: {
1112                 DocIterator from, to;
1113                 if (cur.selection()) {
1114                         from = cur.selectionBegin();
1115                         to = cur.selectionEnd();
1116                 } else {
1117                         from = doc_iterator_begin(buffer_.inset());
1118                         to = doc_iterator_end(buffer_.inset());
1119                 }
1120                 int const count = countWords(from, to);
1121                 docstring message;
1122                 if (count != 1) {
1123                         if (cur.selection())
1124                                 message = bformat(_("%1$d words in selection."),
1125                                           count);
1126                                 else
1127                                         message = bformat(_("%1$d words in document."),
1128                                                           count);
1129                 }
1130                 else {
1131                         if (cur.selection())
1132                                 message = _("One word in selection.");
1133                         else
1134                                 message = _("One word in document.");
1135                 }
1136
1137                 Alert::information(_("Count words"), message);
1138         }
1139                 break;
1140
1141         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1142                 // turn compression on/off
1143                 buffer_.params().compressed = !buffer_.params().compressed;
1144                 break;
1145         
1146         case LFUN_BUFFER_TOGGLE_EMBEDDING:
1147                 // turn embedding on/off
1148                 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1149                 break;
1150
1151         case LFUN_NEXT_INSET_TOGGLE: {
1152                 // this is the real function we want to invoke
1153                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1154                 // if there is an inset at cursor, see whether it
1155                 // wants to toggle.
1156                 Inset * inset = cur.nextInset();
1157                 if (inset) {
1158                         if (inset->isActive()) {
1159                                 Cursor tmpcur = cur;
1160                                 tmpcur.pushBackward(*inset);
1161                                 inset->dispatch(tmpcur, tmpcmd);
1162                                 if (tmpcur.result().dispatched()) {
1163                                         cur.dispatched();
1164                                 }
1165                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1166                                 inset->edit(cur, true);
1167                         }
1168                 }
1169                 // if it did not work, try the underlying inset.
1170                 if (!cur.result().dispatched())
1171                         cur.dispatch(tmpcmd);
1172
1173                 if (cur.result().dispatched())
1174                         cur.clearSelection();
1175
1176                 break;
1177         }
1178
1179         case LFUN_SCREEN_UP:
1180         case LFUN_SCREEN_DOWN: {
1181                 Point p = getPos(cur, cur.boundary());
1182                 if (p.y_ < 0 || p.y_ > height_) {
1183                         // The cursor is off-screen so recenter before proceeding.
1184                         center();
1185                         updateMetrics();
1186                         //FIXME: updateMetrics() does not update paragraph position
1187                         // This is done at draw() time. So we need a redraw!
1188                         // But no screen update is needed.
1189                         d->update_strategy_ = NoScreenUpdate;
1190                         buffer_.changed();
1191                         p = getPos(cur, cur.boundary());
1192                 }
1193                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1194                 cur.reset(buffer_.inset());
1195                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1196                 //FIXME: what to do with cur.x_target()?
1197                 cur.finishUndo();
1198                 // The metrics are already up to date. see scroll()
1199                 updateFlags = Update::None;
1200                 break;
1201         }
1202
1203         case LFUN_SCREEN_UP_SELECT:
1204         case LFUN_SCREEN_DOWN_SELECT: {
1205                 cur.selHandle(true);
1206                 size_t initial_depth = cur.depth();
1207                 Point const p = getPos(cur, cur.boundary());
1208                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1209                 // FIXME: We need to verify if the cursor stayed within an inset...
1210                 //cur.reset(buffer_.inset());
1211                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1212                 cur.finishUndo();
1213                 while (cur.depth() > initial_depth) {
1214                         cur.forwardInset();
1215                 }
1216                 // FIXME: we need to do a redraw again because of the selection
1217                 // But no screen update is needed.
1218                 d->update_strategy_ = NoScreenUpdate;
1219                 buffer_.changed();
1220                 updateFlags = Update::Force | Update::FitCursor;
1221                 break;
1222         }
1223
1224         default:
1225                 updateFlags = Update::None;
1226         }
1227
1228         return updateFlags;
1229 }
1230
1231
1232 docstring const BufferView::requestSelection()
1233 {
1234         Cursor & cur = d->cursor_;
1235
1236         if (!cur.selection()) {
1237                 d->xsel_cache_.set = false;
1238                 return docstring();
1239         }
1240
1241         if (!d->xsel_cache_.set ||
1242             cur.top() != d->xsel_cache_.cursor ||
1243             cur.anchor_.top() != d->xsel_cache_.anchor)
1244         {
1245                 d->xsel_cache_.cursor = cur.top();
1246                 d->xsel_cache_.anchor = cur.anchor_.top();
1247                 d->xsel_cache_.set = cur.selection();
1248                 return cur.selectionAsString(false);
1249         }
1250         return docstring();
1251 }
1252
1253
1254 void BufferView::clearSelection()
1255 {
1256         d->cursor_.clearSelection();
1257         // Clear the selection buffer. Otherwise a subsequent
1258         // middle-mouse-button paste would use the selection buffer,
1259         // not the more current external selection.
1260         cap::clearSelection();
1261         d->xsel_cache_.set = false;
1262         // The buffer did not really change, but this causes the
1263         // redraw we need because we cleared the selection above.
1264         buffer_.changed();
1265 }
1266
1267
1268 void BufferView::resize(int width, int height)
1269 {
1270         // Update from work area
1271         width_ = width;
1272         height_ = height;
1273
1274         updateMetrics();
1275 }
1276
1277
1278 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1279 {
1280         TextMetrics & tm = d->text_metrics_[&text];
1281         Inset * inset = tm.checkInsetHit(x, y);
1282         if (!inset)
1283                 return 0;
1284
1285         if (!inset->descendable())
1286                 // No need to go further down if the inset is not
1287                 // descendable.
1288                 return inset;
1289
1290         size_t cell_number = inset->nargs();
1291         // Check all the inner cell.
1292         for (size_t i = 0; i != cell_number; ++i) {
1293                 Text const * inner_text = inset->getText(i);
1294                 if (inner_text) {
1295                         // Try deeper.
1296                         Inset const * inset_deeper =
1297                                 getCoveringInset(*inner_text, x, y);
1298                         if (inset_deeper)
1299                                 return inset_deeper;
1300                 }
1301         }
1302
1303         return inset;
1304 }
1305
1306
1307 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1308 {
1309         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1310
1311         // This is only called for mouse related events including
1312         // LFUN_FILE_OPEN generated by drag-and-drop.
1313         FuncRequest cmd = cmd0;
1314
1315         Cursor cur(*this);
1316         cur.push(buffer_.inset());
1317         cur.selection() = d->cursor_.selection();
1318
1319         // Either the inset under the cursor or the
1320         // surrounding Text will handle this event.
1321
1322         // make sure we stay within the screen...
1323         cmd.y = min(max(cmd.y, -1), height_);
1324
1325         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1326
1327                 // Get inset under mouse, if there is one.
1328                 Inset const * covering_inset =
1329                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1330                 if (covering_inset == d->last_inset_)
1331                         // Same inset, no need to do anything...
1332                         return;
1333
1334                 bool need_redraw = false;
1335                 // const_cast because of setMouseHover().
1336                 Inset * inset = const_cast<Inset *>(covering_inset);
1337                 if (d->last_inset_)
1338                         // Remove the hint on the last hovered inset (if any).
1339                         need_redraw |= d->last_inset_->setMouseHover(false);
1340                 if (inset)
1341                         // Highlighted the newly hovered inset (if any).
1342                         need_redraw |= inset->setMouseHover(true);
1343                 d->last_inset_ = inset;
1344                 if (!need_redraw)
1345                         return;
1346
1347                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1348                         << cmd.x << ", " << cmd.y << ")");
1349
1350                 d->update_strategy_ = DecorationUpdate;
1351
1352                 // This event (moving without mouse click) is not passed further.
1353                 // This should be changed if it is further utilized.
1354                 buffer_.changed();
1355                 return;
1356         }
1357
1358         // Build temporary cursor.
1359         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1360
1361         // Put anchor at the same position.
1362         cur.resetAnchor();
1363
1364         // Try to dispatch to an non-editable inset near this position
1365         // via the temp cursor. If the inset wishes to change the real
1366         // cursor it has to do so explicitly by using
1367         //  cur.bv().cursor() = cur;  (or similar)
1368         if (inset)
1369                 inset->dispatch(cur, cmd);
1370
1371         // Now dispatch to the temporary cursor. If the real cursor should
1372         // be modified, the inset's dispatch has to do so explicitly.
1373         if (!cur.result().dispatched())
1374                 cur.dispatch(cmd);
1375
1376         //Do we have a selection?
1377         theSelection().haveSelection(cursor().selection());
1378
1379         // If the command has been dispatched,
1380         if (cur.result().dispatched()
1381                 // an update is asked,
1382                 && cur.result().update())
1383                 processUpdateFlags(cur.result().update());
1384 }
1385
1386
1387 void BufferView::scroll(int y)
1388 {
1389         if (y > 0)
1390                 scrollDown(y);
1391         else if (y < 0)
1392                 scrollUp(-y);
1393 }
1394
1395
1396 void BufferView::scrollDown(int offset)
1397 {
1398         Text * text = &buffer_.text();
1399         TextMetrics & tm = d->text_metrics_[text];
1400         int ymax = height_ + offset;
1401         while (true) {
1402                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1403                 int bottom_pos = last.second->position() + last.second->descent();
1404                 if (last.first + 1 == int(text->paragraphs().size())) {
1405                         if (bottom_pos <= height_)
1406                                 return;
1407                         offset = min(offset, bottom_pos - height_);
1408                         break;
1409                 }
1410                 if (bottom_pos > ymax)
1411                         break;
1412                 tm.newParMetricsDown();
1413         }
1414         d->offset_ref_ += offset;
1415         updateMetrics();
1416         buffer_.changed();
1417 }
1418
1419
1420 void BufferView::scrollUp(int offset)
1421 {
1422         Text * text = &buffer_.text();
1423         TextMetrics & tm = d->text_metrics_[text];
1424         int ymin = - offset;
1425         while (true) {
1426                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1427                 int top_pos = first.second->position() - first.second->ascent();
1428                 if (first.first == 0) {
1429                         if (top_pos >= 0)
1430                                 return;
1431                         offset = min(offset, - top_pos);
1432                         break;
1433                 }
1434                 if (top_pos < ymin)
1435                         break;
1436                 tm.newParMetricsUp();
1437         }
1438         d->offset_ref_ -= offset;
1439         updateMetrics();
1440         buffer_.changed();
1441 }
1442
1443
1444 void BufferView::setCursorFromRow(int row)
1445 {
1446         int tmpid = -1;
1447         int tmppos = -1;
1448
1449         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1450
1451         d->cursor_.reset(buffer_.inset());
1452         if (tmpid == -1)
1453                 buffer_.text().setCursor(d->cursor_, 0, 0);
1454         else
1455                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1456 }
1457
1458
1459 void BufferView::gotoLabel(docstring const & label)
1460 {
1461         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1462                 vector<docstring> labels;
1463                 it->getLabelList(buffer_, labels);
1464                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1465                         setCursor(it);
1466                         processUpdateFlags(Update::FitCursor);
1467                         return;
1468                 }
1469         }
1470 }
1471
1472
1473 TextMetrics const & BufferView::textMetrics(Text const * t) const
1474 {
1475         return const_cast<BufferView *>(this)->textMetrics(t);
1476 }
1477
1478
1479 TextMetrics & BufferView::textMetrics(Text const * t)
1480 {
1481         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1482         if (tmc_it == d->text_metrics_.end()) {
1483                 tmc_it = d->text_metrics_.insert(
1484                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1485         }
1486         return tmc_it->second;
1487 }
1488
1489
1490 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1491                 pit_type pit) const
1492 {
1493         return textMetrics(t).parMetrics(pit);
1494 }
1495
1496
1497 int BufferView::workHeight() const
1498 {
1499         return height_;
1500 }
1501
1502
1503 void BufferView::setCursor(DocIterator const & dit)
1504 {
1505         size_t const n = dit.depth();
1506         for (size_t i = 0; i < n; ++i)
1507                 dit[i].inset().edit(d->cursor_, true);
1508
1509         d->cursor_.setCursor(dit);
1510         d->cursor_.selection() = false;
1511 }
1512
1513
1514 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1515 {
1516         // Would be wrong to delete anything if we have a selection.
1517         if (cur.selection())
1518                 return false;
1519
1520         bool need_anchor_change = false;
1521         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1522                 need_anchor_change);
1523
1524         if (need_anchor_change)
1525                 cur.resetAnchor();
1526
1527         if (!changed)
1528                 return false;
1529
1530         updateLabels(buffer_);
1531
1532         updateMetrics();
1533         buffer_.changed();
1534         return true;
1535 }
1536
1537
1538 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1539 {
1540         BOOST_ASSERT(&cur.bv() == this);
1541
1542         if (!select)
1543                 // this event will clear selection so we save selection for
1544                 // persistent selection
1545                 cap::saveSelection(cursor());
1546
1547         // Has the cursor just left the inset?
1548         bool badcursor = false;
1549         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1550         if (leftinset)
1551                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1552
1553         // FIXME: shift-mouse selection doesn't work well across insets.
1554         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1555
1556         // do the dEPM magic if needed
1557         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1558         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1559         // the leftinset bool would not be necessary (badcursor instead).
1560         bool update = leftinset;
1561         if (!do_selection && !badcursor && d->cursor_.inTexted())
1562                 update |= checkDepm(cur, d->cursor_);
1563
1564         // if the cursor was in an empty script inset and the new
1565         // position is in the nucleus of the inset, notifyCursorLeaves
1566         // will kill the script inset itself. So we check all the
1567         // elements of the cursor to make sure that they are correct.
1568         // For an example, see bug 2933:
1569         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1570         // The code below could maybe be moved to a DocIterator method.
1571         //lyxerr << "cur before " << cur <<std::endl;
1572         DocIterator dit(cur.inset());
1573         dit.push_back(cur.bottom());
1574         size_t i = 1;
1575         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1576                 dit.push_back(cur[i]);
1577                 ++i;
1578         }
1579         //lyxerr << "5 cur after" << dit <<std::endl;
1580
1581         d->cursor_.setCursor(dit);
1582         d->cursor_.boundary(cur.boundary());
1583         if (do_selection)
1584                 d->cursor_.setSelection();
1585         else
1586                 d->cursor_.clearSelection();
1587
1588         d->cursor_.finishUndo();
1589         d->cursor_.setCurrentFont();
1590         return update;
1591 }
1592
1593
1594 void BufferView::putSelectionAt(DocIterator const & cur,
1595                                 int length, bool backwards)
1596 {
1597         d->cursor_.clearSelection();
1598
1599         setCursor(cur);
1600
1601         if (length) {
1602                 if (backwards) {
1603                         d->cursor_.pos() += length;
1604                         d->cursor_.setSelection(d->cursor_, -length);
1605                 } else
1606                         d->cursor_.setSelection(d->cursor_, length);
1607         }
1608 }
1609
1610
1611 Cursor & BufferView::cursor()
1612 {
1613         return d->cursor_;
1614 }
1615
1616
1617 Cursor const & BufferView::cursor() const
1618 {
1619         return d->cursor_;
1620 }
1621
1622
1623 pit_type BufferView::anchor_ref() const
1624 {
1625         return d->anchor_ref_;
1626 }
1627
1628
1629 bool BufferView::singleParUpdate()
1630 {
1631         Text & buftext = buffer_.text();
1632         pit_type const bottom_pit = d->cursor_.bottom().pit();
1633         TextMetrics & tm = textMetrics(&buftext);
1634         int old_height = tm.parMetrics(bottom_pit).height();
1635
1636         // In Single Paragraph mode, rebreak only
1637         // the (main text, not inset!) paragraph containing the cursor.
1638         // (if this paragraph contains insets etc., rebreaking will
1639         // recursively descend)
1640         tm.redoParagraph(bottom_pit);
1641         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1642         if (pm.height() != old_height)
1643                 // Paragraph height has changed so we cannot proceed to
1644                 // the singlePar optimisation.
1645                 return false;
1646
1647         d->update_strategy_ = SingleParUpdate;
1648
1649         LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1650                 << "\ny1: " << pm.position() - pm.ascent()
1651                 << " y2: " << pm.position() + pm.descent()
1652                 << " pit: " << bottom_pit
1653                 << " singlepar: 1");
1654         return true;
1655 }
1656
1657
1658 void BufferView::updateMetrics()
1659 {
1660         Text & buftext = buffer_.text();
1661         pit_type const npit = int(buftext.paragraphs().size());
1662
1663         if (d->anchor_ref_ > int(npit - 1)) {
1664                 d->anchor_ref_ = int(npit - 1);
1665                 d->offset_ref_ = 0;
1666         }
1667
1668         // Clear out the position cache in case of full screen redraw,
1669         d->coord_cache_.clear();
1670
1671         // Clear out paragraph metrics to avoid having invalid metrics
1672         // in the cache from paragraphs not relayouted below
1673         // The complete text metrics will be redone.
1674         d->text_metrics_.clear();
1675
1676         TextMetrics & tm = textMetrics(&buftext);
1677
1678         pit_type const pit = d->anchor_ref_;
1679         int pit1 = pit;
1680         int pit2 = pit;
1681
1682         // Rebreak anchor paragraph.
1683         tm.redoParagraph(pit);
1684
1685         // Take care of anchor offset if case a recentering is needed.
1686         updateOffsetRef();
1687
1688         int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1689
1690         // Redo paragraphs above anchor if necessary.
1691         int y1 = y0;
1692         while (y1 > 0 && pit1 > 0) {
1693                 y1 -= tm.parMetrics(pit1).ascent();
1694                 --pit1;
1695                 tm.redoParagraph(pit1);
1696                 y1 -= tm.parMetrics(pit1).descent();
1697         }
1698
1699         // Take care of ascent of first line
1700         y1 -= tm.parMetrics(pit1).ascent();
1701
1702         // Normalize anchor for next time
1703         d->anchor_ref_ = pit1;
1704         d->offset_ref_ = -y1;
1705
1706         // Grey at the beginning is ugly
1707         if (pit1 == 0 && y1 > 0) {
1708                 y0 -= y1;
1709                 y1 = 0;
1710                 d->anchor_ref_ = 0;
1711         }
1712
1713         // Redo paragraphs below the anchor if necessary.
1714         int y2 = y0;
1715         while (y2 < height_ && pit2 < int(npit) - 1) {
1716                 y2 += tm.parMetrics(pit2).descent();
1717                 ++pit2;
1718                 tm.redoParagraph(pit2);
1719                 y2 += tm.parMetrics(pit2).ascent();
1720         }
1721
1722         // Take care of descent of last line
1723         y2 += tm.parMetrics(pit2).descent();
1724
1725         LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1726                 << "\n y1: " << y1
1727                 << " y2: " << y2
1728                 << " pit1: " << pit1
1729                 << " pit2: " << pit2
1730                 << " npit: " << npit
1731                 << " singlepar: 0");
1732
1733         d->update_strategy_ = FullScreenUpdate;
1734
1735         if (lyxerr.debugging(Debug::WORKAREA)) {
1736                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1737                 d->coord_cache_.dump();
1738         }
1739 }
1740
1741
1742 void BufferView::menuInsertLyXFile(string const & filenm)
1743 {
1744         BOOST_ASSERT(d->cursor_.inTexted());
1745         string filename = filenm;
1746
1747         if (filename.empty()) {
1748                 // Launch a file browser
1749                 // FIXME UNICODE
1750                 string initpath = lyxrc.document_path;
1751                 string const trypath = buffer_.filePath();
1752                 // If directory is writeable, use this as default.
1753                 if (FileName(trypath).isDirWritable())
1754                         initpath = trypath;
1755
1756                 // FIXME UNICODE
1757                 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1758                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1759                 dlg.setButton2(_("Examples|#E#e"),
1760                         from_utf8(addPath(package().system_support().absFilename(),
1761                         "examples")));
1762
1763                 FileDialog::Result result =
1764                         dlg.open(from_utf8(initpath),
1765                                      FileFilterList(_("LyX Documents (*.lyx)")),
1766                                      docstring());
1767
1768                 if (result.first == FileDialog::Later)
1769                         return;
1770
1771                 // FIXME UNICODE
1772                 filename = to_utf8(result.second);
1773
1774                 // check selected filename
1775                 if (filename.empty()) {
1776                         // emit message signal.
1777                         message(_("Canceled."));
1778                         return;
1779                 }
1780         }
1781
1782         // Get absolute path of file and add ".lyx"
1783         // to the filename if necessary
1784         filename = fileSearch(string(), filename, "lyx").absFilename();
1785
1786         docstring const disp_fn = makeDisplayPath(filename);
1787         // emit message signal.
1788         message(bformat(_("Inserting document %1$s..."), disp_fn));
1789
1790         docstring res;
1791         Buffer buf("", false);
1792         if (buf.loadLyXFile(FileName(filename))) {
1793                 ErrorList & el = buffer_.errorList("Parse");
1794                 // Copy the inserted document error list into the current buffer one.
1795                 el = buf.errorList("Parse");
1796                 buffer_.undo().recordUndo(d->cursor_);
1797                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1798                                              buf.params().getTextClassPtr(), el);
1799                 res = _("Document %1$s inserted.");
1800         } else {
1801                 res = _("Could not insert document %1$s");
1802         }
1803
1804         // emit message signal.
1805         message(bformat(res, disp_fn));
1806         buffer_.errors("Parse");
1807         updateMetrics();
1808 }
1809
1810
1811 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1812 {
1813         int x = 0;
1814         int y = 0;
1815         int lastw = 0;
1816
1817         // Addup contribution of nested insets, from inside to outside,
1818         // keeping the outer paragraph for a special handling below
1819         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1820                 CursorSlice const & sl = dit[i];
1821                 int xx = 0;
1822                 int yy = 0;
1823                 
1824                 // get relative position inside sl.inset()
1825                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1826                 
1827                 // Make relative position inside of the edited inset relative to sl.inset()
1828                 x += xx;
1829                 y += yy;
1830                 
1831                 // In case of an RTL inset, the edited inset will be positioned to the left
1832                 // of xx:yy
1833                 if (sl.text()) {
1834                         bool boundary_i = boundary && i + 1 == dit.depth();
1835                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1836                         if (rtl)
1837                                 x -= lastw;
1838                 }
1839
1840                 // remember width for the case that sl.inset() is positioned in an RTL inset
1841                 if (i && dit[i - 1].text()) {
1842                         // If this Inset is inside a Text Inset, retrieve the Dimension
1843                         // from the containing text instead of using Inset::dimension() which
1844                         // might not be implemented.
1845                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1846                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1847                         // to be rewritten in light of the new design.
1848                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1849                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1850                         lastw = dim.wid;
1851                 } else {
1852                         Dimension const dim = sl.inset().dimension(*this);
1853                         lastw = dim.wid;
1854                 }
1855                 
1856                 //lyxerr << "Cursor::getPos, i: "
1857                 // << i << " x: " << xx << " y: " << y << endl;
1858         }
1859
1860         // Add contribution of initial rows of outermost paragraph
1861         CursorSlice const & sl = dit[0];
1862         TextMetrics const & tm = textMetrics(sl.text());
1863         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1864         BOOST_ASSERT(!pm.rows().empty());
1865         y -= pm.rows()[0].ascent();
1866 #if 1
1867         // FIXME: document this mess
1868         size_t rend;
1869         if (sl.pos() > 0 && dit.depth() == 1) {
1870                 int pos = sl.pos();
1871                 if (pos && boundary)
1872                         --pos;
1873 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1874                 rend = pm.pos2row(pos);
1875         } else
1876                 rend = pm.pos2row(sl.pos());
1877 #else
1878         size_t rend = pm.pos2row(sl.pos());
1879 #endif
1880         for (size_t rit = 0; rit != rend; ++rit)
1881                 y += pm.rows()[rit].height();
1882         y += pm.rows()[rend].ascent();
1883         
1884         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1885         
1886         // Make relative position from the nested inset now bufferview absolute.
1887         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1888         x += xx;
1889         
1890         // In the RTL case place the nested inset at the left of the cursor in 
1891         // the outer paragraph
1892         bool boundary_1 = boundary && 1 == dit.depth();
1893         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1894         if (rtl)
1895                 x -= lastw;
1896         
1897         return Point(x, y);
1898 }
1899
1900
1901 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1902 {
1903         CursorSlice const & bot = dit.bottom();
1904         TextMetrics const & tm = textMetrics(bot.text());
1905         if (!tm.has(bot.pit()))
1906                 return Point(-1, -1);
1907
1908         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1909         p.y_ += tm.parMetrics(bot.pit()).position();
1910         return p;
1911 }
1912
1913
1914 void BufferView::draw(frontend::Painter & pain)
1915 {
1916         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1917         Text & text = buffer_.text();
1918         TextMetrics const & tm = d->text_metrics_[&text];
1919         int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1920         PainterInfo pi(this, pain);
1921
1922         switch (d->update_strategy_) {
1923
1924         case NoScreenUpdate:
1925                 // If no screen painting is actually needed, only some the different
1926                 // coordinates of insets and paragraphs needs to be updated.
1927                 pi.full_repaint = true;
1928                 pi.pain.setDrawingEnabled(false);
1929                 tm.draw(pi, 0, y);
1930                 break;
1931
1932         case SingleParUpdate:
1933                 pi.full_repaint = false;
1934                 // In general, only the current row of the outermost paragraph
1935                 // will be redrawn. Particular cases where selection spans
1936                 // multiple paragraph are correctly detected in TextMetrics.
1937                 tm.draw(pi, 0, y);
1938                 break;
1939
1940         case DecorationUpdate:
1941                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1942                 // drawing if possible. This is not possible to do easily right now
1943                 // because of the single backing pixmap.
1944
1945         case FullScreenUpdate:
1946                 // The whole screen, including insets, will be refreshed.
1947                 pi.full_repaint = true;
1948
1949                 // Clear background.
1950                 pain.fillRectangle(0, 0, width_, height_,
1951                         buffer_.inset().backgroundColor());
1952                 tm.draw(pi, 0, y);
1953
1954                 // and possibly grey out below
1955                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1956                 int const y2 = lastpm.second->position() + lastpm.second->descent();
1957                 if (y2 < height_)
1958                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1959                 break;
1960         }
1961
1962         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
1963 }
1964
1965
1966 void BufferView::message(docstring const & msg)
1967 {
1968         if (d->gui_)
1969                 d->gui_->message(msg);
1970 }
1971
1972
1973 void BufferView::showDialog(std::string const & name)
1974 {
1975         if (d->gui_)
1976                 d->gui_->showDialog(name, string());
1977 }
1978
1979
1980 void BufferView::showDialog(std::string const & name,
1981         std::string const & data, Inset * inset)
1982 {
1983         if (d->gui_)
1984                 d->gui_->showDialog(name, data, inset);
1985 }
1986
1987
1988 void BufferView::updateDialog(std::string const & name, std::string const & data)
1989 {
1990         if (d->gui_)
1991                 d->gui_->updateDialog(name, data);
1992 }
1993
1994
1995 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1996 {
1997         d->gui_ = gui;
1998 }
1999
2000
2001 // FIXME: Move this out of BufferView again
2002 docstring BufferView::contentsOfPlaintextFile(string const & f,
2003         bool asParagraph)
2004 {
2005         FileName fname(f);
2006
2007         if (fname.empty()) {
2008                 FileDialog dlg(_("Select file to insert"),
2009                                    ( asParagraph
2010                                      ? LFUN_FILE_INSERT_PLAINTEXT_PARA 
2011                                      : LFUN_FILE_INSERT_PLAINTEXT) );
2012
2013                 FileDialog::Result result =
2014                         dlg.open(from_utf8(buffer().filePath()),
2015                                      FileFilterList(), docstring());
2016
2017                 if (result.first == FileDialog::Later)
2018                         return docstring();
2019
2020                 if (result.second.empty())
2021                         return docstring();
2022
2023                 fname = makeAbsPath(to_utf8(result.second));
2024         }
2025
2026         if (!fname.isReadableFile()) {
2027                 docstring const error = from_ascii(strerror(errno));
2028                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2029                 docstring const text =
2030                   bformat(_("Could not read the specified document\n"
2031                             "%1$s\ndue to the error: %2$s"), file, error);
2032                 Alert::error(_("Could not read file"), text);
2033                 return docstring();
2034         }
2035
2036         ifstream ifs(fname.toFilesystemEncoding().c_str());
2037         if (!ifs) {
2038                 docstring const error = from_ascii(strerror(errno));
2039                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2040                 docstring const text =
2041                   bformat(_("Could not open the specified document\n"
2042                             "%1$s\ndue to the error: %2$s"), file, error);
2043                 Alert::error(_("Could not open file"), text);
2044                 return docstring();
2045         }
2046
2047         ifs.unsetf(std::ios::skipws);
2048         istream_iterator<char> ii(ifs);
2049         istream_iterator<char> end;
2050 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2051         // We use this until the compilers get better...
2052         std::vector<char> tmp;
2053         copy(ii, end, back_inserter(tmp));
2054         string const tmpstr(tmp.begin(), tmp.end());
2055 #else
2056         // This is what we want to use and what we will use once the
2057         // compilers get good enough.
2058         //string tmpstr(ii, end); // yet a reason for using std::string
2059         // alternate approach to get the file into a string:
2060         string tmpstr;
2061         copy(ii, end, back_inserter(tmpstr));
2062 #endif
2063
2064         // FIXME UNICODE: We don't know the encoding of the file
2065         docstring file_content = from_utf8(tmpstr);
2066         if (file_content.empty()) {
2067                 Alert::error(_("Reading not UTF-8 encoded file"),
2068                              _("The file is not UTF-8 encoded.\n"
2069                                "It will be read as local 8Bit-encoded.\n"
2070                                "If this does not give the correct result\n"
2071                                "then please change the encoding of the file\n"
2072                                "to UTF-8 with a program other than LyX.\n"));
2073                 file_content = from_local8bit(tmpstr);
2074         }
2075
2076         return normalize_c(file_content);
2077 }
2078
2079
2080 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2081 {
2082         docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2083
2084         if (tmpstr.empty())
2085                 return;
2086
2087         Cursor & cur = cursor();
2088         cap::replaceSelection(cur);
2089         buffer_.undo().recordUndo(cur);
2090         if (asParagraph)
2091                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2092         else
2093                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2094 }
2095
2096 } // namespace lyx