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