]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
transfer cursor position saving (in the session) from ~WorkArea to ~BufferView.
[features.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           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 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
412         int top_id, pos_type top_pos)
413 {
414         cursor_.clearSelection();
415
416         // if a valid par_id is given, try it first
417         // This is the case for a 'live' bookmark when unique paragraph ID
418         // is used to track bookmarks.
419         if (top_id > 0) {
420                 ParIterator par = buffer_.getParFromID(top_id);
421                 if (par != buffer_.par_iterator_end()) {
422                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
423                         // Some slices of the iterator may not be
424                         // reachable (e.g. closed collapsable inset)
425                         // so the dociterator may need to be
426                         // shortened. Otherwise, setCursor may crash
427                         // lyx when the cursor can not be set to these
428                         // insets.
429                         size_t const n = dit.depth();
430                         for (size_t i = 0; i < n; ++i)
431                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
432                                         dit.resize(i);
433                                         break;
434                                 }
435                         setCursor(dit);
436                         // Note: return bottom (document) level pit.
437                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
438                 }
439         }
440         // if top_id == 0, or searching through top_id failed
441         // This is the case for a 'restored' bookmark when only bottom
442         // (document level) pit was saved. Because of this, bookmark
443         // restoration is inaccurate. If a bookmark was within an inset,
444         // it will be restored to the left of the outmost inset that contains
445         // the bookmark.
446         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
447                 DocIterator it = doc_iterator_begin(buffer_.inset());
448                 it.pit() = bottom_pit;
449                 it.pos() = min(bottom_pos, it.paragraph().size());
450                 setCursor(it);
451                 return boost::make_tuple(it.pit(), it.pos(),
452                                          it.paragraph().id());
453         }
454         // both methods fail
455         return boost::make_tuple(pit_type(0), pos_type(0), 0);
456 }
457
458
459 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
460 {
461         if (lyxrc.rtl_support) {
462                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
463                         if (intl_->keymap == Intl::PRIMARY)
464                                 intl_->keyMapSec();
465                 } else {
466                         if (intl_->keymap == Intl::SECONDARY)
467                                 intl_->keyMapPrim();
468                 }
469         }
470         
471         intl_->getTransManager().translateAndInsert(c, t, cur);
472 }
473
474
475 int BufferView::workWidth() const
476 {
477         return width_;
478 }
479
480
481 void BufferView::center()
482 {
483         CursorSlice & bot = cursor_.bottom();
484         TextMetrics & tm = text_metrics_[bot.text()];
485         pit_type const pit = bot.pit();
486         tm.redoParagraph(pit);
487         ParagraphMetrics const & pm = tm.parMetrics(pit);
488         anchor_ref_ = pit;
489         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
490                 + pm.ascent() - height_ / 2;
491 }
492
493
494 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
495 {
496         FuncStatus flag;
497
498         Cursor & cur = cursor_;
499
500         switch (cmd.action) {
501
502         case LFUN_UNDO:
503                 flag.enabled(!buffer_.undostack().empty());
504                 break;
505         case LFUN_REDO:
506                 flag.enabled(!buffer_.redostack().empty());
507                 break;
508         case LFUN_FILE_INSERT:
509         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
510         case LFUN_FILE_INSERT_PLAINTEXT:
511         case LFUN_BOOKMARK_SAVE:
512                 // FIXME: Actually, these LFUNS should be moved to Text
513                 flag.enabled(cur.inTexted());
514                 break;
515         case LFUN_FONT_STATE:
516         case LFUN_LABEL_INSERT:
517         case LFUN_PARAGRAPH_GOTO:
518         // FIXME handle non-trivially
519         case LFUN_OUTLINE_UP:
520         case LFUN_OUTLINE_DOWN:
521         case LFUN_OUTLINE_IN:
522         case LFUN_OUTLINE_OUT:
523         case LFUN_NOTE_NEXT:
524         case LFUN_REFERENCE_NEXT:
525         case LFUN_WORD_FIND:
526         case LFUN_WORD_REPLACE:
527         case LFUN_MARK_OFF:
528         case LFUN_MARK_ON:
529         case LFUN_MARK_TOGGLE:
530         case LFUN_SCREEN_RECENTER:
531         case LFUN_BIBTEX_DATABASE_ADD:
532         case LFUN_BIBTEX_DATABASE_DEL:
533         case LFUN_WORDS_COUNT:
534         case LFUN_NEXT_INSET_TOGGLE:
535                 flag.enabled(true);
536                 break;
537
538         case LFUN_LABEL_GOTO: {
539                 flag.enabled(!cmd.argument().empty()
540                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
541                 break;
542         }
543
544         case LFUN_CHANGES_TRACK:
545                 flag.enabled(true);
546                 flag.setOnOff(buffer_.params().trackChanges);
547                 break;
548
549         case LFUN_CHANGES_OUTPUT:
550                 flag.enabled(true);
551                 flag.setOnOff(buffer_.params().outputChanges);
552                 break;
553
554         case LFUN_CHANGES_MERGE:
555         case LFUN_CHANGE_NEXT:
556         case LFUN_ALL_CHANGES_ACCEPT:
557         case LFUN_ALL_CHANGES_REJECT:
558                 // TODO: context-sensitive enabling of LFUNs
559                 // In principle, these command should only be enabled if there
560                 // is a change in the document. However, without proper
561                 // optimizations, this will inevitably result in poor performance.
562                 flag.enabled(true);
563                 break;
564
565         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
566                 flag.setOnOff(buffer_.params().compressed);
567                 break;
568         }
569
570         default:
571                 flag.enabled(false);
572         }
573
574         return flag;
575 }
576
577
578 Update::flags BufferView::dispatch(FuncRequest const & cmd)
579 {
580         //lyxerr << BOOST_CURRENT_FUNCTION
581         //       << [ cmd = " << cmd << "]" << endl;
582
583         // Make sure that the cached BufferView is correct.
584         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
585                 << " action[" << cmd.action << ']'
586                 << " arg[" << to_utf8(cmd.argument()) << ']'
587                 << " x[" << cmd.x << ']'
588                 << " y[" << cmd.y << ']'
589                 << " button[" << cmd.button() << ']'
590                 << endl;
591
592         Cursor & cur = cursor_;
593         // Default Update flags.
594         Update::flags updateFlags = Update::Force | Update::FitCursor;
595
596         switch (cmd.action) {
597
598         case LFUN_UNDO:
599                 cur.message(_("Undo"));
600                 cur.clearSelection();
601                 if (!textUndo(*this)) {
602                         cur.message(_("No further undo information"));
603                         updateFlags = Update::None;
604                 }
605                 break;
606
607         case LFUN_REDO:
608                 cur.message(_("Redo"));
609                 cur.clearSelection();
610                 if (!textRedo(*this)) {
611                         cur.message(_("No further redo information"));
612                         updateFlags = Update::None;
613                 }
614                 break;
615
616         case LFUN_FILE_INSERT:
617                 // FIXME UNICODE
618                 menuInsertLyXFile(to_utf8(cmd.argument()));
619                 break;
620
621         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
622                 // FIXME UNICODE
623                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
624                 break;
625
626         case LFUN_FILE_INSERT_PLAINTEXT:
627                 // FIXME UNICODE
628                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
629                 break;
630
631         case LFUN_FONT_STATE:
632                 cur.message(cur.currentState());
633                 break;
634
635         case LFUN_BOOKMARK_SAVE:
636                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
637                 break;
638
639         case LFUN_LABEL_GOTO: {
640                 docstring label = cmd.argument();
641                 if (label.empty()) {
642                         InsetRef * inset =
643                                 getInsetByCode<InsetRef>(cursor_,
644                                                          Inset::REF_CODE);
645                         if (inset) {
646                                 label = inset->getParam("reference");
647                                 // persistent=false: use temp_bookmark
648                                 saveBookmark(0);
649                         }
650                 }
651
652                 if (!label.empty())
653                         gotoLabel(label);
654                 break;
655         }
656
657         case LFUN_PARAGRAPH_GOTO: {
658                 int const id = convert<int>(to_utf8(cmd.argument()));
659                 int i = 0;
660                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
661                         b = theBufferList().next(b)) {
662
663                         ParIterator par = b->getParFromID(id);
664                         if (par == b->par_iterator_end()) {
665                                 LYXERR(Debug::INFO)
666                                         << "No matching paragraph found! ["
667                                         << id << "]." << endl;
668                         } else {
669                                 LYXERR(Debug::INFO)
670                                         << "Paragraph " << par->id()
671                                         << " found in buffer `"
672                                         << b->fileName() << "'." << endl;
673
674                                 if (b == &buffer_) {
675                                         // Set the cursor
676                                         setCursor(makeDocIterator(par, 0));
677                                 } else {
678                                         // Switch to other buffer view and resend cmd
679                                         theLyXFunc().dispatch(FuncRequest(
680                                                 LFUN_BUFFER_SWITCH, b->fileName()));
681                                         theLyXFunc().dispatch(cmd);
682                                         updateFlags = Update::None;
683                                 }
684                                 break;
685                         }
686                         ++i;
687                 }
688                 break;
689         }
690
691         case LFUN_OUTLINE_UP:
692                 toc::outline(toc::Up, cursor_);
693                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
694                 updateLabels(buffer_);
695                 break;
696         case LFUN_OUTLINE_DOWN:
697                 toc::outline(toc::Down, cursor_);
698                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
699                 updateLabels(buffer_);
700                 break;
701         case LFUN_OUTLINE_IN:
702                 toc::outline(toc::In, cursor_);
703                 updateLabels(buffer_);
704                 break;
705         case LFUN_OUTLINE_OUT:
706                 toc::outline(toc::Out, cursor_);
707                 updateLabels(buffer_);
708                 break;
709
710         case LFUN_NOTE_NEXT:
711                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
712                 break;
713
714         case LFUN_REFERENCE_NEXT: {
715                 vector<Inset_code> tmp;
716                 tmp.push_back(Inset::LABEL_CODE);
717                 tmp.push_back(Inset::REF_CODE);
718                 bv_funcs::gotoInset(this, tmp, true);
719                 break;
720         }
721
722         case LFUN_CHANGES_TRACK:
723                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
724                 break;
725
726         case LFUN_CHANGES_OUTPUT:
727                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
728                 if (buffer_.params().outputChanges) {
729                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
730                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
731                                           LaTeXFeatures::isAvailable("xcolor");
732
733                         if (!dvipost && !xcolorsoul) {
734                                 Alert::warning(_("Changes not shown in LaTeX output"),
735                                                _("Changes will not be highlighted in LaTeX output, "
736                                                  "because neither dvipost nor xcolor/soul are installed.\n"
737                                                  "Please install these packages or redefine "
738                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
739                         } else if (!xcolorsoul) {
740                                 Alert::warning(_("Changes not shown in LaTeX output"),
741                                                _("Changes will not be highlighted in LaTeX output "
742                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
743                                                  "Please install both packages or redefine "
744                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
745                         }
746                 }
747                 break;
748
749         case LFUN_CHANGE_NEXT:
750                 findNextChange(this);
751                 break;
752
753         case LFUN_CHANGES_MERGE:
754                 if (findNextChange(this))
755                         showDialog("changes");
756                 break;
757
758         case LFUN_ALL_CHANGES_ACCEPT:
759                 // select complete document
760                 cursor_.reset(buffer_.inset());
761                 cursor_.selHandle(true);
762                 buffer_.text().cursorBottom(cursor_);
763                 // accept everything in a single step to support atomic undo
764                 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
765                 break;
766
767         case LFUN_ALL_CHANGES_REJECT:
768                 // select complete document
769                 cursor_.reset(buffer_.inset());
770                 cursor_.selHandle(true);
771                 buffer_.text().cursorBottom(cursor_);
772                 // reject everything in a single step to support atomic undo
773                 // Note: reject does not work recursively; the user may have to repeat the operation
774                 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
775                 break;
776
777         case LFUN_WORD_FIND:
778                 find(this, cmd);
779                 break;
780
781         case LFUN_WORD_REPLACE: {
782                 bool has_deleted = false;
783                 if (cur.selection()) {
784                         DocIterator beg = cur.selectionBegin();
785                         DocIterator end = cur.selectionEnd();
786                         if (beg.pit() == end.pit()) {
787                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
788                                         if (cur.paragraph().isDeleted(p))
789                                                 has_deleted = true;
790                                 }
791                         }
792                 }
793                 replace(this, cmd, has_deleted);
794                 break;
795         }
796
797         case LFUN_MARK_OFF:
798                 cur.clearSelection();
799                 cur.resetAnchor();
800                 cur.message(from_utf8(N_("Mark off")));
801                 break;
802
803         case LFUN_MARK_ON:
804                 cur.clearSelection();
805                 cur.mark() = true;
806                 cur.resetAnchor();
807                 cur.message(from_utf8(N_("Mark on")));
808                 break;
809
810         case LFUN_MARK_TOGGLE:
811                 cur.clearSelection();
812                 if (cur.mark()) {
813                         cur.mark() = false;
814                         cur.message(from_utf8(N_("Mark removed")));
815                 } else {
816                         cur.mark() = true;
817                         cur.message(from_utf8(N_("Mark set")));
818                 }
819                 cur.resetAnchor();
820                 break;
821
822         case LFUN_SCREEN_RECENTER:
823                 center();
824                 break;
825
826         case LFUN_BIBTEX_DATABASE_ADD: {
827                 Cursor tmpcur = cursor_;
828                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
829                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
830                                                 Inset::BIBTEX_CODE);
831                 if (inset) {
832                         if (inset->addDatabase(to_utf8(cmd.argument())))
833                                 buffer_.updateBibfilesCache();
834                 }
835                 break;
836         }
837
838         case LFUN_BIBTEX_DATABASE_DEL: {
839                 Cursor tmpcur = cursor_;
840                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
841                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
842                                                 Inset::BIBTEX_CODE);
843                 if (inset) {
844                         if (inset->delDatabase(to_utf8(cmd.argument())))
845                                 buffer_.updateBibfilesCache();
846                 }
847                 break;
848         }
849
850         case LFUN_WORDS_COUNT: {
851                 DocIterator from, to;
852                 if (cur.selection()) {
853                         from = cur.selectionBegin();
854                         to = cur.selectionEnd();
855                 } else {
856                         from = doc_iterator_begin(buffer_.inset());
857                         to = doc_iterator_end(buffer_.inset());
858                 }
859                 int const count = countWords(from, to);
860                 docstring message;
861                 if (count != 1) {
862                         if (cur.selection())
863                                 message = bformat(_("%1$d words in selection."),
864                                           count);
865                                 else
866                                         message = bformat(_("%1$d words in document."),
867                                                           count);
868                 }
869                 else {
870                         if (cur.selection())
871                                 message = _("One word in selection.");
872                         else
873                                 message = _("One word in document.");
874                 }
875
876                 Alert::information(_("Count words"), message);
877         }
878                 break;
879
880         case LFUN_BUFFER_TOGGLE_COMPRESSION:
881                 // turn compression on/off
882                 buffer_.params().compressed = !buffer_.params().compressed;
883                 break;
884
885         case LFUN_NEXT_INSET_TOGGLE: {
886                 // this is the real function we want to invoke
887                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
888                 // if there is an inset at cursor, see whether it
889                 // wants to toggle.
890                 Inset * inset = cur.nextInset();
891                 if (inset && inset->isActive()) {
892                         Cursor tmpcur = cur;
893                         tmpcur.pushLeft(*inset);
894                         inset->dispatch(tmpcur, tmpcmd);
895                         if (tmpcur.result().dispatched()) {
896                                 cur.dispatched();
897                         }
898                 }
899                 // if it did not work, try the underlying inset.
900                 if (!cur.result().dispatched())
901                         cur.dispatch(tmpcmd);
902
903                 if (cur.result().dispatched())
904                         cur.clearSelection();
905
906                 break;
907         }
908
909         default:
910                 updateFlags = Update::None;
911         }
912
913         return updateFlags;
914 }
915
916
917 docstring const BufferView::requestSelection()
918 {
919         Cursor & cur = cursor_;
920
921         if (!cur.selection()) {
922                 xsel_cache_.set = false;
923                 return docstring();
924         }
925
926         if (!xsel_cache_.set ||
927             cur.top() != xsel_cache_.cursor ||
928             cur.anchor_.top() != xsel_cache_.anchor)
929         {
930                 xsel_cache_.cursor = cur.top();
931                 xsel_cache_.anchor = cur.anchor_.top();
932                 xsel_cache_.set = cur.selection();
933                 return cur.selectionAsString(false);
934         }
935         return docstring();
936 }
937
938
939 void BufferView::clearSelection()
940 {
941         cursor_.clearSelection();
942         // Clear the selection buffer. Otherwise a subsequent
943         // middle-mouse-button paste would use the selection buffer,
944         // not the more current external selection.
945         cap::clearSelection();
946         xsel_cache_.set = false;
947         // The buffer did not really change, but this causes the
948         // redraw we need because we cleared the selection above.
949         buffer_.changed();
950 }
951
952
953 void BufferView::workAreaResize(int width, int height)
954 {
955         // Update from work area
956         width_ = width;
957         height_ = height;
958
959         // The complete text metrics will be redone.
960         text_metrics_.clear();
961         updateMetrics(false);
962 }
963
964
965 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
966 {
967         pit_type pit = text.getPitNearY(*this, y);
968         BOOST_ASSERT(pit != -1);
969         Paragraph const & par = text.getPar(pit);
970
971         LYXERR(Debug::DEBUG)
972                 << BOOST_CURRENT_FUNCTION
973                 << ": x: " << x
974                 << " y: " << y
975                 << "  pit: " << pit
976                 << endl;
977         InsetList::const_iterator iit = par.insetlist.begin();
978         InsetList::const_iterator iend = par.insetlist.end();
979         for (; iit != iend; ++iit) {
980                 Inset * const inset = iit->inset;
981                 if (inset->covers(*this, x, y)) {
982                         if (!inset->descendable())
983                                 // No need to go further down if the inset is not
984                                 // descendable.
985                                 return inset;
986
987                         size_t cell_number = inset->nargs();
988                         // Check all the inner cell.
989                         for (size_t i = 0; i != cell_number; ++i) {
990                                 Text const * inner_text = inset->getText(i);
991                                 if (inner_text) {
992                                         // Try deeper.
993                                         Inset const * inset_deeper =
994                                                 getCoveringInset(*inner_text, x, y);
995                                         if (inset_deeper)
996                                                 return inset_deeper;
997                                 }
998                         }
999
1000                         LYXERR(Debug::DEBUG)
1001                                 << BOOST_CURRENT_FUNCTION
1002                                 << ": Hit inset: " << inset << endl;
1003                         return inset;
1004                 }
1005         }
1006         LYXERR(Debug::DEBUG)
1007                 << BOOST_CURRENT_FUNCTION
1008                 << ": No inset hit. " << endl;
1009         return 0;
1010 }
1011
1012
1013 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1014 {
1015         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1016
1017         // This is only called for mouse related events including
1018         // LFUN_FILE_OPEN generated by drag-and-drop.
1019         FuncRequest cmd = cmd0;
1020
1021         Cursor cur(*this);
1022         cur.push(buffer_.inset());
1023         cur.selection() = cursor_.selection();
1024
1025         // Either the inset under the cursor or the
1026         // surrounding Text will handle this event.
1027
1028         // make sure we stay within the screen...
1029         cmd.y = min(max(cmd.y, -1), height_);
1030
1031         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1032
1033                 // Get inset under mouse, if there is one.
1034                 Inset const * covering_inset =
1035                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1036                 if (covering_inset == last_inset_)
1037                         // Same inset, no need to do anything...
1038                         return false;
1039
1040                 bool need_redraw = false;
1041                 // const_cast because of setMouseHover().
1042                 Inset * inset = const_cast<Inset *>(covering_inset);
1043                 if (last_inset_)
1044                         // Remove the hint on the last hovered inset (if any).
1045                         need_redraw |= last_inset_->setMouseHover(false);
1046                 if (inset)
1047                         // Highlighted the newly hovered inset (if any).
1048                         need_redraw |= inset->setMouseHover(true);
1049                 last_inset_ = inset;
1050
1051                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1052                 // not expose the button for redraw. We adjust here the metrics dimension
1053                 // to enable a full redraw.
1054                 // FIXME: It is possible to redraw only the area around the button!
1055                 if (need_redraw
1056                         && metrics_info_.update_strategy == SingleParUpdate) {
1057                         // FIXME: It should be possible to redraw only the area around
1058                         // the button by doing this:
1059                         //
1060                         //metrics_info_.singlepar = false;
1061                         //metrics_info_.y1 = ymin of button;
1062                         //metrics_info_.y2 = ymax of button;
1063                         //
1064                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1065                         // between background updates and text updates. So we use the hammer
1066                         // solution for now. We could also avoid the updateMetrics() below
1067                         // by using the first and last pit of the CoordCache. Have a look
1068                         // at Text::getPitNearY() to see what I mean.
1069                         //
1070                         //metrics_info_.pit1 = first pit of CoordCache;
1071                         //metrics_info_.pit2 = last pit of CoordCache;
1072                         //metrics_info_.singlepar = false;
1073                         //metrics_info_.y1 = 0;
1074                         //metrics_info_.y2 = height_;
1075                         //
1076                         updateMetrics(false);
1077                 }
1078
1079                 // This event (moving without mouse click) is not passed further.
1080                 // This should be changed if it is further utilized.
1081                 return need_redraw;
1082         }
1083
1084         // Build temporary cursor.
1085         Inset * inset = buffer_.text().editXY(cur, cmd.x, cmd.y);
1086
1087         // Put anchor at the same position.
1088         cur.resetAnchor();
1089
1090         // Try to dispatch to an non-editable inset near this position
1091         // via the temp cursor. If the inset wishes to change the real
1092         // cursor it has to do so explicitly by using
1093         //  cur.bv().cursor() = cur;  (or similar)
1094         if (inset) {
1095                 inset->dispatch(cur, cmd);
1096         }
1097
1098         // Now dispatch to the temporary cursor. If the real cursor should
1099         // be modified, the inset's dispatch has to do so explicitly.
1100         if (!cur.result().dispatched())
1101                 cur.dispatch(cmd);
1102
1103         //Do we have a selection?
1104         theSelection().haveSelection(cursor().selection());
1105
1106         // Redraw if requested and necessary.
1107         if (cur.result().dispatched() && cur.result().update())
1108                 return update(cur.result().update());
1109
1110         return false;
1111 }
1112
1113
1114 void BufferView::scroll(int /*lines*/)
1115 {
1116 //      Text const * t = buffer_.text();
1117 //      int const line_height = defaultRowHeight();
1118 //
1119 //      // The new absolute coordinate
1120 //      int new_top_y = top_y() + lines * line_height;
1121 //
1122 //      // Restrict to a valid value
1123 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1124 //      new_top_y = std::max(0, new_top_y);
1125 //
1126 //      scrollDocView(new_top_y);
1127 //
1128 }
1129
1130
1131 void BufferView::setCursorFromRow(int row)
1132 {
1133         int tmpid = -1;
1134         int tmppos = -1;
1135
1136         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1137
1138         cursor_.reset(buffer_.inset());
1139         if (tmpid == -1)
1140                 buffer_.text().setCursor(cursor_, 0, 0);
1141         else
1142                 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1143 }
1144
1145
1146 void BufferView::gotoLabel(docstring const & label)
1147 {
1148         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1149                 vector<docstring> labels;
1150                 it->getLabelList(buffer_, labels);
1151                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1152                         setCursor(it);
1153                         update();
1154                         return;
1155                 }
1156         }
1157 }
1158
1159
1160 TextMetrics const & BufferView::textMetrics(Text const * t) const
1161 {
1162         return const_cast<BufferView *>(this)->textMetrics(t);
1163 }
1164
1165
1166 TextMetrics & BufferView::textMetrics(Text const * t)
1167 {
1168         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1169         if (tmc_it == text_metrics_.end()) {
1170                 tmc_it = text_metrics_.insert(
1171                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1172         }
1173         return tmc_it->second;
1174 }
1175
1176
1177 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1178                 pit_type pit) const
1179 {
1180         return textMetrics(t).parMetrics(pit);
1181 }
1182
1183
1184 int BufferView::workHeight() const
1185 {
1186         return height_;
1187 }
1188
1189
1190 void BufferView::setCursor(DocIterator const & dit)
1191 {
1192         size_t const n = dit.depth();
1193         for (size_t i = 0; i < n; ++i)
1194                 dit[i].inset().edit(cursor_, true);
1195
1196         cursor_.setCursor(dit);
1197         cursor_.selection() = false;
1198 }
1199
1200
1201 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1202 {
1203         // Would be wrong to delete anything if we have a selection.
1204         if (cur.selection())
1205                 return false;
1206
1207         bool need_anchor_change = false;
1208         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1209                 need_anchor_change);
1210
1211         if (need_anchor_change)
1212                 cur.resetAnchor();
1213
1214         if (!changed)
1215                 return false;
1216
1217         updateLabels(buffer_);
1218
1219         updateMetrics(false);
1220         buffer_.changed();
1221         return true;
1222 }
1223
1224
1225 bool BufferView::mouseSetCursor(Cursor & cur)
1226 {
1227         BOOST_ASSERT(&cur.bv() == this);
1228
1229         // this event will clear selection so we save selection for
1230         // persistent selection
1231         cap::saveSelection(cursor());
1232
1233         // Has the cursor just left the inset?
1234         bool badcursor = false;
1235         bool leftinset = (&cursor_.inset() != &cur.inset());
1236         if (leftinset)
1237                 badcursor = notifyCursorLeaves(cursor_, cur);
1238
1239         // do the dEPM magic if needed
1240         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1241         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1242         // the leftinset bool would not be necessary (badcursor instead).
1243         bool update = leftinset;
1244         if (!badcursor && cursor_.inTexted())
1245                 update |= checkDepm(cur, cursor_);
1246
1247         // if the cursor was in an empty script inset and the new
1248         // position is in the nucleus of the inset, notifyCursorLeaves
1249         // will kill the script inset itself. So we check all the
1250         // elements of the cursor to make sure that they are correct.
1251         // For an example, see bug 2933:
1252         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1253         // The code below could maybe be moved to a DocIterator method.
1254         //lyxerr << "cur before " << cur <<std::endl;
1255         DocIterator dit(cur.inset());
1256         dit.push_back(cur.bottom());
1257         size_t i = 1;
1258         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1259                 dit.push_back(cur[i]);
1260                 ++i;
1261         }
1262         //lyxerr << "5 cur after" << dit <<std::endl;
1263
1264         cursor_.setCursor(dit);
1265         cursor_.boundary(cur.boundary());
1266         cursor_.clearSelection();
1267         finishUndo();
1268         return update;
1269 }
1270
1271
1272 void BufferView::putSelectionAt(DocIterator const & cur,
1273                                 int length, bool backwards)
1274 {
1275         cursor_.clearSelection();
1276
1277         setCursor(cur);
1278
1279         if (length) {
1280                 if (backwards) {
1281                         cursor_.pos() += length;
1282                         cursor_.setSelection(cursor_, -length);
1283                 } else
1284                         cursor_.setSelection(cursor_, length);
1285         }
1286 }
1287
1288
1289 Cursor & BufferView::cursor()
1290 {
1291         return cursor_;
1292 }
1293
1294
1295 Cursor const & BufferView::cursor() const
1296 {
1297         return cursor_;
1298 }
1299
1300
1301 pit_type BufferView::anchor_ref() const
1302 {
1303         return anchor_ref_;
1304 }
1305
1306
1307 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1308 {
1309         return metrics_info_;
1310 }
1311
1312
1313 // FIXME: We should split-up updateMetrics() for the singlepar case.
1314 void BufferView::updateMetrics(bool singlepar)
1315 {
1316         Text & buftext = buffer_.text();
1317         TextMetrics & tm = textMetrics(&buftext);
1318         pit_type size = int(buftext.paragraphs().size());
1319
1320         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1321                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1322                 offset_ref_ = 0;
1323         }
1324
1325         if (!singlepar) {
1326                 // Clear out the position cache in case of full screen redraw,
1327                 coord_cache_.clear();
1328         
1329                 // Clear out paragraph metrics to avoid having invalid metrics
1330                 // in the cache from paragraphs not relayouted below
1331                 tm.clear();
1332         }
1333
1334         // If the paragraph metrics has changed, we can not
1335         // use the singlepar optimisation.
1336         if (singlepar
1337                 // In Single Paragraph mode, rebreak only
1338                 // the (main text, not inset!) paragraph containing the cursor.
1339                 // (if this paragraph contains insets etc., rebreaking will
1340                 // recursively descend)
1341                 && tm.redoParagraph(cursor_.bottom().pit()))
1342                 singlepar = false;
1343
1344         pit_type const pit = anchor_ref_;
1345         int pit1 = pit;
1346         int pit2 = pit;
1347         size_t const npit = buftext.paragraphs().size();
1348
1349         // Rebreak anchor paragraph.
1350         if (!singlepar)
1351                 tm.redoParagraph(pit);
1352
1353         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1354
1355         // Redo paragraphs above anchor if necessary.
1356         int y1 = y0;
1357         while (y1 > 0 && pit1 > 0) {
1358                 y1 -= tm.parMetrics(pit1).ascent();
1359                 --pit1;
1360                 if (!singlepar)
1361                         tm.redoParagraph(pit1);
1362                 y1 -= tm.parMetrics(pit1).descent();
1363         }
1364
1365
1366         // Take care of ascent of first line
1367         y1 -= tm.parMetrics(pit1).ascent();
1368
1369         // Normalize anchor for next time
1370         anchor_ref_ = pit1;
1371         offset_ref_ = -y1;
1372
1373         // Grey at the beginning is ugly
1374         if (pit1 == 0 && y1 > 0) {
1375                 y0 -= y1;
1376                 y1 = 0;
1377                 anchor_ref_ = 0;
1378         }
1379
1380         // Redo paragraphs below the anchor if necessary.
1381         int y2 = y0;
1382         while (y2 < height_ && pit2 < int(npit) - 1) {
1383                 y2 += tm.parMetrics(pit2).descent();
1384                 ++pit2;
1385                 if (!singlepar)
1386                         tm.redoParagraph(pit2);
1387                 y2 += tm.parMetrics(pit2).ascent();
1388         }
1389
1390         // Take care of descent of last line
1391         y2 += tm.parMetrics(pit2).descent();
1392
1393         // The coordinates of all these paragraphs are correct, cache them
1394         int y = y1;
1395         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1396         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1397                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1398                 y += pm.ascent();
1399                 parPos[pit] = Point(0, y);
1400                 if (singlepar && pit == cursor_.bottom().pit()) {
1401                         // In Single Paragraph mode, collect here the
1402                         // y1 and y2 of the (one) paragraph the cursor is in
1403                         y1 = y - pm.ascent();
1404                         y2 = y + pm.descent();
1405                 }
1406                 y += pm.descent();
1407         }
1408
1409         if (singlepar) {
1410                 // collect cursor paragraph iter bounds
1411                 pit1 = cursor_.bottom().pit();
1412                 pit2 = cursor_.bottom().pit();
1413         }
1414
1415         LYXERR(Debug::DEBUG)
1416                 << BOOST_CURRENT_FUNCTION
1417                 << " y1: " << y1
1418                 << " y2: " << y2
1419                 << " pit1: " << pit1
1420                 << " pit2: " << pit2
1421                 << " npit: " << npit
1422                 << " singlepar: " << singlepar
1423                 << "size: " << size
1424                 << endl;
1425
1426         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1427                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1428
1429         if (lyxerr.debugging(Debug::WORKAREA)) {
1430                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1431                 coord_cache_.dump();
1432         }
1433 }
1434
1435
1436 void BufferView::menuInsertLyXFile(string const & filenm)
1437 {
1438         BOOST_ASSERT(cursor_.inTexted());
1439         string filename = filenm;
1440
1441         if (filename.empty()) {
1442                 // Launch a file browser
1443                 // FIXME UNICODE
1444                 string initpath = lyxrc.document_path;
1445                 string const trypath = buffer_.filePath();
1446                 // If directory is writeable, use this as default.
1447                 if (isDirWriteable(FileName(trypath)))
1448                         initpath = trypath;
1449
1450                 // FIXME UNICODE
1451                 FileDialog fileDlg(_("Select LyX document to insert"),
1452                         LFUN_FILE_INSERT,
1453                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1454                         make_pair(_("Examples|#E#e"),
1455                                     from_utf8(addPath(package().system_support().absFilename(),
1456                                     "examples"))));
1457
1458                 FileDialog::Result result =
1459                         fileDlg.open(from_utf8(initpath),
1460                                      FileFilterList(_("LyX Documents (*.lyx)")),
1461                                      docstring());
1462
1463                 if (result.first == FileDialog::Later)
1464                         return;
1465
1466                 // FIXME UNICODE
1467                 filename = to_utf8(result.second);
1468
1469                 // check selected filename
1470                 if (filename.empty()) {
1471                         // emit message signal.
1472                         message(_("Canceled."));
1473                         return;
1474                 }
1475         }
1476
1477         // Get absolute path of file and add ".lyx"
1478         // to the filename if necessary
1479         filename = fileSearch(string(), filename, "lyx").absFilename();
1480
1481         docstring const disp_fn = makeDisplayPath(filename);
1482         // emit message signal.
1483         message(bformat(_("Inserting document %1$s..."), disp_fn));
1484
1485         docstring res;
1486         Buffer buf("", false);
1487         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1488                 ErrorList & el = buffer_.errorList("Parse");
1489                 // Copy the inserted document error list into the current buffer one.
1490                 el = buf.errorList("Parse");
1491                 recordUndo(cursor_);
1492                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1493                                              buf.params().textclass, el);
1494                 res = _("Document %1$s inserted.");
1495         } else
1496                 res = _("Could not insert document %1$s");
1497
1498         // emit message signal.
1499         message(bformat(res, disp_fn));
1500         buffer_.errors("Parse");
1501         updateMetrics(false);
1502 }
1503
1504 } // namespace lyx