]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Remind scons users to check config.log when configure fails
[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 "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81 using std::distance;
82 using std::endl;
83 using std::istringstream;
84 using std::make_pair;
85 using std::min;
86 using std::max;
87 using std::mem_fun_ref;
88 using std::string;
89 using std::vector;
90
91
92 namespace lyx {
93
94 using support::addPath;
95 using support::bformat;
96 using support::FileFilterList;
97 using support::FileName;
98 using support::fileSearch;
99 using support::isDirWriteable;
100 using support::isFileReadable;
101 using support::makeDisplayPath;
102 using support::package;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 Buffer * BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the current selection if any
153                 cap::saveSelection(cursor_);
154                 // Save the actual cursor position and anchor inside the
155                 // buffer so that it can be restored in case we rechange
156                 // to this buffer later on.
157                 buffer_->saveCursor(cursor_.selectionBegin(),
158                                     cursor_.selectionEnd());
159                 // update bookmark pit of the current buffer before switch
160                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
161                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
162                         if (buffer()->fileName() != bm.filename.absFilename())
163                                 continue;
164                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
165                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
166                         pit_type new_pit;
167                         pos_type new_pos;
168                         int new_id;
169                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
170                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
171                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
172                 }
173                 // current buffer is going to be switched-off, save cursor pos
174                 // Ideally, the whole cursor stack should be saved, but session
175                 // currently can only handle bottom (whole document) level pit and pos.
176                 // That is to say, if a cursor is in a nested inset, it will be
177                 // restore to the left of the top level inset.
178                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
179                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180         }
181
182         // If we're quitting lyx, don't bother updating stuff
183         if (quitting) {
184                 buffer_ = 0;
185                 return 0;
186         }
187
188         //FIXME Fix for bug 3440 is here.
189         // If we are closing current buffer, switch to the first in
190         // buffer list.
191         if (!b) {
192                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
193                                     << " No Buffer!" << endl;
194                 // We are closing the buffer, use the first buffer as current
195                 //FIXME 3440
196                 // if (last_buffer_) buffer_ = last_buffer_;
197                 // also check that this is in theBufferList()?
198                 buffer_ = theBufferList().first();
199         } else {
200                 //FIXME 3440
201                 // last_buffer = buffer_;
202                 // Set current buffer
203                 buffer_ = b;
204         }
205
206         // Reset old cursor
207         cursor_ = Cursor(*this);
208         anchor_ref_ = 0;
209         offset_ref_ = 0;
210
211         if (!buffer_)
212                 return 0;
213
214         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
215                                         << "Buffer addr: " << buffer_ << endl;
216         cursor_.push(buffer_->inset());
217         cursor_.resetAnchor();
218         buffer_->text().setCurrentFont(cursor_);
219
220         // Update the metrics now that we have a proper Cursor.
221         updateMetrics(false);
222
223         // FIXME: This code won't be needed once we switch to
224         // "one Buffer" / "one BufferView".
225         if (buffer_->getCursor().size() > 0 &&
226                         buffer_->getAnchor().size() > 0)
227         {
228                 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
229                 cursor_.resetAnchor();
230                 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
231                 cursor_.setSelection();
232                 // do not set selection to the new buffer because we
233                 // only paste recent selection.
234
235                 // Make sure that the restored cursor is not broken. This can happen for
236                 // example if this Buffer has been modified by another view.
237                 cursor_.fixIfBroken();
238
239                 if (fitCursor())
240                         // Update the metrics if the cursor new position was off screen.
241                         updateMetrics(false);
242         }
243
244         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
245                 graphics::Previews::get().generateBufferPreviews(*buffer_);
246         return buffer_;
247 }
248
249
250 void BufferView::resize()
251 {
252         if (!buffer_)
253                 return;
254
255         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
256
257         updateMetrics(false);
258 }
259
260
261 bool BufferView::fitCursor()
262 {
263         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
264                 frontend::FontMetrics const & fm =
265                         theFontMetrics(cursor_.getFont());
266                 int const asc = fm.maxAscent();
267                 int const des = fm.maxDescent();
268                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
269                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
270                         return false;
271         }
272         center();
273         return true;
274 }
275
276
277 bool BufferView::multiParSel()
278 {
279         if (!cursor_.selection())
280                 return false;
281         bool ret = multiparsel_cache_;
282         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
283         // Either this, or previous selection spans paragraphs
284         return ret || multiparsel_cache_;
285 }
286
287
288 bool BufferView::update(Update::flags flags)
289 {
290         // last_inset_ points to the last visited inset. This pointer may become
291         // invalid because of keyboard editing. Since all such operations
292         // causes screen update(), I reset last_inset_ to avoid such a problem.
293         last_inset_ = 0;
294         // This is close to a hot-path.
295         LYXERR(Debug::DEBUG)
296                 << BOOST_CURRENT_FUNCTION
297                 << "[fitcursor = " << (flags & Update::FitCursor)
298                 << ", forceupdate = " << (flags & Update::Force)
299                 << ", singlepar = " << (flags & Update::SinglePar)
300                 << "]  buffer: " << buffer_ << endl;
301
302         // Check needed to survive LyX startup
303         if (!buffer_)
304                 return false;
305
306         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
307
308         // Update macro store
309         if (!(cursor().inMathed() && cursor().inMacroMode()))
310                 buffer_->buildMacros();
311
312         // Now do the first drawing step if needed. This consists on updating
313         // the CoordCache in updateMetrics().
314         // The second drawing step is done in WorkArea::redraw() if needed.
315
316         // Case when no explicit update is requested.
317         if (!flags) {
318                 // no need to redraw anything.
319                 metrics_info_.update_strategy = NoScreenUpdate;
320                 return false;
321         }
322
323         if (flags == Update::Decoration) {
324                 metrics_info_.update_strategy = DecorationUpdate;
325                 return true;
326         }
327
328         if (flags == Update::FitCursor
329                 || flags == (Update::Decoration | Update::FitCursor)) {
330                 bool const fit_cursor = fitCursor();
331                 // tell the frontend to update the screen if needed.
332                 if (fit_cursor) {
333                         updateMetrics(false);
334                         return true;
335                 }
336                 if (flags & Update::Decoration) {
337                         metrics_info_.update_strategy = DecorationUpdate;
338                         return true;
339                 }
340                 // no screen update is needed.
341                 metrics_info_.update_strategy = NoScreenUpdate;
342                 return false;
343         }
344
345         bool full_metrics = flags & Update::Force;
346         if (flags & Update::MultiParSel)
347                 full_metrics |= multiParSel();
348
349         bool const single_par = !full_metrics;
350         updateMetrics(single_par);
351
352         if (flags & Update::FitCursor && fitCursor())
353                 updateMetrics(false);
354
355         // tell the frontend to update the screen.
356         return true;
357 }
358
359
360 void BufferView::updateScrollbar()
361 {
362         if (!buffer_) {
363                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
364                                      << " no text in updateScrollbar" << endl;
365                 scrollbarParameters_.reset();
366                 return;
367         }
368
369         Text & t = buffer_->text();
370         TextMetrics & tm = text_metrics_[&t];
371
372         int const parsize = int(t.paragraphs().size() - 1);
373         if (anchor_ref_ >  parsize)  {
374                 anchor_ref_ = parsize;
375                 offset_ref_ = 0;
376         }
377
378         LYXERR(Debug::GUI)
379                 << BOOST_CURRENT_FUNCTION
380                 << " Updating scrollbar: height: " << t.paragraphs().size()
381                 << " curr par: " << cursor_.bottom().pit()
382                 << " default height " << defaultRowHeight() << endl;
383
384         // It would be better to fix the scrollbar to understand
385         // values in [0..1] and divide everything by wh
386
387         // estimated average paragraph height:
388         if (wh_ == 0)
389                 wh_ = height_ / 4;
390
391         int h = tm.parMetrics(anchor_ref_).height();
392
393         // Normalize anchor/offset (MV):
394         while (offset_ref_ > h && anchor_ref_ < parsize) {
395                 anchor_ref_++;
396                 offset_ref_ -= h;
397                 h = tm.parMetrics(anchor_ref_).height();
398         }
399         // Look at paragraph heights on-screen
400         int sumh = 0;
401         int nh = 0;
402         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
403                 if (sumh > height_)
404                         break;
405                 int const h2 = tm.parMetrics(pit).height();
406                 sumh += h2;
407                 nh++;
408         }
409
410         BOOST_ASSERT(nh);
411         int const hav = sumh / nh;
412         // More realistic average paragraph height
413         if (hav > wh_)
414                 wh_ = hav;
415
416         BOOST_ASSERT(h);
417         scrollbarParameters_.height = (parsize + 1) * wh_;
418         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
419         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
420 }
421
422
423 ScrollbarParameters const & BufferView::scrollbarParameters() const
424 {
425         return scrollbarParameters_;
426 }
427
428
429 void BufferView::scrollDocView(int value)
430 {
431         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
432                            << "[ value = " << value << "]" << endl;
433
434         if (!buffer_)
435                 return;
436
437         Text & t = buffer_->text();
438         TextMetrics & tm = text_metrics_[&t];
439
440         float const bar = value / float(wh_ * t.paragraphs().size());
441
442         anchor_ref_ = int(bar * t.paragraphs().size());
443         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
444                 anchor_ref_ = int(t.paragraphs().size()) - 1;
445
446         tm.redoParagraph(anchor_ref_);
447         int const h = tm.parMetrics(anchor_ref_).height();
448         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
449         updateMetrics(false);
450 }
451
452
453 void BufferView::setCursorFromScrollbar()
454 {
455         if (!buffer_)
456                 return;
457
458         Text & t = buffer_->text();
459
460         int const height = 2 * defaultRowHeight();
461         int const first = height;
462         int const last = height_ - height;
463         Cursor & cur = cursor_;
464
465         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
466
467         switch (st) {
468         case bv_funcs::CUR_ABOVE:
469                 // We reset the cursor because bv_funcs::status() does not
470                 // work when the cursor is within mathed.
471                 cur.reset(buffer_->inset());
472                 t.setCursorFromCoordinates(cur, 0, first);
473                 cur.clearSelection();
474                 break;
475         case bv_funcs::CUR_BELOW:
476                 // We reset the cursor because bv_funcs::status() does not
477                 // work when the cursor is within mathed.
478                 cur.reset(buffer_->inset());
479                 t.setCursorFromCoordinates(cur, 0, last);
480                 cur.clearSelection();
481                 break;
482         case bv_funcs::CUR_INSIDE:
483                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
484                 int const newy = min(last, max(y, first));
485                 if (y != newy) {
486                         cur.reset(buffer_->inset());
487                         t.setCursorFromCoordinates(cur, 0, newy);
488                 }
489         }
490 }
491
492
493 Change const BufferView::getCurrentChange() const
494 {
495         if (!cursor_.selection())
496                 return Change(Change::UNCHANGED);
497
498         DocIterator dit = cursor_.selectionBegin();
499         return dit.paragraph().lookupChange(dit.pos());
500 }
501
502
503 void BufferView::saveBookmark(unsigned int idx)
504 {
505         // tenatively save bookmark, id and pos will be used to
506         // acturately locate a bookmark in a 'live' lyx session.
507         // pit and pos will be updated with bottom level pit/pos
508         // when lyx exits.
509         LyX::ref().session().bookmarks().save(
510                 FileName(buffer_->fileName()),
511                 cursor_.bottom().pit(),
512                 cursor_.bottom().pos(),
513                 cursor_.paragraph().id(),
514                 cursor_.pos(),
515                 idx
516         );
517         if (idx)
518                 // emit message signal.
519                 message(_("Save bookmark"));
520 }
521
522
523 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
524         int top_id, pos_type top_pos)
525 {
526         cursor_.clearSelection();
527
528         // if a valid par_id is given, try it first
529         // This is the case for a 'live' bookmark when unique paragraph ID
530         // is used to track bookmarks.
531         if (top_id > 0) {
532                 ParIterator par = buffer_->getParFromID(top_id);
533                 if (par != buffer_->par_iterator_end()) {
534                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
535                         // Some slices of the iterator may not be
536                         // reachable (e.g. closed collapsable inset)
537                         // so the dociterator may need to be
538                         // shortened. Otherwise, setCursor may crash
539                         // lyx when the cursor can not be set to these
540                         // insets.
541                         size_t const n = dit.depth();
542                         for (size_t i = 0; i < n; ++i)
543                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
544                                         dit.resize(i);
545                                         break;
546                                 }
547                         setCursor(dit);
548                         // Note: return bottom (document) level pit.
549                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
550                 }
551         }
552         // if top_id == 0, or searching through top_id failed
553         // This is the case for a 'restored' bookmark when only bottom
554         // (document level) pit was saved. Because of this, bookmark
555         // restoration is inaccurate. If a bookmark was within an inset,
556         // it will be restored to the left of the outmost inset that contains
557         // the bookmark.
558         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
559                 DocIterator it = doc_iterator_begin(buffer_->inset());
560                 it.pit() = bottom_pit;
561                 it.pos() = min(bottom_pos, it.paragraph().size());
562                 setCursor(it);
563                 return boost::make_tuple(it.pit(), it.pos(),
564                                          it.paragraph().id());
565         }
566         // both methods fail
567         return boost::make_tuple(pit_type(0), pos_type(0), 0);
568 }
569
570
571 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
572 {
573         if (lyxrc.rtl_support) {
574                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
575                         if (intl_->keymap == Intl::PRIMARY)
576                                 intl_->keyMapSec();
577                 } else {
578                         if (intl_->keymap == Intl::SECONDARY)
579                                 intl_->keyMapPrim();
580                 }
581         }
582         
583         intl_->getTransManager().translateAndInsert(c, t, cur);
584 }
585
586
587 int BufferView::workWidth() const
588 {
589         return width_;
590 }
591
592
593 void BufferView::center()
594 {
595         CursorSlice & bot = cursor_.bottom();
596         TextMetrics & tm = text_metrics_[bot.text()];
597         pit_type const pit = bot.pit();
598         tm.redoParagraph(pit);
599         ParagraphMetrics const & pm = tm.parMetrics(pit);
600         anchor_ref_ = pit;
601         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
602                 + pm.ascent() - height_ / 2;
603 }
604
605
606 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
607 {
608         FuncStatus flag;
609
610         Cursor & cur = cursor_;
611
612         switch (cmd.action) {
613
614         case LFUN_UNDO:
615                 flag.enabled(!buffer_->undostack().empty());
616                 break;
617         case LFUN_REDO:
618                 flag.enabled(!buffer_->redostack().empty());
619                 break;
620         case LFUN_FILE_INSERT:
621         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
622         case LFUN_FILE_INSERT_PLAINTEXT:
623         case LFUN_BOOKMARK_SAVE:
624                 // FIXME: Actually, these LFUNS should be moved to Text
625                 flag.enabled(cur.inTexted());
626                 break;
627         case LFUN_FONT_STATE:
628         case LFUN_LABEL_INSERT:
629         case LFUN_PARAGRAPH_GOTO:
630         // FIXME handle non-trivially
631         case LFUN_OUTLINE_UP:
632         case LFUN_OUTLINE_DOWN:
633         case LFUN_OUTLINE_IN:
634         case LFUN_OUTLINE_OUT:
635         case LFUN_NOTE_NEXT:
636         case LFUN_REFERENCE_NEXT:
637         case LFUN_WORD_FIND:
638         case LFUN_WORD_REPLACE:
639         case LFUN_MARK_OFF:
640         case LFUN_MARK_ON:
641         case LFUN_MARK_TOGGLE:
642         case LFUN_SCREEN_RECENTER:
643         case LFUN_BIBTEX_DATABASE_ADD:
644         case LFUN_BIBTEX_DATABASE_DEL:
645         case LFUN_WORDS_COUNT:
646         case LFUN_NEXT_INSET_TOGGLE:
647                 flag.enabled(true);
648                 break;
649
650         case LFUN_LABEL_GOTO: {
651                 flag.enabled(!cmd.argument().empty()
652                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
653                 break;
654         }
655
656         case LFUN_CHANGES_TRACK:
657                 flag.enabled(true);
658                 flag.setOnOff(buffer_->params().trackChanges);
659                 break;
660
661         case LFUN_CHANGES_OUTPUT:
662                 flag.enabled(buffer_);
663                 flag.setOnOff(buffer_->params().outputChanges);
664                 break;
665
666         case LFUN_CHANGES_MERGE:
667         case LFUN_CHANGE_NEXT:
668         case LFUN_ALL_CHANGES_ACCEPT:
669         case LFUN_ALL_CHANGES_REJECT:
670                 // TODO: context-sensitive enabling of LFUNs
671                 // In principle, these command should only be enabled if there
672                 // is a change in the document. However, without proper
673                 // optimizations, this will inevitably result in poor performance.
674                 flag.enabled(buffer_);
675                 break;
676
677         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
678                 flag.setOnOff(buffer_->params().compressed);
679                 break;
680         }
681
682         default:
683                 flag.enabled(false);
684         }
685
686         return flag;
687 }
688
689
690 Update::flags BufferView::dispatch(FuncRequest const & cmd)
691 {
692         //lyxerr << BOOST_CURRENT_FUNCTION
693         //       << [ cmd = " << cmd << "]" << endl;
694
695         // Make sure that the cached BufferView is correct.
696         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
697                 << " action[" << cmd.action << ']'
698                 << " arg[" << to_utf8(cmd.argument()) << ']'
699                 << " x[" << cmd.x << ']'
700                 << " y[" << cmd.y << ']'
701                 << " button[" << cmd.button() << ']'
702                 << endl;
703
704         // FIXME: this should not be possible.
705         if (!buffer_)
706                 return Update::None;
707
708         Cursor & cur = cursor_;
709         // Default Update flags.
710         Update::flags updateFlags = Update::Force | Update::FitCursor;
711
712         switch (cmd.action) {
713
714         case LFUN_UNDO:
715                 cur.message(_("Undo"));
716                 cur.clearSelection();
717                 if (!textUndo(*this)) {
718                         cur.message(_("No further undo information"));
719                         updateFlags = Update::None;
720                 }
721                 break;
722
723         case LFUN_REDO:
724                 cur.message(_("Redo"));
725                 cur.clearSelection();
726                 if (!textRedo(*this)) {
727                         cur.message(_("No further redo information"));
728                         updateFlags = Update::None;
729                 }
730                 break;
731
732         case LFUN_FILE_INSERT:
733                 // FIXME UNICODE
734                 menuInsertLyXFile(to_utf8(cmd.argument()));
735                 break;
736
737         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
738                 // FIXME UNICODE
739                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
740                 break;
741
742         case LFUN_FILE_INSERT_PLAINTEXT:
743                 // FIXME UNICODE
744                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
745                 break;
746
747         case LFUN_FONT_STATE:
748                 cur.message(cur.currentState());
749                 break;
750
751         case LFUN_BOOKMARK_SAVE:
752                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
753                 break;
754
755         case LFUN_LABEL_GOTO: {
756                 docstring label = cmd.argument();
757                 if (label.empty()) {
758                         InsetRef * inset =
759                                 getInsetByCode<InsetRef>(cursor_,
760                                                          Inset::REF_CODE);
761                         if (inset) {
762                                 label = inset->getParam("reference");
763                                 // persistent=false: use temp_bookmark
764                                 saveBookmark(0);
765                         }
766                 }
767
768                 if (!label.empty())
769                         gotoLabel(label);
770                 break;
771         }
772
773         case LFUN_PARAGRAPH_GOTO: {
774                 int const id = convert<int>(to_utf8(cmd.argument()));
775                 int i = 0;
776                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
777                         ParIterator par = b->getParFromID(id);
778                         if (par == b->par_iterator_end()) {
779                                 LYXERR(Debug::INFO)
780                                         << "No matching paragraph found! ["
781                                         << id << "]." << endl;
782                         } else {
783                                 LYXERR(Debug::INFO)
784                                         << "Paragraph " << par->id()
785                                         << " found in buffer `"
786                                         << b->fileName() << "'." << endl;
787
788                                 if (b == buffer_) {
789                                         // Set the cursor
790                                         setCursor(makeDocIterator(par, 0));
791                                 } else {
792                                         // Switch to other buffer view and resend cmd
793                                         theLyXFunc().dispatch(FuncRequest(
794                                                 LFUN_BUFFER_SWITCH, b->fileName()));
795                                         theLyXFunc().dispatch(cmd);
796                                         updateFlags = Update::None;
797                                 }
798                                 break;
799                         }
800                         ++i;
801                 }
802                 break;
803         }
804
805         case LFUN_OUTLINE_UP:
806                 toc::outline(toc::Up, cursor_);
807                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
808                 updateLabels(*buffer_);
809                 break;
810         case LFUN_OUTLINE_DOWN:
811                 toc::outline(toc::Down, cursor_);
812                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
813                 updateLabels(*buffer_);
814                 break;
815         case LFUN_OUTLINE_IN:
816                 toc::outline(toc::In, cursor_);
817                 updateLabels(*buffer_);
818                 break;
819         case LFUN_OUTLINE_OUT:
820                 toc::outline(toc::Out, cursor_);
821                 updateLabels(*buffer_);
822                 break;
823
824         case LFUN_NOTE_NEXT:
825                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
826                 break;
827
828         case LFUN_REFERENCE_NEXT: {
829                 vector<Inset_code> tmp;
830                 tmp.push_back(Inset::LABEL_CODE);
831                 tmp.push_back(Inset::REF_CODE);
832                 bv_funcs::gotoInset(this, tmp, true);
833                 break;
834         }
835
836         case LFUN_CHANGES_TRACK:
837                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
838                 break;
839
840         case LFUN_CHANGES_OUTPUT:
841                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
842                 if (buffer_->params().outputChanges) {
843                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
844                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
845                                           LaTeXFeatures::isAvailable("xcolor");
846
847                         if (!dvipost && !xcolorsoul) {
848                                 Alert::warning(_("Changes not shown in LaTeX output"),
849                                                _("Changes will not be highlighted in LaTeX output, "
850                                                  "because neither dvipost nor xcolor/soul are installed.\n"
851                                                  "Please install these packages or redefine "
852                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
853                         } else if (!xcolorsoul) {
854                                 Alert::warning(_("Changes not shown in LaTeX output"),
855                                                _("Changes will not be highlighted in LaTeX output "
856                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
857                                                  "Please install both packages or redefine "
858                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
859                         }
860                 }
861                 break;
862
863         case LFUN_CHANGE_NEXT:
864                 findNextChange(this);
865                 break;
866
867         case LFUN_CHANGES_MERGE:
868                 if (findNextChange(this))
869                         showDialog("changes");
870                 break;
871
872         case LFUN_ALL_CHANGES_ACCEPT:
873                 // select complete document
874                 cursor_.reset(buffer_->inset());
875                 cursor_.selHandle(true);
876                 buffer_->text().cursorBottom(cursor_);
877                 // accept everything in a single step to support atomic undo
878                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
879                 break;
880
881         case LFUN_ALL_CHANGES_REJECT:
882                 // select complete document
883                 cursor_.reset(buffer_->inset());
884                 cursor_.selHandle(true);
885                 buffer_->text().cursorBottom(cursor_);
886                 // reject everything in a single step to support atomic undo
887                 // Note: reject does not work recursively; the user may have to repeat the operation
888                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
889                 break;
890
891         case LFUN_WORD_FIND:
892                 find(this, cmd);
893                 break;
894
895         case LFUN_WORD_REPLACE: {
896                 bool has_deleted = false;
897                 if (cur.selection()) {
898                         DocIterator beg = cur.selectionBegin();
899                         DocIterator end = cur.selectionEnd();
900                         if (beg.pit() == end.pit()) {
901                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
902                                         if (cur.paragraph().isDeleted(p))
903                                                 has_deleted = true;
904                                 }
905                         }
906                 }
907                 replace(this, cmd, has_deleted);
908                 break;
909         }
910
911         case LFUN_MARK_OFF:
912                 cur.clearSelection();
913                 cur.resetAnchor();
914                 cur.message(from_utf8(N_("Mark off")));
915                 break;
916
917         case LFUN_MARK_ON:
918                 cur.clearSelection();
919                 cur.mark() = true;
920                 cur.resetAnchor();
921                 cur.message(from_utf8(N_("Mark on")));
922                 break;
923
924         case LFUN_MARK_TOGGLE:
925                 cur.clearSelection();
926                 if (cur.mark()) {
927                         cur.mark() = false;
928                         cur.message(from_utf8(N_("Mark removed")));
929                 } else {
930                         cur.mark() = true;
931                         cur.message(from_utf8(N_("Mark set")));
932                 }
933                 cur.resetAnchor();
934                 break;
935
936         case LFUN_SCREEN_RECENTER:
937                 center();
938                 break;
939
940         case LFUN_BIBTEX_DATABASE_ADD: {
941                 Cursor tmpcur = cursor_;
942                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
943                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
944                                                 Inset::BIBTEX_CODE);
945                 if (inset) {
946                         if (inset->addDatabase(to_utf8(cmd.argument())))
947                                 buffer_->updateBibfilesCache();
948                 }
949                 break;
950         }
951
952         case LFUN_BIBTEX_DATABASE_DEL: {
953                 Cursor tmpcur = cursor_;
954                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
955                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
956                                                 Inset::BIBTEX_CODE);
957                 if (inset) {
958                         if (inset->delDatabase(to_utf8(cmd.argument())))
959                                 buffer_->updateBibfilesCache();
960                 }
961                 break;
962         }
963
964         case LFUN_WORDS_COUNT: {
965                 DocIterator from, to;
966                 if (cur.selection()) {
967                         from = cur.selectionBegin();
968                         to = cur.selectionEnd();
969                 } else {
970                         from = doc_iterator_begin(buffer_->inset());
971                         to = doc_iterator_end(buffer_->inset());
972                 }
973                 int const count = countWords(from, to);
974                 docstring message;
975                 if (count != 1) {
976                         if (cur.selection())
977                                 message = bformat(_("%1$d words in selection."),
978                                           count);
979                                 else
980                                         message = bformat(_("%1$d words in document."),
981                                                           count);
982                 }
983                 else {
984                         if (cur.selection())
985                                 message = _("One word in selection.");
986                         else
987                                 message = _("One word in document.");
988                 }
989
990                 Alert::information(_("Count words"), message);
991         }
992                 break;
993
994         case LFUN_BUFFER_TOGGLE_COMPRESSION:
995                 // turn compression on/off
996                 buffer_->params().compressed = !buffer_->params().compressed;
997                 break;
998
999         case LFUN_NEXT_INSET_TOGGLE: {
1000                 // this is the real function we want to invoke
1001                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1002                 // if there is an inset at cursor, see whether it
1003                 // wants to toggle.
1004                 Inset * inset = cur.nextInset();
1005                 if (inset && inset->isActive()) {
1006                         Cursor tmpcur = cur;
1007                         tmpcur.pushLeft(*inset);
1008                         inset->dispatch(tmpcur, tmpcmd);
1009                         if (tmpcur.result().dispatched()) {
1010                                 cur.dispatched();
1011                         }
1012                 }
1013                 // if it did not work, try the underlying inset.
1014                 if (!cur.result().dispatched())
1015                         cur.dispatch(tmpcmd);
1016
1017                 if (cur.result().dispatched())
1018                         cur.clearSelection();
1019
1020                 break;
1021         }
1022
1023         default:
1024                 updateFlags = Update::None;
1025         }
1026
1027         return updateFlags;
1028 }
1029
1030
1031 docstring const BufferView::requestSelection()
1032 {
1033         if (!buffer_)
1034                 return docstring();
1035
1036         Cursor & cur = cursor_;
1037
1038         if (!cur.selection()) {
1039                 xsel_cache_.set = false;
1040                 return docstring();
1041         }
1042
1043         if (!xsel_cache_.set ||
1044             cur.top() != xsel_cache_.cursor ||
1045             cur.anchor_.top() != xsel_cache_.anchor)
1046         {
1047                 xsel_cache_.cursor = cur.top();
1048                 xsel_cache_.anchor = cur.anchor_.top();
1049                 xsel_cache_.set = cur.selection();
1050                 return cur.selectionAsString(false);
1051         }
1052         return docstring();
1053 }
1054
1055
1056 void BufferView::clearSelection()
1057 {
1058         if (buffer_) {
1059                 cursor_.clearSelection();
1060                 // Clear the selection buffer. Otherwise a subsequent
1061                 // middle-mouse-button paste would use the selection buffer,
1062                 // not the more current external selection.
1063                 cap::clearSelection();
1064                 xsel_cache_.set = false;
1065                 // The buffer did not really change, but this causes the
1066                 // redraw we need because we cleared the selection above.
1067                 buffer_->changed();
1068         }
1069 }
1070
1071
1072 void BufferView::workAreaResize(int width, int height)
1073 {
1074         // Update from work area
1075         width_ = width;
1076         height_ = height;
1077
1078         // The complete text metrics will be redone.
1079         text_metrics_.clear();
1080
1081         if (buffer_)
1082                 resize();
1083 }
1084
1085
1086 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1087 {
1088         pit_type pit = text.getPitNearY(*this, y);
1089         BOOST_ASSERT(pit != -1);
1090         Paragraph const & par = text.getPar(pit);
1091
1092         LYXERR(Debug::DEBUG)
1093                 << BOOST_CURRENT_FUNCTION
1094                 << ": x: " << x
1095                 << " y: " << y
1096                 << "  pit: " << pit
1097                 << endl;
1098         InsetList::const_iterator iit = par.insetlist.begin();
1099         InsetList::const_iterator iend = par.insetlist.end();
1100         for (; iit != iend; ++iit) {
1101                 Inset * const inset = iit->inset;
1102                 if (inset->covers(*this, x, y)) {
1103                         if (!inset->descendable())
1104                                 // No need to go further down if the inset is not
1105                                 // descendable.
1106                                 return inset;
1107
1108                         size_t cell_number = inset->nargs();
1109                         // Check all the inner cell.
1110                         for (size_t i = 0; i != cell_number; ++i) {
1111                                 Text const * inner_text = inset->getText(i);
1112                                 if (inner_text) {
1113                                         // Try deeper.
1114                                         Inset const * inset_deeper =
1115                                                 getCoveringInset(*inner_text, x, y);
1116                                         if (inset_deeper)
1117                                                 return inset_deeper;
1118                                 }
1119                         }
1120
1121                         LYXERR(Debug::DEBUG)
1122                                 << BOOST_CURRENT_FUNCTION
1123                                 << ": Hit inset: " << inset << endl;
1124                         return inset;
1125                 }
1126         }
1127         LYXERR(Debug::DEBUG)
1128                 << BOOST_CURRENT_FUNCTION
1129                 << ": No inset hit. " << endl;
1130         return 0;
1131 }
1132
1133
1134 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1135 {
1136         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1137
1138         // This is only called for mouse related events including
1139         // LFUN_FILE_OPEN generated by drag-and-drop.
1140         FuncRequest cmd = cmd0;
1141
1142         // E.g. Qt mouse press when no buffer
1143         if (!buffer_)
1144                 return false;
1145
1146         Cursor cur(*this);
1147         cur.push(buffer_->inset());
1148         cur.selection() = cursor_.selection();
1149
1150         // Either the inset under the cursor or the
1151         // surrounding Text will handle this event.
1152
1153         // make sure we stay within the screen...
1154         cmd.y = min(max(cmd.y, -1), height_);
1155
1156         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1157
1158                 // Get inset under mouse, if there is one.
1159                 Inset const * covering_inset =
1160                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1161                 if (covering_inset == last_inset_)
1162                         // Same inset, no need to do anything...
1163                         return false;
1164
1165                 bool need_redraw = false;
1166                 // const_cast because of setMouseHover().
1167                 Inset * inset = const_cast<Inset *>(covering_inset);
1168                 if (last_inset_)
1169                         // Remove the hint on the last hovered inset (if any).
1170                         need_redraw |= last_inset_->setMouseHover(false);
1171                 if (inset)
1172                         // Highlighted the newly hovered inset (if any).
1173                         need_redraw |= inset->setMouseHover(true);
1174                 last_inset_ = inset;
1175
1176                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1177                 // not expose the button for redraw. We adjust here the metrics dimension
1178                 // to enable a full redraw.
1179                 // FIXME: It is possible to redraw only the area around the button!
1180                 if (need_redraw
1181                         && metrics_info_.update_strategy == SingleParUpdate) {
1182                         // FIXME: It should be possible to redraw only the area around
1183                         // the button by doing this:
1184                         //
1185                         //metrics_info_.singlepar = false;
1186                         //metrics_info_.y1 = ymin of button;
1187                         //metrics_info_.y2 = ymax of button;
1188                         //
1189                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1190                         // between background updates and text updates. So we use the hammer
1191                         // solution for now. We could also avoid the updateMetrics() below
1192                         // by using the first and last pit of the CoordCache. Have a look
1193                         // at Text::getPitNearY() to see what I mean.
1194                         //
1195                         //metrics_info_.pit1 = first pit of CoordCache;
1196                         //metrics_info_.pit2 = last pit of CoordCache;
1197                         //metrics_info_.singlepar = false;
1198                         //metrics_info_.y1 = 0;
1199                         //metrics_info_.y2 = height_;
1200                         //
1201                         updateMetrics(false);
1202                 }
1203
1204                 // This event (moving without mouse click) is not passed further.
1205                 // This should be changed if it is further utilized.
1206                 return need_redraw;
1207         }
1208
1209         // Build temporary cursor.
1210         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1211
1212         // Put anchor at the same position.
1213         cur.resetAnchor();
1214
1215         // Try to dispatch to an non-editable inset near this position
1216         // via the temp cursor. If the inset wishes to change the real
1217         // cursor it has to do so explicitly by using
1218         //  cur.bv().cursor() = cur;  (or similar)
1219         if (inset) {
1220                 inset->dispatch(cur, cmd);
1221         }
1222
1223         // Now dispatch to the temporary cursor. If the real cursor should
1224         // be modified, the inset's dispatch has to do so explicitly.
1225         if (!cur.result().dispatched())
1226                 cur.dispatch(cmd);
1227
1228         // Redraw if requested and necessary.
1229         if (cur.result().dispatched() && cur.result().update())
1230                 return update(cur.result().update());
1231
1232         return false;
1233 }
1234
1235
1236 void BufferView::scroll(int /*lines*/)
1237 {
1238 //      if (!buffer_)
1239 //              return;
1240 //
1241 //      Text const * t = &buffer_->text();
1242 //      int const line_height = defaultRowHeight();
1243 //
1244 //      // The new absolute coordinate
1245 //      int new_top_y = top_y() + lines * line_height;
1246 //
1247 //      // Restrict to a valid value
1248 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1249 //      new_top_y = std::max(0, new_top_y);
1250 //
1251 //      scrollDocView(new_top_y);
1252 //
1253 }
1254
1255
1256 void BufferView::setCursorFromRow(int row)
1257 {
1258         int tmpid = -1;
1259         int tmppos = -1;
1260
1261         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1262
1263         cursor_.reset(buffer_->inset());
1264         if (tmpid == -1)
1265                 buffer_->text().setCursor(cursor_, 0, 0);
1266         else
1267                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1268 }
1269
1270
1271 void BufferView::gotoLabel(docstring const & label)
1272 {
1273         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1274                 vector<docstring> labels;
1275                 it->getLabelList(*buffer_, labels);
1276                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1277                         setCursor(it);
1278                         update();
1279                         return;
1280                 }
1281         }
1282 }
1283
1284
1285 TextMetrics const & BufferView::textMetrics(Text const * t) const
1286 {
1287         return const_cast<BufferView *>(this)->textMetrics(t);
1288 }
1289
1290
1291 TextMetrics & BufferView::textMetrics(Text const * t)
1292 {
1293         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1294         if (tmc_it == text_metrics_.end()) {
1295                 tmc_it = text_metrics_.insert(
1296                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1297         }
1298         return tmc_it->second;
1299 }
1300
1301
1302 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1303                 pit_type pit) const
1304 {
1305         return textMetrics(t).parMetrics(pit);
1306 }
1307
1308
1309 int BufferView::workHeight() const
1310 {
1311         return height_;
1312 }
1313
1314
1315 void BufferView::setCursor(DocIterator const & dit)
1316 {
1317         size_t const n = dit.depth();
1318         for (size_t i = 0; i < n; ++i)
1319                 dit[i].inset().edit(cursor_, true);
1320
1321         cursor_.setCursor(dit);
1322         cursor_.selection() = false;
1323 }
1324
1325
1326 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1327 {
1328         // Would be wrong to delete anything if we have a selection.
1329         if (cur.selection())
1330                 return false;
1331
1332         bool need_anchor_change = false;
1333         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1334                 need_anchor_change);
1335
1336         if (need_anchor_change)
1337                 cur.resetAnchor();
1338
1339         if (!changed)
1340                 return false;
1341
1342         updateLabels(*buffer_);
1343
1344         updateMetrics(false);
1345         buffer_->changed();
1346         return true;
1347 }
1348
1349
1350 bool BufferView::mouseSetCursor(Cursor & cur)
1351 {
1352         BOOST_ASSERT(&cur.bv() == this);
1353
1354         // this event will clear selection so we save selection for
1355         // persistent selection
1356         cap::saveSelection(cursor());
1357
1358         // Has the cursor just left the inset?
1359         bool badcursor = false;
1360         bool leftinset = (&cursor_.inset() != &cur.inset());
1361         if (leftinset)
1362                 badcursor = notifyCursorLeaves(cursor_, cur);
1363
1364         // do the dEPM magic if needed
1365         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1366         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1367         // the leftinset bool would not be necessary (badcursor instead).
1368         bool update = leftinset;
1369         if (!badcursor && cursor_.inTexted())
1370                 update |= checkDepm(cur, cursor_);
1371
1372         // if the cursor was in an empty script inset and the new
1373         // position is in the nucleus of the inset, notifyCursorLeaves
1374         // will kill the script inset itself. So we check all the
1375         // elements of the cursor to make sure that they are correct.
1376         // For an example, see bug 2933:
1377         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1378         // The code below could maybe be moved to a DocIterator method.
1379         //lyxerr << "cur before " << cur <<std::endl;
1380         DocIterator dit(cur.inset());
1381         dit.push_back(cur.bottom());
1382         size_t i = 1;
1383         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1384                 dit.push_back(cur[i]);
1385                 ++i;
1386         }
1387         //lyxerr << "5 cur after" << dit <<std::endl;
1388
1389         cursor_.setCursor(dit);
1390         cursor_.boundary(cur.boundary());
1391         cursor_.clearSelection();
1392         finishUndo();
1393         return update;
1394 }
1395
1396
1397 void BufferView::putSelectionAt(DocIterator const & cur,
1398                                 int length, bool backwards)
1399 {
1400         cursor_.clearSelection();
1401
1402         setCursor(cur);
1403
1404         if (length) {
1405                 if (backwards) {
1406                         cursor_.pos() += length;
1407                         cursor_.setSelection(cursor_, -length);
1408                 } else
1409                         cursor_.setSelection(cursor_, length);
1410         }
1411 }
1412
1413
1414 Cursor & BufferView::cursor()
1415 {
1416         return cursor_;
1417 }
1418
1419
1420 Cursor const & BufferView::cursor() const
1421 {
1422         return cursor_;
1423 }
1424
1425
1426 pit_type BufferView::anchor_ref() const
1427 {
1428         return anchor_ref_;
1429 }
1430
1431
1432 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1433 {
1434         return metrics_info_;
1435 }
1436
1437
1438 // FIXME: We should split-up updateMetrics() for the singlepar case.
1439 void BufferView::updateMetrics(bool singlepar)
1440 {
1441         Text & buftext = buffer_->text();
1442         TextMetrics & tm = textMetrics(&buftext);
1443         pit_type size = int(buftext.paragraphs().size());
1444
1445         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1446                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1447                 offset_ref_ = 0;
1448         }
1449
1450         if (!singlepar) {
1451                 // Clear out the position cache in case of full screen redraw,
1452                 coord_cache_.clear();
1453         
1454                 // Clear out paragraph metrics to avoid having invalid metrics
1455                 // in the cache from paragraphs not relayouted below
1456                 tm.clear();
1457         }
1458
1459         // If the paragraph metrics has changed, we can not
1460         // use the singlepar optimisation.
1461         if (singlepar
1462                 // In Single Paragraph mode, rebreak only
1463                 // the (main text, not inset!) paragraph containing the cursor.
1464                 // (if this paragraph contains insets etc., rebreaking will
1465                 // recursively descend)
1466                 && tm.redoParagraph(cursor_.bottom().pit()))
1467                 singlepar = false;
1468
1469         pit_type const pit = anchor_ref_;
1470         int pit1 = pit;
1471         int pit2 = pit;
1472         size_t const npit = buftext.paragraphs().size();
1473
1474         // Rebreak anchor paragraph.
1475         if (!singlepar)
1476                 tm.redoParagraph(pit);
1477
1478         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1479
1480         // Redo paragraphs above anchor if necessary.
1481         int y1 = y0;
1482         while (y1 > 0 && pit1 > 0) {
1483                 y1 -= tm.parMetrics(pit1).ascent();
1484                 --pit1;
1485                 if (!singlepar)
1486                         tm.redoParagraph(pit1);
1487                 y1 -= tm.parMetrics(pit1).descent();
1488         }
1489
1490
1491         // Take care of ascent of first line
1492         y1 -= tm.parMetrics(pit1).ascent();
1493
1494         // Normalize anchor for next time
1495         anchor_ref_ = pit1;
1496         offset_ref_ = -y1;
1497
1498         // Grey at the beginning is ugly
1499         if (pit1 == 0 && y1 > 0) {
1500                 y0 -= y1;
1501                 y1 = 0;
1502                 anchor_ref_ = 0;
1503         }
1504
1505         // Redo paragraphs below the anchor if necessary.
1506         int y2 = y0;
1507         while (y2 < height_ && pit2 < int(npit) - 1) {
1508                 y2 += tm.parMetrics(pit2).descent();
1509                 ++pit2;
1510                 if (!singlepar)
1511                         tm.redoParagraph(pit2);
1512                 y2 += tm.parMetrics(pit2).ascent();
1513         }
1514
1515         // Take care of descent of last line
1516         y2 += tm.parMetrics(pit2).descent();
1517
1518         // The coordinates of all these paragraphs are correct, cache them
1519         int y = y1;
1520         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1521         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1522                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1523                 y += pm.ascent();
1524                 parPos[pit] = Point(0, y);
1525                 if (singlepar && pit == cursor_.bottom().pit()) {
1526                         // In Single Paragraph mode, collect here the
1527                         // y1 and y2 of the (one) paragraph the cursor is in
1528                         y1 = y - pm.ascent();
1529                         y2 = y + pm.descent();
1530                 }
1531                 y += pm.descent();
1532         }
1533
1534         if (singlepar) {
1535                 // collect cursor paragraph iter bounds
1536                 pit1 = cursor_.bottom().pit();
1537                 pit2 = cursor_.bottom().pit();
1538         }
1539
1540         LYXERR(Debug::DEBUG)
1541                 << BOOST_CURRENT_FUNCTION
1542                 << " y1: " << y1
1543                 << " y2: " << y2
1544                 << " pit1: " << pit1
1545                 << " pit2: " << pit2
1546                 << " npit: " << npit
1547                 << " singlepar: " << singlepar
1548                 << "size: " << size
1549                 << endl;
1550
1551         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1552                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1553
1554         if (lyxerr.debugging(Debug::WORKAREA)) {
1555                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1556                 coord_cache_.dump();
1557         }
1558 }
1559
1560
1561 void BufferView::menuInsertLyXFile(string const & filenm)
1562 {
1563         BOOST_ASSERT(cursor_.inTexted());
1564         string filename = filenm;
1565
1566         if (filename.empty()) {
1567                 // Launch a file browser
1568                 // FIXME UNICODE
1569                 string initpath = lyxrc.document_path;
1570
1571                 if (buffer_) {
1572                         string const trypath = buffer_->filePath();
1573                         // If directory is writeable, use this as default.
1574                         if (isDirWriteable(FileName(trypath)))
1575                                 initpath = trypath;
1576                 }
1577
1578                 // FIXME UNICODE
1579                 FileDialog fileDlg(_("Select LyX document to insert"),
1580                         LFUN_FILE_INSERT,
1581                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1582                         make_pair(_("Examples|#E#e"),
1583                                     from_utf8(addPath(package().system_support().absFilename(),
1584                                     "examples"))));
1585
1586                 FileDialog::Result result =
1587                         fileDlg.open(from_utf8(initpath),
1588                                      FileFilterList(_("LyX Documents (*.lyx)")),
1589                                      docstring());
1590
1591                 if (result.first == FileDialog::Later)
1592                         return;
1593
1594                 // FIXME UNICODE
1595                 filename = to_utf8(result.second);
1596
1597                 // check selected filename
1598                 if (filename.empty()) {
1599                         // emit message signal.
1600                         message(_("Canceled."));
1601                         return;
1602                 }
1603         }
1604
1605         // Get absolute path of file and add ".lyx"
1606         // to the filename if necessary
1607         filename = fileSearch(string(), filename, "lyx").absFilename();
1608
1609         docstring const disp_fn = makeDisplayPath(filename);
1610         // emit message signal.
1611         message(bformat(_("Inserting document %1$s..."), disp_fn));
1612
1613         docstring res;
1614         Buffer buf("", false);
1615         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1616                 ErrorList & el = buffer_->errorList("Parse");
1617                 // Copy the inserted document error list into the current buffer one.
1618                 el = buf.errorList("Parse");
1619                 recordUndo(cursor_);
1620                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1621                                              buf.params().textclass, el);
1622                 res = _("Document %1$s inserted.");
1623         } else
1624                 res = _("Could not insert document %1$s");
1625
1626         // emit message signal.
1627         message(bformat(res, disp_fn));
1628         buffer_->errors("Parse");
1629         resize();
1630 }
1631
1632 } // namespace lyx