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