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