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